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.

814 lines
28KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. class iOSAudioIODevice;
  24. static const char* const iOSAudioDeviceName = "iOS Audio";
  25. //==============================================================================
  26. struct AudioSessionHolder
  27. {
  28. AudioSessionHolder();
  29. ~AudioSessionHolder();
  30. void handleStatusChange (bool enabled, const char* reason) const;
  31. void handleRouteChange (const char* reason) const;
  32. Array<iOSAudioIODevice*> activeDevices;
  33. id nativeSession;
  34. };
  35. static const char* getRoutingChangeReason (AVAudioSessionRouteChangeReason reason) noexcept
  36. {
  37. switch (reason)
  38. {
  39. case AVAudioSessionRouteChangeReasonNewDeviceAvailable: return "New device available";
  40. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: return "Old device unavailable";
  41. case AVAudioSessionRouteChangeReasonCategoryChange: return "Category change";
  42. case AVAudioSessionRouteChangeReasonOverride: return "Override";
  43. case AVAudioSessionRouteChangeReasonWakeFromSleep: return "Wake from sleep";
  44. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory: return "No suitable route for category";
  45. case AVAudioSessionRouteChangeReasonRouteConfigurationChange: return "Route configuration change";
  46. case AVAudioSessionRouteChangeReasonUnknown:
  47. default: return "Unknown";
  48. }
  49. }
  50. bool getNotificationValueForKey (NSNotification* notification, NSString* key, NSUInteger& value) noexcept
  51. {
  52. if (notification != nil)
  53. {
  54. if (NSDictionary* userInfo = [notification userInfo])
  55. {
  56. if (NSNumber* number = [userInfo objectForKey: key])
  57. {
  58. value = [number unsignedIntegerValue];
  59. return true;
  60. }
  61. }
  62. }
  63. jassertfalse;
  64. return false;
  65. }
  66. } // juce namespace
  67. //==============================================================================
  68. @interface iOSAudioSessionNative : NSObject
  69. {
  70. @private
  71. juce::AudioSessionHolder* audioSessionHolder;
  72. };
  73. - (id) init: (juce::AudioSessionHolder*) holder;
  74. - (void) dealloc;
  75. - (void) audioSessionDidChangeInterruptionType: (NSNotification*) notification;
  76. - (void) handleMediaServicesReset;
  77. - (void) handleMediaServicesLost;
  78. - (void) handleRouteChange: (NSNotification*) notification;
  79. @end
  80. @implementation iOSAudioSessionNative
  81. - (id) init: (juce::AudioSessionHolder*) holder
  82. {
  83. self = [super init];
  84. if (self != nil)
  85. {
  86. audioSessionHolder = holder;
  87. auto session = [AVAudioSession sharedInstance];
  88. auto centre = [NSNotificationCenter defaultCenter];
  89. [centre addObserver: self
  90. selector: @selector (audioSessionDidChangeInterruptionType:)
  91. name: AVAudioSessionInterruptionNotification
  92. object: session];
  93. [centre addObserver: self
  94. selector: @selector (handleMediaServicesLost)
  95. name: AVAudioSessionMediaServicesWereLostNotification
  96. object: session];
  97. [centre addObserver: self
  98. selector: @selector (handleMediaServicesReset)
  99. name: AVAudioSessionMediaServicesWereResetNotification
  100. object: session];
  101. [centre addObserver: self
  102. selector: @selector (handleRouteChange:)
  103. name: AVAudioSessionRouteChangeNotification
  104. object: session];
  105. }
  106. else
  107. {
  108. jassertfalse;
  109. }
  110. return self;
  111. }
  112. - (void) dealloc
  113. {
  114. [[NSNotificationCenter defaultCenter] removeObserver: self];
  115. [super dealloc];
  116. }
  117. - (void) audioSessionDidChangeInterruptionType: (NSNotification*) notification
  118. {
  119. NSUInteger value;
  120. if (juce::getNotificationValueForKey (notification, AVAudioSessionInterruptionTypeKey, value))
  121. {
  122. switch ((AVAudioSessionInterruptionType) value)
  123. {
  124. case AVAudioSessionInterruptionTypeBegan:
  125. audioSessionHolder->handleStatusChange (false, "AVAudioSessionInterruptionTypeBegan");
  126. break;
  127. case AVAudioSessionInterruptionTypeEnded:
  128. audioSessionHolder->handleStatusChange (true, "AVAudioSessionInterruptionTypeEnded");
  129. break;
  130. // No default so the code doesn't compile if this enum is extended.
  131. }
  132. }
  133. }
  134. - (void) handleMediaServicesReset
  135. {
  136. audioSessionHolder->handleStatusChange (true, "AVAudioSessionMediaServicesWereResetNotification");
  137. }
  138. - (void) handleMediaServicesLost
  139. {
  140. audioSessionHolder->handleStatusChange (false, "AVAudioSessionMediaServicesWereLostNotification");
  141. }
  142. - (void) handleRouteChange: (NSNotification*) notification
  143. {
  144. NSUInteger value;
  145. if (juce::getNotificationValueForKey (notification, AVAudioSessionRouteChangeReasonKey, value))
  146. audioSessionHolder->handleRouteChange (juce::getRoutingChangeReason ((AVAudioSessionRouteChangeReason) value));
  147. }
  148. @end
  149. //==============================================================================
  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 iOSAudioIODevice : public AudioIODevice
  170. {
  171. public:
  172. iOSAudioIODevice (const String& deviceName)
  173. : AudioIODevice (deviceName, iOSAudioDeviceName)
  174. {
  175. sessionHolder->activeDevices.add (this);
  176. updateSampleRateAndAudioInput();
  177. }
  178. ~iOSAudioIODevice()
  179. {
  180. sessionHolder->activeDevices.removeFirstMatchingValue (this);
  181. close();
  182. }
  183. StringArray getOutputChannelNames() override
  184. {
  185. return { "Left", "Right" };
  186. }
  187. StringArray getInputChannelNames() override
  188. {
  189. if (audioInputIsAvailable)
  190. return { "Left", "Right" };
  191. return {};
  192. }
  193. static void setAudioSessionActive (bool enabled)
  194. {
  195. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setActive: enabled
  196. error: &error]);
  197. }
  198. static double trySampleRate (double rate)
  199. {
  200. auto session = [AVAudioSession sharedInstance];
  201. JUCE_NSERROR_CHECK ([session setPreferredSampleRate: rate
  202. error: &error]);
  203. return session.sampleRate;
  204. }
  205. Array<double> getAvailableSampleRates() override
  206. {
  207. Array<double> rates;
  208. // Important: the supported audio sample rates change on the iPhone 6S
  209. // depending on whether the headphones are plugged in or not!
  210. setAudioSessionActive (true);
  211. const double lowestRate = trySampleRate (4000);
  212. const double highestRate = trySampleRate (192000);
  213. for (double rate = lowestRate; rate <= highestRate; rate += 1000)
  214. {
  215. const double supportedRate = trySampleRate (rate);
  216. rates.addIfNotAlreadyThere (supportedRate);
  217. rate = jmax (rate, supportedRate);
  218. }
  219. trySampleRate (sampleRate);
  220. for (auto r : rates)
  221. {
  222. ignoreUnused (r);
  223. JUCE_IOS_AUDIO_LOG ("available rate = " + String (r, 0) + "Hz");
  224. }
  225. return rates;
  226. }
  227. Array<int> getAvailableBufferSizes() override
  228. {
  229. Array<int> r;
  230. for (int i = 6; i < 12; ++i)
  231. r.add (1 << i);
  232. return r;
  233. }
  234. int getDefaultBufferSize() override
  235. {
  236. #if TARGET_IPHONE_SIMULATOR
  237. return 512;
  238. #else
  239. return 256;
  240. #endif
  241. }
  242. String open (const BigInteger& inputChannelsWanted,
  243. const BigInteger& outputChannelsWanted,
  244. double targetSampleRate, int bufferSize) override
  245. {
  246. close();
  247. lastError.clear();
  248. preferredBufferSize = bufferSize <= 0 ? getDefaultBufferSize()
  249. : bufferSize;
  250. // xxx set up channel mapping
  251. activeOutputChans = outputChannelsWanted;
  252. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  253. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  254. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  255. activeInputChans = inputChannelsWanted;
  256. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  257. numInputChannels = activeInputChans.countNumberOfSetBits();
  258. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  259. setAudioSessionActive (true);
  260. // Set the session category & options:
  261. auto session = [AVAudioSession sharedInstance];
  262. const bool useInputs = (numInputChannels > 0 && audioInputIsAvailable);
  263. NSString* category = (useInputs ? AVAudioSessionCategoryPlayAndRecord : AVAudioSessionCategoryPlayback);
  264. NSUInteger options = AVAudioSessionCategoryOptionMixWithOthers; // Alternatively AVAudioSessionCategoryOptionDuckOthers
  265. if (useInputs) // These options are only valid for category = PlayAndRecord
  266. options |= (AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionAllowBluetooth);
  267. JUCE_NSERROR_CHECK ([session setCategory: category
  268. withOptions: options
  269. error: &error]);
  270. fixAudioRouteIfSetToReceiver();
  271. // Set the sample rate
  272. trySampleRate (targetSampleRate);
  273. updateSampleRateAndAudioInput();
  274. updateCurrentBufferSize();
  275. prepareFloatBuffers (actualBufferSize);
  276. isRunning = true;
  277. handleRouteChange ("Started AudioUnit");
  278. lastError = (audioUnit != 0 ? "" : "Couldn't open the device");
  279. setAudioSessionActive (true);
  280. return lastError;
  281. }
  282. void close() override
  283. {
  284. if (isRunning)
  285. {
  286. isRunning = false;
  287. if (audioUnit != 0)
  288. {
  289. AudioOutputUnitStart (audioUnit);
  290. AudioComponentInstanceDispose (audioUnit);
  291. audioUnit = 0;
  292. }
  293. setAudioSessionActive (false);
  294. }
  295. }
  296. bool isOpen() override { return isRunning; }
  297. int getCurrentBufferSizeSamples() override { return actualBufferSize; }
  298. double getCurrentSampleRate() override { return sampleRate; }
  299. int getCurrentBitDepth() override { return 16; }
  300. BigInteger getActiveOutputChannels() const override { return activeOutputChans; }
  301. BigInteger getActiveInputChannels() const override { return activeInputChans; }
  302. int getOutputLatencyInSamples() override { return roundToInt (getCurrentSampleRate() * [AVAudioSession sharedInstance].outputLatency); }
  303. int getInputLatencyInSamples() override { return roundToInt (getCurrentSampleRate() * [AVAudioSession sharedInstance].inputLatency); }
  304. void start (AudioIODeviceCallback* newCallback) override
  305. {
  306. if (isRunning && callback != newCallback)
  307. {
  308. if (newCallback != nullptr)
  309. newCallback->audioDeviceAboutToStart (this);
  310. const ScopedLock sl (callbackLock);
  311. callback = newCallback;
  312. }
  313. }
  314. void stop() override
  315. {
  316. if (isRunning)
  317. {
  318. AudioIODeviceCallback* lastCallback;
  319. {
  320. const ScopedLock sl (callbackLock);
  321. lastCallback = callback;
  322. callback = nullptr;
  323. }
  324. if (lastCallback != nullptr)
  325. lastCallback->audioDeviceStopped();
  326. }
  327. }
  328. bool isPlaying() override { return isRunning && callback != nullptr; }
  329. String getLastError() override { return lastError; }
  330. bool setAudioPreprocessingEnabled (bool enable) override
  331. {
  332. auto session = [AVAudioSession sharedInstance];
  333. NSString* mode = (enable ? AVAudioSessionModeMeasurement
  334. : AVAudioSessionModeDefault);
  335. JUCE_NSERROR_CHECK ([session setMode: mode
  336. error: &error]);
  337. return session.mode == mode;
  338. }
  339. void invokeAudioDeviceErrorCallback (const String& reason)
  340. {
  341. const ScopedLock sl (callbackLock);
  342. if (callback != nullptr)
  343. callback->audioDeviceError (reason);
  344. }
  345. void handleStatusChange (bool enabled, const char* reason)
  346. {
  347. const ScopedLock myScopedLock (callbackLock);
  348. JUCE_IOS_AUDIO_LOG ("handleStatusChange: enabled: " << (int) enabled << ", reason: " << reason);
  349. isRunning = enabled;
  350. setAudioSessionActive (enabled);
  351. if (enabled)
  352. AudioOutputUnitStart (audioUnit);
  353. else
  354. AudioOutputUnitStop (audioUnit);
  355. if (! enabled)
  356. invokeAudioDeviceErrorCallback (reason);
  357. }
  358. void handleRouteChange (const char* reason)
  359. {
  360. const ScopedLock myScopedLock (callbackLock);
  361. JUCE_IOS_AUDIO_LOG ("handleRouteChange: reason: " << reason);
  362. fixAudioRouteIfSetToReceiver();
  363. if (isRunning)
  364. {
  365. invokeAudioDeviceErrorCallback (reason);
  366. updateSampleRateAndAudioInput();
  367. updateCurrentBufferSize();
  368. createAudioUnit();
  369. setAudioSessionActive (true);
  370. if (audioUnit != 0)
  371. {
  372. UInt32 formatSize = sizeof (format);
  373. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  374. AudioOutputUnitStart (audioUnit);
  375. }
  376. if (callback != nullptr)
  377. callback->audioDeviceAboutToStart (this);
  378. }
  379. }
  380. private:
  381. //==============================================================================
  382. SharedResourcePointer<AudioSessionHolder> sessionHolder;
  383. CriticalSection callbackLock;
  384. NSTimeInterval sampleRate = 0;
  385. int numInputChannels = 2, numOutputChannels = 2;
  386. int preferredBufferSize = 0, actualBufferSize = 0;
  387. bool isRunning = false;
  388. String lastError;
  389. AudioStreamBasicDescription format;
  390. AudioUnit audioUnit {};
  391. bool audioInputIsAvailable = false;
  392. AudioIODeviceCallback* callback = nullptr;
  393. BigInteger activeOutputChans, activeInputChans;
  394. AudioSampleBuffer floatData;
  395. float* inputChannels[3];
  396. float* outputChannels[3];
  397. bool monoInputChannelNumber, monoOutputChannelNumber;
  398. void prepareFloatBuffers (int bufferSize)
  399. {
  400. if (numInputChannels + numOutputChannels > 0)
  401. {
  402. floatData.setSize (numInputChannels + numOutputChannels, bufferSize);
  403. zeromem (inputChannels, sizeof (inputChannels));
  404. zeromem (outputChannels, sizeof (outputChannels));
  405. for (int i = 0; i < numInputChannels; ++i)
  406. inputChannels[i] = floatData.getWritePointer (i);
  407. for (int i = 0; i < numOutputChannels; ++i)
  408. outputChannels[i] = floatData.getWritePointer (i + numInputChannels);
  409. }
  410. }
  411. //==============================================================================
  412. OSStatus process (AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  413. const UInt32 numFrames, AudioBufferList* data)
  414. {
  415. OSStatus err = noErr;
  416. if (audioInputIsAvailable && numInputChannels > 0)
  417. err = AudioUnitRender (audioUnit, flags, time, 1, numFrames, data);
  418. const ScopedTryLock stl (callbackLock);
  419. if (stl.isLocked() && callback != nullptr)
  420. {
  421. if ((int) numFrames > floatData.getNumSamples())
  422. prepareFloatBuffers ((int) numFrames);
  423. if (audioInputIsAvailable && numInputChannels > 0)
  424. {
  425. short* shortData = (short*) data->mBuffers[0].mData;
  426. if (numInputChannels >= 2)
  427. {
  428. for (UInt32 i = 0; i < numFrames; ++i)
  429. {
  430. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  431. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  432. }
  433. }
  434. else
  435. {
  436. if (monoInputChannelNumber > 0)
  437. ++shortData;
  438. for (UInt32 i = 0; i < numFrames; ++i)
  439. {
  440. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  441. ++shortData;
  442. }
  443. }
  444. }
  445. else
  446. {
  447. for (int i = numInputChannels; --i >= 0;)
  448. zeromem (inputChannels[i], sizeof (float) * numFrames);
  449. }
  450. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  451. outputChannels, numOutputChannels, (int) numFrames);
  452. short* const shortData = (short*) data->mBuffers[0].mData;
  453. int n = 0;
  454. if (numOutputChannels >= 2)
  455. {
  456. for (UInt32 i = 0; i < numFrames; ++i)
  457. {
  458. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  459. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  460. }
  461. }
  462. else if (numOutputChannels == 1)
  463. {
  464. for (UInt32 i = 0; i < numFrames; ++i)
  465. {
  466. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  467. shortData [n++] = s;
  468. shortData [n++] = s;
  469. }
  470. }
  471. else
  472. {
  473. zeromem (data->mBuffers[0].mData, 2 * sizeof (short) * numFrames);
  474. }
  475. }
  476. else
  477. {
  478. zeromem (data->mBuffers[0].mData, 2 * sizeof (short) * numFrames);
  479. }
  480. return err;
  481. }
  482. void updateSampleRateAndAudioInput()
  483. {
  484. auto session = [AVAudioSession sharedInstance];
  485. sampleRate = session.sampleRate;
  486. audioInputIsAvailable = session.isInputAvailable;
  487. actualBufferSize = roundToInt (sampleRate * session.IOBufferDuration);
  488. JUCE_IOS_AUDIO_LOG ("AVAudioSession: sampleRate: " << sampleRate
  489. << "Hz, audioInputAvailable: " << (int) audioInputIsAvailable);
  490. }
  491. void updateCurrentBufferSize()
  492. {
  493. NSTimeInterval bufferDuration = sampleRate > 0 ? (NSTimeInterval) ((preferredBufferSize + 1) / sampleRate) : 0.0;
  494. JUCE_NSERROR_CHECK ([[AVAudioSession sharedInstance] setPreferredIOBufferDuration: bufferDuration
  495. error: &error]);
  496. updateSampleRateAndAudioInput();
  497. }
  498. //==============================================================================
  499. static OSStatus processStatic (void* client, AudioUnitRenderActionFlags* flags, const AudioTimeStamp* time,
  500. UInt32 /*busNumber*/, UInt32 numFrames, AudioBufferList* data)
  501. {
  502. return static_cast<iOSAudioIODevice*> (client)->process (flags, time, numFrames, data);
  503. }
  504. //==============================================================================
  505. void resetFormat (const int numChannels) noexcept
  506. {
  507. zerostruct (format);
  508. format.mFormatID = kAudioFormatLinearPCM;
  509. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kAudioFormatFlagsNativeEndian;
  510. format.mBitsPerChannel = 8 * sizeof (short);
  511. format.mChannelsPerFrame = (UInt32) numChannels;
  512. format.mFramesPerPacket = 1;
  513. format.mBytesPerFrame = format.mBytesPerPacket = (UInt32) numChannels * sizeof (short);
  514. }
  515. bool createAudioUnit()
  516. {
  517. if (audioUnit != 0)
  518. {
  519. AudioComponentInstanceDispose (audioUnit);
  520. audioUnit = 0;
  521. }
  522. resetFormat (2);
  523. AudioComponentDescription desc;
  524. desc.componentType = kAudioUnitType_Output;
  525. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  526. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  527. desc.componentFlags = 0;
  528. desc.componentFlagsMask = 0;
  529. AudioComponent comp = AudioComponentFindNext (0, &desc);
  530. AudioComponentInstanceNew (comp, &audioUnit);
  531. if (audioUnit == 0)
  532. return false;
  533. if (numInputChannels > 0)
  534. {
  535. const UInt32 one = 1;
  536. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  537. }
  538. {
  539. AudioChannelLayout layout;
  540. layout.mChannelBitmap = 0;
  541. layout.mNumberChannelDescriptions = 0;
  542. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  543. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  544. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  545. }
  546. {
  547. AURenderCallbackStruct inputProc;
  548. inputProc.inputProc = processStatic;
  549. inputProc.inputProcRefCon = this;
  550. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  551. }
  552. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  553. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  554. UInt32 framesPerSlice;
  555. UInt32 dataSize = sizeof (framesPerSlice);
  556. AudioUnitInitialize (audioUnit);
  557. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_MaximumFramesPerSlice,
  558. kAudioUnitScope_Global, 0, &actualBufferSize, sizeof (actualBufferSize));
  559. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_MaximumFramesPerSlice,
  560. kAudioUnitScope_Global, 0, &framesPerSlice, &dataSize) == noErr
  561. && dataSize == sizeof (framesPerSlice) && static_cast<int> (framesPerSlice) != actualBufferSize)
  562. {
  563. actualBufferSize = static_cast<int> (framesPerSlice);
  564. prepareFloatBuffers (actualBufferSize);
  565. }
  566. return true;
  567. }
  568. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  569. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  570. static void fixAudioRouteIfSetToReceiver()
  571. {
  572. auto session = [AVAudioSession sharedInstance];
  573. auto route = session.currentRoute;
  574. for (AVAudioSessionPortDescription* port in route.inputs)
  575. {
  576. ignoreUnused (port);
  577. JUCE_IOS_AUDIO_LOG ("AVAudioSession: input: " << [port.description UTF8String]);
  578. }
  579. for (AVAudioSessionPortDescription* port in route.outputs)
  580. {
  581. JUCE_IOS_AUDIO_LOG ("AVAudioSession: output: " << [port.description UTF8String]);
  582. if ([port.portName isEqualToString: @"Receiver"])
  583. {
  584. JUCE_NSERROR_CHECK ([session overrideOutputAudioPort: AVAudioSessionPortOverrideSpeaker
  585. error: &error]);
  586. setAudioSessionActive (true);
  587. }
  588. }
  589. }
  590. JUCE_DECLARE_NON_COPYABLE (iOSAudioIODevice)
  591. };
  592. //==============================================================================
  593. class iOSAudioIODeviceType : public AudioIODeviceType
  594. {
  595. public:
  596. iOSAudioIODeviceType() : AudioIODeviceType (iOSAudioDeviceName) {}
  597. void scanForDevices() {}
  598. StringArray getDeviceNames (bool /*wantInputNames*/) const { return StringArray (iOSAudioDeviceName); }
  599. int getDefaultDeviceIndex (bool /*forInput*/) const { return 0; }
  600. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const { return d != nullptr ? 0 : -1; }
  601. bool hasSeparateInputsAndOutputs() const { return false; }
  602. AudioIODevice* createDevice (const String& outputDeviceName, const String& inputDeviceName)
  603. {
  604. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  605. return new iOSAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName : inputDeviceName);
  606. return nullptr;
  607. }
  608. private:
  609. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSAudioIODeviceType)
  610. };
  611. //==============================================================================
  612. AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()
  613. {
  614. return new iOSAudioIODeviceType();
  615. }
  616. //==============================================================================
  617. AudioSessionHolder::AudioSessionHolder() { nativeSession = [[iOSAudioSessionNative alloc] init: this]; }
  618. AudioSessionHolder::~AudioSessionHolder() { [nativeSession release]; }
  619. void AudioSessionHolder::handleStatusChange (bool enabled, const char* reason) const
  620. {
  621. for (auto device: activeDevices)
  622. device->handleStatusChange (enabled, reason);
  623. }
  624. void AudioSessionHolder::handleRouteChange (const char* reason) const
  625. {
  626. struct RouteChangeMessage : public CallbackMessage
  627. {
  628. RouteChangeMessage (Array<iOSAudioIODevice*> devs, const char* r)
  629. : devices (devs), changeReason (r)
  630. {
  631. }
  632. void messageCallback() override
  633. {
  634. for (auto device: devices)
  635. device->handleRouteChange (changeReason);
  636. }
  637. Array<iOSAudioIODevice*> devices;
  638. const char* changeReason;
  639. };
  640. (new RouteChangeMessage (activeDevices, reason))->post();
  641. }
  642. #undef JUCE_NSERROR_CHECK