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.

1472 lines
54KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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. namespace juce
  18. {
  19. class iOSAudioIODevice;
  20. constexpr const char* const iOSAudioDeviceName = "iOS Audio";
  21. #ifndef JUCE_IOS_AUDIO_EXPLICIT_SAMPLERATES
  22. #define JUCE_IOS_AUDIO_EXPLICIT_SAMPLERATES
  23. #endif
  24. constexpr std::initializer_list<double> iOSExplicitSampleRates { JUCE_IOS_AUDIO_EXPLICIT_SAMPLERATES };
  25. //==============================================================================
  26. struct AudioSessionHolder
  27. {
  28. AudioSessionHolder();
  29. ~AudioSessionHolder();
  30. void handleStatusChange (bool enabled, const char* reason) const;
  31. void handleRouteChange (AVAudioSessionRouteChangeReason reason);
  32. Array<iOSAudioIODevice::Pimpl*> activeDevices;
  33. Array<iOSAudioIODeviceType*> activeDeviceTypes;
  34. id nativeSession;
  35. };
  36. static const char* getRoutingChangeReason (AVAudioSessionRouteChangeReason reason) noexcept
  37. {
  38. switch (reason)
  39. {
  40. case AVAudioSessionRouteChangeReasonNewDeviceAvailable: return "New device available";
  41. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: return "Old device unavailable";
  42. case AVAudioSessionRouteChangeReasonCategoryChange: return "Category change";
  43. case AVAudioSessionRouteChangeReasonOverride: return "Override";
  44. case AVAudioSessionRouteChangeReasonWakeFromSleep: return "Wake from sleep";
  45. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory: return "No suitable route for category";
  46. case AVAudioSessionRouteChangeReasonRouteConfigurationChange: return "Route configuration change";
  47. case AVAudioSessionRouteChangeReasonUnknown:
  48. default: return "Unknown";
  49. }
  50. }
  51. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wmissing-prototypes")
  52. bool getNotificationValueForKey (NSNotification* notification, NSString* key, NSUInteger& value) noexcept
  53. {
  54. if (notification != nil)
  55. {
  56. if (NSDictionary* userInfo = [notification userInfo])
  57. {
  58. if (NSNumber* number = [userInfo objectForKey: key])
  59. {
  60. value = [number unsignedIntegerValue];
  61. return true;
  62. }
  63. }
  64. }
  65. jassertfalse;
  66. return false;
  67. }
  68. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  69. } // namespace juce
  70. //==============================================================================
  71. @interface iOSAudioSessionNative : NSObject
  72. {
  73. @private
  74. juce::AudioSessionHolder* audioSessionHolder;
  75. };
  76. - (id) init: (juce::AudioSessionHolder*) holder;
  77. - (void) dealloc;
  78. - (void) audioSessionChangedInterruptionType: (NSNotification*) notification;
  79. - (void) handleMediaServicesReset;
  80. - (void) handleMediaServicesLost;
  81. - (void) handleRouteChange: (NSNotification*) notification;
  82. @end
  83. @implementation iOSAudioSessionNative
  84. - (id) init: (juce::AudioSessionHolder*) holder
  85. {
  86. self = [super init];
  87. if (self != nil)
  88. {
  89. audioSessionHolder = holder;
  90. auto session = [AVAudioSession sharedInstance];
  91. auto centre = [NSNotificationCenter defaultCenter];
  92. [centre addObserver: self
  93. selector: @selector (audioSessionChangedInterruptionType:)
  94. name: AVAudioSessionInterruptionNotification
  95. object: session];
  96. [centre addObserver: self
  97. selector: @selector (handleMediaServicesLost)
  98. name: AVAudioSessionMediaServicesWereLostNotification
  99. object: session];
  100. [centre addObserver: self
  101. selector: @selector (handleMediaServicesReset)
  102. name: AVAudioSessionMediaServicesWereResetNotification
  103. object: session];
  104. [centre addObserver: self
  105. selector: @selector (handleRouteChange:)
  106. name: AVAudioSessionRouteChangeNotification
  107. object: session];
  108. }
  109. else
  110. {
  111. jassertfalse;
  112. }
  113. return self;
  114. }
  115. - (void) dealloc
  116. {
  117. [[NSNotificationCenter defaultCenter] removeObserver: self];
  118. [super dealloc];
  119. }
  120. - (void) audioSessionChangedInterruptionType: (NSNotification*) notification
  121. {
  122. NSUInteger value;
  123. if (juce::getNotificationValueForKey (notification, AVAudioSessionInterruptionTypeKey, value))
  124. {
  125. switch ((AVAudioSessionInterruptionType) value)
  126. {
  127. case AVAudioSessionInterruptionTypeBegan:
  128. audioSessionHolder->handleStatusChange (false, "AVAudioSessionInterruptionTypeBegan");
  129. break;
  130. case AVAudioSessionInterruptionTypeEnded:
  131. audioSessionHolder->handleStatusChange (true, "AVAudioSessionInterruptionTypeEnded");
  132. break;
  133. // No default so the code doesn't compile if this enum is extended.
  134. }
  135. }
  136. }
  137. - (void) handleMediaServicesReset
  138. {
  139. audioSessionHolder->handleStatusChange (true, "AVAudioSessionMediaServicesWereResetNotification");
  140. }
  141. - (void) handleMediaServicesLost
  142. {
  143. audioSessionHolder->handleStatusChange (false, "AVAudioSessionMediaServicesWereLostNotification");
  144. }
  145. - (void) handleRouteChange: (NSNotification*) notification
  146. {
  147. NSUInteger value;
  148. if (juce::getNotificationValueForKey (notification, AVAudioSessionRouteChangeReasonKey, value))
  149. audioSessionHolder->handleRouteChange ((AVAudioSessionRouteChangeReason) value);
  150. }
  151. @end
  152. //==============================================================================
  153. #if JUCE_MODULE_AVAILABLE_juce_graphics
  154. #include <juce_graphics/native/juce_mac_CoreGraphicsHelpers.h>
  155. #endif
  156. namespace juce {
  157. #ifndef JUCE_IOS_AUDIO_LOGGING
  158. #define JUCE_IOS_AUDIO_LOGGING 0
  159. #endif
  160. #if JUCE_IOS_AUDIO_LOGGING
  161. #define JUCE_IOS_AUDIO_LOG(x) DBG(x)
  162. #else
  163. #define JUCE_IOS_AUDIO_LOG(x)
  164. #endif
  165. static void logNSError (NSError* e)
  166. {
  167. if (e != nil)
  168. {
  169. JUCE_IOS_AUDIO_LOG ("iOS Audio error: " << [e.localizedDescription UTF8String]);
  170. jassertfalse;
  171. }
  172. }
  173. #define JUCE_NSERROR_CHECK(X) { NSError* error = nil; X; logNSError (error); }
  174. //==============================================================================
  175. class iOSAudioIODeviceType : public AudioIODeviceType,
  176. public AsyncUpdater
  177. {
  178. public:
  179. iOSAudioIODeviceType();
  180. ~iOSAudioIODeviceType() override;
  181. void scanForDevices() override;
  182. StringArray getDeviceNames (bool) const override;
  183. int getDefaultDeviceIndex (bool) const override;
  184. int getIndexOfDevice (AudioIODevice*, bool) const override;
  185. bool hasSeparateInputsAndOutputs() const override;
  186. AudioIODevice* createDevice (const String&, const String&) override;
  187. private:
  188. void handleRouteChange (AVAudioSessionRouteChangeReason);
  189. void handleAsyncUpdate() override;
  190. friend struct AudioSessionHolder;
  191. friend struct iOSAudioIODevice::Pimpl;
  192. SharedResourcePointer<AudioSessionHolder> sessionHolder;
  193. JUCE_DECLARE_WEAK_REFERENCEABLE (iOSAudioIODeviceType)
  194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSAudioIODeviceType)
  195. };
  196. //==============================================================================
  197. struct iOSAudioIODevice::Pimpl : public AudioPlayHead,
  198. public AsyncUpdater
  199. {
  200. Pimpl (iOSAudioIODeviceType* ioDeviceType, iOSAudioIODevice& ioDevice)
  201. : deviceType (ioDeviceType),
  202. owner (ioDevice)
  203. {
  204. JUCE_IOS_AUDIO_LOG ("Creating iOS audio device");
  205. // We need to activate the audio session here to obtain the available sample rates and buffer sizes,
  206. // but if we don't set a category first then background audio will always be stopped. This category
  207. // may be changed later.
  208. setAudioSessionCategory (AVAudioSessionCategoryPlayAndRecord);
  209. setAudioSessionActive (true);
  210. updateHardwareInfo();
  211. channelData.reconfigure ({}, {});
  212. setAudioSessionActive (false);
  213. sessionHolder->activeDevices.add (this);
  214. }
  215. ~Pimpl() override
  216. {
  217. sessionHolder->activeDevices.removeFirstMatchingValue (this);
  218. close();
  219. }
  220. static void setAudioSessionCategory (NSString* category)
  221. {
  222. NSUInteger options = 0;
  223. #if ! JUCE_DISABLE_AUDIO_MIXING_WITH_OTHER_APPS
  224. options |= AVAudioSessionCategoryOptionMixWithOthers; // Alternatively AVAudioSessionCategoryOptionDuckOthers
  225. #endif
  226. if (category == AVAudioSessionCategoryPlayAndRecord)
  227. options |= (AVAudioSessionCategoryOptionDefaultToSpeaker
  228. | AVAudioSessionCategoryOptionAllowBluetooth
  229. | AVAudioSessionCategoryOptionAllowBluetoothA2DP);
  230. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setCategory: category
  231. withOptions: options
  232. error: &error]);
  233. }
  234. static void setAudioSessionActive (bool enabled)
  235. {
  236. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setActive: enabled
  237. error: &error]);
  238. }
  239. int getBufferSize (const double currentSampleRate)
  240. {
  241. return roundToInt (currentSampleRate * [AVAudioSession sharedInstance].IOBufferDuration);
  242. }
  243. int tryBufferSize (const double currentSampleRate, const int newBufferSize)
  244. {
  245. NSTimeInterval bufferDuration = currentSampleRate > 0 ? (NSTimeInterval) ((newBufferSize + 1) / currentSampleRate) : 0.0;
  246. auto session = [AVAudioSession sharedInstance];
  247. JUCE_NSERROR_CHECK ([session setPreferredIOBufferDuration: bufferDuration
  248. error: &error]);
  249. return getBufferSize (currentSampleRate);
  250. }
  251. void updateAvailableBufferSizes()
  252. {
  253. availableBufferSizes.clear();
  254. auto newBufferSize = tryBufferSize (sampleRate, 64);
  255. jassert (newBufferSize > 0);
  256. const auto longestBufferSize = tryBufferSize (sampleRate, 4096);
  257. while (newBufferSize <= longestBufferSize)
  258. {
  259. availableBufferSizes.add (newBufferSize);
  260. newBufferSize *= 2;
  261. }
  262. // Sometimes the largest supported buffer size is not a power of 2
  263. availableBufferSizes.addIfNotAlreadyThere (longestBufferSize);
  264. bufferSize = tryBufferSize (sampleRate, bufferSize);
  265. #if JUCE_IOS_AUDIO_LOGGING
  266. {
  267. String info ("Available buffer sizes:");
  268. for (auto size : availableBufferSizes)
  269. info << " " << size;
  270. JUCE_IOS_AUDIO_LOG (info);
  271. }
  272. #endif
  273. JUCE_IOS_AUDIO_LOG ("Buffer size after detecting available buffer sizes: " << bufferSize);
  274. }
  275. double trySampleRate (double rate)
  276. {
  277. auto session = [AVAudioSession sharedInstance];
  278. JUCE_NSERROR_CHECK ([session setPreferredSampleRate: rate
  279. error: &error]);
  280. return session.sampleRate;
  281. }
  282. // Important: the supported audio sample rates change on the iPhone 6S
  283. // depending on whether the headphones are plugged in or not!
  284. void updateAvailableSampleRates()
  285. {
  286. if (iOSExplicitSampleRates.size() != 0)
  287. {
  288. availableSampleRates = Array<double> (iOSExplicitSampleRates);
  289. return;
  290. }
  291. availableSampleRates.clear();
  292. AudioUnitRemovePropertyListenerWithUserData (audioUnit,
  293. kAudioUnitProperty_StreamFormat,
  294. dispatchAudioUnitPropertyChange,
  295. this);
  296. const double lowestRate = trySampleRate (4000);
  297. availableSampleRates.add (lowestRate);
  298. const double highestRate = trySampleRate (192000);
  299. JUCE_IOS_AUDIO_LOG ("Lowest supported sample rate: " << lowestRate);
  300. JUCE_IOS_AUDIO_LOG ("Highest supported sample rate: " << highestRate);
  301. for (double rate = lowestRate + 1000; rate < highestRate; rate += 1000)
  302. {
  303. const double supportedRate = trySampleRate (rate);
  304. JUCE_IOS_AUDIO_LOG ("Trying a sample rate of " << rate << ", got " << supportedRate);
  305. availableSampleRates.addIfNotAlreadyThere (supportedRate);
  306. rate = jmax (rate, supportedRate);
  307. }
  308. availableSampleRates.addIfNotAlreadyThere (highestRate);
  309. // Restore the original values.
  310. sampleRate = trySampleRate (sampleRate);
  311. bufferSize = tryBufferSize (sampleRate, bufferSize);
  312. AudioUnitAddPropertyListener (audioUnit,
  313. kAudioUnitProperty_StreamFormat,
  314. dispatchAudioUnitPropertyChange,
  315. this);
  316. // Check the current stream format in case things have changed whilst we
  317. // were going through the sample rates
  318. handleStreamFormatChange();
  319. #if JUCE_IOS_AUDIO_LOGGING
  320. {
  321. String info ("Available sample rates:");
  322. for (auto rate : availableSampleRates)
  323. info << " " << rate;
  324. JUCE_IOS_AUDIO_LOG (info);
  325. }
  326. #endif
  327. JUCE_IOS_AUDIO_LOG ("Sample rate after detecting available sample rates: " << sampleRate);
  328. }
  329. void updateHardwareInfo (bool forceUpdate = false)
  330. {
  331. if (! forceUpdate && ! hardwareInfoNeedsUpdating.compareAndSetBool (false, true))
  332. return;
  333. JUCE_IOS_AUDIO_LOG ("Updating hardware info");
  334. updateAvailableSampleRates();
  335. updateAvailableBufferSizes();
  336. if (deviceType != nullptr)
  337. deviceType->callDeviceChangeListeners();
  338. }
  339. void setTargetSampleRateAndBufferSize()
  340. {
  341. JUCE_IOS_AUDIO_LOG ("Setting target sample rate: " << targetSampleRate);
  342. sampleRate = trySampleRate (targetSampleRate);
  343. JUCE_IOS_AUDIO_LOG ("Actual sample rate: " << sampleRate);
  344. JUCE_IOS_AUDIO_LOG ("Setting target buffer size: " << targetBufferSize);
  345. bufferSize = tryBufferSize (sampleRate, targetBufferSize);
  346. JUCE_IOS_AUDIO_LOG ("Actual buffer size: " << bufferSize);
  347. }
  348. String open (const BigInteger& inputChannelsWanted,
  349. const BigInteger& outputChannelsWanted,
  350. double sampleRateWanted, int bufferSizeWanted)
  351. {
  352. close();
  353. firstHostTime = true;
  354. lastNumFrames = 0;
  355. xrun = 0;
  356. lastError.clear();
  357. requestedInputChannels = inputChannelsWanted;
  358. requestedOutputChannels = outputChannelsWanted;
  359. targetSampleRate = sampleRateWanted;
  360. targetBufferSize = bufferSizeWanted > 0 ? bufferSizeWanted : defaultBufferSize;
  361. JUCE_IOS_AUDIO_LOG ("Opening audio device:"
  362. << " inputChannelsWanted: " << requestedInputChannels .toString (2)
  363. << ", outputChannelsWanted: " << requestedOutputChannels.toString (2)
  364. << ", targetSampleRate: " << targetSampleRate
  365. << ", targetBufferSize: " << targetBufferSize);
  366. setAudioSessionActive (true);
  367. setAudioSessionCategory (requestedInputChannels > 0 ? AVAudioSessionCategoryPlayAndRecord
  368. : AVAudioSessionCategoryPlayback);
  369. channelData.reconfigure (requestedInputChannels, requestedOutputChannels);
  370. updateHardwareInfo (true);
  371. setTargetSampleRateAndBufferSize();
  372. fixAudioRouteIfSetToReceiver();
  373. isRunning = true;
  374. if (! createAudioUnit())
  375. {
  376. lastError = "Couldn't open the device";
  377. return lastError;
  378. }
  379. const ScopedLock sl (callbackLock);
  380. AudioOutputUnitStart (audioUnit);
  381. if (callback != nullptr)
  382. callback->audioDeviceAboutToStart (&owner);
  383. return lastError;
  384. }
  385. void close()
  386. {
  387. stop();
  388. if (isRunning)
  389. {
  390. isRunning = false;
  391. if (audioUnit != nullptr)
  392. {
  393. AudioOutputUnitStart (audioUnit);
  394. AudioComponentInstanceDispose (audioUnit);
  395. audioUnit = nullptr;
  396. }
  397. setAudioSessionActive (false);
  398. }
  399. }
  400. void start (AudioIODeviceCallback* newCallback)
  401. {
  402. if (isRunning && callback != newCallback)
  403. {
  404. if (newCallback != nullptr)
  405. newCallback->audioDeviceAboutToStart (&owner);
  406. const ScopedLock sl (callbackLock);
  407. callback = newCallback;
  408. }
  409. }
  410. void stop()
  411. {
  412. if (isRunning)
  413. {
  414. AudioIODeviceCallback* lastCallback;
  415. {
  416. const ScopedLock sl (callbackLock);
  417. lastCallback = callback;
  418. callback = nullptr;
  419. }
  420. if (lastCallback != nullptr)
  421. lastCallback->audioDeviceStopped();
  422. }
  423. }
  424. bool setAudioPreprocessingEnabled (bool enable)
  425. {
  426. auto session = [AVAudioSession sharedInstance];
  427. NSString* mode = (enable ? AVAudioSessionModeDefault
  428. : AVAudioSessionModeMeasurement);
  429. JUCE_NSERROR_CHECK ([session setMode: mode
  430. error: &error]);
  431. return session.mode == mode;
  432. }
  433. //==============================================================================
  434. bool canControlTransport() override { return interAppAudioConnected; }
  435. void transportPlay (bool shouldSartPlaying) override
  436. {
  437. if (! canControlTransport())
  438. return;
  439. HostCallbackInfo callbackInfo;
  440. fillHostCallbackInfo (callbackInfo);
  441. Boolean hostIsPlaying = NO;
  442. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  443. &hostIsPlaying,
  444. nullptr,
  445. nullptr,
  446. nullptr,
  447. nullptr,
  448. nullptr,
  449. nullptr);
  450. ignoreUnused (err);
  451. jassert (err == noErr);
  452. if (hostIsPlaying != shouldSartPlaying)
  453. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_TogglePlayPause);
  454. }
  455. void transportRecord (bool shouldStartRecording) override
  456. {
  457. if (! canControlTransport())
  458. return;
  459. HostCallbackInfo callbackInfo;
  460. fillHostCallbackInfo (callbackInfo);
  461. Boolean hostIsRecording = NO;
  462. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  463. nullptr,
  464. &hostIsRecording,
  465. nullptr,
  466. nullptr,
  467. nullptr,
  468. nullptr,
  469. nullptr);
  470. ignoreUnused (err);
  471. jassert (err == noErr);
  472. if (hostIsRecording != shouldStartRecording)
  473. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_ToggleRecord);
  474. }
  475. void transportRewind() override
  476. {
  477. if (canControlTransport())
  478. handleAudioTransportEvent (kAudioUnitRemoteControlEvent_Rewind);
  479. }
  480. bool getCurrentPosition (CurrentPositionInfo& result) override
  481. {
  482. if (! canControlTransport())
  483. return false;
  484. zerostruct (result);
  485. HostCallbackInfo callbackInfo;
  486. fillHostCallbackInfo (callbackInfo);
  487. if (callbackInfo.hostUserData == nullptr)
  488. return false;
  489. Boolean hostIsPlaying = NO;
  490. Boolean hostIsRecording = NO;
  491. Float64 hostCurrentSampleInTimeLine = 0;
  492. Boolean hostIsCycling = NO;
  493. Float64 hostCycleStartBeat = 0;
  494. Float64 hostCycleEndBeat = 0;
  495. OSStatus err = callbackInfo.transportStateProc2 (callbackInfo.hostUserData,
  496. &hostIsPlaying,
  497. &hostIsRecording,
  498. nullptr,
  499. &hostCurrentSampleInTimeLine,
  500. &hostIsCycling,
  501. &hostCycleStartBeat,
  502. &hostCycleEndBeat);
  503. if (err == kAUGraphErr_CannotDoInCurrentContext)
  504. return false;
  505. jassert (err == noErr);
  506. result.timeInSamples = (int64) hostCurrentSampleInTimeLine;
  507. result.isPlaying = hostIsPlaying;
  508. result.isRecording = hostIsRecording;
  509. result.isLooping = hostIsCycling;
  510. result.ppqLoopStart = hostCycleStartBeat;
  511. result.ppqLoopEnd = hostCycleEndBeat;
  512. result.timeInSeconds = result.timeInSamples / sampleRate;
  513. Float64 hostBeat = 0;
  514. Float64 hostTempo = 0;
  515. err = callbackInfo.beatAndTempoProc (callbackInfo.hostUserData,
  516. &hostBeat,
  517. &hostTempo);
  518. jassert (err == noErr);
  519. result.ppqPosition = hostBeat;
  520. result.bpm = hostTempo;
  521. Float32 hostTimeSigNumerator = 0;
  522. UInt32 hostTimeSigDenominator = 0;
  523. Float64 hostCurrentMeasureDownBeat = 0;
  524. err = callbackInfo.musicalTimeLocationProc (callbackInfo.hostUserData,
  525. nullptr,
  526. &hostTimeSigNumerator,
  527. &hostTimeSigDenominator,
  528. &hostCurrentMeasureDownBeat);
  529. jassert (err == noErr);
  530. result.ppqPositionOfLastBarStart = hostCurrentMeasureDownBeat;
  531. result.timeSigNumerator = (int) hostTimeSigNumerator;
  532. result.timeSigDenominator = (int) hostTimeSigDenominator;
  533. result.frameRate = AudioPlayHead::fpsUnknown;
  534. return true;
  535. }
  536. //==============================================================================
  537. #if JUCE_MODULE_AVAILABLE_juce_graphics
  538. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  539. Image getIcon (int size)
  540. {
  541. if (interAppAudioConnected)
  542. {
  543. UIImage* hostUIImage = AudioOutputUnitGetHostIcon (audioUnit, size);
  544. if (hostUIImage != nullptr)
  545. return juce_createImageFromUIImage (hostUIImage);
  546. }
  547. return Image();
  548. }
  549. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  550. #endif
  551. void switchApplication()
  552. {
  553. if (! interAppAudioConnected)
  554. return;
  555. CFURLRef hostUrl;
  556. UInt32 dataSize = sizeof (hostUrl);
  557. OSStatus err = AudioUnitGetProperty(audioUnit,
  558. kAudioUnitProperty_PeerURL,
  559. kAudioUnitScope_Global,
  560. 0,
  561. &hostUrl,
  562. &dataSize);
  563. if (err == noErr)
  564. {
  565. #if (! defined __IPHONE_10_0) || (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0)
  566. [[UIApplication sharedApplication] openURL: (NSURL*)hostUrl];
  567. #else
  568. [[UIApplication sharedApplication] openURL: (NSURL*)hostUrl options: @{} completionHandler: nil];
  569. #endif
  570. }
  571. }
  572. //==============================================================================
  573. void invokeAudioDeviceErrorCallback (const String& reason)
  574. {
  575. const ScopedLock sl (callbackLock);
  576. if (callback != nullptr)
  577. callback->audioDeviceError (reason);
  578. }
  579. void handleStatusChange (bool enabled, const char* reason)
  580. {
  581. const ScopedLock myScopedLock (callbackLock);
  582. JUCE_IOS_AUDIO_LOG ("handleStatusChange: enabled: " << (int) enabled << ", reason: " << reason);
  583. isRunning = enabled;
  584. setAudioSessionActive (enabled);
  585. if (enabled)
  586. AudioOutputUnitStart (audioUnit);
  587. else
  588. AudioOutputUnitStop (audioUnit);
  589. if (! enabled)
  590. invokeAudioDeviceErrorCallback (reason);
  591. }
  592. void handleRouteChange (AVAudioSessionRouteChangeReason reason)
  593. {
  594. const ScopedLock myScopedLock (callbackLock);
  595. const String reasonString (getRoutingChangeReason (reason));
  596. JUCE_IOS_AUDIO_LOG ("handleRouteChange: " << reasonString);
  597. if (isRunning)
  598. invokeAudioDeviceErrorCallback (reasonString);
  599. switch (reason)
  600. {
  601. case AVAudioSessionRouteChangeReasonCategoryChange:
  602. case AVAudioSessionRouteChangeReasonOverride:
  603. case AVAudioSessionRouteChangeReasonRouteConfigurationChange:
  604. break;
  605. case AVAudioSessionRouteChangeReasonUnknown:
  606. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  607. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
  608. case AVAudioSessionRouteChangeReasonWakeFromSleep:
  609. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
  610. {
  611. hardwareInfoNeedsUpdating = true;
  612. triggerAsyncUpdate();
  613. break;
  614. }
  615. // No default so the code doesn't compile if this enum is extended.
  616. }
  617. }
  618. void handleAudioUnitPropertyChange (AudioUnit,
  619. AudioUnitPropertyID propertyID,
  620. AudioUnitScope scope,
  621. AudioUnitElement element)
  622. {
  623. ignoreUnused (scope);
  624. ignoreUnused (element);
  625. JUCE_IOS_AUDIO_LOG ("handleAudioUnitPropertyChange: propertyID: " << String (propertyID)
  626. << " scope: " << String (scope)
  627. << " element: " << String (element));
  628. switch (propertyID)
  629. {
  630. case kAudioUnitProperty_IsInterAppConnected:
  631. handleInterAppAudioConnectionChange();
  632. return;
  633. case kAudioUnitProperty_StreamFormat:
  634. handleStreamFormatChange();
  635. return;
  636. default:
  637. jassertfalse;
  638. }
  639. }
  640. void handleInterAppAudioConnectionChange()
  641. {
  642. UInt32 connected;
  643. UInt32 dataSize = sizeof (connected);
  644. OSStatus err = AudioUnitGetProperty (audioUnit, kAudioUnitProperty_IsInterAppConnected,
  645. kAudioUnitScope_Global, 0, &connected, &dataSize);
  646. ignoreUnused (err);
  647. jassert (err == noErr);
  648. JUCE_IOS_AUDIO_LOG ("handleInterAppAudioConnectionChange: " << (connected ? "connected"
  649. : "disconnected"));
  650. if (connected != interAppAudioConnected)
  651. {
  652. const ScopedLock myScopedLock (callbackLock);
  653. interAppAudioConnected = connected;
  654. UIApplicationState appstate = [UIApplication sharedApplication].applicationState;
  655. bool inForeground = (appstate != UIApplicationStateBackground);
  656. if (interAppAudioConnected || inForeground)
  657. {
  658. setAudioSessionActive (true);
  659. AudioOutputUnitStart (audioUnit);
  660. if (callback != nullptr)
  661. callback->audioDeviceAboutToStart (&owner);
  662. }
  663. else if (! inForeground)
  664. {
  665. AudioOutputUnitStop (audioUnit);
  666. setAudioSessionActive (false);
  667. if (callback != nullptr)
  668. callback->audioDeviceStopped();
  669. }
  670. }
  671. }
  672. //==============================================================================
  673. OSStatus process (AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  674. const UInt32 numFrames, AudioBufferList* data)
  675. {
  676. OSStatus err = noErr;
  677. recordXruns (time, numFrames);
  678. const bool useInput = channelData.areInputChannelsAvailable();
  679. if (useInput)
  680. err = AudioUnitRender (audioUnit, flags, time, 1, numFrames, data);
  681. const auto channelDataSize = sizeof (float) * numFrames;
  682. const ScopedTryLock stl (callbackLock);
  683. if (stl.isLocked() && callback != nullptr)
  684. {
  685. if ((int) numFrames > channelData.getFloatBufferSize())
  686. channelData.setFloatBufferSize ((int) numFrames);
  687. float** const inputData = channelData.audioData.getArrayOfWritePointers();
  688. float** const outputData = inputData + channelData.inputs->numActiveChannels;
  689. if (useInput)
  690. {
  691. for (int c = 0; c < channelData.inputs->numActiveChannels; ++c)
  692. {
  693. auto channelIndex = channelData.inputs->activeChannelIndices[c];
  694. memcpy (inputData[c], (float*) data->mBuffers[channelIndex].mData, channelDataSize);
  695. }
  696. }
  697. else
  698. {
  699. for (int c = 0; c < channelData.inputs->numActiveChannels; ++c)
  700. zeromem (inputData[c], channelDataSize);
  701. }
  702. callback->audioDeviceIOCallback ((const float**) inputData, channelData.inputs ->numActiveChannels,
  703. outputData, channelData.outputs->numActiveChannels,
  704. (int) numFrames);
  705. for (int c = 0; c < channelData.outputs->numActiveChannels; ++c)
  706. {
  707. auto channelIndex = channelData.outputs->activeChannelIndices[c];
  708. memcpy (data->mBuffers[channelIndex].mData, outputData[c], channelDataSize);
  709. }
  710. for (auto c : channelData.outputs->inactiveChannelIndices)
  711. zeromem (data->mBuffers[c].mData, channelDataSize);
  712. }
  713. else
  714. {
  715. for (uint32 c = 0; c < data->mNumberBuffers; ++c)
  716. zeromem (data->mBuffers[c].mData, channelDataSize);
  717. }
  718. return err;
  719. }
  720. void recordXruns (const AudioTimeStamp* time, UInt32 numFrames)
  721. {
  722. if (time != nullptr && (time->mFlags & kAudioTimeStampSampleTimeValid) != 0)
  723. {
  724. if (! firstHostTime)
  725. {
  726. if ((time->mSampleTime - lastSampleTime) != lastNumFrames)
  727. xrun++;
  728. }
  729. else
  730. firstHostTime = false;
  731. lastSampleTime = time->mSampleTime;
  732. }
  733. else
  734. firstHostTime = true;
  735. lastNumFrames = numFrames;
  736. }
  737. //==============================================================================
  738. static OSStatus processStatic (void* client, AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  739. UInt32 /*busNumber*/, UInt32 numFrames, AudioBufferList* data)
  740. {
  741. return static_cast<Pimpl*> (client)->process (flags, time, numFrames, data);
  742. }
  743. //==============================================================================
  744. bool createAudioUnit()
  745. {
  746. JUCE_IOS_AUDIO_LOG ("Creating the audio unit");
  747. if (audioUnit != nullptr)
  748. {
  749. AudioComponentInstanceDispose (audioUnit);
  750. audioUnit = nullptr;
  751. }
  752. AudioComponentDescription desc;
  753. desc.componentType = kAudioUnitType_Output;
  754. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  755. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  756. desc.componentFlags = 0;
  757. desc.componentFlagsMask = 0;
  758. AudioComponent comp = AudioComponentFindNext (nullptr, &desc);
  759. AudioComponentInstanceNew (comp, &audioUnit);
  760. if (audioUnit == nullptr)
  761. return false;
  762. #if JucePlugin_Enable_IAA
  763. AudioComponentDescription appDesc;
  764. appDesc.componentType = JucePlugin_IAAType;
  765. appDesc.componentSubType = JucePlugin_IAASubType;
  766. appDesc.componentManufacturer = JucePlugin_ManufacturerCode;
  767. appDesc.componentFlags = 0;
  768. appDesc.componentFlagsMask = 0;
  769. OSStatus err = AudioOutputUnitPublish (&appDesc,
  770. CFSTR(JucePlugin_IAAName),
  771. JucePlugin_VersionCode,
  772. audioUnit);
  773. // This assert will be hit if the Inter-App Audio entitlement has not
  774. // been enabled, or the description being published with
  775. // AudioOutputUnitPublish is different from any in the AudioComponents
  776. // array in this application's .plist file.
  777. jassert (err == noErr);
  778. err = AudioUnitAddPropertyListener (audioUnit,
  779. kAudioUnitProperty_IsInterAppConnected,
  780. dispatchAudioUnitPropertyChange,
  781. this);
  782. jassert (err == noErr);
  783. AudioOutputUnitMIDICallbacks midiCallbacks;
  784. midiCallbacks.userData = this;
  785. midiCallbacks.MIDIEventProc = midiEventCallback;
  786. midiCallbacks.MIDISysExProc = midiSysExCallback;
  787. err = AudioUnitSetProperty (audioUnit,
  788. kAudioOutputUnitProperty_MIDICallbacks,
  789. kAudioUnitScope_Global,
  790. 0,
  791. &midiCallbacks,
  792. sizeof (midiCallbacks));
  793. jassert (err == noErr);
  794. #endif
  795. if (channelData.areInputChannelsAvailable())
  796. {
  797. const UInt32 one = 1;
  798. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  799. }
  800. {
  801. AURenderCallbackStruct inputProc;
  802. inputProc.inputProc = processStatic;
  803. inputProc.inputProcRefCon = this;
  804. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  805. }
  806. {
  807. AudioStreamBasicDescription format;
  808. zerostruct (format);
  809. format.mSampleRate = sampleRate;
  810. format.mFormatID = kAudioFormatLinearPCM;
  811. format.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsNonInterleaved | kAudioFormatFlagsNativeEndian | kLinearPCMFormatFlagIsPacked;
  812. format.mBitsPerChannel = 8 * sizeof (float);
  813. format.mFramesPerPacket = 1;
  814. format.mChannelsPerFrame = (UInt32) jmax (channelData.inputs->numHardwareChannels, channelData.outputs->numHardwareChannels);
  815. format.mBytesPerFrame = format.mBytesPerPacket = sizeof (float);
  816. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  817. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  818. }
  819. AudioUnitInitialize (audioUnit);
  820. {
  821. // Querying the kAudioUnitProperty_MaximumFramesPerSlice property after calling AudioUnitInitialize
  822. // seems to be more reliable than calling it before.
  823. UInt32 framesPerSlice, dataSize = sizeof (framesPerSlice);
  824. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_MaximumFramesPerSlice,
  825. kAudioUnitScope_Global, 0, &framesPerSlice, &dataSize) == noErr
  826. && dataSize == sizeof (framesPerSlice)
  827. && static_cast<int> (framesPerSlice) != bufferSize)
  828. {
  829. JUCE_IOS_AUDIO_LOG ("Internal buffer size: " << String (framesPerSlice));
  830. channelData.setFloatBufferSize (static_cast<int> (framesPerSlice));
  831. }
  832. }
  833. AudioUnitAddPropertyListener (audioUnit, kAudioUnitProperty_StreamFormat, dispatchAudioUnitPropertyChange, this);
  834. return true;
  835. }
  836. void fillHostCallbackInfo (HostCallbackInfo& callbackInfo)
  837. {
  838. zerostruct (callbackInfo);
  839. UInt32 dataSize = sizeof (HostCallbackInfo);
  840. OSStatus err = AudioUnitGetProperty (audioUnit,
  841. kAudioUnitProperty_HostCallbacks,
  842. kAudioUnitScope_Global,
  843. 0,
  844. &callbackInfo,
  845. &dataSize);
  846. ignoreUnused (err);
  847. jassert (err == noErr);
  848. }
  849. void handleAudioTransportEvent (AudioUnitRemoteControlEvent event)
  850. {
  851. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_RemoteControlToHost,
  852. kAudioUnitScope_Global, 0, &event, sizeof (event));
  853. ignoreUnused (err);
  854. jassert (err == noErr);
  855. }
  856. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  857. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  858. static void fixAudioRouteIfSetToReceiver()
  859. {
  860. auto session = [AVAudioSession sharedInstance];
  861. auto route = session.currentRoute;
  862. for (AVAudioSessionPortDescription* port in route.outputs)
  863. {
  864. if ([port.portName isEqualToString: @"Receiver"])
  865. {
  866. JUCE_NSERROR_CHECK ([session overrideOutputAudioPort: AVAudioSessionPortOverrideSpeaker
  867. error: &error]);
  868. setAudioSessionActive (true);
  869. }
  870. }
  871. }
  872. void restart()
  873. {
  874. const ScopedLock sl (callbackLock);
  875. updateHardwareInfo();
  876. setTargetSampleRateAndBufferSize();
  877. if (isRunning)
  878. {
  879. if (audioUnit != nullptr)
  880. {
  881. AudioComponentInstanceDispose (audioUnit);
  882. audioUnit = nullptr;
  883. if (callback != nullptr)
  884. callback->audioDeviceStopped();
  885. }
  886. channelData.reconfigure (requestedInputChannels, requestedOutputChannels);
  887. createAudioUnit();
  888. if (audioUnit != nullptr)
  889. {
  890. isRunning = true;
  891. if (callback != nullptr)
  892. callback->audioDeviceAboutToStart (&owner);
  893. AudioOutputUnitStart (audioUnit);
  894. }
  895. }
  896. }
  897. void handleAsyncUpdate() override
  898. {
  899. restart();
  900. }
  901. void handleStreamFormatChange()
  902. {
  903. AudioStreamBasicDescription desc;
  904. zerostruct (desc);
  905. UInt32 dataSize = sizeof (desc);
  906. AudioUnitGetProperty (audioUnit,
  907. kAudioUnitProperty_StreamFormat,
  908. kAudioUnitScope_Output,
  909. 0,
  910. &desc,
  911. &dataSize);
  912. if (desc.mSampleRate != 0 && desc.mSampleRate != sampleRate)
  913. {
  914. JUCE_IOS_AUDIO_LOG ("Stream format has changed: Sample rate " << desc.mSampleRate);
  915. triggerAsyncUpdate();
  916. }
  917. }
  918. static void dispatchAudioUnitPropertyChange (void* data, AudioUnit unit, AudioUnitPropertyID propertyID,
  919. AudioUnitScope scope, AudioUnitElement element)
  920. {
  921. static_cast<Pimpl*> (data)->handleAudioUnitPropertyChange (unit, propertyID, scope, element);
  922. }
  923. static double getTimestampForMIDI()
  924. {
  925. return Time::getMillisecondCounter() / 1000.0;
  926. }
  927. static void midiEventCallback (void *client, UInt32 status, UInt32 data1, UInt32 data2, UInt32)
  928. {
  929. return static_cast<Pimpl*> (client)->handleMidiMessage (MidiMessage ((int) status,
  930. (int) data1,
  931. (int) data2,
  932. getTimestampForMIDI()));
  933. }
  934. static void midiSysExCallback (void *client, const UInt8 *data, UInt32 length)
  935. {
  936. return static_cast<Pimpl*> (client)->handleMidiMessage (MidiMessage (data, (int) length, getTimestampForMIDI()));
  937. }
  938. void handleMidiMessage (MidiMessage msg)
  939. {
  940. if (messageCollector != nullptr)
  941. messageCollector->addMessageToQueue (msg);
  942. }
  943. struct IOChannelData
  944. {
  945. class IOChannelConfig
  946. {
  947. public:
  948. IOChannelConfig (const bool isInput, const BigInteger requiredChannels)
  949. : hardwareChannelNames (getHardwareChannelNames (isInput)),
  950. numHardwareChannels (hardwareChannelNames.size()),
  951. areChannelsAccessible ((! isInput) || [AVAudioSession sharedInstance].isInputAvailable),
  952. activeChannels (limitRequiredChannelsToHardware (numHardwareChannels, requiredChannels)),
  953. numActiveChannels (activeChannels.countNumberOfSetBits()),
  954. activeChannelIndices (getActiveChannelIndices (activeChannels)),
  955. inactiveChannelIndices (getInactiveChannelIndices (activeChannelIndices, numHardwareChannels))
  956. {
  957. #if JUCE_IOS_AUDIO_LOGGING
  958. {
  959. String info;
  960. info << "Number of hardware channels: " << numHardwareChannels
  961. << ", Hardware channel names:";
  962. for (auto& name : hardwareChannelNames)
  963. info << " \"" << name << "\"";
  964. info << ", Are channels available: " << (areChannelsAccessible ? "yes" : "no")
  965. << ", Active channel indices:";
  966. for (auto i : activeChannelIndices)
  967. info << " " << i;
  968. info << ", Inactive channel indices:";
  969. for (auto i : inactiveChannelIndices)
  970. info << " " << i;
  971. JUCE_IOS_AUDIO_LOG ((isInput ? "Input" : "Output") << " channel configuration: {" << info << "}");
  972. }
  973. #endif
  974. }
  975. const StringArray hardwareChannelNames;
  976. const int numHardwareChannels;
  977. const bool areChannelsAccessible;
  978. const BigInteger activeChannels;
  979. const int numActiveChannels;
  980. const Array<int> activeChannelIndices, inactiveChannelIndices;
  981. private:
  982. static StringArray getHardwareChannelNames (const bool isInput)
  983. {
  984. StringArray result;
  985. auto route = [AVAudioSession sharedInstance].currentRoute;
  986. for (AVAudioSessionPortDescription* port in (isInput ? route.inputs : route.outputs))
  987. {
  988. for (AVAudioSessionChannelDescription* desc in port.channels)
  989. result.add (nsStringToJuce (desc.channelName));
  990. }
  991. // A fallback for the iOS simulator and older iOS versions
  992. if (result.isEmpty())
  993. return { "Left", "Right" };
  994. return result;
  995. }
  996. static BigInteger limitRequiredChannelsToHardware (const int numHardwareChannelsAvailable,
  997. BigInteger requiredChannels)
  998. {
  999. requiredChannels.setRange (numHardwareChannelsAvailable,
  1000. requiredChannels.getHighestBit() + 1,
  1001. false);
  1002. return requiredChannels;
  1003. }
  1004. static Array<int> getActiveChannelIndices (const BigInteger activeChannelsToIndex)
  1005. {
  1006. Array<int> result;
  1007. auto index = activeChannelsToIndex.findNextSetBit (0);
  1008. while (index != -1)
  1009. {
  1010. result.add (index);
  1011. index = activeChannelsToIndex.findNextSetBit (++index);
  1012. }
  1013. return result;
  1014. }
  1015. static Array<int> getInactiveChannelIndices (const Array<int>& activeIndices, int numChannels)
  1016. {
  1017. Array<int> result;
  1018. auto nextActiveChannel = activeIndices.begin();
  1019. for (int i = 0; i < numChannels; ++i)
  1020. if (nextActiveChannel != activeIndices.end() && i == *nextActiveChannel)
  1021. ++nextActiveChannel;
  1022. else
  1023. result.add (i);
  1024. return result;
  1025. }
  1026. };
  1027. void reconfigure (const BigInteger requiredInputChannels,
  1028. const BigInteger requiredOutputChannels)
  1029. {
  1030. inputs .reset (new IOChannelConfig (true, requiredInputChannels));
  1031. outputs.reset (new IOChannelConfig (false, requiredOutputChannels));
  1032. audioData.setSize (inputs->numActiveChannels + outputs->numActiveChannels,
  1033. audioData.getNumSamples());
  1034. }
  1035. int getFloatBufferSize() const
  1036. {
  1037. return audioData.getNumSamples();
  1038. }
  1039. void setFloatBufferSize (const int newSize)
  1040. {
  1041. audioData.setSize (audioData.getNumChannels(), newSize);
  1042. }
  1043. bool areInputChannelsAvailable() const
  1044. {
  1045. return inputs->areChannelsAccessible && inputs->numActiveChannels > 0;
  1046. }
  1047. std::unique_ptr<IOChannelConfig> inputs;
  1048. std::unique_ptr<IOChannelConfig> outputs;
  1049. AudioBuffer<float> audioData { 0, 0 };
  1050. };
  1051. IOChannelData channelData;
  1052. BigInteger requestedInputChannels, requestedOutputChannels;
  1053. bool isRunning = false;
  1054. AudioIODeviceCallback* callback = nullptr;
  1055. String lastError;
  1056. #if TARGET_IPHONE_SIMULATOR
  1057. static constexpr int defaultBufferSize = 512;
  1058. #else
  1059. static constexpr int defaultBufferSize = 256;
  1060. #endif
  1061. int targetBufferSize = defaultBufferSize, bufferSize = targetBufferSize;
  1062. double targetSampleRate = 44100.0, sampleRate = targetSampleRate;
  1063. Array<double> availableSampleRates;
  1064. Array<int> availableBufferSizes;
  1065. bool interAppAudioConnected = false;
  1066. MidiMessageCollector* messageCollector = nullptr;
  1067. WeakReference<iOSAudioIODeviceType> deviceType;
  1068. iOSAudioIODevice& owner;
  1069. CriticalSection callbackLock;
  1070. Atomic<bool> hardwareInfoNeedsUpdating { true };
  1071. AudioUnit audioUnit {};
  1072. SharedResourcePointer<AudioSessionHolder> sessionHolder;
  1073. bool firstHostTime;
  1074. Float64 lastSampleTime;
  1075. unsigned int lastNumFrames;
  1076. int xrun;
  1077. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  1078. };
  1079. //==============================================================================
  1080. iOSAudioIODevice::iOSAudioIODevice (iOSAudioIODeviceType* ioDeviceType, const String&, const String&)
  1081. : AudioIODevice (iOSAudioDeviceName, iOSAudioDeviceName),
  1082. pimpl (new Pimpl (ioDeviceType, *this))
  1083. {
  1084. }
  1085. //==============================================================================
  1086. String iOSAudioIODevice::open (const BigInteger& inChans, const BigInteger& outChans,
  1087. double requestedSampleRate, int requestedBufferSize)
  1088. {
  1089. return pimpl->open (inChans, outChans, requestedSampleRate, requestedBufferSize);
  1090. }
  1091. void iOSAudioIODevice::close() { pimpl->close(); }
  1092. void iOSAudioIODevice::start (AudioIODeviceCallback* callbackToUse) { pimpl->start (callbackToUse); }
  1093. void iOSAudioIODevice::stop() { pimpl->stop(); }
  1094. Array<double> iOSAudioIODevice::getAvailableSampleRates() { return pimpl->availableSampleRates; }
  1095. Array<int> iOSAudioIODevice::getAvailableBufferSizes() { return pimpl->availableBufferSizes; }
  1096. bool iOSAudioIODevice::setAudioPreprocessingEnabled (bool enabled) { return pimpl->setAudioPreprocessingEnabled (enabled); }
  1097. bool iOSAudioIODevice::isPlaying() { return pimpl->isRunning && pimpl->callback != nullptr; }
  1098. bool iOSAudioIODevice::isOpen() { return pimpl->isRunning; }
  1099. String iOSAudioIODevice::getLastError() { return pimpl->lastError; }
  1100. StringArray iOSAudioIODevice::getOutputChannelNames() { return pimpl->channelData.outputs->hardwareChannelNames; }
  1101. StringArray iOSAudioIODevice::getInputChannelNames() { return pimpl->channelData.inputs->areChannelsAccessible ? pimpl->channelData.inputs->hardwareChannelNames : StringArray(); }
  1102. int iOSAudioIODevice::getDefaultBufferSize() { return pimpl->defaultBufferSize; }
  1103. int iOSAudioIODevice::getCurrentBufferSizeSamples() { return pimpl->bufferSize; }
  1104. double iOSAudioIODevice::getCurrentSampleRate() { return pimpl->sampleRate; }
  1105. int iOSAudioIODevice::getCurrentBitDepth() { return 16; }
  1106. BigInteger iOSAudioIODevice::getActiveInputChannels() const { return pimpl->channelData.inputs->activeChannels; }
  1107. BigInteger iOSAudioIODevice::getActiveOutputChannels() const { return pimpl->channelData.outputs->activeChannels; }
  1108. int iOSAudioIODevice::getInputLatencyInSamples() { return roundToInt (pimpl->sampleRate * [AVAudioSession sharedInstance].inputLatency); }
  1109. int iOSAudioIODevice::getOutputLatencyInSamples() { return roundToInt (pimpl->sampleRate * [AVAudioSession sharedInstance].outputLatency); }
  1110. int iOSAudioIODevice::getXRunCount() const noexcept { return pimpl->xrun; }
  1111. void iOSAudioIODevice::setMidiMessageCollector (MidiMessageCollector* collector) { pimpl->messageCollector = collector; }
  1112. AudioPlayHead* iOSAudioIODevice::getAudioPlayHead() const { return pimpl.get(); }
  1113. bool iOSAudioIODevice::isInterAppAudioConnected() const { return pimpl->interAppAudioConnected; }
  1114. #if JUCE_MODULE_AVAILABLE_juce_graphics
  1115. Image iOSAudioIODevice::getIcon (int size) { return pimpl->getIcon (size); }
  1116. #endif
  1117. void iOSAudioIODevice::switchApplication() { return pimpl->switchApplication(); }
  1118. //==============================================================================
  1119. iOSAudioIODeviceType::iOSAudioIODeviceType()
  1120. : AudioIODeviceType (iOSAudioDeviceName)
  1121. {
  1122. sessionHolder->activeDeviceTypes.add (this);
  1123. }
  1124. iOSAudioIODeviceType::~iOSAudioIODeviceType()
  1125. {
  1126. sessionHolder->activeDeviceTypes.removeFirstMatchingValue (this);
  1127. }
  1128. // The list of devices is updated automatically
  1129. void iOSAudioIODeviceType::scanForDevices() {}
  1130. StringArray iOSAudioIODeviceType::getDeviceNames (bool) const { return { iOSAudioDeviceName }; }
  1131. int iOSAudioIODeviceType::getDefaultDeviceIndex (bool) const { return 0; }
  1132. int iOSAudioIODeviceType::getIndexOfDevice (AudioIODevice*, bool) const { return 0; }
  1133. bool iOSAudioIODeviceType::hasSeparateInputsAndOutputs() const { return false; }
  1134. AudioIODevice* iOSAudioIODeviceType::createDevice (const String& outputDeviceName, const String& inputDeviceName)
  1135. {
  1136. return new iOSAudioIODevice (this, outputDeviceName, inputDeviceName);
  1137. }
  1138. void iOSAudioIODeviceType::handleRouteChange (AVAudioSessionRouteChangeReason)
  1139. {
  1140. triggerAsyncUpdate();
  1141. }
  1142. void iOSAudioIODeviceType::handleAsyncUpdate()
  1143. {
  1144. callDeviceChangeListeners();
  1145. }
  1146. //==============================================================================
  1147. AudioSessionHolder::AudioSessionHolder() { nativeSession = [[iOSAudioSessionNative alloc] init: this]; }
  1148. AudioSessionHolder::~AudioSessionHolder() { [nativeSession release]; }
  1149. void AudioSessionHolder::handleStatusChange (bool enabled, const char* reason) const
  1150. {
  1151. for (auto device: activeDevices)
  1152. device->handleStatusChange (enabled, reason);
  1153. }
  1154. void AudioSessionHolder::handleRouteChange (AVAudioSessionRouteChangeReason reason)
  1155. {
  1156. for (auto device: activeDevices)
  1157. device->handleRouteChange (reason);
  1158. for (auto deviceType: activeDeviceTypes)
  1159. deviceType->handleRouteChange (reason);
  1160. }
  1161. #undef JUCE_NSERROR_CHECK
  1162. } // namespace juce