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.

1448 lines
54KB

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