Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_ios_Audio.cpp 55KB

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