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.

1508 lines
56KB

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