The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1135 lines
43KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. class iOSAudioIODevice;
  24. static const char* const iOSAudioDeviceName = "iOS Audio";
  25. //==============================================================================
  26. struct AudioSessionHolder
  27. {
  28. AudioSessionHolder();
  29. ~AudioSessionHolder();
  30. void handleStatusChange (bool enabled, const char* reason) const;
  31. void handleRouteChange (const char* reason) const;
  32. Array<iOSAudioIODevice*> activeDevices;
  33. id nativeSession;
  34. };
  35. static const char* getRoutingChangeReason (AVAudioSessionRouteChangeReason reason) noexcept
  36. {
  37. switch (reason)
  38. {
  39. case AVAudioSessionRouteChangeReasonNewDeviceAvailable: return "New device available";
  40. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: return "Old device unavailable";
  41. case AVAudioSessionRouteChangeReasonCategoryChange: return "Category change";
  42. case AVAudioSessionRouteChangeReasonOverride: return "Override";
  43. case AVAudioSessionRouteChangeReasonWakeFromSleep: return "Wake from sleep";
  44. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory: return "No suitable route for category";
  45. case AVAudioSessionRouteChangeReasonRouteConfigurationChange: return "Route configuration change";
  46. case AVAudioSessionRouteChangeReasonUnknown:
  47. default: return "Unknown";
  48. }
  49. }
  50. bool getNotificationValueForKey (NSNotification* notification, NSString* key, NSUInteger& value) noexcept
  51. {
  52. if (notification != nil)
  53. {
  54. if (NSDictionary* userInfo = [notification userInfo])
  55. {
  56. if (NSNumber* number = [userInfo objectForKey: key])
  57. {
  58. value = [number unsignedIntegerValue];
  59. return true;
  60. }
  61. }
  62. }
  63. jassertfalse;
  64. return false;
  65. }
  66. } // juce namespace
  67. //==============================================================================
  68. @interface iOSAudioSessionNative : NSObject
  69. {
  70. @private
  71. juce::AudioSessionHolder* audioSessionHolder;
  72. };
  73. - (id) init: (juce::AudioSessionHolder*) holder;
  74. - (void) dealloc;
  75. - (void) audioSessionChangedInterruptionType: (NSNotification*) notification;
  76. - (void) handleMediaServicesReset;
  77. - (void) handleMediaServicesLost;
  78. - (void) handleRouteChange: (NSNotification*) notification;
  79. @end
  80. @implementation iOSAudioSessionNative
  81. - (id) init: (juce::AudioSessionHolder*) holder
  82. {
  83. self = [super init];
  84. if (self != nil)
  85. {
  86. audioSessionHolder = holder;
  87. auto session = [AVAudioSession sharedInstance];
  88. auto centre = [NSNotificationCenter defaultCenter];
  89. [centre addObserver: self
  90. selector: @selector (audioSessionChangedInterruptionType:)
  91. name: AVAudioSessionInterruptionNotification
  92. object: session];
  93. [centre addObserver: self
  94. selector: @selector (handleMediaServicesLost)
  95. name: AVAudioSessionMediaServicesWereLostNotification
  96. object: session];
  97. [centre addObserver: self
  98. selector: @selector (handleMediaServicesReset)
  99. name: AVAudioSessionMediaServicesWereResetNotification
  100. object: session];
  101. [centre addObserver: self
  102. selector: @selector (handleRouteChange:)
  103. name: AVAudioSessionRouteChangeNotification
  104. object: session];
  105. }
  106. else
  107. {
  108. jassertfalse;
  109. }
  110. return self;
  111. }
  112. - (void) dealloc
  113. {
  114. [[NSNotificationCenter defaultCenter] removeObserver: self];
  115. [super dealloc];
  116. }
  117. - (void) audioSessionChangedInterruptionType: (NSNotification*) notification
  118. {
  119. NSUInteger value;
  120. if (juce::getNotificationValueForKey (notification, AVAudioSessionInterruptionTypeKey, value))
  121. {
  122. switch ((AVAudioSessionInterruptionType) value)
  123. {
  124. case AVAudioSessionInterruptionTypeBegan:
  125. audioSessionHolder->handleStatusChange (false, "AVAudioSessionInterruptionTypeBegan");
  126. break;
  127. case AVAudioSessionInterruptionTypeEnded:
  128. audioSessionHolder->handleStatusChange (true, "AVAudioSessionInterruptionTypeEnded");
  129. break;
  130. // No default so the code doesn't compile if this enum is extended.
  131. }
  132. }
  133. }
  134. - (void) handleMediaServicesReset
  135. {
  136. audioSessionHolder->handleStatusChange (true, "AVAudioSessionMediaServicesWereResetNotification");
  137. }
  138. - (void) handleMediaServicesLost
  139. {
  140. audioSessionHolder->handleStatusChange (false, "AVAudioSessionMediaServicesWereLostNotification");
  141. }
  142. - (void) handleRouteChange: (NSNotification*) notification
  143. {
  144. NSUInteger value;
  145. if (juce::getNotificationValueForKey (notification, AVAudioSessionRouteChangeReasonKey, value))
  146. audioSessionHolder->handleRouteChange (juce::getRoutingChangeReason ((AVAudioSessionRouteChangeReason) value));
  147. }
  148. @end
  149. //==============================================================================
  150. namespace juce {
  151. #ifndef JUCE_IOS_AUDIO_LOGGING
  152. #define JUCE_IOS_AUDIO_LOGGING 0
  153. #endif
  154. #if JUCE_IOS_AUDIO_LOGGING
  155. #define JUCE_IOS_AUDIO_LOG(x) DBG(x)
  156. #else
  157. #define JUCE_IOS_AUDIO_LOG(x)
  158. #endif
  159. static void logNSError (NSError* e)
  160. {
  161. if (e != nil)
  162. {
  163. JUCE_IOS_AUDIO_LOG ("iOS Audio error: " << [e.localizedDescription UTF8String]);
  164. jassertfalse;
  165. }
  166. }
  167. #define JUCE_NSERROR_CHECK(X) { NSError* error = nil; X; logNSError (error); }
  168. #if JUCE_MODULE_AVAILABLE_juce_graphics
  169. #include <juce_graphics/native/juce_mac_CoreGraphicsHelpers.h>
  170. #endif
  171. //==============================================================================
  172. class iOSAudioIODevice::Pimpl : public AudioPlayHead
  173. {
  174. public:
  175. Pimpl (iOSAudioIODevice& ioDevice)
  176. : owner (ioDevice)
  177. {
  178. sessionHolder->activeDevices.add (&owner);
  179. }
  180. ~Pimpl()
  181. {
  182. sessionHolder->activeDevices.removeFirstMatchingValue (&owner);
  183. owner.close();
  184. }
  185. static void setAudioSessionActive (bool enabled)
  186. {
  187. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setActive: enabled
  188. error: &error]);
  189. }
  190. static double trySampleRate (double rate)
  191. {
  192. auto session = [AVAudioSession sharedInstance];
  193. JUCE_NSERROR_CHECK ([session setPreferredSampleRate: rate
  194. error: &error]);
  195. return session.sampleRate;
  196. }
  197. Array<double> getAvailableSampleRates()
  198. {
  199. Array<double> rates;
  200. // Important: the supported audio sample rates change on the iPhone 6S
  201. // depending on whether the headphones are plugged in or not!
  202. setAudioSessionActive (true);
  203. AudioUnitRemovePropertyListenerWithUserData (audioUnit,
  204. kAudioUnitProperty_StreamFormat,
  205. handleStreamFormatChangeCallback,
  206. this);
  207. const double lowestRate = trySampleRate (4000);
  208. const double highestRate = trySampleRate (192000);
  209. for (double rate = lowestRate; rate <= highestRate; rate += 1000)
  210. {
  211. const double supportedRate = trySampleRate (rate);
  212. rates.addIfNotAlreadyThere (supportedRate);
  213. rate = jmax (rate, supportedRate);
  214. }
  215. trySampleRate (owner.getCurrentSampleRate());
  216. AudioUnitAddPropertyListener (audioUnit,
  217. kAudioUnitProperty_StreamFormat,
  218. handleStreamFormatChangeCallback,
  219. this);
  220. for (auto r : rates)
  221. {
  222. ignoreUnused (r);
  223. JUCE_IOS_AUDIO_LOG ("available rate = " + String (r, 0) + "Hz");
  224. }
  225. return rates;
  226. }
  227. Array<int> getAvailableBufferSizes()
  228. {
  229. Array<int> r;
  230. for (int i = 6; i < 13; ++i)
  231. r.add (1 << i);
  232. return r;
  233. }
  234. String open (const BigInteger& inputChannelsWanted,
  235. const BigInteger& outputChannelsWanted,
  236. double targetSampleRate, int bufferSize)
  237. {
  238. close();
  239. owner.lastError.clear();
  240. owner.preferredBufferSize = bufferSize <= 0 ? owner.getDefaultBufferSize() : bufferSize;
  241. // xxx set up channel mapping
  242. owner.activeOutputChans = outputChannelsWanted;
  243. owner.activeOutputChans.setRange (2, owner.activeOutputChans.getHighestBit(), false);
  244. owner.numOutputChannels = owner.activeOutputChans.countNumberOfSetBits();
  245. monoOutputChannelNumber = owner.activeOutputChans.findNextSetBit (0);
  246. owner.activeInputChans = inputChannelsWanted;
  247. owner.activeInputChans.setRange (2, owner.activeInputChans.getHighestBit(), false);
  248. owner.numInputChannels = owner.activeInputChans.countNumberOfSetBits();
  249. monoInputChannelNumber = owner.activeInputChans.findNextSetBit (0);
  250. setAudioSessionActive (true);
  251. // Set the session category & options:
  252. auto session = [AVAudioSession sharedInstance];
  253. const bool useInputs = (owner.numInputChannels > 0 && owner.audioInputIsAvailable);
  254. NSString* category = (useInputs ? AVAudioSessionCategoryPlayAndRecord : AVAudioSessionCategoryPlayback);
  255. NSUInteger options = AVAudioSessionCategoryOptionMixWithOthers; // Alternatively AVAudioSessionCategoryOptionDuckOthers
  256. if (useInputs) // These options are only valid for category = PlayAndRecord
  257. options |= (AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetooth);
  258. JUCE_NSERROR_CHECK ([session setCategory: category
  259. withOptions: options
  260. error: &error]);
  261. fixAudioRouteIfSetToReceiver();
  262. // Set the sample rate
  263. trySampleRate (targetSampleRate);
  264. owner.updateSampleRateAndAudioInput();
  265. updateCurrentBufferSize();
  266. prepareFloatBuffers (owner.actualBufferSize);
  267. owner.isRunning = true;
  268. handleRouteChange ("Started AudioUnit");
  269. owner.lastError = (audioUnit != 0 ? "" : "Couldn't open the device");
  270. setAudioSessionActive (true);
  271. return owner.lastError;
  272. }
  273. void close()
  274. {
  275. if (owner.isRunning)
  276. {
  277. owner.isRunning = false;
  278. if (audioUnit != 0)
  279. {
  280. AudioOutputUnitStart (audioUnit);
  281. AudioComponentInstanceDispose (audioUnit);
  282. audioUnit = 0;
  283. }
  284. setAudioSessionActive (false);
  285. }
  286. }
  287. void start (AudioIODeviceCallback* newCallback)
  288. {
  289. if (owner.isRunning && owner.callback != newCallback)
  290. {
  291. if (newCallback != nullptr)
  292. newCallback->audioDeviceAboutToStart (&owner);
  293. const ScopedLock sl (callbackLock);
  294. owner.callback = newCallback;
  295. }
  296. }
  297. void stop()
  298. {
  299. if (owner.isRunning)
  300. {
  301. AudioIODeviceCallback* lastCallback;
  302. {
  303. const ScopedLock sl (callbackLock);
  304. lastCallback = owner.callback;
  305. owner.callback = nullptr;
  306. }
  307. if (lastCallback != nullptr)
  308. lastCallback->audioDeviceStopped();
  309. }
  310. }
  311. bool setAudioPreprocessingEnabled (bool enable)
  312. {
  313. auto session = [AVAudioSession sharedInstance];
  314. NSString* mode = (enable ? AVAudioSessionModeMeasurement
  315. : AVAudioSessionModeDefault);
  316. JUCE_NSERROR_CHECK ([session setMode: mode
  317. error: &error]);
  318. return session.mode == mode;
  319. }
  320. //==============================================================================
  321. bool canControlTransport() override { return owner.interAppAudioConnected; }
  322. void transportPlay (bool shouldSartPlaying) override
  323. {
  324. if (! canControlTransport())
  325. return;
  326. HostCallbackInfo callbackInfo;
  327. fillHostCallbackInfo (callbackInfo);
  328. Boolean hostIsPlaying = NO;
  329. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  330. &hostIsPlaying,
  331. NULL,
  332. NULL,
  333. NULL,
  334. NULL,
  335. NULL,
  336. NULL);
  337. jassert (err == noErr);
  338. if (hostIsPlaying != shouldSartPlaying)
  339. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_TogglePlayPause);
  340. }
  341. void transportRecord (bool shouldStartRecording) override
  342. {
  343. if (! canControlTransport())
  344. return;
  345. HostCallbackInfo callbackInfo;
  346. fillHostCallbackInfo (callbackInfo);
  347. Boolean hostIsRecording = NO;
  348. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  349. NULL,
  350. &hostIsRecording,
  351. NULL,
  352. NULL,
  353. NULL,
  354. NULL,
  355. NULL);
  356. jassert (err == noErr);
  357. if (hostIsRecording != shouldStartRecording)
  358. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_ToggleRecord);
  359. }
  360. void transportRewind() override
  361. {
  362. if (canControlTransport())
  363. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_Rewind);
  364. }
  365. bool getCurrentPosition (CurrentPositionInfo& result) override
  366. {
  367. if (! canControlTransport())
  368. return false;
  369. zerostruct (result);
  370. HostCallbackInfo callbackInfo;
  371. fillHostCallbackInfo (callbackInfo);
  372. if (callbackInfo.hostUserData == nullptr)
  373. return false;
  374. Boolean hostIsPlaying = NO;
  375. Boolean hostIsRecording = NO;
  376. Float64 hostCurrentSampleInTimeLine = 0;
  377. Boolean hostIsCycling = NO;
  378. Float64 hostCycleStartBeat = 0;
  379. Float64 hostCycleEndBeat = 0;
  380. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  381. &hostIsPlaying,
  382. &hostIsRecording,
  383. NULL,
  384. &hostCurrentSampleInTimeLine,
  385. &hostIsCycling,
  386. &hostCycleStartBeat,
  387. &hostCycleEndBeat);
  388. if (err == kAUGraphErr_CannotDoInCurrentContext)
  389. return false;
  390. jassert (err == noErr);
  391. result.timeInSamples = (int64) hostCurrentSampleInTimeLine;
  392. result.isPlaying = hostIsPlaying;
  393. result.isRecording = hostIsRecording;
  394. result.isLooping = hostIsCycling;
  395. result.ppqLoopStart = hostCycleStartBeat;
  396. result.ppqLoopEnd = hostCycleEndBeat;
  397. result.timeInSeconds = result.timeInSamples / owner.sampleRate;
  398. Float64 hostBeat = 0;
  399. Float64 hostTempo = 0;
  400. err = callbackInfo.beatAndTempoProc (callbackInfo.hostUserData,
  401. &hostBeat,
  402. &hostTempo);
  403. jassert (err == noErr);
  404. result.ppqPosition = hostBeat;
  405. result.bpm = hostTempo;
  406. Float32 hostTimeSigNumerator = 0;
  407. UInt32 hostTimeSigDenominator = 0;
  408. Float64 hostCurrentMeasureDownBeat = 0;
  409. err = callbackInfo.musicalTimeLocationProc (callbackInfo.hostUserData,
  410. NULL,
  411. &hostTimeSigNumerator,
  412. &hostTimeSigDenominator,
  413. &hostCurrentMeasureDownBeat);
  414. jassert (err == noErr);
  415. result.ppqPositionOfLastBarStart = hostCurrentMeasureDownBeat;
  416. result.timeSigNumerator = (int) hostTimeSigNumerator;
  417. result.timeSigDenominator = (int) hostTimeSigDenominator;
  418. result.frameRate = AudioPlayHead::fpsUnknown;
  419. return true;
  420. }
  421. //==============================================================================
  422. #if JUCE_MODULE_AVAILABLE_juce_gui_basics
  423. Image getIcon (int size)
  424. {
  425. if (owner.interAppAudioConnected)
  426. {
  427. UIImage* hostUIImage = AudioOutputUnitGetHostIcon (audioUnit, size);
  428. if (hostUIImage != nullptr)
  429. return juce_createImageFromUIImage (hostUIImage);
  430. }
  431. return Image();
  432. }
  433. #endif
  434. void switchApplication()
  435. {
  436. if (! owner.interAppAudioConnected)
  437. return;
  438. CFURLRef hostUrl;
  439. UInt32 dataSize = sizeof (hostUrl);
  440. OSStatus err = AudioUnitGetProperty(audioUnit,
  441. kAudioUnitProperty_PeerURL,
  442. kAudioUnitScope_Global,
  443. 0,
  444. &hostUrl,
  445. &dataSize);
  446. if (err == noErr)
  447. [[UIApplication sharedApplication] openURL:(NSURL*)hostUrl];
  448. }
  449. //==============================================================================
  450. void invokeAudioDeviceErrorCallback (const String& reason)
  451. {
  452. const ScopedLock sl (callbackLock);
  453. if (owner.callback != nullptr)
  454. owner.callback->audioDeviceError (reason);
  455. }
  456. void handleStatusChange (bool enabled, const char* reason)
  457. {
  458. const ScopedLock myScopedLock (callbackLock);
  459. JUCE_IOS_AUDIO_LOG ("handleStatusChange: enabled: " << (int) enabled << ", reason: " << reason);
  460. owner.isRunning = enabled;
  461. setAudioSessionActive (enabled);
  462. if (enabled)
  463. AudioOutputUnitStart (audioUnit);
  464. else
  465. AudioOutputUnitStop (audioUnit);
  466. if (! enabled)
  467. invokeAudioDeviceErrorCallback (reason);
  468. }
  469. void handleRouteChange (const char* reason)
  470. {
  471. const ScopedLock myScopedLock (callbackLock);
  472. JUCE_IOS_AUDIO_LOG ("handleRouteChange: reason: " << reason);
  473. fixAudioRouteIfSetToReceiver();
  474. if (owner.isRunning)
  475. {
  476. invokeAudioDeviceErrorCallback (reason);
  477. owner.updateSampleRateAndAudioInput();
  478. updateCurrentBufferSize();
  479. createAudioUnit();
  480. setAudioSessionActive (true);
  481. if (audioUnit != 0)
  482. {
  483. UInt32 formatSize = sizeof (format);
  484. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  485. AudioOutputUnitStart (audioUnit);
  486. }
  487. if (owner.callback != nullptr)
  488. {
  489. owner.callback->audioDeviceStopped();
  490. owner.callback->audioDeviceAboutToStart (&owner);
  491. }
  492. }
  493. }
  494. void handleAudioUnitPropertyChange (AudioUnit,
  495. AudioUnitPropertyID propertyID,
  496. AudioUnitScope,
  497. AudioUnitElement)
  498. {
  499. const ScopedLock myScopedLock (callbackLock);
  500. switch (propertyID)
  501. {
  502. case kAudioUnitProperty_IsInterAppConnected: return handleInterAppAudioConnectionChange();
  503. default: return;
  504. }
  505. }
  506. void handleInterAppAudioConnectionChange()
  507. {
  508. UInt32 connected;
  509. UInt32 dataSize = sizeof (connected);
  510. OSStatus err = AudioUnitGetProperty (audioUnit, kAudioUnitProperty_IsInterAppConnected,
  511. kAudioUnitScope_Global, 0, &connected, &dataSize);
  512. jassert (err == noErr);
  513. JUCE_IOS_AUDIO_LOG ("handleInterAppAudioConnectionChange: " << connected ? "connected"
  514. : "disconnected");
  515. if (connected != owner.interAppAudioConnected)
  516. {
  517. const ScopedLock myScopedLock (callbackLock);
  518. owner.interAppAudioConnected = connected;
  519. UIApplicationState appstate = [UIApplication sharedApplication].applicationState;
  520. bool inForeground = (appstate != UIApplicationStateBackground);
  521. if (owner.interAppAudioConnected || inForeground)
  522. {
  523. setAudioSessionActive (true);
  524. AudioOutputUnitStart (audioUnit);
  525. if (owner.callback != nullptr)
  526. owner.callback->audioDeviceAboutToStart (&owner);
  527. }
  528. else if (! inForeground)
  529. {
  530. AudioOutputUnitStop (audioUnit);
  531. setAudioSessionActive (false);
  532. }
  533. }
  534. }
  535. private:
  536. //==============================================================================
  537. iOSAudioIODevice& owner;
  538. SharedResourcePointer<AudioSessionHolder> sessionHolder;
  539. CriticalSection callbackLock;
  540. AudioStreamBasicDescription format;
  541. AudioUnit audioUnit {};
  542. AudioSampleBuffer floatData;
  543. float* inputChannels[3];
  544. float* outputChannels[3];
  545. bool monoInputChannelNumber, monoOutputChannelNumber;
  546. void prepareFloatBuffers (int bufferSize)
  547. {
  548. if (owner.numInputChannels + owner.numOutputChannels > 0)
  549. {
  550. floatData.setSize (owner.numInputChannels + owner.numOutputChannels, bufferSize);
  551. zeromem (inputChannels, sizeof (inputChannels));
  552. zeromem (outputChannels, sizeof (outputChannels));
  553. for (int i = 0; i < owner.numInputChannels; ++i)
  554. inputChannels[i] = floatData.getWritePointer (i);
  555. for (int i = 0; i < owner.numOutputChannels; ++i)
  556. outputChannels[i] = floatData.getWritePointer (i + owner.numInputChannels);
  557. }
  558. }
  559. //==============================================================================
  560. OSStatus process (AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  561. const UInt32 numFrames, AudioBufferList* data)
  562. {
  563. OSStatus err = noErr;
  564. if (owner.audioInputIsAvailable && owner.numInputChannels > 0)
  565. err = AudioUnitRender (audioUnit, flags, time, 1, numFrames, data);
  566. const ScopedTryLock stl (callbackLock);
  567. if (stl.isLocked() && owner.callback != nullptr)
  568. {
  569. if ((int) numFrames > floatData.getNumSamples())
  570. prepareFloatBuffers ((int) numFrames);
  571. if (owner.audioInputIsAvailable && owner.numInputChannels > 0)
  572. {
  573. short* shortData = (short*) data->mBuffers[0].mData;
  574. if (owner.numInputChannels >= 2)
  575. {
  576. for (UInt32 i = 0; i < numFrames; ++i)
  577. {
  578. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  579. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  580. }
  581. }
  582. else
  583. {
  584. if (monoInputChannelNumber > 0)
  585. ++shortData;
  586. for (UInt32 i = 0; i < numFrames; ++i)
  587. {
  588. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  589. ++shortData;
  590. }
  591. }
  592. }
  593. else
  594. {
  595. for (int i = owner.numInputChannels; --i >= 0;)
  596. zeromem (inputChannels[i], sizeof (float) * numFrames);
  597. }
  598. owner.callback->audioDeviceIOCallback ((const float**) inputChannels, owner.numInputChannels,
  599. outputChannels, owner.numOutputChannels, (int) numFrames);
  600. short* const shortData = (short*) data->mBuffers[0].mData;
  601. int n = 0;
  602. if (owner.numOutputChannels >= 2)
  603. {
  604. for (UInt32 i = 0; i < numFrames; ++i)
  605. {
  606. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  607. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  608. }
  609. }
  610. else if (owner.numOutputChannels == 1)
  611. {
  612. for (UInt32 i = 0; i < numFrames; ++i)
  613. {
  614. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  615. shortData [n++] = s;
  616. shortData [n++] = s;
  617. }
  618. }
  619. else
  620. {
  621. zeromem (data->mBuffers[0].mData, 2 * sizeof (short) * numFrames);
  622. }
  623. }
  624. else
  625. {
  626. zeromem (data->mBuffers[0].mData, 2 * sizeof (short) * numFrames);
  627. }
  628. return err;
  629. }
  630. void updateCurrentBufferSize()
  631. {
  632. NSTimeInterval bufferDuration = owner.sampleRate > 0 ? (NSTimeInterval) ((owner.preferredBufferSize + 1) / owner.sampleRate) : 0.0;
  633. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setPreferredIOBufferDuration: bufferDuration
  634. error: &error]);
  635. owner.updateSampleRateAndAudioInput();
  636. }
  637. //==============================================================================
  638. static OSStatus processStatic (void* client, AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  639. UInt32 /*busNumber*/, UInt32 numFrames, AudioBufferList* data)
  640. {
  641. return static_cast<Pimpl*> (client)->process (flags, time, numFrames, data);
  642. }
  643. //==============================================================================
  644. void resetFormat (const int numChannels) noexcept
  645. {
  646. zerostruct (format);
  647. format.mFormatID = kAudioFormatLinearPCM;
  648. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kAudioFormatFlagsNativeEndian;
  649. format.mBitsPerChannel = 8 * sizeof (short);
  650. format.mChannelsPerFrame = (UInt32) numChannels;
  651. format.mFramesPerPacket = 1;
  652. format.mBytesPerFrame = format.mBytesPerPacket = (UInt32) numChannels * sizeof (short);
  653. }
  654. bool createAudioUnit()
  655. {
  656. if (audioUnit != 0)
  657. {
  658. AudioComponentInstanceDispose (audioUnit);
  659. audioUnit = 0;
  660. }
  661. resetFormat (2);
  662. AudioComponentDescription desc;
  663. desc.componentType = kAudioUnitType_Output;
  664. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  665. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  666. desc.componentFlags = 0;
  667. desc.componentFlagsMask = 0;
  668. AudioComponent comp = AudioComponentFindNext (0, &desc);
  669. AudioComponentInstanceNew (comp, &audioUnit);
  670. if (audioUnit == 0)
  671. return false;
  672. #if JucePlugin_Enable_IAA
  673. AudioComponentDescription appDesc;
  674. appDesc.componentType = JucePlugin_IAAType;
  675. appDesc.componentSubType = JucePlugin_IAASubType;
  676. appDesc.componentManufacturer = JucePlugin_ManufacturerCode;
  677. appDesc.componentFlags = 0;
  678. appDesc.componentFlagsMask = 0;
  679. OSStatus err = AudioOutputUnitPublish (&appDesc,
  680. CFSTR(JucePlugin_IAAName),
  681. JucePlugin_VersionCode,
  682. audioUnit);
  683. // This assert will be hit if the Inter-App Audio entitlement has not
  684. // been enabled, or the description being published with
  685. // AudioOutputUnitPublish is different from any in the AudioComponents
  686. // array in this application's .plist file.
  687. jassert (err == noErr);
  688. err = AudioUnitAddPropertyListener(audioUnit,
  689. kAudioUnitProperty_IsInterAppConnected,
  690. audioUnitPropertyChangeDispatcher,
  691. this);
  692. jassert (err == noErr);
  693. #endif
  694. if (owner.numInputChannels > 0)
  695. {
  696. const UInt32 one = 1;
  697. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  698. }
  699. {
  700. AudioChannelLayout layout;
  701. layout.mChannelBitmap = 0;
  702. layout.mNumberChannelDescriptions = 0;
  703. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  704. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  705. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  706. }
  707. {
  708. AURenderCallbackStruct inputProc;
  709. inputProc.inputProc = processStatic;
  710. inputProc.inputProcRefCon = this;
  711. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  712. }
  713. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  714. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  715. UInt32 framesPerSlice;
  716. UInt32 dataSize = sizeof (framesPerSlice);
  717. AudioUnitInitialize (audioUnit);
  718. updateCurrentBufferSize();
  719. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_MaximumFramesPerSlice,
  720. kAudioUnitScope_Global, 0, &framesPerSlice, &dataSize) == noErr
  721. && dataSize == sizeof (framesPerSlice) && static_cast<int> (framesPerSlice) != owner.actualBufferSize)
  722. {
  723. prepareFloatBuffers (static_cast<int> (framesPerSlice));
  724. }
  725. AudioUnitAddPropertyListener (audioUnit, kAudioUnitProperty_StreamFormat, handleStreamFormatChangeCallback, this);
  726. return true;
  727. }
  728. void fillHostCallbackInfo (HostCallbackInfo& callbackInfo)
  729. {
  730. zerostruct (callbackInfo);
  731. UInt32 dataSize = sizeof (HostCallbackInfo);
  732. OSStatus err = AudioUnitGetProperty (audioUnit,
  733. kAudioUnitProperty_HostCallbacks,
  734. kAudioUnitScope_Global,
  735. 0,
  736. &callbackInfo,
  737. &dataSize);
  738. jassert (err == noErr);
  739. }
  740. void handleAudioTransportEvent (AudioUnitRemoteControlEvent event)
  741. {
  742. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_RemoteControlToHost,
  743. kAudioUnitScope_Global, 0, &event, sizeof (event));
  744. jassert (err == noErr);
  745. }
  746. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  747. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  748. static void fixAudioRouteIfSetToReceiver()
  749. {
  750. auto session = [AVAudioSession sharedInstance];
  751. auto route = session.currentRoute;
  752. for (AVAudioSessionPortDescription* port in route.inputs)
  753. {
  754. ignoreUnused (port);
  755. JUCE_IOS_AUDIO_LOG ("AVAudioSession: input: " << [port.description UTF8String]);
  756. }
  757. for (AVAudioSessionPortDescription* port in route.outputs)
  758. {
  759. JUCE_IOS_AUDIO_LOG ("AVAudioSession: output: " << [port.description UTF8String]);
  760. if ([port.portName isEqualToString: @"Receiver"])
  761. {
  762. JUCE_NSERROR_CHECK ([session overrideOutputAudioPort: AVAudioSessionPortOverrideSpeaker
  763. error: &error]);
  764. setAudioSessionActive (true);
  765. }
  766. }
  767. }
  768. void handleStreamFormatChange()
  769. {
  770. AudioStreamBasicDescription desc;
  771. zerostruct (desc);
  772. UInt32 dataSize = sizeof (desc);
  773. AudioUnitGetProperty(audioUnit,
  774. kAudioUnitProperty_StreamFormat,
  775. kAudioUnitScope_Output,
  776. 0,
  777. &desc,
  778. &dataSize);
  779. if (desc.mSampleRate != owner.getCurrentSampleRate())
  780. {
  781. owner.updateSampleRateAndAudioInput();
  782. const ScopedLock sl (callbackLock);
  783. if (owner.callback != nullptr)
  784. {
  785. owner.callback->audioDeviceStopped();
  786. owner.callback->audioDeviceAboutToStart (&owner);
  787. }
  788. }
  789. }
  790. static void handleStreamFormatChangeCallback (void* device,
  791. AudioUnit,
  792. AudioUnitPropertyID,
  793. AudioUnitScope scope,
  794. AudioUnitElement element)
  795. {
  796. if (scope == kAudioUnitScope_Output && element == 0)
  797. static_cast<Pimpl*> (device)->handleStreamFormatChange();
  798. }
  799. static void audioUnitPropertyChangeDispatcher (void* data, AudioUnit unit, AudioUnitPropertyID propertyID,
  800. AudioUnitScope scope, AudioUnitElement element)
  801. {
  802. Pimpl* device = (Pimpl*)data;
  803. device->handleAudioUnitPropertyChange (unit, propertyID, scope, element);
  804. }
  805. void handleMidiMessage (MidiMessage msg)
  806. {
  807. if (owner.messageCollector != nullptr)
  808. owner.messageCollector->addMessageToQueue (msg);
  809. }
  810. static void midiEventCallback (void *client, UInt32 status, UInt32 data1, UInt32 data2, UInt32)
  811. {
  812. return static_cast<Pimpl*> (client)->handleMidiMessage (MidiMessage ((int) status,
  813. (int) data1,
  814. (int) data2,
  815. Time::getMillisecondCounter() / 1000.0));
  816. }
  817. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  818. };
  819. //==============================================================================
  820. iOSAudioIODevice::iOSAudioIODevice (const String& deviceName)
  821. : AudioIODevice (deviceName, iOSAudioDeviceName),
  822. #if TARGET_IPHONE_SIMULATOR
  823. defaultBufferSize (512),
  824. #else
  825. defaultBufferSize (256),
  826. #endif
  827. sampleRate (0), numInputChannels (2), numOutputChannels (2),
  828. preferredBufferSize (0), actualBufferSize (0), isRunning (false),
  829. audioInputIsAvailable (false), interAppAudioConnected (false),
  830. callback (nullptr), messageCollector (nullptr),
  831. pimpl (new Pimpl (*this))
  832. {
  833. updateSampleRateAndAudioInput();
  834. }
  835. //==============================================================================
  836. int iOSAudioIODevice::getOutputLatencyInSamples() { return roundToInt (sampleRate * [AVAudioSession sharedInstance].outputLatency); }
  837. int iOSAudioIODevice::getInputLatencyInSamples() { return roundToInt (sampleRate * [AVAudioSession sharedInstance].inputLatency); }
  838. //==============================================================================
  839. AudioPlayHead* iOSAudioIODevice::getAudioPlayHead() const { return pimpl; }
  840. void iOSAudioIODevice::close() { pimpl->close(); }
  841. void iOSAudioIODevice::start (AudioIODeviceCallback* callbackToUse) { pimpl->start (callbackToUse); }
  842. void iOSAudioIODevice::stop() { pimpl->stop(); }
  843. Array<double> iOSAudioIODevice::getAvailableSampleRates() { return pimpl->getAvailableSampleRates(); }
  844. Array<int> iOSAudioIODevice::getAvailableBufferSizes() { return pimpl->getAvailableBufferSizes(); }
  845. bool iOSAudioIODevice::setAudioPreprocessingEnabled (bool enabled) { return pimpl->setAudioPreprocessingEnabled (enabled); }
  846. void iOSAudioIODevice::switchApplication() { return pimpl->switchApplication(); }
  847. //==============================================================================
  848. void iOSAudioIODevice::handleStatusChange (bool enabled, const char* reason) { pimpl->handleStatusChange (enabled, reason); }
  849. void iOSAudioIODevice::handleRouteChange (const char* reason) { pimpl->handleRouteChange (reason); }
  850. #if JUCE_MODULE_AVAILABLE_juce_gui_basics
  851. Image iOSAudioIODevice::getIcon (int size) { return pimpl->getIcon (size); }
  852. #endif
  853. //==============================================================================
  854. String iOSAudioIODevice::open (const BigInteger& inChans, const BigInteger& outChans, double requestedSampleRate, int requestedBufferSize)
  855. {
  856. return pimpl->open (inChans, outChans, requestedSampleRate, requestedBufferSize);
  857. }
  858. void iOSAudioIODevice::updateSampleRateAndAudioInput()
  859. {
  860. auto session = [AVAudioSession sharedInstance];
  861. sampleRate = session.sampleRate;
  862. audioInputIsAvailable = session.isInputAvailable;
  863. actualBufferSize = roundToInt (sampleRate * session.IOBufferDuration);
  864. JUCE_IOS_AUDIO_LOG ("AVAudioSession: sampleRate: " << sampleRate
  865. << " Hz, audioInputAvailable: " << (int) audioInputIsAvailable
  866. << ", buffer size: " << actualBufferSize);
  867. }
  868. //==============================================================================
  869. class iOSAudioIODeviceType : public AudioIODeviceType
  870. {
  871. public:
  872. iOSAudioIODeviceType() : AudioIODeviceType (iOSAudioDeviceName) {}
  873. void scanForDevices() {}
  874. StringArray getDeviceNames (bool /*wantInputNames*/) const { return StringArray (iOSAudioDeviceName); }
  875. int getDefaultDeviceIndex (bool /*forInput*/) const { return 0; }
  876. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const { return d != nullptr ? 0 : -1; }
  877. bool hasSeparateInputsAndOutputs() const { return false; }
  878. AudioIODevice* createDevice (const String& outputDeviceName, const String& inputDeviceName)
  879. {
  880. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  881. return new iOSAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName : inputDeviceName);
  882. return nullptr;
  883. }
  884. private:
  885. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSAudioIODeviceType)
  886. };
  887. //==============================================================================
  888. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()
  889. {
  890. return new iOSAudioIODeviceType();
  891. }
  892. //==============================================================================
  893. AudioSessionHolder::AudioSessionHolder() { nativeSession = [[iOSAudioSessionNative alloc] init: this]; }
  894. AudioSessionHolder::~AudioSessionHolder() { [nativeSession release]; }
  895. void AudioSessionHolder::handleStatusChange (bool enabled, const char* reason) const
  896. {
  897. for (auto device: activeDevices)
  898. device->handleStatusChange (enabled, reason);
  899. }
  900. void AudioSessionHolder::handleRouteChange (const char* reason) const
  901. {
  902. struct RouteChangeMessage : public CallbackMessage
  903. {
  904. RouteChangeMessage (Array<iOSAudioIODevice*> devs, const char* r)
  905. : devices (devs), changeReason (r)
  906. {
  907. }
  908. void messageCallback() override
  909. {
  910. for (auto device: devices)
  911. device->handleRouteChange (changeReason);
  912. }
  913. Array<iOSAudioIODevice*> devices;
  914. const char* changeReason;
  915. };
  916. (new RouteChangeMessage (activeDevices, reason))->post();
  917. }
  918. #undef JUCE_NSERROR_CHECK