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.

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