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.

1149 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. nullptr,
  332. nullptr,
  333. nullptr,
  334. nullptr,
  335. nullptr,
  336. nullptr);
  337. ignoreUnused (err);
  338. jassert (err == noErr);
  339. if (hostIsPlaying != shouldSartPlaying)
  340. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_TogglePlayPause);
  341. }
  342. void transportRecord (bool shouldStartRecording) override
  343. {
  344. if (! canControlTransport())
  345. return;
  346. HostCallbackInfo callbackInfo;
  347. fillHostCallbackInfo (callbackInfo);
  348. Boolean hostIsRecording = NO;
  349. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  350. nullptr,
  351. &hostIsRecording,
  352. nullptr,
  353. nullptr,
  354. nullptr,
  355. nullptr,
  356. nullptr);
  357. ignoreUnused (err);
  358. jassert (err == noErr);
  359. if (hostIsRecording != shouldStartRecording)
  360. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_ToggleRecord);
  361. }
  362. void transportRewind() override
  363. {
  364. if (canControlTransport())
  365. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_Rewind);
  366. }
  367. bool getCurrentPosition (CurrentPositionInfo& result) override
  368. {
  369. if (! canControlTransport())
  370. return false;
  371. zerostruct (result);
  372. HostCallbackInfo callbackInfo;
  373. fillHostCallbackInfo (callbackInfo);
  374. if (callbackInfo.hostUserData == nullptr)
  375. return false;
  376. Boolean hostIsPlaying = NO;
  377. Boolean hostIsRecording = NO;
  378. Float64 hostCurrentSampleInTimeLine = 0;
  379. Boolean hostIsCycling = NO;
  380. Float64 hostCycleStartBeat = 0;
  381. Float64 hostCycleEndBeat = 0;
  382. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  383. &hostIsPlaying,
  384. &hostIsRecording,
  385. nullptr,
  386. &hostCurrentSampleInTimeLine,
  387. &hostIsCycling,
  388. &hostCycleStartBeat,
  389. &hostCycleEndBeat);
  390. if (err == kAUGraphErr_CannotDoInCurrentContext)
  391. return false;
  392. jassert (err == noErr);
  393. result.timeInSamples = (int64) hostCurrentSampleInTimeLine;
  394. result.isPlaying = hostIsPlaying;
  395. result.isRecording = hostIsRecording;
  396. result.isLooping = hostIsCycling;
  397. result.ppqLoopStart = hostCycleStartBeat;
  398. result.ppqLoopEnd = hostCycleEndBeat;
  399. result.timeInSeconds = result.timeInSamples / owner.sampleRate;
  400. Float64 hostBeat = 0;
  401. Float64 hostTempo = 0;
  402. err = callbackInfo.beatAndTempoProc (callbackInfo.hostUserData,
  403. &hostBeat,
  404. &hostTempo);
  405. jassert (err == noErr);
  406. result.ppqPosition = hostBeat;
  407. result.bpm = hostTempo;
  408. Float32 hostTimeSigNumerator = 0;
  409. UInt32 hostTimeSigDenominator = 0;
  410. Float64 hostCurrentMeasureDownBeat = 0;
  411. err = callbackInfo.musicalTimeLocationProc (callbackInfo.hostUserData,
  412. nullptr,
  413. &hostTimeSigNumerator,
  414. &hostTimeSigDenominator,
  415. &hostCurrentMeasureDownBeat);
  416. jassert (err == noErr);
  417. result.ppqPositionOfLastBarStart = hostCurrentMeasureDownBeat;
  418. result.timeSigNumerator = (int) hostTimeSigNumerator;
  419. result.timeSigDenominator = (int) hostTimeSigDenominator;
  420. result.frameRate = AudioPlayHead::fpsUnknown;
  421. return true;
  422. }
  423. //==============================================================================
  424. #if JUCE_MODULE_AVAILABLE_juce_graphics
  425. Image getIcon (int size)
  426. {
  427. if (owner.interAppAudioConnected)
  428. {
  429. UIImage* hostUIImage = AudioOutputUnitGetHostIcon (audioUnit, size);
  430. if (hostUIImage != nullptr)
  431. return juce_createImageFromUIImage (hostUIImage);
  432. }
  433. return Image();
  434. }
  435. #endif
  436. void switchApplication()
  437. {
  438. if (! owner.interAppAudioConnected)
  439. return;
  440. CFURLRef hostUrl;
  441. UInt32 dataSize = sizeof (hostUrl);
  442. OSStatus err = AudioUnitGetProperty(audioUnit,
  443. kAudioUnitProperty_PeerURL,
  444. kAudioUnitScope_Global,
  445. 0,
  446. &hostUrl,
  447. &dataSize);
  448. if (err == noErr)
  449. [[UIApplication sharedApplication] openURL:(NSURL*)hostUrl];
  450. }
  451. //==============================================================================
  452. void invokeAudioDeviceErrorCallback (const String& reason)
  453. {
  454. const ScopedLock sl (callbackLock);
  455. if (owner.callback != nullptr)
  456. owner.callback->audioDeviceError (reason);
  457. }
  458. void handleStatusChange (bool enabled, const char* reason)
  459. {
  460. const ScopedLock myScopedLock (callbackLock);
  461. JUCE_IOS_AUDIO_LOG ("handleStatusChange: enabled: " << (int) enabled << ", reason: " << reason);
  462. owner.isRunning = enabled;
  463. setAudioSessionActive (enabled);
  464. if (enabled)
  465. AudioOutputUnitStart (audioUnit);
  466. else
  467. AudioOutputUnitStop (audioUnit);
  468. if (! enabled)
  469. invokeAudioDeviceErrorCallback (reason);
  470. }
  471. void handleRouteChange (const char* reason)
  472. {
  473. const ScopedLock myScopedLock (callbackLock);
  474. JUCE_IOS_AUDIO_LOG ("handleRouteChange: reason: " << reason);
  475. fixAudioRouteIfSetToReceiver();
  476. if (owner.isRunning)
  477. {
  478. invokeAudioDeviceErrorCallback (reason);
  479. owner.updateSampleRateAndAudioInput();
  480. updateCurrentBufferSize();
  481. createAudioUnit();
  482. setAudioSessionActive (true);
  483. if (audioUnit != 0)
  484. {
  485. UInt32 formatSize = sizeof (format);
  486. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  487. AudioOutputUnitStart (audioUnit);
  488. }
  489. if (owner.callback != nullptr)
  490. {
  491. owner.callback->audioDeviceStopped();
  492. owner.callback->audioDeviceAboutToStart (&owner);
  493. }
  494. }
  495. }
  496. void handleAudioUnitPropertyChange (AudioUnit,
  497. AudioUnitPropertyID propertyID,
  498. AudioUnitScope,
  499. AudioUnitElement)
  500. {
  501. const ScopedLock myScopedLock (callbackLock);
  502. switch (propertyID)
  503. {
  504. case kAudioUnitProperty_IsInterAppConnected: return handleInterAppAudioConnectionChange();
  505. default: return;
  506. }
  507. }
  508. void handleInterAppAudioConnectionChange()
  509. {
  510. UInt32 connected;
  511. UInt32 dataSize = sizeof (connected);
  512. OSStatus err = AudioUnitGetProperty (audioUnit, kAudioUnitProperty_IsInterAppConnected,
  513. kAudioUnitScope_Global, 0, &connected, &dataSize);
  514. ignoreUnused (err);
  515. jassert (err == noErr);
  516. JUCE_IOS_AUDIO_LOG ("handleInterAppAudioConnectionChange: " << (connected ? "connected"
  517. : "disconnected"));
  518. if (connected != owner.interAppAudioConnected)
  519. {
  520. const ScopedLock myScopedLock (callbackLock);
  521. owner.interAppAudioConnected = connected;
  522. UIApplicationState appstate = [UIApplication sharedApplication].applicationState;
  523. bool inForeground = (appstate != UIApplicationStateBackground);
  524. if (owner.interAppAudioConnected || inForeground)
  525. {
  526. setAudioSessionActive (true);
  527. AudioOutputUnitStart (audioUnit);
  528. if (owner.callback != nullptr)
  529. owner.callback->audioDeviceAboutToStart (&owner);
  530. }
  531. else if (! inForeground)
  532. {
  533. AudioOutputUnitStop (audioUnit);
  534. setAudioSessionActive (false);
  535. }
  536. }
  537. }
  538. private:
  539. //==============================================================================
  540. iOSAudioIODevice& owner;
  541. SharedResourcePointer<AudioSessionHolder> sessionHolder;
  542. CriticalSection callbackLock;
  543. AudioStreamBasicDescription format;
  544. AudioUnit audioUnit {};
  545. AudioSampleBuffer floatData;
  546. float* inputChannels[3];
  547. float* outputChannels[3];
  548. bool monoInputChannelNumber, monoOutputChannelNumber;
  549. void prepareFloatBuffers (int bufferSize)
  550. {
  551. if (owner.numInputChannels + owner.numOutputChannels > 0)
  552. {
  553. floatData.setSize (owner.numInputChannels + owner.numOutputChannels, bufferSize);
  554. zeromem (inputChannels, sizeof (inputChannels));
  555. zeromem (outputChannels, sizeof (outputChannels));
  556. for (int i = 0; i < owner.numInputChannels; ++i)
  557. inputChannels[i] = floatData.getWritePointer (i);
  558. for (int i = 0; i < owner.numOutputChannels; ++i)
  559. outputChannels[i] = floatData.getWritePointer (i + owner.numInputChannels);
  560. }
  561. }
  562. //==============================================================================
  563. OSStatus process (AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  564. const UInt32 numFrames, AudioBufferList* data)
  565. {
  566. OSStatus err = noErr;
  567. if (owner.audioInputIsAvailable && owner.numInputChannels > 0)
  568. err = AudioUnitRender (audioUnit, flags, time, 1, numFrames, data);
  569. const ScopedTryLock stl (callbackLock);
  570. if (stl.isLocked() && owner.callback != nullptr)
  571. {
  572. if ((int) numFrames > floatData.getNumSamples())
  573. prepareFloatBuffers ((int) numFrames);
  574. if (owner.audioInputIsAvailable && owner.numInputChannels > 0)
  575. {
  576. short* shortData = (short*) data->mBuffers[0].mData;
  577. if (owner.numInputChannels >= 2)
  578. {
  579. for (UInt32 i = 0; i < numFrames; ++i)
  580. {
  581. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  582. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  583. }
  584. }
  585. else
  586. {
  587. if (monoInputChannelNumber > 0)
  588. ++shortData;
  589. for (UInt32 i = 0; i < numFrames; ++i)
  590. {
  591. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  592. ++shortData;
  593. }
  594. }
  595. }
  596. else
  597. {
  598. for (int i = owner.numInputChannels; --i >= 0;)
  599. zeromem (inputChannels[i], sizeof (float) * numFrames);
  600. }
  601. owner.callback->audioDeviceIOCallback ((const float**) inputChannels, owner.numInputChannels,
  602. outputChannels, owner.numOutputChannels, (int) numFrames);
  603. short* const shortData = (short*) data->mBuffers[0].mData;
  604. int n = 0;
  605. if (owner.numOutputChannels >= 2)
  606. {
  607. for (UInt32 i = 0; i < numFrames; ++i)
  608. {
  609. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  610. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  611. }
  612. }
  613. else if (owner.numOutputChannels == 1)
  614. {
  615. for (UInt32 i = 0; i < numFrames; ++i)
  616. {
  617. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  618. shortData [n++] = s;
  619. shortData [n++] = s;
  620. }
  621. }
  622. else
  623. {
  624. zeromem (data->mBuffers[0].mData, 2 * sizeof (short) * numFrames);
  625. }
  626. }
  627. else
  628. {
  629. zeromem (data->mBuffers[0].mData, 2 * sizeof (short) * numFrames);
  630. }
  631. return err;
  632. }
  633. void updateCurrentBufferSize()
  634. {
  635. NSTimeInterval bufferDuration = owner.sampleRate > 0 ? (NSTimeInterval) ((owner.preferredBufferSize + 1) / owner.sampleRate) : 0.0;
  636. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setPreferredIOBufferDuration: bufferDuration
  637. error: &error]);
  638. owner.updateSampleRateAndAudioInput();
  639. }
  640. //==============================================================================
  641. static OSStatus processStatic (void* client, AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  642. UInt32 /*busNumber*/, UInt32 numFrames, AudioBufferList* data)
  643. {
  644. return static_cast<Pimpl*> (client)->process (flags, time, numFrames, data);
  645. }
  646. //==============================================================================
  647. void resetFormat (const int numChannels) noexcept
  648. {
  649. zerostruct (format);
  650. format.mFormatID = kAudioFormatLinearPCM;
  651. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kAudioFormatFlagsNativeEndian;
  652. format.mBitsPerChannel = 8 * sizeof (short);
  653. format.mChannelsPerFrame = (UInt32) numChannels;
  654. format.mFramesPerPacket = 1;
  655. format.mBytesPerFrame = format.mBytesPerPacket = (UInt32) numChannels * sizeof (short);
  656. }
  657. bool createAudioUnit()
  658. {
  659. if (audioUnit != 0)
  660. {
  661. AudioComponentInstanceDispose (audioUnit);
  662. audioUnit = 0;
  663. }
  664. resetFormat (2);
  665. AudioComponentDescription desc;
  666. desc.componentType = kAudioUnitType_Output;
  667. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  668. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  669. desc.componentFlags = 0;
  670. desc.componentFlagsMask = 0;
  671. AudioComponent comp = AudioComponentFindNext (0, &desc);
  672. AudioComponentInstanceNew (comp, &audioUnit);
  673. if (audioUnit == 0)
  674. return false;
  675. #if JucePlugin_Enable_IAA
  676. AudioComponentDescription appDesc;
  677. appDesc.componentType = JucePlugin_IAAType;
  678. appDesc.componentSubType = JucePlugin_IAASubType;
  679. appDesc.componentManufacturer = JucePlugin_ManufacturerCode;
  680. appDesc.componentFlags = 0;
  681. appDesc.componentFlagsMask = 0;
  682. OSStatus err = AudioOutputUnitPublish (&appDesc,
  683. CFSTR(JucePlugin_IAAName),
  684. JucePlugin_VersionCode,
  685. audioUnit);
  686. // This assert will be hit if the Inter-App Audio entitlement has not
  687. // been enabled, or the description being published with
  688. // AudioOutputUnitPublish is different from any in the AudioComponents
  689. // array in this application's .plist file.
  690. jassert (err == noErr);
  691. err = AudioUnitAddPropertyListener(audioUnit,
  692. kAudioUnitProperty_IsInterAppConnected,
  693. audioUnitPropertyChangeDispatcher,
  694. this);
  695. jassert (err == noErr);
  696. #endif
  697. if (owner.numInputChannels > 0)
  698. {
  699. const UInt32 one = 1;
  700. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  701. }
  702. {
  703. AudioChannelLayout layout;
  704. layout.mChannelBitmap = 0;
  705. layout.mNumberChannelDescriptions = 0;
  706. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  707. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  708. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  709. }
  710. {
  711. AURenderCallbackStruct inputProc;
  712. inputProc.inputProc = processStatic;
  713. inputProc.inputProcRefCon = this;
  714. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  715. }
  716. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  717. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  718. UInt32 framesPerSlice;
  719. UInt32 dataSize = sizeof (framesPerSlice);
  720. AudioUnitInitialize (audioUnit);
  721. updateCurrentBufferSize();
  722. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_MaximumFramesPerSlice,
  723. kAudioUnitScope_Global, 0, &framesPerSlice, &dataSize) == noErr
  724. && dataSize == sizeof (framesPerSlice) && static_cast<int> (framesPerSlice) != owner.actualBufferSize)
  725. {
  726. prepareFloatBuffers (static_cast<int> (framesPerSlice));
  727. }
  728. AudioUnitAddPropertyListener (audioUnit, kAudioUnitProperty_StreamFormat, handleStreamFormatChangeCallback, this);
  729. return true;
  730. }
  731. void fillHostCallbackInfo (HostCallbackInfo& callbackInfo)
  732. {
  733. zerostruct (callbackInfo);
  734. UInt32 dataSize = sizeof (HostCallbackInfo);
  735. OSStatus err = AudioUnitGetProperty (audioUnit,
  736. kAudioUnitProperty_HostCallbacks,
  737. kAudioUnitScope_Global,
  738. 0,
  739. &callbackInfo,
  740. &dataSize);
  741. ignoreUnused (err);
  742. jassert (err == noErr);
  743. }
  744. void handleAudioTransportEvent (AudioUnitRemoteControlEvent event)
  745. {
  746. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_RemoteControlToHost,
  747. kAudioUnitScope_Global, 0, &event, sizeof (event));
  748. ignoreUnused (err);
  749. jassert (err == noErr);
  750. }
  751. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  752. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  753. static void fixAudioRouteIfSetToReceiver()
  754. {
  755. auto session = [AVAudioSession sharedInstance];
  756. auto route = session.currentRoute;
  757. for (AVAudioSessionPortDescription* port in route.inputs)
  758. {
  759. ignoreUnused (port);
  760. JUCE_IOS_AUDIO_LOG ("AVAudioSession: input: " << [port.description UTF8String]);
  761. }
  762. for (AVAudioSessionPortDescription* port in route.outputs)
  763. {
  764. JUCE_IOS_AUDIO_LOG ("AVAudioSession: output: " << [port.description UTF8String]);
  765. if ([port.portName isEqualToString: @"Receiver"])
  766. {
  767. JUCE_NSERROR_CHECK ([session overrideOutputAudioPort: AVAudioSessionPortOverrideSpeaker
  768. error: &error]);
  769. setAudioSessionActive (true);
  770. }
  771. }
  772. }
  773. void handleStreamFormatChange()
  774. {
  775. AudioStreamBasicDescription desc;
  776. zerostruct (desc);
  777. UInt32 dataSize = sizeof (desc);
  778. AudioUnitGetProperty(audioUnit,
  779. kAudioUnitProperty_StreamFormat,
  780. kAudioUnitScope_Output,
  781. 0,
  782. &desc,
  783. &dataSize);
  784. if (desc.mSampleRate != owner.getCurrentSampleRate())
  785. {
  786. struct RouteChangeMessage : public CallbackMessage
  787. {
  788. RouteChangeMessage (iOSAudioIODevice& dev) : device (dev)
  789. {}
  790. void messageCallback() override
  791. {
  792. device.handleRouteChange ("Stream format change");
  793. }
  794. iOSAudioIODevice& device;
  795. };
  796. (new RouteChangeMessage (owner))->post();
  797. }
  798. }
  799. static void handleStreamFormatChangeCallback (void* device,
  800. AudioUnit,
  801. AudioUnitPropertyID,
  802. AudioUnitScope scope,
  803. AudioUnitElement element)
  804. {
  805. if (scope == kAudioUnitScope_Output && element == 0)
  806. static_cast<Pimpl*> (device)->handleStreamFormatChange();
  807. }
  808. static void audioUnitPropertyChangeDispatcher (void* data, AudioUnit unit, AudioUnitPropertyID propertyID,
  809. AudioUnitScope scope, AudioUnitElement element)
  810. {
  811. Pimpl* device = (Pimpl*)data;
  812. device->handleAudioUnitPropertyChange (unit, propertyID, scope, element);
  813. }
  814. void handleMidiMessage (MidiMessage msg)
  815. {
  816. if (owner.messageCollector != nullptr)
  817. owner.messageCollector->addMessageToQueue (msg);
  818. }
  819. static void midiEventCallback (void *client, UInt32 status, UInt32 data1, UInt32 data2, UInt32)
  820. {
  821. return static_cast<Pimpl*> (client)->handleMidiMessage (MidiMessage ((int) status,
  822. (int) data1,
  823. (int) data2,
  824. Time::getMillisecondCounter() / 1000.0));
  825. }
  826. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  827. };
  828. //==============================================================================
  829. iOSAudioIODevice::iOSAudioIODevice (const String& deviceName)
  830. : AudioIODevice (deviceName, iOSAudioDeviceName),
  831. #if TARGET_IPHONE_SIMULATOR
  832. defaultBufferSize (512),
  833. #else
  834. defaultBufferSize (256),
  835. #endif
  836. sampleRate (0), numInputChannels (2), numOutputChannels (2),
  837. preferredBufferSize (0), actualBufferSize (0), isRunning (false),
  838. audioInputIsAvailable (false), interAppAudioConnected (false),
  839. callback (nullptr), messageCollector (nullptr),
  840. pimpl (new Pimpl (*this))
  841. {
  842. updateSampleRateAndAudioInput();
  843. }
  844. //==============================================================================
  845. int iOSAudioIODevice::getOutputLatencyInSamples() { return roundToInt (sampleRate * [AVAudioSession sharedInstance].outputLatency); }
  846. int iOSAudioIODevice::getInputLatencyInSamples() { return roundToInt (sampleRate * [AVAudioSession sharedInstance].inputLatency); }
  847. //==============================================================================
  848. AudioPlayHead* iOSAudioIODevice::getAudioPlayHead() const { return pimpl; }
  849. void iOSAudioIODevice::close() { pimpl->close(); }
  850. void iOSAudioIODevice::start (AudioIODeviceCallback* callbackToUse) { pimpl->start (callbackToUse); }
  851. void iOSAudioIODevice::stop() { pimpl->stop(); }
  852. Array<double> iOSAudioIODevice::getAvailableSampleRates() { return pimpl->getAvailableSampleRates(); }
  853. Array<int> iOSAudioIODevice::getAvailableBufferSizes() { return pimpl->getAvailableBufferSizes(); }
  854. bool iOSAudioIODevice::setAudioPreprocessingEnabled (bool enabled) { return pimpl->setAudioPreprocessingEnabled (enabled); }
  855. void iOSAudioIODevice::switchApplication() { return pimpl->switchApplication(); }
  856. //==============================================================================
  857. void iOSAudioIODevice::handleStatusChange (bool enabled, const char* reason) { pimpl->handleStatusChange (enabled, reason); }
  858. void iOSAudioIODevice::handleRouteChange (const char* reason) { pimpl->handleRouteChange (reason); }
  859. #if JUCE_MODULE_AVAILABLE_juce_graphics
  860. Image iOSAudioIODevice::getIcon (int size) { return pimpl->getIcon (size); }
  861. #endif
  862. //==============================================================================
  863. String iOSAudioIODevice::open (const BigInteger& inChans, const BigInteger& outChans, double requestedSampleRate, int requestedBufferSize)
  864. {
  865. return pimpl->open (inChans, outChans, requestedSampleRate, requestedBufferSize);
  866. }
  867. void iOSAudioIODevice::updateSampleRateAndAudioInput()
  868. {
  869. auto session = [AVAudioSession sharedInstance];
  870. sampleRate = session.sampleRate;
  871. audioInputIsAvailable = session.isInputAvailable;
  872. actualBufferSize = roundToInt (sampleRate * session.IOBufferDuration);
  873. JUCE_IOS_AUDIO_LOG ("AVAudioSession: sampleRate: " << sampleRate
  874. << " Hz, audioInputAvailable: " << (int) audioInputIsAvailable
  875. << ", buffer size: " << actualBufferSize);
  876. }
  877. //==============================================================================
  878. class iOSAudioIODeviceType : public AudioIODeviceType
  879. {
  880. public:
  881. iOSAudioIODeviceType() : AudioIODeviceType (iOSAudioDeviceName) {}
  882. void scanForDevices() {}
  883. StringArray getDeviceNames (bool /*wantInputNames*/) const { return StringArray (iOSAudioDeviceName); }
  884. int getDefaultDeviceIndex (bool /*forInput*/) const { return 0; }
  885. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const { return d != nullptr ? 0 : -1; }
  886. bool hasSeparateInputsAndOutputs() const { return false; }
  887. AudioIODevice* createDevice (const String& outputDeviceName, const String& inputDeviceName)
  888. {
  889. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  890. return new iOSAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName : inputDeviceName);
  891. return nullptr;
  892. }
  893. private:
  894. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSAudioIODeviceType)
  895. };
  896. //==============================================================================
  897. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()
  898. {
  899. return new iOSAudioIODeviceType();
  900. }
  901. //==============================================================================
  902. AudioSessionHolder::AudioSessionHolder() { nativeSession = [[iOSAudioSessionNative alloc] init: this]; }
  903. AudioSessionHolder::~AudioSessionHolder() { [nativeSession release]; }
  904. void AudioSessionHolder::handleStatusChange (bool enabled, const char* reason) const
  905. {
  906. for (auto device: activeDevices)
  907. device->handleStatusChange (enabled, reason);
  908. }
  909. void AudioSessionHolder::handleRouteChange (const char* reason) const
  910. {
  911. struct RouteChangeMessage : public CallbackMessage
  912. {
  913. RouteChangeMessage (Array<iOSAudioIODevice*> devs, const char* r)
  914. : devices (devs), changeReason (r)
  915. {
  916. }
  917. void messageCallback() override
  918. {
  919. for (auto device: devices)
  920. device->handleRouteChange (changeReason);
  921. }
  922. Array<iOSAudioIODevice*> devices;
  923. const char* changeReason;
  924. };
  925. (new RouteChangeMessage (activeDevices, reason))->post();
  926. }
  927. #undef JUCE_NSERROR_CHECK