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.

1445 lines
53KB

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