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.

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