Audio plugin host https://kx.studio/carla
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.

1462 lines
54KB

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