-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
juce_audio_plugin_client_AUv3.mm
2014 lines (1609 loc) · 83.3 KB
/
juce_audio_plugin_client_AUv3.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include <juce_core/system/juce_TargetPlatform.h>
#include <juce_audio_plugin_client/detail/juce_CheckSettingMacros.h>
#if JucePlugin_Build_AUv3
#if JUCE_MAC && ! (defined (MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_11)
#error AUv3 needs Deployment Target OS X 10.11 or higher to compile
#endif
#ifndef __OBJC2__
#error AUv3 needs Objective-C 2 support (compile with 64-bit)
#endif
#define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
#include <juce_audio_plugin_client/detail/juce_IncludeSystemHeaders.h>
#include <juce_audio_plugin_client/detail/juce_PluginUtilities.h>
#import <CoreAudioKit/CoreAudioKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#include <juce_graphics/native/juce_CoreGraphicsHelpers_mac.h>
#include <juce_audio_basics/native/juce_CoreAudioLayouts_mac.h>
#include <juce_audio_basics/native/juce_CoreAudioTimeConversions_mac.h>
#include <juce_audio_basics/native/juce_AudioWorkgroup_mac.h>
#include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
#include <juce_audio_processors/format_types/juce_AU_Shared.h>
#define JUCE_VIEWCONTROLLER_OBJC_NAME(x) JUCE_JOIN_MACRO (x, FactoryAUv3)
#if JUCE_IOS
#define JUCE_IOS_MAC_VIEW UIView
#else
#define JUCE_IOS_MAC_VIEW NSView
#endif
#define JUCE_AUDIOUNIT_OBJC_NAME(x) JUCE_JOIN_MACRO (x, AUv3)
#include <future>
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnullability-completeness")
using namespace juce;
struct AudioProcessorHolder final : public ReferenceCountedObject
{
AudioProcessorHolder() = default;
explicit AudioProcessorHolder (std::unique_ptr<AudioProcessor> p) : processor (std::move (p)) {}
AudioProcessor& operator*() noexcept { return *processor; }
AudioProcessor* operator->() noexcept { return processor.get(); }
AudioProcessor* get() noexcept { return processor.get(); }
struct ViewConfig
{
double width;
double height;
bool hostHasMIDIController;
};
std::unique_ptr<ViewConfig> viewConfiguration;
using Ptr = ReferenceCountedObjectPtr<AudioProcessorHolder>;
private:
std::unique_ptr<AudioProcessor> processor;
AudioProcessorHolder& operator= (AudioProcessor*) = delete;
AudioProcessorHolder (AudioProcessorHolder&) = delete;
AudioProcessorHolder& operator= (AudioProcessorHolder&) = delete;
};
#if ! JUCE_AUDIOWORKGROUP_TYPES_AVAILABLE
struct AudioUnitRenderContext;
typedef void (^AURenderContextObserver) (const AudioUnitRenderContext*);
#endif
//==============================================================================
//=========================== The actual AudioUnit =============================
//==============================================================================
class JuceAudioUnitv3 final : public AudioProcessorListener,
public AudioPlayHead,
private AudioProcessorParameter::Listener
{
public:
JuceAudioUnitv3 (const AudioProcessorHolder::Ptr& processor,
const AudioComponentDescription& descr,
AudioComponentInstantiationOptions options,
NSError** error)
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wobjc-method-access")
: au ([getClass().createInstance() initWithComponentDescription: descr
options: options
error: error
juceClass: this]),
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
processorHolder (processor)
{
init();
}
JuceAudioUnitv3 (AUAudioUnit* audioUnit, AudioComponentDescription, AudioComponentInstantiationOptions, NSError**)
: au (audioUnit),
processorHolder (new AudioProcessorHolder (createPluginFilterOfType (AudioProcessor::wrapperType_AudioUnitv3)))
{
jassert (MessageManager::getInstance()->isThisTheMessageThread());
initialiseJuce_GUI();
init();
}
~JuceAudioUnitv3() override
{
auto& processor = getAudioProcessor();
processor.removeListener (this);
if (bypassParam != nullptr)
bypassParam->removeListener (this);
removeEditor (processor);
}
//==============================================================================
void init()
{
inParameterChangedCallback = false;
AudioProcessor& processor = getAudioProcessor();
const AUAudioFrameCount maxFrames = [au maximumFramesToRender];
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
const int numConfigs = sizeof (configs) / sizeof (short[2]);
jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
processor.setPlayConfigDetails (configs[0][0], configs[0][1], kDefaultSampleRate, static_cast<int> (maxFrames));
Array<AUChannelInfo> channelInfos;
for (int i = 0; i < numConfigs; ++i)
{
AUChannelInfo channelInfo;
channelInfo.inChannels = configs[i][0];
channelInfo.outChannels = configs[i][1];
channelInfos.add (channelInfo);
}
#else
Array<AUChannelInfo> channelInfos = AudioUnitHelpers::getAUChannelInfo (processor);
#endif
processor.setPlayHead (this);
totalInChannels = processor.getTotalNumInputChannels();
totalOutChannels = processor.getTotalNumOutputChannels();
{
channelCapabilities.reset ([[NSMutableArray<NSNumber*> alloc] init]);
for (int i = 0; i < channelInfos.size(); ++i)
{
AUChannelInfo& info = channelInfos.getReference (i);
[channelCapabilities.get() addObject: [NSNumber numberWithInteger: info.inChannels]];
[channelCapabilities.get() addObject: [NSNumber numberWithInteger: info.outChannels]];
}
}
internalRenderBlock = CreateObjCBlock (this, &JuceAudioUnitv3::renderCallback);
#if JUCE_AUDIOWORKGROUP_TYPES_AVAILABLE
renderContextObserver = ^(const AudioUnitRenderContext* context)
{
getAudioProcessor().audioWorkgroupContextChanged (makeRealAudioWorkgroup (context->workgroup));
};
#else
renderContextObserver = ^(const AudioUnitRenderContext*) {};
#endif
processor.setRateAndBufferSizeDetails (kDefaultSampleRate, static_cast<int> (maxFrames));
processor.prepareToPlay (kDefaultSampleRate, static_cast<int> (maxFrames));
processor.addListener (this);
addParameters();
addPresets();
addAudioUnitBusses (true);
addAudioUnitBusses (false);
}
AudioProcessor& getAudioProcessor() const noexcept { return **processorHolder; }
//==============================================================================
void reset()
{
midiMessages.clear();
lastTimeStamp.mSampleTime = std::numeric_limits<Float64>::max();
lastTimeStamp.mFlags = 0;
}
//==============================================================================
AUAudioUnitPreset* getCurrentPreset() const
{
return factoryPresets.getAtIndex (getAudioProcessor().getCurrentProgram());
}
void setCurrentPreset (AUAudioUnitPreset* preset)
{
getAudioProcessor().setCurrentProgram (static_cast<int> ([preset number]));
}
NSArray<AUAudioUnitPreset*>* getFactoryPresets() const
{
return factoryPresets.get();
}
NSDictionary<NSString*, id>* getFullState() const
{
NSMutableDictionary<NSString*, id>* retval = [[NSMutableDictionary<NSString*, id> alloc] init];
{
auto* superRetval = ObjCMsgSendSuper<AUAudioUnit, NSDictionary<NSString*, id>*> (au, @selector (fullState));
if (superRetval != nullptr)
[retval addEntriesFromDictionary:superRetval];
}
juce::MemoryBlock state;
#if JUCE_AU_WRAPPERS_SAVE_PROGRAM_STATES
getAudioProcessor().getCurrentProgramStateInformation (state);
#else
getAudioProcessor().getStateInformation (state);
#endif
if (state.getSize() > 0)
{
[retval setObject: [[NSData alloc] initWithBytes: state.getData() length: state.getSize()]
forKey: @JUCE_STATE_DICTIONARY_KEY];
}
return [retval autorelease];
}
void setFullState (NSDictionary<NSString*, id>* state)
{
if (state == nullptr)
return;
NSObject* obj = [state objectForKey: @JUCE_STATE_DICTIONARY_KEY];
if (obj == nullptr || ! [obj isKindOfClass: [NSData class]])
return;
auto* data = reinterpret_cast<NSData*> (obj);
const auto numBytes = static_cast<int> ([data length]);
if (numBytes <= 0)
return;
auto* rawBytes = reinterpret_cast<const juce::uint8* const> ([data bytes]);
ScopedKeyChange scope (au, @"allParameterValues");
#if JUCE_AU_WRAPPERS_SAVE_PROGRAM_STATES
getAudioProcessor().setCurrentProgramStateInformation (rawBytes, numBytes);
#else
getAudioProcessor().setStateInformation (rawBytes, numBytes);
#endif
}
AUParameterTree* getParameterTree() const
{
return paramTree.get();
}
NSArray<NSNumber*>* parametersForOverviewWithCount (int count) const
{
auto* retval = [[[NSMutableArray<NSNumber*> alloc] init] autorelease];
for (const auto& address : addressForIndex)
{
if (static_cast<size_t> (count) <= [retval count])
break;
[retval addObject: [NSNumber numberWithUnsignedLongLong: address]];
}
return retval;
}
//==============================================================================
NSTimeInterval getLatency() const
{
auto& p = getAudioProcessor();
return p.getLatencySamples() / p.getSampleRate();
}
NSTimeInterval getTailTime() const
{
return getAudioProcessor().getTailLengthSeconds();
}
//==============================================================================
AUAudioUnitBusArray* getInputBusses() const { return inputBusses.get(); }
AUAudioUnitBusArray* getOutputBusses() const { return outputBusses.get(); }
NSArray<NSNumber*>* getChannelCapabilities() const { return channelCapabilities.get(); }
bool shouldChangeToFormat (AVAudioFormat* format, AUAudioUnitBus* auBus)
{
const bool isInput = ([auBus busType] == AUAudioUnitBusTypeInput);
const int busIdx = static_cast<int> ([auBus index]);
const int newNumChannels = static_cast<int> ([format channelCount]);
AudioProcessor& processor = getAudioProcessor();
if ([[maybe_unused]] AudioProcessor::Bus* bus = processor.getBus (isInput, busIdx))
{
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
if (! AudioUnitHelpers::isLayoutSupported (processor, isInput, busIdx, newNumChannels, configs))
return false;
#else
const AVAudioChannelLayout* layout = [format channelLayout];
const AudioChannelLayoutTag layoutTag = (layout != nullptr ? [layout layoutTag] : 0);
if (layoutTag != 0)
{
AudioChannelSet newLayout = CoreAudioLayouts::fromCoreAudio (layoutTag);
if (newLayout.size() != newNumChannels)
return false;
if (! bus->isLayoutSupported (newLayout))
return false;
}
else
{
if (! bus->isNumberOfChannelsSupported (newNumChannels))
return false;
}
#endif
return true;
}
return false;
}
//==============================================================================
int getVirtualMIDICableCount() const
{
#if JucePlugin_WantsMidiInput
return 1;
#else
return 0;
#endif
}
bool getSupportsMPE() const
{
return getAudioProcessor().supportsMPE();
}
NSArray<NSString*>* getMIDIOutputNames() const
{
#if JucePlugin_ProducesMidiOutput
return @[@"MIDI Out"];
#else
return @[];
#endif
}
//==============================================================================
AUInternalRenderBlock getInternalRenderBlock() const { return internalRenderBlock; }
AURenderContextObserver getInternalContextObserver() const { return renderContextObserver; }
bool getRenderingOffline() const { return getAudioProcessor().isNonRealtime(); }
void setRenderingOffline (bool offline)
{
auto& processor = getAudioProcessor();
auto isCurrentlyNonRealtime = processor.isNonRealtime();
if (isCurrentlyNonRealtime != offline)
{
ScopedLock callbackLock (processor.getCallbackLock());
processor.setNonRealtime (offline);
processor.prepareToPlay (processor.getSampleRate(), processor.getBlockSize());
}
}
bool getShouldBypassEffect() const
{
if (bypassParam != nullptr)
return (bypassParam->getValue() != 0.0f);
return (ObjCMsgSendSuper<AUAudioUnit, BOOL> (au, @selector (shouldBypassEffect)) == YES);
}
void setShouldBypassEffect (bool shouldBypass)
{
if (bypassParam != nullptr)
bypassParam->setValue (shouldBypass ? 1.0f : 0.0f);
ObjCMsgSendSuper<AUAudioUnit, void> (au, @selector (setShouldBypassEffect:), shouldBypass ? YES : NO);
}
//==============================================================================
NSString* getContextName() const { return juceStringToNS (contextName); }
void setContextName (NSString* str)
{
if (str != nullptr)
{
AudioProcessor::TrackProperties props;
props.name = nsStringToJuce (str);
getAudioProcessor().updateTrackProperties (props);
}
}
//==============================================================================
bool allocateRenderResourcesAndReturnError (NSError **outError)
{
AudioProcessor& processor = getAudioProcessor();
const AUAudioFrameCount maxFrames = [au maximumFramesToRender];
if (ObjCMsgSendSuper<AUAudioUnit, BOOL, NSError**> (au, @selector (allocateRenderResourcesAndReturnError:), outError) == NO)
return false;
if (outError != nullptr)
*outError = nullptr;
AudioProcessor::BusesLayout layouts;
for (int dir = 0; dir < 2; ++dir)
{
const bool isInput = (dir == 0);
const int n = AudioUnitHelpers::getBusCountForWrapper (processor, isInput);
Array<AudioChannelSet>& channelSets = (isInput ? layouts.inputBuses : layouts.outputBuses);
AUAudioUnitBusArray* auBuses = (isInput ? [au inputBusses] : [au outputBusses]);
jassert ([auBuses count] == static_cast<NSUInteger> (n));
for (int busIdx = 0; busIdx < n; ++busIdx)
{
if (AudioProcessor::Bus* bus = processor.getBus (isInput, busIdx))
{
AVAudioFormat* format = [[auBuses objectAtIndexedSubscript:static_cast<NSUInteger> (busIdx)] format];
AudioChannelSet newLayout;
const AVAudioChannelLayout* layout = [format channelLayout];
const AudioChannelLayoutTag layoutTag = (layout != nullptr ? [layout layoutTag] : 0);
if (layoutTag != 0)
newLayout = CoreAudioLayouts::fromCoreAudio (layoutTag);
else
newLayout = bus->supportedLayoutWithChannels (static_cast<int> ([format channelCount]));
if (newLayout.isDisabled())
return false;
channelSets.add (newLayout);
}
}
}
#ifdef JucePlugin_PreferredChannelConfigurations
short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
if (! AudioProcessor::containsLayout (layouts, configs))
{
if (outError != nullptr)
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_FormatNotSupported userInfo:nullptr];
return false;
}
#endif
if (! AudioUnitHelpers::setBusesLayout (&getAudioProcessor(), layouts))
{
if (outError != nullptr)
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:kAudioUnitErr_FormatNotSupported userInfo:nullptr];
return false;
}
totalInChannels = processor.getTotalNumInputChannels();
totalOutChannels = processor.getTotalNumOutputChannels();
allocateBusBuffer (true);
allocateBusBuffer (false);
mapper.alloc (processor);
audioBuffer.prepare (AudioUnitHelpers::getBusesLayout (&processor), static_cast<int> (maxFrames));
auto sampleRate = [&]
{
for (auto* buffer : { inputBusses.get(), outputBusses.get() })
if ([buffer count] > 0)
return [[[buffer objectAtIndexedSubscript: 0] format] sampleRate];
return 44100.0;
}();
processor.setRateAndBufferSizeDetails (sampleRate, static_cast<int> (maxFrames));
processor.prepareToPlay (sampleRate, static_cast<int> (maxFrames));
midiMessages.ensureSize (2048);
midiMessages.clear();
hostMusicalContextCallback = [au musicalContextBlock];
hostTransportStateCallback = [au transportStateBlock];
if (@available (macOS 10.13, iOS 11.0, *))
midiOutputEventBlock = [au MIDIOutputEventBlock];
reset();
return true;
}
void deallocateRenderResources()
{
midiOutputEventBlock = nullptr;
hostMusicalContextCallback = nullptr;
hostTransportStateCallback = nullptr;
getAudioProcessor().releaseResources();
audioBuffer.release();
inBusBuffers. clear();
outBusBuffers.clear();
mapper.release();
ObjCMsgSendSuper<AUAudioUnit, void> (au, @selector (deallocateRenderResources));
}
//==============================================================================
struct ScopedKeyChange
{
ScopedKeyChange (AUAudioUnit* a, NSString* k)
: au (a), key (k)
{
[au willChangeValueForKey: key];
}
~ScopedKeyChange()
{
[au didChangeValueForKey: key];
}
AUAudioUnit* au;
NSString* key;
};
//==============================================================================
void audioProcessorChanged ([[maybe_unused]] AudioProcessor* processor, const ChangeDetails& details) override
{
if (details.programChanged)
{
{
ScopedKeyChange scope (au, @"allParameterValues");
addPresets();
}
{
ScopedKeyChange scope (au, @"currentPreset");
}
}
if (details.latencyChanged)
{
ScopedKeyChange scope (au, @"latency");
}
if (details.parameterInfoChanged)
{
ScopedKeyChange scope (au, @"parameterTree");
auto nodes = createParameterNodes<NodeArrayResult> (processor->getParameterTree());
installNewParameterTree (std::move (nodes.nodeArray));
}
}
void sendParameterEvent (int idx, const float* newValue, AUParameterAutomationEventType type)
{
if (inParameterChangedCallback.get())
{
inParameterChangedCallback = false;
return;
}
if (auto* juceParam = juceParameters.getParamForIndex (idx))
{
if (auto* param = [paramTree.get() parameterWithAddress: getAUParameterAddressForIndex (idx)])
{
const auto value = (newValue != nullptr ? *newValue : juceParam->getValue()) * getMaximumParameterValue (*juceParam);
if (@available (macOS 10.12, iOS 10.0, *))
{
[param setValue: value
originator: editorObserverToken.get()
atHostTime: lastTimeStamp.mHostTime
eventType: type];
}
else if (type == AUParameterAutomationEventTypeValue)
{
[param setValue: value originator: editorObserverToken.get()];
}
}
}
}
void audioProcessorParameterChanged (AudioProcessor*, int idx, float newValue) override
{
sendParameterEvent (idx, &newValue, AUParameterAutomationEventTypeValue);
}
void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int idx) override
{
sendParameterEvent (idx, nullptr, AUParameterAutomationEventTypeTouch);
}
void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int idx) override
{
sendParameterEvent (idx, nullptr, AUParameterAutomationEventTypeRelease);
}
//==============================================================================
Optional<PositionInfo> getPosition() const override
{
PositionInfo info;
info.setTimeInSamples ((int64) (lastTimeStamp.mSampleTime + 0.5));
info.setTimeInSeconds (*info.getTimeInSamples() / getAudioProcessor().getSampleRate());
info.setFrameRate ([this]
{
switch (lastTimeStamp.mSMPTETime.mType)
{
case kSMPTETimeType2398: return FrameRate().withBaseRate (24).withPullDown();
case kSMPTETimeType24: return FrameRate().withBaseRate (24);
case kSMPTETimeType25: return FrameRate().withBaseRate (25);
case kSMPTETimeType30Drop: return FrameRate().withBaseRate (30).withDrop();
case kSMPTETimeType30: return FrameRate().withBaseRate (30);
case kSMPTETimeType2997: return FrameRate().withBaseRate (30).withPullDown();
case kSMPTETimeType2997Drop: return FrameRate().withBaseRate (30).withPullDown().withDrop();
case kSMPTETimeType60: return FrameRate().withBaseRate (60);
case kSMPTETimeType60Drop: return FrameRate().withBaseRate (60).withDrop();
case kSMPTETimeType5994: return FrameRate().withBaseRate (60).withPullDown();
case kSMPTETimeType5994Drop: return FrameRate().withBaseRate (60).withPullDown().withDrop();
case kSMPTETimeType50: return FrameRate().withBaseRate (50);
default: break;
}
return FrameRate();
}());
double num;
NSInteger den;
NSInteger outDeltaSampleOffsetToNextBeat;
double outCurrentMeasureDownBeat, bpm;
double ppqPosition;
if (hostMusicalContextCallback != nullptr)
{
AUHostMusicalContextBlock musicalContextCallback = hostMusicalContextCallback;
if (musicalContextCallback (&bpm, &num, &den, &ppqPosition, &outDeltaSampleOffsetToNextBeat, &outCurrentMeasureDownBeat))
{
info.setTimeSignature (TimeSignature { (int) num, (int) den });
info.setPpqPositionOfLastBarStart (outCurrentMeasureDownBeat);
info.setBpm (bpm);
info.setPpqPosition (ppqPosition);
}
}
double outCurrentSampleInTimeLine = 0, outCycleStartBeat = 0, outCycleEndBeat = 0;
AUHostTransportStateFlags flags;
if (hostTransportStateCallback != nullptr)
{
AUHostTransportStateBlock transportStateCallback = hostTransportStateCallback;
if (transportStateCallback (&flags, &outCurrentSampleInTimeLine, &outCycleStartBeat, &outCycleEndBeat))
{
info.setTimeInSamples ((int64) (outCurrentSampleInTimeLine + 0.5));
info.setTimeInSeconds (*info.getTimeInSamples() / getAudioProcessor().getSampleRate());
info.setIsPlaying ((flags & AUHostTransportStateMoving) != 0);
info.setIsLooping ((flags & AUHostTransportStateCycling) != 0);
info.setIsRecording ((flags & AUHostTransportStateRecording) != 0);
info.setLoopPoints (LoopPoints { outCycleStartBeat, outCycleEndBeat });
}
}
if ((lastTimeStamp.mFlags & kAudioTimeStampHostTimeValid) != 0)
info.setHostTimeNs (timeConversions.hostTimeToNanos (lastTimeStamp.mHostTime));
return info;
}
//==============================================================================
static void removeEditor (AudioProcessor& processor)
{
ScopedLock editorLock (processor.getCallbackLock());
if (AudioProcessorEditor* editor = processor.getActiveEditor())
{
processor.editorBeingDeleted (editor);
delete editor;
}
}
AUAudioUnit* getAudioUnit() const { return au; }
private:
struct Class final : public ObjCClass<AUAudioUnit>
{
Class() : ObjCClass<AUAudioUnit> ("AUAudioUnit_")
{
addIvar<JuceAudioUnitv3*> ("cppObject");
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
addMethod (@selector (initWithComponentDescription:options:error:juceClass:), [] (id _self,
SEL,
AudioComponentDescription descr,
AudioComponentInstantiationOptions options,
NSError** error,
JuceAudioUnitv3* juceAU)
{
AUAudioUnit* self = _self;
self = ObjCMsgSendSuper<AUAudioUnit, AUAudioUnit*, AudioComponentDescription,
AudioComponentInstantiationOptions, NSError**> (self, @selector (initWithComponentDescription:options:error:), descr, options, error);
setThis (self, juceAU);
return self;
});
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
addMethod (@selector (initWithComponentDescription:options:error:), [] (id _self,
SEL,
AudioComponentDescription descr,
AudioComponentInstantiationOptions options,
NSError** error)
{
AUAudioUnit* self = _self;
self = ObjCMsgSendSuper<AUAudioUnit, AUAudioUnit*, AudioComponentDescription,
AudioComponentInstantiationOptions, NSError**> (self, @selector (initWithComponentDescription:options:error:), descr, options, error);
auto* juceAU = JuceAudioUnitv3::create (self, descr, options, error);
setThis (self, juceAU);
return self;
});
addMethod (@selector (dealloc), [] (id self, SEL)
{
if (! MessageManager::getInstance()->isThisTheMessageThread())
{
WaitableEvent deletionEvent;
struct AUDeleter final : public CallbackMessage
{
AUDeleter (id selfToDelete, WaitableEvent& event)
: parentSelf (selfToDelete), parentDeletionEvent (event)
{
}
void messageCallback() override
{
delete _this (parentSelf);
parentDeletionEvent.signal();
}
id parentSelf;
WaitableEvent& parentDeletionEvent;
};
(new AUDeleter (self, deletionEvent))->post();
deletionEvent.wait (-1);
}
else
{
delete _this (self);
}
});
//==============================================================================
addMethod (@selector (reset), [] (id self, SEL) { return _this (self)->reset(); });
//==============================================================================
addMethod (@selector (currentPreset), [] (id self, SEL) { return _this (self)->getCurrentPreset(); });
addMethod (@selector (setCurrentPreset:), [] (id self, SEL, AUAudioUnitPreset* preset) { return _this (self)->setCurrentPreset (preset); });
addMethod (@selector (factoryPresets), [] (id self, SEL) { return _this (self)->getFactoryPresets(); });
addMethod (@selector (fullState), [] (id self, SEL) { return _this (self)->getFullState(); });
addMethod (@selector (setFullState:), [] (id self, SEL, NSDictionary<NSString *, id>* state) { return _this (self)->setFullState (state); });
addMethod (@selector (parameterTree), [] (id self, SEL) { return _this (self)->getParameterTree(); });
addMethod (@selector (parametersForOverviewWithCount:), [] (id self, SEL, NSInteger count) { return _this (self)->parametersForOverviewWithCount (static_cast<int> (count)); });
//==============================================================================
addMethod (@selector (latency), [] (id self, SEL) { return _this (self)->getLatency(); });
addMethod (@selector (tailTime), [] (id self, SEL) { return _this (self)->getTailTime(); });
//==============================================================================
addMethod (@selector (inputBusses), [] (id self, SEL) { return _this (self)->getInputBusses(); });
addMethod (@selector (outputBusses), [] (id self, SEL) { return _this (self)->getOutputBusses(); });
addMethod (@selector (channelCapabilities), [] (id self, SEL) { return _this (self)->getChannelCapabilities(); });
addMethod (@selector (shouldChangeToFormat:forBus:), [] (id self, SEL, AVAudioFormat* format, AUAudioUnitBus* bus) { return _this (self)->shouldChangeToFormat (format, bus) ? YES : NO; });
//==============================================================================
addMethod (@selector (virtualMIDICableCount), [] (id self, SEL) { return _this (self)->getVirtualMIDICableCount(); });
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
addMethod (@selector (supportsMPE), [] (id self, SEL) { return _this (self)->getSupportsMPE() ? YES : NO; });
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
if (@available (macOS 10.13, iOS 11.0, *))
addMethod (@selector (MIDIOutputNames), [] (id self, SEL) { return _this (self)->getMIDIOutputNames(); });
//==============================================================================
addMethod (@selector (internalRenderBlock), [] (id self, SEL) { return _this (self)->getInternalRenderBlock(); });
addMethod (@selector (canProcessInPlace), [] (id, SEL) { return NO; });
addMethod (@selector (isRenderingOffline), [] (id self, SEL) { return _this (self)->getRenderingOffline() ? YES : NO; });
addMethod (@selector (setRenderingOffline:), [] (id self, SEL, BOOL renderingOffline) { return _this (self)->setRenderingOffline (renderingOffline); });
addMethod (@selector (shouldBypassEffect), [] (id self, SEL) { return _this (self)->getShouldBypassEffect() ? YES : NO; });
addMethod (@selector (setShouldBypassEffect:), [] (id self, SEL, BOOL shouldBypass) { return _this (self)->setShouldBypassEffect (shouldBypass); });
addMethod (@selector (allocateRenderResourcesAndReturnError:), [] (id self, SEL, NSError** error) { return _this (self)->allocateRenderResourcesAndReturnError (error) ? YES : NO; });
addMethod (@selector (deallocateRenderResources), [] (id self, SEL) { return _this (self)->deallocateRenderResources(); });
//==============================================================================
addMethod (@selector (contextName), [] (id self, SEL) { return _this (self)->getContextName(); });
addMethod (@selector (setContextName:), [] (id self, SEL, NSString* str) { return _this (self)->setContextName (str); });
#if JUCE_AUDIOWORKGROUP_TYPES_AVAILABLE
addMethod (@selector (renderContextObserver), [] (id self, SEL) { return _this (self)->getInternalContextObserver(); });
#endif
//==============================================================================
if (@available (macOS 10.13, iOS 11.0, *))
{
addMethod (@selector (supportedViewConfigurations:), [] (id self, SEL, NSArray<AUAudioUnitViewConfiguration*>* configs)
{
auto supportedViewIndices = [[NSMutableIndexSet alloc] init];
auto n = [configs count];
if (auto* editor = _this (self)->getAudioProcessor().createEditorIfNeeded())
{
// If you hit this assertion then your plug-in's editor is reporting that it doesn't support
// any host MIDI controller configurations!
jassert (editor->supportsHostMIDIControllerPresence (true) || editor->supportsHostMIDIControllerPresence (false));
for (auto i = 0u; i < n; ++i)
{
if (auto viewConfiguration = [configs objectAtIndex: i])
{
if (editor->supportsHostMIDIControllerPresence ([viewConfiguration hostHasController] == YES))
{
auto* constrainer = editor->getConstrainer();
auto height = (int) [viewConfiguration height];
auto width = (int) [viewConfiguration width];
const auto maxLimits = std::numeric_limits<int>::max() / 2;
const Rectangle<int> requestedBounds { width, height };
auto modifiedBounds = requestedBounds;
constrainer->checkBounds (modifiedBounds, editor->getBounds().withZeroOrigin(), { maxLimits, maxLimits }, false, false, false, false);
if (modifiedBounds == requestedBounds)
[supportedViewIndices addIndex: i];
}
}
}
}
return [supportedViewIndices autorelease];
});
addMethod (@selector (selectViewConfiguration:), [] (id self, SEL, AUAudioUnitViewConfiguration* config)
{
_this (self)->processorHolder->viewConfiguration.reset (new AudioProcessorHolder::ViewConfig { [config width], [config height], [config hostHasController] == YES });
});
}
registerClass();
}
//==============================================================================
static JuceAudioUnitv3* _this (id self) { return getIvar<JuceAudioUnitv3*> (self, "cppObject"); }
static void setThis (id self, JuceAudioUnitv3* cpp) { object_setInstanceVariable (self, "cppObject", cpp); }
};
static JuceAudioUnitv3* create (AUAudioUnit* audioUnit, AudioComponentDescription descr, AudioComponentInstantiationOptions options, NSError** error)
{
return new JuceAudioUnitv3 (audioUnit, descr, options, error);
}
//==============================================================================
static Class& getClass()
{
static Class result;
return result;
}
//==============================================================================
struct BusBuffer
{
BusBuffer (AUAudioUnitBus* bus, int maxFramesPerBuffer)
: auBus (bus),
maxFrames (maxFramesPerBuffer),
numberOfChannels (static_cast<int> ([[auBus format] channelCount])),
isInterleaved ([[auBus format] isInterleaved])
{
alloc();
}
//==============================================================================
void alloc()
{
const int numBuffers = isInterleaved ? 1 : numberOfChannels;
int bytes = static_cast<int> (sizeof (AudioBufferList))
+ ((numBuffers - 1) * static_cast<int> (sizeof (::AudioBuffer)));
jassert (bytes > 0);
bufferListStorage.calloc (static_cast<size_t> (bytes));
bufferList = reinterpret_cast<AudioBufferList*> (bufferListStorage.getData());
const int bufferChannels = isInterleaved ? numberOfChannels : 1;
scratchBuffer.setSize (numBuffers, bufferChannels * maxFrames);
}
void dealloc()
{
bufferList = nullptr;
bufferListStorage.free();
scratchBuffer.setSize (0, 0);
}
//==============================================================================
int numChannels() const noexcept { return numberOfChannels; }
bool interleaved() const noexcept { return isInterleaved; }
AudioBufferList* get() const noexcept { return bufferList; }
//==============================================================================
void prepare (UInt32 nFrames, const AudioBufferList* other = nullptr) noexcept
{
const int numBuffers = isInterleaved ? 1 : numberOfChannels;
const bool isCompatible = isCompatibleWith (other);
bufferList->mNumberBuffers = static_cast<UInt32> (numBuffers);
for (int i = 0; i < numBuffers; ++i)
{
const UInt32 bufferChannels = static_cast<UInt32> (isInterleaved ? numberOfChannels : 1);
bufferList->mBuffers[i].mNumberChannels = bufferChannels;
bufferList->mBuffers[i].mData = (isCompatible ? other->mBuffers[i].mData
: scratchBuffer.getWritePointer (i));
bufferList->mBuffers[i].mDataByteSize = nFrames * bufferChannels * sizeof (float);
}
}
//==============================================================================
bool isCompatibleWith (const AudioBufferList* other) const noexcept
{
if (other == nullptr)
return false;
if (other->mNumberBuffers > 0)
{
const bool otherInterleaved = AudioUnitHelpers::isAudioBufferInterleaved (*other);
const int otherChannels = static_cast<int> (otherInterleaved ? other->mBuffers[0].mNumberChannels
: other->mNumberBuffers);