jack2 codebase
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.

1964 lines
75KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include "JackCoreAudioDriver.h"
  16. #include "JackEngineControl.h"
  17. #include "JackMachThread.h"
  18. #include "JackGraphManager.h"
  19. #include "JackError.h"
  20. #include "JackClientControl.h"
  21. #include "JackDriverLoader.h"
  22. #include "JackGlobals.h"
  23. #include "JackTools.h"
  24. #include "JackCompilerDeps.h"
  25. #include <iostream>
  26. #include <CoreServices/CoreServices.h>
  27. #include <CoreFoundation/CFNumber.h>
  28. namespace Jack
  29. {
  30. static void Print4CharCode(const char* msg, long c)
  31. {
  32. UInt32 __4CC_number = (c);
  33. char __4CC_string[5];
  34. *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
  35. __4CC_string[4] = 0;
  36. jack_log("%s'%s'", (msg), __4CC_string);
  37. }
  38. static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
  39. {
  40. jack_log("- - - - - - - - - - - - - - - - - - - -");
  41. jack_log(" Sample Rate:%f", inDesc->mSampleRate);
  42. jack_log(" Format ID:%.*s", (int) sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
  43. jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
  44. jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
  45. jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
  46. jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
  47. jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
  48. jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
  49. jack_log("- - - - - - - - - - - - - - - - - - - -\n");
  50. }
  51. static void printError(OSStatus err)
  52. {
  53. switch (err) {
  54. case kAudioHardwareNoError:
  55. jack_log("error code : kAudioHardwareNoError");
  56. break;
  57. case kAudioConverterErr_FormatNotSupported:
  58. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  59. break;
  60. case kAudioConverterErr_OperationNotSupported:
  61. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  62. break;
  63. case kAudioConverterErr_PropertyNotSupported:
  64. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  65. break;
  66. case kAudioConverterErr_InvalidInputSize:
  67. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  68. break;
  69. case kAudioConverterErr_InvalidOutputSize:
  70. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  71. break;
  72. case kAudioConverterErr_UnspecifiedError:
  73. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  74. break;
  75. case kAudioConverterErr_BadPropertySizeError:
  76. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  77. break;
  78. case kAudioConverterErr_RequiresPacketDescriptionsError:
  79. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  80. break;
  81. case kAudioConverterErr_InputSampleRateOutOfRange:
  82. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  83. break;
  84. case kAudioConverterErr_OutputSampleRateOutOfRange:
  85. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  86. break;
  87. case kAudioHardwareNotRunningError:
  88. jack_log("error code : kAudioHardwareNotRunningError");
  89. break;
  90. case kAudioHardwareUnknownPropertyError:
  91. jack_log("error code : kAudioHardwareUnknownPropertyError");
  92. break;
  93. case kAudioHardwareIllegalOperationError:
  94. jack_log("error code : kAudioHardwareIllegalOperationError");
  95. break;
  96. case kAudioHardwareBadDeviceError:
  97. jack_log("error code : kAudioHardwareBadDeviceError");
  98. break;
  99. case kAudioHardwareBadStreamError:
  100. jack_log("error code : kAudioHardwareBadStreamError");
  101. break;
  102. case kAudioDeviceUnsupportedFormatError:
  103. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  104. break;
  105. case kAudioDevicePermissionsError:
  106. jack_log("error code : kAudioDevicePermissionsError");
  107. break;
  108. case kAudioHardwareBadObjectError:
  109. jack_log("error code : kAudioHardwareBadObjectError");
  110. break;
  111. case kAudioHardwareUnsupportedOperationError:
  112. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  113. break;
  114. default:
  115. Print4CharCode("error code : unknown", err);
  116. break;
  117. }
  118. }
  119. static OSStatus DisplayDeviceNames()
  120. {
  121. UInt32 size;
  122. Boolean isWritable;
  123. int i, deviceNum;
  124. OSStatus err;
  125. CFStringRef UIname;
  126. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  127. if (err != noErr)
  128. return err;
  129. deviceNum = size / sizeof(AudioDeviceID);
  130. AudioDeviceID devices[deviceNum];
  131. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  132. if (err != noErr)
  133. return err;
  134. for (i = 0; i < deviceNum; i++) {
  135. char device_name[256];
  136. char internal_name[256];
  137. size = sizeof(CFStringRef);
  138. UIname = NULL;
  139. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  140. if (err == noErr) {
  141. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  142. } else {
  143. goto error;
  144. }
  145. size = 256;
  146. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  147. if (err != noErr)
  148. return err;
  149. jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
  150. }
  151. return noErr;
  152. error:
  153. if (UIname != NULL)
  154. CFRelease(UIname);
  155. return err;
  156. }
  157. static CFStringRef GetDeviceName(AudioDeviceID id)
  158. {
  159. UInt32 size = sizeof(CFStringRef);
  160. CFStringRef UIname;
  161. OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  162. return (err == noErr) ? UIname : NULL;
  163. }
  164. OSStatus JackCoreAudioDriver::Render(void *inRefCon,
  165. AudioUnitRenderActionFlags *ioActionFlags,
  166. const AudioTimeStamp *inTimeStamp,
  167. UInt32 inBusNumber,
  168. UInt32 inNumberFrames,
  169. AudioBufferList *ioData)
  170. {
  171. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inRefCon;
  172. driver->fActionFags = ioActionFlags;
  173. driver->fCurrentTime = (AudioTimeStamp *)inTimeStamp;
  174. driver->fDriverOutputData = ioData;
  175. driver->CycleTakeBeginTime();
  176. return driver->Process();
  177. }
  178. int JackCoreAudioDriver::Read()
  179. {
  180. AudioUnitRender(fAUHAL, fActionFags, fCurrentTime, 1, fEngineControl->fBufferSize, fJackInputData);
  181. return 0;
  182. }
  183. int JackCoreAudioDriver::Write()
  184. {
  185. for (int i = 0; i < fPlaybackChannels; i++) {
  186. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[i]) > 0) {
  187. float* buffer = GetOutputBuffer(i);
  188. int size = sizeof(float) * fEngineControl->fBufferSize;
  189. memcpy((float*)fDriverOutputData->mBuffers[i].mData, buffer, size);
  190. // Monitor ports
  191. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[i]) > 0)
  192. memcpy(GetMonitorBuffer(i), buffer, size);
  193. } else {
  194. memset((float*)fDriverOutputData->mBuffers[i].mData, 0, sizeof(float) * fEngineControl->fBufferSize);
  195. }
  196. }
  197. return 0;
  198. }
  199. // Will run only once
  200. OSStatus JackCoreAudioDriver::MeasureCallback(AudioDeviceID inDevice,
  201. const AudioTimeStamp* inNow,
  202. const AudioBufferList* inInputData,
  203. const AudioTimeStamp* inInputTime,
  204. AudioBufferList* outOutputData,
  205. const AudioTimeStamp* inOutputTime,
  206. void* inClientData)
  207. {
  208. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  209. AudioDeviceStop(driver->fDeviceID, MeasureCallback);
  210. jack_log("JackCoreAudioDriver::MeasureCallback called");
  211. JackMachThread::GetParams(pthread_self(), &driver->fEngineControl->fPeriod, &driver->fEngineControl->fComputation, &driver->fEngineControl->fConstraint);
  212. if (driver->fComputationGrain > 0) {
  213. jack_log("JackCoreAudioDriver::MeasureCallback : RT thread computation setup to %d percent of period", int(driver->fComputationGrain * 100));
  214. driver->fEngineControl->fComputation = driver->fEngineControl->fPeriod * driver->fComputationGrain;
  215. }
  216. // Signal waiting start function...
  217. driver->fState = true;
  218. // Setup threadded based log function
  219. set_threaded_log_function();
  220. return noErr;
  221. }
  222. OSStatus JackCoreAudioDriver::SRNotificationCallback(AudioDeviceID inDevice,
  223. UInt32 inChannel,
  224. Boolean isInput,
  225. AudioDevicePropertyID inPropertyID,
  226. void* inClientData)
  227. {
  228. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  229. switch (inPropertyID) {
  230. case kAudioDevicePropertyNominalSampleRate: {
  231. jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  232. driver->fState = true;
  233. break;
  234. }
  235. }
  236. return noErr;
  237. }
  238. // A better implementation would possibly try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  239. OSStatus JackCoreAudioDriver::DeviceNotificationCallback(AudioDeviceID inDevice,
  240. UInt32 inChannel,
  241. Boolean isInput,
  242. AudioDevicePropertyID inPropertyID,
  243. void* inClientData)
  244. {
  245. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  246. switch (inPropertyID) {
  247. case kAudioDeviceProcessorOverload: {
  248. jack_error("JackCoreAudioDriver::DeviceNotificationCallback kAudioDeviceProcessorOverload");
  249. jack_time_t cur_time = GetMicroSeconds();
  250. driver->NotifyXRun(cur_time, float(cur_time - driver->fBeginDateUst)); // Better this value than nothing...
  251. break;
  252. }
  253. case kAudioDevicePropertyStreamConfiguration: {
  254. jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration : server will quit...");
  255. driver->NotifyFailure(JackBackendError, "Another application has changed the device configuration."); // Message length limited to JACK_MESSAGE_SIZE
  256. driver->CloseAUHAL();
  257. kill(JackTools::GetPID(), SIGINT);
  258. return kAudioHardwareUnsupportedOperationError;
  259. }
  260. case kAudioDevicePropertyNominalSampleRate: {
  261. jack_error("Cannot handle kAudioDevicePropertyNominalSampleRate : server will quit...");
  262. driver->NotifyFailure(JackBackendError, "Another application has changed the sample rate."); // Message length limited to JACK_MESSAGE_SIZE
  263. driver->CloseAUHAL();
  264. kill(JackTools::GetPID(), SIGINT);
  265. return kAudioHardwareUnsupportedOperationError;
  266. }
  267. }
  268. return noErr;
  269. }
  270. OSStatus JackCoreAudioDriver::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  271. {
  272. UInt32 size = sizeof(AudioValueTranslation);
  273. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  274. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  275. if (inIUD == NULL) {
  276. return kAudioHardwareUnspecifiedError;
  277. } else {
  278. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  279. CFRelease(inIUD);
  280. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  281. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  282. }
  283. }
  284. OSStatus JackCoreAudioDriver::GetDefaultDevice(AudioDeviceID* id)
  285. {
  286. OSStatus res;
  287. UInt32 theSize = sizeof(UInt32);
  288. AudioDeviceID inDefault;
  289. AudioDeviceID outDefault;
  290. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  291. return res;
  292. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  293. return res;
  294. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  295. // Get the device only if default input and output are the same
  296. if (inDefault == outDefault) {
  297. *id = inDefault;
  298. return noErr;
  299. } else {
  300. jack_error("Default input and output devices are not the same !!");
  301. return kAudioHardwareBadDeviceError;
  302. }
  303. }
  304. OSStatus JackCoreAudioDriver::GetDefaultInputDevice(AudioDeviceID* id)
  305. {
  306. OSStatus res;
  307. UInt32 theSize = sizeof(UInt32);
  308. AudioDeviceID inDefault;
  309. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  310. return res;
  311. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  312. *id = inDefault;
  313. return noErr;
  314. }
  315. OSStatus JackCoreAudioDriver::GetDefaultOutputDevice(AudioDeviceID* id)
  316. {
  317. OSStatus res;
  318. UInt32 theSize = sizeof(UInt32);
  319. AudioDeviceID outDefault;
  320. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  321. return res;
  322. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  323. *id = outDefault;
  324. return noErr;
  325. }
  326. OSStatus JackCoreAudioDriver::GetDeviceNameFromID(AudioDeviceID id, char* name)
  327. {
  328. UInt32 size = 256;
  329. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  330. }
  331. OSStatus JackCoreAudioDriver::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  332. {
  333. OSStatus err = noErr;
  334. UInt32 outSize;
  335. Boolean outWritable;
  336. channelCount = 0;
  337. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  338. if (err == noErr) {
  339. AudioBufferList bufferList[outSize];
  340. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  341. if (err == noErr) {
  342. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  343. channelCount += bufferList->mBuffers[i].mNumberChannels;
  344. }
  345. }
  346. return err;
  347. }
  348. JackCoreAudioDriver::JackCoreAudioDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
  349. : JackAudioDriver(name, alias, engine, table),
  350. fJackInputData(NULL),
  351. fDriverOutputData(NULL),
  352. fPluginID(0),
  353. fState(false),
  354. fHogged(false),
  355. fIOUsage(1.f),
  356. fComputationGrain(-1.f)
  357. {}
  358. JackCoreAudioDriver::~JackCoreAudioDriver()
  359. {}
  360. OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
  361. {
  362. OSStatus osErr = noErr;
  363. AudioObjectPropertyAddress pluginAOPA;
  364. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  365. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  366. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  367. UInt32 outDataSize;
  368. if (fPluginID > 0) {
  369. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  370. if (osErr != noErr) {
  371. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  372. printError(osErr);
  373. return osErr;
  374. }
  375. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  376. if (osErr != noErr) {
  377. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  378. printError(osErr);
  379. return osErr;
  380. }
  381. }
  382. return noErr;
  383. }
  384. OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  385. {
  386. OSStatus err = noErr;
  387. AudioObjectID sub_device[32];
  388. UInt32 outSize = sizeof(sub_device);
  389. err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  390. vector<AudioDeviceID> captureDeviceIDArray;
  391. if (err != noErr) {
  392. jack_log("Input device does not have subdevices");
  393. captureDeviceIDArray.push_back(captureDeviceID);
  394. } else {
  395. int num_devices = outSize / sizeof(AudioObjectID);
  396. jack_log("Input device has %d subdevices", num_devices);
  397. for (int i = 0; i < num_devices; i++) {
  398. captureDeviceIDArray.push_back(sub_device[i]);
  399. }
  400. }
  401. err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  402. vector<AudioDeviceID> playbackDeviceIDArray;
  403. if (err != noErr) {
  404. jack_log("Output device does not have subdevices");
  405. playbackDeviceIDArray.push_back(playbackDeviceID);
  406. } else {
  407. int num_devices = outSize / sizeof(AudioObjectID);
  408. jack_log("Output device has %d subdevices", num_devices);
  409. for (int i = 0; i < num_devices; i++) {
  410. playbackDeviceIDArray.push_back(sub_device[i]);
  411. }
  412. }
  413. return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
  414. }
  415. OSStatus JackCoreAudioDriver::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  416. {
  417. OSStatus osErr = noErr;
  418. UInt32 outSize;
  419. Boolean outWritable;
  420. //---------------------------------------------------------------------------
  421. // Setup SR of both devices otherwise creating AD may fail...
  422. //---------------------------------------------------------------------------
  423. UInt32 keptclockdomain = 0;
  424. UInt32 clockdomain = 0;
  425. outSize = sizeof(UInt32);
  426. bool clock_drift = false;
  427. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  428. if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
  429. jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of input device");
  430. } else {
  431. // Check clock domain
  432. osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  433. if (osErr != 0) {
  434. jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  435. printError(osErr);
  436. } else {
  437. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  438. jack_log("JackCoreAudioDriver::CreateAggregateDevice : input clockdomain = %d", clockdomain);
  439. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  440. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  441. clock_drift = true;
  442. }
  443. }
  444. }
  445. }
  446. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  447. if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
  448. jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of output device");
  449. } else {
  450. // Check clock domain
  451. osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  452. if (osErr != 0) {
  453. jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  454. printError(osErr);
  455. } else {
  456. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  457. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output clockdomain = %d", clockdomain);
  458. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  459. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  460. clock_drift = true;
  461. }
  462. }
  463. }
  464. }
  465. //---------------------------------------------------------------------------
  466. // Start to create a new aggregate by getting the base audio hardware plugin
  467. //---------------------------------------------------------------------------
  468. char device_name[256];
  469. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  470. GetDeviceNameFromID(captureDeviceID[i], device_name);
  471. jack_info("Separated input = '%s' ", device_name);
  472. }
  473. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  474. GetDeviceNameFromID(playbackDeviceID[i], device_name);
  475. jack_info("Separated output = '%s' ", device_name);
  476. }
  477. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  478. if (osErr != noErr) {
  479. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
  480. printError(osErr);
  481. return osErr;
  482. }
  483. AudioValueTranslation pluginAVT;
  484. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  485. pluginAVT.mInputData = &inBundleRef;
  486. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  487. pluginAVT.mOutputData = &fPluginID;
  488. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  489. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  490. if (osErr != noErr) {
  491. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
  492. printError(osErr);
  493. return osErr;
  494. }
  495. //-------------------------------------------------
  496. // Create a CFDictionary for our aggregate device
  497. //-------------------------------------------------
  498. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  499. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  500. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  501. // add the name of the device to the dictionary
  502. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  503. // add our choice of UID for the aggregate device to the dictionary
  504. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  505. // add a "private aggregate key" to the dictionary
  506. int value = 1;
  507. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  508. SInt32 system;
  509. Gestalt(gestaltSystemVersion, &system);
  510. jack_log("JackCoreAudioDriver::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
  511. // Starting with 10.5.4 systems, the AD can be internal... (better)
  512. if (system < 0x00001054) {
  513. jack_log("JackCoreAudioDriver::CreateAggregateDevice : public aggregate device....");
  514. } else {
  515. jack_log("JackCoreAudioDriver::CreateAggregateDevice : private aggregate device....");
  516. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  517. }
  518. // Prepare sub-devices for clock drift compensation
  519. CFMutableArrayRef subDevicesArrayClock = NULL;
  520. if (clock_drift) {
  521. if (fClockDriftCompensate) {
  522. subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  523. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  524. CFStringRef UID = GetDeviceName(captureDeviceID[i]);
  525. if (UID) {
  526. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  527. jack_info("JackCoreAudioDriver::CreateAggregateDevice : IN kAudioSubDeviceDriftCompensationKey");
  528. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  529. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  530. //CFRelease(UID);
  531. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  532. }
  533. }
  534. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  535. CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
  536. if (UID) {
  537. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  538. jack_info("JackCoreAudioDriver::CreateAggregateDevice : OUT kAudioSubDeviceDriftCompensationKey");
  539. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  540. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  541. //CFRelease(UID);
  542. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  543. }
  544. }
  545. // add sub-device clock array for the aggregate device to the dictionary
  546. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
  547. } else {
  548. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock and -s is not used...");
  549. return -1;
  550. }
  551. }
  552. //-------------------------------------------------
  553. // Create a CFMutableArray for our sub-device list
  554. //-------------------------------------------------
  555. // we need to append the UID for each device to a CFMutableArray, so create one here
  556. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  557. vector<CFStringRef> captureDeviceUID;
  558. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  559. CFStringRef ref = GetDeviceName(captureDeviceID[i]);
  560. if (ref == NULL)
  561. return -1;
  562. captureDeviceUID.push_back(ref);
  563. // input sub-devices in this example, so append the sub-device's UID to the CFArray
  564. CFArrayAppendValue(subDevicesArray, ref);
  565. }
  566. vector<CFStringRef> playbackDeviceUID;
  567. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  568. CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
  569. if (ref == NULL)
  570. return -1;
  571. playbackDeviceUID.push_back(ref);
  572. // output sub-devices in this example, so append the sub-device's UID to the CFArray
  573. CFArrayAppendValue(subDevicesArray, ref);
  574. }
  575. //-----------------------------------------------------------------------
  576. // Feed the dictionary to the plugin, to create a blank aggregate device
  577. //-----------------------------------------------------------------------
  578. AudioObjectPropertyAddress pluginAOPA;
  579. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  580. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  581. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  582. UInt32 outDataSize;
  583. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  584. if (osErr != noErr) {
  585. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
  586. printError(osErr);
  587. goto error;
  588. }
  589. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  590. if (osErr != noErr) {
  591. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyData error");
  592. printError(osErr);
  593. goto error;
  594. }
  595. // pause for a bit to make sure that everything completed correctly
  596. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  597. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  598. //-------------------------
  599. // Set the sub-device list
  600. //-------------------------
  601. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  602. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  603. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  604. outDataSize = sizeof(CFMutableArrayRef);
  605. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  606. if (osErr != noErr) {
  607. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
  608. printError(osErr);
  609. goto error;
  610. }
  611. // pause again to give the changes time to take effect
  612. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  613. //-----------------------
  614. // Set the master device
  615. //-----------------------
  616. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  617. // pass in the UID of the device you want to use
  618. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  619. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  620. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  621. outDataSize = sizeof(CFStringRef);
  622. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
  623. if (osErr != noErr) {
  624. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
  625. printError(osErr);
  626. goto error;
  627. }
  628. // pause again to give the changes time to take effect
  629. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  630. //----------
  631. // Clean up
  632. //----------
  633. // release the private AD key
  634. CFRelease(AggregateDeviceNumberRef);
  635. // release the CF objects we have created - we don't need them any more
  636. CFRelease(aggDeviceDict);
  637. CFRelease(subDevicesArray);
  638. if (subDevicesArrayClock)
  639. CFRelease(subDevicesArrayClock);
  640. // release the device UID
  641. for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
  642. CFRelease(captureDeviceUID[i]);
  643. }
  644. for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
  645. CFRelease(playbackDeviceUID[i]);
  646. }
  647. jack_log("New aggregate device %ld", *outAggregateDevice);
  648. return noErr;
  649. error:
  650. DestroyAggregateDevice();
  651. return -1;
  652. }
  653. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid,
  654. const char* playback_driver_uid,
  655. char* capture_driver_name,
  656. char* playback_driver_name,
  657. jack_nframes_t samplerate)
  658. {
  659. capture_driver_name[0] = 0;
  660. playback_driver_name[0] = 0;
  661. // Duplex
  662. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  663. jack_log("JackCoreAudioDriver::Open duplex");
  664. // Same device for capture and playback...
  665. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  666. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  667. jack_log("Will take default in/out");
  668. if (GetDefaultDevice(&fDeviceID) != noErr) {
  669. jack_error("Cannot open default device");
  670. return -1;
  671. }
  672. }
  673. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  674. jack_error("Cannot get device name from device ID");
  675. return -1;
  676. }
  677. } else {
  678. // Creates aggregate device
  679. AudioDeviceID captureID, playbackID;
  680. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  681. jack_log("Will take default input");
  682. if (GetDefaultInputDevice(&captureID) != noErr) {
  683. jack_error("Cannot open default device");
  684. return -1;
  685. }
  686. }
  687. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  688. jack_log("Will take default output");
  689. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  690. jack_error("Cannot open default device");
  691. return -1;
  692. }
  693. }
  694. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  695. return -1;
  696. }
  697. // Capture only
  698. } else if (strcmp(capture_driver_uid, "") != 0) {
  699. jack_log("JackCoreAudioDriver::Open capture only");
  700. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  701. jack_log("Will take default input");
  702. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  703. jack_error("Cannot open default device");
  704. return -1;
  705. }
  706. }
  707. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  708. jack_error("Cannot get device name from device ID");
  709. return -1;
  710. }
  711. // Playback only
  712. } else if (strcmp(playback_driver_uid, "") != 0) {
  713. jack_log("JackCoreAudioDriver::Open playback only");
  714. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  715. jack_log("Will take default output");
  716. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  717. jack_error("Cannot open default device");
  718. return -1;
  719. }
  720. }
  721. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  722. jack_error("Cannot get device name from device ID");
  723. return -1;
  724. }
  725. // Use default driver in duplex mode
  726. } else {
  727. jack_log("JackCoreAudioDriver::Open default driver");
  728. if (GetDefaultDevice(&fDeviceID) != noErr) {
  729. jack_error("Cannot open default device");
  730. return -1;
  731. }
  732. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  733. jack_error("Cannot get device name from device ID");
  734. return -1;
  735. }
  736. }
  737. if (fHogged) {
  738. if (TakeHog()) {
  739. jack_info("Device = %ld has been hogged", fDeviceID);
  740. } else {
  741. jack_error("Cannot hog device = %ld", fDeviceID);
  742. }
  743. }
  744. return 0;
  745. }
  746. /*
  747. Return the max possible input channels in in_nChannels and output channels in out_nChannels.
  748. */
  749. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
  750. {
  751. OSStatus err = noErr;
  752. if (capturing) {
  753. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  754. if (err != noErr) {
  755. jack_error("Cannot get input channel number");
  756. printError(err);
  757. return -1;
  758. } else {
  759. jack_log("Max input channels : %d", in_nChannels);
  760. }
  761. }
  762. if (playing) {
  763. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  764. if (err != noErr) {
  765. jack_error("Cannot get output channel number");
  766. printError(err);
  767. return -1;
  768. } else {
  769. jack_log("Max output channels : %d", out_nChannels);
  770. }
  771. }
  772. if (inchannels > in_nChannels) {
  773. jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
  774. if (strict)
  775. return -1;
  776. }
  777. if (outchannels > out_nChannels) {
  778. jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
  779. if (strict)
  780. return -1;
  781. }
  782. if (inchannels == -1) {
  783. jack_log("Setup max in channels = %d", in_nChannels);
  784. inchannels = in_nChannels;
  785. }
  786. if (outchannels == -1) {
  787. jack_log("Setup max out channels = %d", out_nChannels);
  788. outchannels = out_nChannels;
  789. }
  790. return 0;
  791. }
  792. int JackCoreAudioDriver::SetupBufferSize(jack_nframes_t buffer_size)
  793. {
  794. // Setting buffer size
  795. UInt32 outSize = sizeof(UInt32);
  796. OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  797. if (err != noErr) {
  798. jack_error("Cannot set buffer size %ld", buffer_size);
  799. printError(err);
  800. return -1;
  801. }
  802. return 0;
  803. }
  804. int JackCoreAudioDriver::SetupSampleRate(jack_nframes_t samplerate)
  805. {
  806. return SetupSampleRateAux(fDeviceID, samplerate);
  807. }
  808. int JackCoreAudioDriver::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
  809. {
  810. OSStatus err = noErr;
  811. UInt32 outSize;
  812. Float64 sampleRate;
  813. // Get sample rate
  814. outSize = sizeof(Float64);
  815. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  816. if (err != noErr) {
  817. jack_error("Cannot get current sample rate");
  818. printError(err);
  819. return -1;
  820. }
  821. // If needed, set new sample rate
  822. if (samplerate != (jack_nframes_t)sampleRate) {
  823. sampleRate = (Float64)samplerate;
  824. // To get SR change notification
  825. err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  826. if (err != noErr) {
  827. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  828. printError(err);
  829. return -1;
  830. }
  831. err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  832. if (err != noErr) {
  833. jack_error("Cannot set sample rate = %ld", samplerate);
  834. printError(err);
  835. return -1;
  836. }
  837. // Waiting for SR change notification
  838. int count = 0;
  839. while (!fState && count++ < WAIT_COUNTER) {
  840. usleep(100000);
  841. jack_log("Wait count = %d", count);
  842. }
  843. // Remove SR change notification
  844. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  845. }
  846. return 0;
  847. }
  848. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  849. bool playing,
  850. int inchannels,
  851. int outchannels,
  852. int in_nChannels,
  853. int out_nChannels,
  854. jack_nframes_t buffer_size,
  855. jack_nframes_t samplerate)
  856. {
  857. ComponentResult err1;
  858. UInt32 enableIO;
  859. AudioStreamBasicDescription srcFormat, dstFormat;
  860. AudioDeviceID currAudioDeviceID;
  861. UInt32 size;
  862. jack_log("OpenAUHAL capturing = %d playing = %d inchannels = %d outchannels = %d in_nChannels = %d out_nChannels = %d", capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels);
  863. if (inchannels == 0 && outchannels == 0) {
  864. jack_error("No input and output channels...");
  865. return -1;
  866. }
  867. // AUHAL
  868. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  869. Component HALOutput = FindNextComponent(NULL, &cd);
  870. err1 = OpenAComponent(HALOutput, &fAUHAL);
  871. if (err1 != noErr) {
  872. jack_error("Error calling OpenAComponent");
  873. printError(err1);
  874. goto error;
  875. }
  876. err1 = AudioUnitInitialize(fAUHAL);
  877. if (err1 != noErr) {
  878. jack_error("Cannot initialize AUHAL unit");
  879. printError(err1);
  880. goto error;
  881. }
  882. // Start I/O
  883. if (capturing && inchannels > 0) {
  884. enableIO = 1;
  885. jack_log("Setup AUHAL input on");
  886. } else {
  887. enableIO = 0;
  888. jack_log("Setup AUHAL input off");
  889. }
  890. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  891. if (err1 != noErr) {
  892. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  893. printError(err1);
  894. goto error;
  895. }
  896. if (playing && outchannels > 0) {
  897. enableIO = 1;
  898. jack_log("Setup AUHAL output on");
  899. } else {
  900. enableIO = 0;
  901. jack_log("Setup AUHAL output off");
  902. }
  903. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  904. if (err1 != noErr) {
  905. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  906. printError(err1);
  907. goto error;
  908. }
  909. size = sizeof(AudioDeviceID);
  910. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  911. if (err1 != noErr) {
  912. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  913. printError(err1);
  914. goto error;
  915. } else {
  916. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  917. }
  918. // Setup up choosen device, in both input and output cases
  919. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  920. if (err1 != noErr) {
  921. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  922. printError(err1);
  923. goto error;
  924. }
  925. // Set buffer size
  926. if (capturing && inchannels > 0) {
  927. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  928. if (err1 != noErr) {
  929. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  930. printError(err1);
  931. goto error;
  932. }
  933. }
  934. if (playing && outchannels > 0) {
  935. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  936. if (err1 != noErr) {
  937. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  938. printError(err1);
  939. goto error;
  940. }
  941. }
  942. // Setup channel map
  943. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  944. SInt32 chanArr[in_nChannels];
  945. for (int i = 0; i < in_nChannels; i++) {
  946. chanArr[i] = -1;
  947. }
  948. for (int i = 0; i < inchannels; i++) {
  949. chanArr[i] = i;
  950. }
  951. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  952. if (err1 != noErr) {
  953. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  954. printError(err1);
  955. goto error;
  956. }
  957. }
  958. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  959. SInt32 chanArr[out_nChannels];
  960. for (int i = 0; i < out_nChannels; i++) {
  961. chanArr[i] = -1;
  962. }
  963. for (int i = 0; i < outchannels; i++) {
  964. chanArr[i] = i;
  965. }
  966. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  967. if (err1 != noErr) {
  968. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  969. printError(err1);
  970. goto error;
  971. }
  972. }
  973. // Setup stream converters
  974. if (capturing && inchannels > 0) {
  975. size = sizeof(AudioStreamBasicDescription);
  976. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &srcFormat, &size);
  977. if (err1 != noErr) {
  978. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  979. printError(err1);
  980. goto error;
  981. }
  982. PrintStreamDesc(&srcFormat);
  983. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  984. srcFormat.mSampleRate = samplerate;
  985. srcFormat.mFormatID = kAudioFormatLinearPCM;
  986. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  987. srcFormat.mBytesPerPacket = sizeof(float);
  988. srcFormat.mFramesPerPacket = 1;
  989. srcFormat.mBytesPerFrame = sizeof(float);
  990. srcFormat.mChannelsPerFrame = inchannels;
  991. srcFormat.mBitsPerChannel = 32;
  992. PrintStreamDesc(&srcFormat);
  993. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
  994. if (err1 != noErr) {
  995. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  996. printError(err1);
  997. goto error;
  998. }
  999. }
  1000. if (playing && outchannels > 0) {
  1001. size = sizeof(AudioStreamBasicDescription);
  1002. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &dstFormat, &size);
  1003. if (err1 != noErr) {
  1004. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1005. printError(err1);
  1006. goto error;
  1007. }
  1008. PrintStreamDesc(&dstFormat);
  1009. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  1010. dstFormat.mSampleRate = samplerate;
  1011. dstFormat.mFormatID = kAudioFormatLinearPCM;
  1012. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1013. dstFormat.mBytesPerPacket = sizeof(float);
  1014. dstFormat.mFramesPerPacket = 1;
  1015. dstFormat.mBytesPerFrame = sizeof(float);
  1016. dstFormat.mChannelsPerFrame = outchannels;
  1017. dstFormat.mBitsPerChannel = 32;
  1018. PrintStreamDesc(&dstFormat);
  1019. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
  1020. if (err1 != noErr) {
  1021. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1022. printError(err1);
  1023. goto error;
  1024. }
  1025. }
  1026. // Setup callbacks
  1027. if (inchannels > 0 && outchannels == 0) {
  1028. AURenderCallbackStruct output;
  1029. output.inputProc = Render;
  1030. output.inputProcRefCon = this;
  1031. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  1032. if (err1 != noErr) {
  1033. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  1034. printError(err1);
  1035. goto error;
  1036. }
  1037. } else {
  1038. AURenderCallbackStruct output;
  1039. output.inputProc = Render;
  1040. output.inputProcRefCon = this;
  1041. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  1042. if (err1 != noErr) {
  1043. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  1044. printError(err1);
  1045. goto error;
  1046. }
  1047. }
  1048. return 0;
  1049. error:
  1050. CloseAUHAL();
  1051. return -1;
  1052. }
  1053. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  1054. {
  1055. // Prepare buffers
  1056. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  1057. fJackInputData->mNumberBuffers = inchannels;
  1058. for (int i = 0; i < fCaptureChannels; i++) {
  1059. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1060. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  1061. }
  1062. return 0;
  1063. }
  1064. void JackCoreAudioDriver::DisposeBuffers()
  1065. {
  1066. if (fJackInputData) {
  1067. free(fJackInputData);
  1068. fJackInputData = 0;
  1069. }
  1070. }
  1071. void JackCoreAudioDriver::CloseAUHAL()
  1072. {
  1073. AudioUnitUninitialize(fAUHAL);
  1074. CloseComponent(fAUHAL);
  1075. }
  1076. int JackCoreAudioDriver::AddListeners()
  1077. {
  1078. OSStatus err = noErr;
  1079. // Add listeners
  1080. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  1081. if (err != noErr) {
  1082. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  1083. printError(err);
  1084. return -1;
  1085. }
  1086. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  1087. if (err != noErr) {
  1088. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  1089. printError(err);
  1090. return -1;
  1091. }
  1092. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  1093. if (err != noErr) {
  1094. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  1095. printError(err);
  1096. return -1;
  1097. }
  1098. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  1099. if (err != noErr) {
  1100. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  1101. printError(err);
  1102. return -1;
  1103. }
  1104. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1105. if (err != noErr) {
  1106. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1107. printError(err);
  1108. return -1;
  1109. }
  1110. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1111. if (err != noErr) {
  1112. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1113. printError(err);
  1114. return -1;
  1115. }
  1116. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  1117. UInt32 outSize = sizeof(float);
  1118. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  1119. if (err != noErr) {
  1120. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  1121. printError(err);
  1122. }
  1123. }
  1124. return 0;
  1125. }
  1126. void JackCoreAudioDriver::RemoveListeners()
  1127. {
  1128. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  1129. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  1130. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  1131. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  1132. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1133. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1134. }
  1135. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  1136. jack_nframes_t samplerate,
  1137. bool capturing,
  1138. bool playing,
  1139. int inchannels,
  1140. int outchannels,
  1141. bool monitor,
  1142. const char* capture_driver_uid,
  1143. const char* playback_driver_uid,
  1144. jack_nframes_t capture_latency,
  1145. jack_nframes_t playback_latency,
  1146. int async_output_latency,
  1147. int computation_grain,
  1148. bool hogged,
  1149. bool clock_drift)
  1150. {
  1151. int in_nChannels = 0;
  1152. int out_nChannels = 0;
  1153. char capture_driver_name[256];
  1154. char playback_driver_name[256];
  1155. // Keep initial state
  1156. fCapturing = capturing;
  1157. fPlaying = playing;
  1158. fInChannels = inchannels;
  1159. fOutChannels = outchannels;
  1160. fMonitor = monitor;
  1161. strcpy(fCaptureUID, capture_driver_uid);
  1162. strcpy(fPlaybackUID, playback_driver_uid);
  1163. fCaptureLatency = capture_latency;
  1164. fPlaybackLatency = playback_latency;
  1165. fIOUsage = float(async_output_latency) / 100.f;
  1166. fComputationGrain = float(computation_grain) / 100.f;
  1167. fHogged = hogged;
  1168. fClockDriftCompensate = clock_drift;
  1169. SInt32 major;
  1170. SInt32 minor;
  1171. Gestalt(gestaltSystemVersionMajor, &major);
  1172. Gestalt(gestaltSystemVersionMinor, &minor);
  1173. // Starting with 10.6 systems, the HAL notification thread is created internally
  1174. if (major == 10 && minor >= 6) {
  1175. CFRunLoopRef theRunLoop = NULL;
  1176. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1177. OSStatus theError = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  1178. if (theError != noErr) {
  1179. jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
  1180. }
  1181. }
  1182. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name, samplerate) < 0)
  1183. goto error;
  1184. // Generic JackAudioDriver Open
  1185. if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
  1186. goto error;
  1187. if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
  1188. goto error;
  1189. if (SetupBufferSize(buffer_size) < 0)
  1190. goto error;
  1191. if (SetupSampleRate(samplerate) < 0)
  1192. goto error;
  1193. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate) < 0)
  1194. goto error;
  1195. if (capturing && inchannels > 0)
  1196. if (SetupBuffers(inchannels) < 0)
  1197. goto error;
  1198. if (AddListeners() < 0)
  1199. goto error;
  1200. // Core driver may have changed the in/out values
  1201. fCaptureChannels = inchannels;
  1202. fPlaybackChannels = outchannels;
  1203. return noErr;
  1204. error:
  1205. Close();
  1206. return -1;
  1207. }
  1208. int JackCoreAudioDriver::Close()
  1209. {
  1210. jack_log("JackCoreAudioDriver::Close");
  1211. Stop();
  1212. JackAudioDriver::Close();
  1213. RemoveListeners();
  1214. DisposeBuffers();
  1215. CloseAUHAL();
  1216. DestroyAggregateDevice();
  1217. return 0;
  1218. }
  1219. int JackCoreAudioDriver::Attach()
  1220. {
  1221. OSStatus err;
  1222. JackPort* port;
  1223. jack_port_id_t port_index;
  1224. UInt32 size;
  1225. Boolean isWritable;
  1226. char channel_name[64];
  1227. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1228. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1229. unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  1230. jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  1231. for (int i = 0; i < fCaptureChannels; i++) {
  1232. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  1233. if (err != noErr)
  1234. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  1235. if (err == noErr && size > 0) {
  1236. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1237. if (err != noErr)
  1238. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  1239. snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1240. } else {
  1241. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1242. }
  1243. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  1244. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  1245. jack_error("Cannot register port for %s", name);
  1246. return -1;
  1247. }
  1248. size = sizeof(UInt32);
  1249. UInt32 value1 = 0;
  1250. UInt32 value2 = 0;
  1251. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1252. if (err != noErr)
  1253. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  1254. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1255. if (err != noErr)
  1256. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  1257. port = fGraphManager->GetPort(port_index);
  1258. port->SetAlias(alias);
  1259. port->SetLatency(fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency);
  1260. fCapturePortList[i] = port_index;
  1261. }
  1262. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  1263. for (int i = 0; i < fPlaybackChannels; i++) {
  1264. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1265. if (err != noErr)
  1266. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  1267. if (err == noErr && size > 0) {
  1268. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1269. if (err != noErr)
  1270. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  1271. snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1272. } else {
  1273. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1274. }
  1275. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  1276. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  1277. jack_error("Cannot register port for %s", name);
  1278. return -1;
  1279. }
  1280. size = sizeof(UInt32);
  1281. UInt32 value1 = 0;
  1282. UInt32 value2 = 0;
  1283. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1284. if (err != noErr)
  1285. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  1286. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1287. if (err != noErr)
  1288. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  1289. port = fGraphManager->GetPort(port_index);
  1290. port->SetAlias(alias);
  1291. // Add more latency if "async" mode is used...
  1292. port->SetLatency(fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency);
  1293. fPlaybackPortList[i] = port_index;
  1294. // Monitor ports
  1295. if (fWithMonitorPorts) {
  1296. jack_log("Create monitor port ");
  1297. snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
  1298. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, fEngineControl->fBufferSize)) == NO_PORT) {
  1299. jack_error("Cannot register monitor port for %s", name);
  1300. return -1;
  1301. } else {
  1302. port = fGraphManager->GetPort(port_index);
  1303. port->SetAlias(alias);
  1304. port->SetLatency(fEngineControl->fBufferSize);
  1305. fMonitorPortList[i] = port_index;
  1306. }
  1307. }
  1308. }
  1309. // Input buffers do no change : prepare them only once
  1310. for (int i = 0; i < fCaptureChannels; i++) {
  1311. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1312. }
  1313. return 0;
  1314. }
  1315. int JackCoreAudioDriver::Start()
  1316. {
  1317. jack_log("JackCoreAudioDriver::Start");
  1318. JackAudioDriver::Start();
  1319. /*
  1320. #ifdef MAC_OS_X_VERSION_10_5
  1321. OSStatus err = AudioDeviceCreateIOProcID(fDeviceID, MeasureCallback, this, &fMesureCallbackID);
  1322. #else
  1323. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  1324. #endif
  1325. */
  1326. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  1327. if (err != noErr)
  1328. return -1;
  1329. err = AudioOutputUnitStart(fAUHAL);
  1330. if (err != noErr)
  1331. return -1;
  1332. if ((err = AudioDeviceStart(fDeviceID, MeasureCallback)) != noErr) {
  1333. jack_error("Cannot start MeasureCallback");
  1334. printError(err);
  1335. return -1;
  1336. }
  1337. // Waiting for Measure callback to be called ( = driver has started)
  1338. fState = false;
  1339. int count = 0;
  1340. while (!fState && count++ < WAIT_COUNTER) {
  1341. usleep(100000);
  1342. jack_log("JackCoreAudioDriver::Start wait count = %d", count);
  1343. }
  1344. if (count < WAIT_COUNTER) {
  1345. jack_info("CoreAudio driver is running...");
  1346. return 0;
  1347. } else {
  1348. jack_error("CoreAudio driver cannot start...");
  1349. return -1;
  1350. }
  1351. }
  1352. int JackCoreAudioDriver::Stop()
  1353. {
  1354. jack_log("JackCoreAudioDriver::Stop");
  1355. AudioDeviceStop(fDeviceID, MeasureCallback);
  1356. /*
  1357. #ifdef MAC_OS_X_VERSION_10_5
  1358. AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
  1359. #else
  1360. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  1361. #endif
  1362. */
  1363. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  1364. return (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  1365. }
  1366. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  1367. {
  1368. OSStatus err;
  1369. UInt32 outSize = sizeof(UInt32);
  1370. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  1371. if (err != noErr) {
  1372. jack_error("Cannot set buffer size %ld", buffer_size);
  1373. printError(err);
  1374. return -1;
  1375. }
  1376. JackAudioDriver::SetBufferSize(buffer_size); // never fails
  1377. // Input buffers do no change : prepare them only once
  1378. for (int i = 0; i < fCaptureChannels; i++) {
  1379. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1380. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  1381. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1382. }
  1383. return 0;
  1384. }
  1385. bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
  1386. {
  1387. pid_t hog_pid;
  1388. OSStatus err;
  1389. UInt32 propSize = sizeof(hog_pid);
  1390. err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  1391. if (err) {
  1392. jack_error("Cannot read hog state...");
  1393. printError(err);
  1394. }
  1395. if (hog_pid != getpid()) {
  1396. hog_pid = getpid();
  1397. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  1398. if (err != noErr) {
  1399. jack_error("Can't hog device = %d because it's being hogged by another program", deviceID);
  1400. return false;
  1401. }
  1402. }
  1403. return true;
  1404. }
  1405. bool JackCoreAudioDriver::TakeHog()
  1406. {
  1407. OSStatus err = noErr;
  1408. AudioObjectID sub_device[32];
  1409. UInt32 outSize = sizeof(sub_device);
  1410. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1411. if (err != noErr) {
  1412. jack_log("Device does not have subdevices");
  1413. return TakeHogAux(fDeviceID, true);
  1414. } else {
  1415. int num_devices = outSize / sizeof(AudioObjectID);
  1416. jack_log("Device does has %d subdevices", num_devices);
  1417. for (int i = 0; i < num_devices; i++) {
  1418. if (!TakeHogAux(sub_device[i], true)) {
  1419. return false;
  1420. }
  1421. }
  1422. return true;
  1423. }
  1424. }
  1425. bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
  1426. {
  1427. UInt32 deviceType, outSize = sizeof(UInt32);
  1428. OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
  1429. if (err != noErr) {
  1430. jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
  1431. return false;
  1432. } else {
  1433. return (deviceType == kAudioDeviceTransportTypeAggregate);
  1434. }
  1435. }
  1436. } // end of namespace
  1437. #ifdef __cplusplus
  1438. extern "C"
  1439. {
  1440. #endif
  1441. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1442. {
  1443. jack_driver_desc_t *desc;
  1444. unsigned int i;
  1445. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  1446. strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  1447. strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  1448. desc->nparams = 17;
  1449. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  1450. i = 0;
  1451. strcpy(desc->params[i].name, "channels");
  1452. desc->params[i].character = 'c';
  1453. desc->params[i].type = JackDriverParamInt;
  1454. desc->params[i].value.ui = -1;
  1455. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  1456. strcpy(desc->params[i].long_desc, "Maximum number of channels. If -1, max possible number of channels will be used");
  1457. i++;
  1458. strcpy(desc->params[i].name, "inchannels");
  1459. desc->params[i].character = 'i';
  1460. desc->params[i].type = JackDriverParamInt;
  1461. desc->params[i].value.ui = -1;
  1462. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  1463. strcpy(desc->params[i].long_desc, "Maximum number of input channels. If -1, max possible number of input channels will be used");
  1464. i++;
  1465. strcpy(desc->params[i].name, "outchannels");
  1466. desc->params[i].character = 'o';
  1467. desc->params[i].type = JackDriverParamInt;
  1468. desc->params[i].value.ui = -1;
  1469. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  1470. strcpy(desc->params[i].long_desc, "Maximum number of output channels. If -1, max possible number of output channels will be used");
  1471. i++;
  1472. strcpy(desc->params[i].name, "capture");
  1473. desc->params[i].character = 'C';
  1474. desc->params[i].type = JackDriverParamString;
  1475. strcpy(desc->params[i].short_desc, "Input CoreAudio device name");
  1476. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1477. i++;
  1478. strcpy(desc->params[i].name, "playback");
  1479. desc->params[i].character = 'P';
  1480. desc->params[i].type = JackDriverParamString;
  1481. strcpy(desc->params[i].short_desc, "Output CoreAudio device name");
  1482. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1483. i++;
  1484. strcpy (desc->params[i].name, "monitor");
  1485. desc->params[i].character = 'm';
  1486. desc->params[i].type = JackDriverParamBool;
  1487. desc->params[i].value.i = 0;
  1488. strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
  1489. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1490. i++;
  1491. strcpy(desc->params[i].name, "duplex");
  1492. desc->params[i].character = 'D';
  1493. desc->params[i].type = JackDriverParamBool;
  1494. desc->params[i].value.i = TRUE;
  1495. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  1496. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1497. i++;
  1498. strcpy(desc->params[i].name, "rate");
  1499. desc->params[i].character = 'r';
  1500. desc->params[i].type = JackDriverParamUInt;
  1501. desc->params[i].value.ui = 44100U;
  1502. strcpy(desc->params[i].short_desc, "Sample rate");
  1503. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1504. i++;
  1505. strcpy(desc->params[i].name, "period");
  1506. desc->params[i].character = 'p';
  1507. desc->params[i].type = JackDriverParamUInt;
  1508. desc->params[i].value.ui = 128U;
  1509. strcpy(desc->params[i].short_desc, "Frames per period");
  1510. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1511. i++;
  1512. strcpy(desc->params[i].name, "device");
  1513. desc->params[i].character = 'd';
  1514. desc->params[i].type = JackDriverParamString;
  1515. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  1516. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1517. i++;
  1518. strcpy(desc->params[i].name, "input-latency");
  1519. desc->params[i].character = 'I';
  1520. desc->params[i].type = JackDriverParamUInt;
  1521. desc->params[i].value.i = 0;
  1522. strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
  1523. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1524. i++;
  1525. strcpy(desc->params[i].name, "output-latency");
  1526. desc->params[i].character = 'O';
  1527. desc->params[i].type = JackDriverParamUInt;
  1528. desc->params[i].value.i = 0;
  1529. strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
  1530. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1531. i++;
  1532. strcpy(desc->params[i].name, "list-devices");
  1533. desc->params[i].character = 'l';
  1534. desc->params[i].type = JackDriverParamBool;
  1535. desc->params[i].value.i = FALSE;
  1536. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  1537. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1538. i++;
  1539. strcpy(desc->params[i].name, "hog");
  1540. desc->params[i].character = 'H';
  1541. desc->params[i].type = JackDriverParamBool;
  1542. desc->params[i].value.i = FALSE;
  1543. strcpy(desc->params[i].short_desc, "Take exclusive access of the audio device");
  1544. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1545. i++;
  1546. strcpy(desc->params[i].name, "async-latency");
  1547. desc->params[i].character = 'L';
  1548. desc->params[i].type = JackDriverParamUInt;
  1549. desc->params[i].value.i = 100;
  1550. strcpy(desc->params[i].short_desc, "Extra output latency in asynchronous mode (percent)");
  1551. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1552. i++;
  1553. strcpy(desc->params[i].name, "grain");
  1554. desc->params[i].character = 'G';
  1555. desc->params[i].type = JackDriverParamUInt;
  1556. desc->params[i].value.i = 100;
  1557. strcpy(desc->params[i].short_desc, "Computation grain in RT thread (percent)");
  1558. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1559. i++;
  1560. strcpy(desc->params[i].name, "clock-drift");
  1561. desc->params[i].character = 's';
  1562. desc->params[i].type = JackDriverParamBool;
  1563. desc->params[i].value.i = FALSE;
  1564. strcpy(desc->params[i].short_desc, "Clock drift compensation");
  1565. strcpy(desc->params[i].long_desc, "Whether to compensate clock drift in dynamically created aggregate device");
  1566. return desc;
  1567. }
  1568. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1569. {
  1570. jack_nframes_t srate = 44100;
  1571. jack_nframes_t frames_per_interrupt = 128;
  1572. bool capture = false;
  1573. bool playback = false;
  1574. int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
  1575. int chan_out = -1; // Default: ifĂ  not explicitely set, then max possible will be used...
  1576. bool monitor = false;
  1577. const char* capture_driver_uid = "";
  1578. const char* playback_driver_uid = "";
  1579. const JSList *node;
  1580. const jack_driver_param_t *param;
  1581. jack_nframes_t systemic_input_latency = 0;
  1582. jack_nframes_t systemic_output_latency = 0;
  1583. int async_output_latency = 100;
  1584. int computation_grain = -1;
  1585. bool hogged = false;
  1586. bool clock_drift = false;
  1587. for (node = params; node; node = jack_slist_next(node)) {
  1588. param = (const jack_driver_param_t *) node->data;
  1589. switch (param->character) {
  1590. case 'd':
  1591. capture_driver_uid = strdup(param->value.str);
  1592. playback_driver_uid = strdup(param->value.str);
  1593. break;
  1594. case 'D':
  1595. capture = true;
  1596. playback = true;
  1597. break;
  1598. case 'c':
  1599. chan_in = chan_out = (int)param->value.ui;
  1600. break;
  1601. case 'i':
  1602. chan_in = (int)param->value.ui;
  1603. break;
  1604. case 'o':
  1605. chan_out = (int)param->value.ui;
  1606. break;
  1607. case 'C':
  1608. capture = true;
  1609. if (strcmp(param->value.str, "none") != 0) {
  1610. capture_driver_uid = strdup(param->value.str);
  1611. }
  1612. break;
  1613. case 'P':
  1614. playback = true;
  1615. if (strcmp(param->value.str, "none") != 0) {
  1616. playback_driver_uid = strdup(param->value.str);
  1617. }
  1618. break;
  1619. case 'm':
  1620. monitor = param->value.i;
  1621. break;
  1622. case 'r':
  1623. srate = param->value.ui;
  1624. break;
  1625. case 'p':
  1626. frames_per_interrupt = (unsigned int)param->value.ui;
  1627. break;
  1628. case 'I':
  1629. systemic_input_latency = param->value.ui;
  1630. break;
  1631. case 'O':
  1632. systemic_output_latency = param->value.ui;
  1633. break;
  1634. case 'l':
  1635. Jack::DisplayDeviceNames();
  1636. break;
  1637. case 'H':
  1638. hogged = true;
  1639. break;
  1640. case 'L':
  1641. async_output_latency = param->value.ui;
  1642. break;
  1643. case 'G':
  1644. computation_grain = param->value.ui;
  1645. break;
  1646. case 's':
  1647. clock_drift = true;
  1648. break;
  1649. }
  1650. }
  1651. /* duplex is the default */
  1652. if (!capture && !playback) {
  1653. capture = true;
  1654. playback = true;
  1655. }
  1656. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  1657. if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
  1658. playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain, hogged, clock_drift) == 0) {
  1659. return driver;
  1660. } else {
  1661. delete driver;
  1662. return NULL;
  1663. }
  1664. }
  1665. #ifdef __cplusplus
  1666. }
  1667. #endif