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.

1127 lines
42KB

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