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.

1165 lines
43KB

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