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.

2465 lines
96KB

  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 "JackLockedEngine.h"
  25. #include <sstream>
  26. #include <iostream>
  27. #include <CoreServices/CoreServices.h>
  28. #include <CoreFoundation/CFNumber.h>
  29. namespace Jack
  30. {
  31. static void Print4CharCode(const char* msg, long c)
  32. {
  33. UInt32 __4CC_number = (c);
  34. char __4CC_string[5];
  35. *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
  36. __4CC_string[4] = 0;
  37. jack_log("%s'%s'", (msg), __4CC_string);
  38. }
  39. static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
  40. {
  41. jack_log("- - - - - - - - - - - - - - - - - - - -");
  42. jack_log(" Sample Rate:%f", inDesc->mSampleRate);
  43. jack_log(" Format ID:%.*s", (int) sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
  44. jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
  45. jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
  46. jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
  47. jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
  48. jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
  49. jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
  50. jack_log("- - - - - - - - - - - - - - - - - - - -");
  51. }
  52. static void printError(OSStatus err)
  53. {
  54. switch (err) {
  55. case kAudioHardwareNoError:
  56. jack_log("error code : kAudioHardwareNoError");
  57. break;
  58. case kAudioConverterErr_FormatNotSupported:
  59. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  60. break;
  61. case kAudioConverterErr_OperationNotSupported:
  62. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  63. break;
  64. case kAudioConverterErr_PropertyNotSupported:
  65. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  66. break;
  67. case kAudioConverterErr_InvalidInputSize:
  68. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  69. break;
  70. case kAudioConverterErr_InvalidOutputSize:
  71. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  72. break;
  73. case kAudioConverterErr_UnspecifiedError:
  74. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  75. break;
  76. case kAudioConverterErr_BadPropertySizeError:
  77. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  78. break;
  79. case kAudioConverterErr_RequiresPacketDescriptionsError:
  80. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  81. break;
  82. case kAudioConverterErr_InputSampleRateOutOfRange:
  83. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  84. break;
  85. case kAudioConverterErr_OutputSampleRateOutOfRange:
  86. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  87. break;
  88. case kAudioHardwareNotRunningError:
  89. jack_log("error code : kAudioHardwareNotRunningError");
  90. break;
  91. case kAudioHardwareUnknownPropertyError:
  92. jack_log("error code : kAudioHardwareUnknownPropertyError");
  93. break;
  94. case kAudioHardwareIllegalOperationError:
  95. jack_log("error code : kAudioHardwareIllegalOperationError");
  96. break;
  97. case kAudioHardwareBadDeviceError:
  98. jack_log("error code : kAudioHardwareBadDeviceError");
  99. break;
  100. case kAudioHardwareBadStreamError:
  101. jack_log("error code : kAudioHardwareBadStreamError");
  102. break;
  103. case kAudioDeviceUnsupportedFormatError:
  104. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  105. break;
  106. case kAudioDevicePermissionsError:
  107. jack_log("error code : kAudioDevicePermissionsError");
  108. break;
  109. case kAudioHardwareBadObjectError:
  110. jack_log("error code : kAudioHardwareBadObjectError");
  111. break;
  112. case kAudioHardwareUnsupportedOperationError:
  113. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  114. break;
  115. default:
  116. Print4CharCode("error code : unknown", err);
  117. break;
  118. }
  119. }
  120. static bool CheckAvailableDeviceName(const char* device_name, AudioDeviceID* device_id)
  121. {
  122. UInt32 size;
  123. Boolean isWritable;
  124. int i, deviceNum;
  125. OSStatus err;
  126. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  127. if (err != noErr) {
  128. return false;
  129. }
  130. deviceNum = size / sizeof(AudioDeviceID);
  131. AudioDeviceID devices[deviceNum];
  132. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  133. if (err != noErr) {
  134. return false;
  135. }
  136. for (i = 0; i < deviceNum; i++) {
  137. char device_name_aux[256];
  138. size = 256;
  139. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name_aux);
  140. if (err != noErr) {
  141. return false;
  142. }
  143. if (strcmp(device_name_aux, device_name) == 0) {
  144. *device_id = devices[i];
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. static bool CheckAvailableDevice(AudioDeviceID device_id)
  151. {
  152. UInt32 size;
  153. Boolean isWritable;
  154. int i, deviceNum;
  155. OSStatus err;
  156. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  157. if (err != noErr) {
  158. return false;
  159. }
  160. deviceNum = size / sizeof(AudioDeviceID);
  161. AudioDeviceID devices[deviceNum];
  162. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  163. if (err != noErr) {
  164. return false;
  165. }
  166. for (i = 0; i < deviceNum; i++) {
  167. if (device_id == devices[i]) {
  168. return true;
  169. }
  170. }
  171. return false;
  172. }
  173. static OSStatus DisplayDeviceNames()
  174. {
  175. UInt32 size;
  176. Boolean isWritable;
  177. int i, deviceNum;
  178. OSStatus err;
  179. CFStringRef UIname;
  180. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  181. if (err != noErr) {
  182. return err;
  183. }
  184. deviceNum = size / sizeof(AudioDeviceID);
  185. AudioDeviceID devices[deviceNum];
  186. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  187. if (err != noErr) {
  188. return err;
  189. }
  190. for (i = 0; i < deviceNum; i++) {
  191. char device_name[256];
  192. char internal_name[256];
  193. size = sizeof(CFStringRef);
  194. UIname = NULL;
  195. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  196. if (err == noErr) {
  197. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  198. } else {
  199. goto error;
  200. }
  201. size = 256;
  202. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  203. if (err != noErr) {
  204. return err;
  205. }
  206. jack_info("Device ID = \'%d\' name = \'%s\', internal name = \'%s\' (to be used as -C, -P, or -d parameter)", devices[i], device_name, internal_name);
  207. }
  208. return noErr;
  209. error:
  210. if (UIname != NULL) {
  211. CFRelease(UIname);
  212. }
  213. return err;
  214. }
  215. static CFStringRef GetDeviceName(AudioDeviceID id)
  216. {
  217. UInt32 size = sizeof(CFStringRef);
  218. CFStringRef UIname;
  219. OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  220. return (err == noErr) ? UIname : NULL;
  221. }
  222. static void ParseChannelList(const string& list, vector<int>& result)
  223. {
  224. stringstream ss(list);
  225. string token;
  226. int chan;
  227. while (ss >> token) {
  228. istringstream ins;
  229. ins.str(token);
  230. ins >> chan;
  231. result.push_back(chan);
  232. }
  233. }
  234. OSStatus JackCoreAudioDriver::Render(void* inRefCon,
  235. AudioUnitRenderActionFlags* ioActionFlags,
  236. const AudioTimeStamp* inTimeStamp,
  237. UInt32 inBusNumber,
  238. UInt32 inNumberFrames,
  239. AudioBufferList* ioData)
  240. {
  241. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inRefCon;
  242. driver->fActionFags = ioActionFlags;
  243. driver->fCurrentTime = inTimeStamp;
  244. driver->fDriverOutputData = ioData;
  245. // Setup threaded based log function et get RT thread parameters once...
  246. if (set_threaded_log_function()) {
  247. jack_log("JackCoreAudioDriver::Render : set_threaded_log_function");
  248. JackMachThread::GetParams(pthread_self(), &driver->fEngineControl->fPeriod, &driver->fEngineControl->fComputation, &driver->fEngineControl->fConstraint);
  249. if (driver->fComputationGrain > 0) {
  250. jack_log("JackCoreAudioDriver::Render : RT thread computation setup to %d percent of period", int(driver->fComputationGrain * 100));
  251. driver->fEngineControl->fComputation = driver->fEngineControl->fPeriod * driver->fComputationGrain;
  252. }
  253. }
  254. // Signal waiting start function...
  255. driver->fState = true;
  256. driver->CycleTakeBeginTime();
  257. if (driver->Process() < 0) {
  258. jack_error("Process error, stopping driver");
  259. driver->NotifyFailure(JackBackendError, "Process error, stopping driver"); // Message length limited to JACK_MESSAGE_SIZE
  260. driver->Stop();
  261. kill(JackTools::GetPID(), SIGINT);
  262. return kAudioHardwareUnsupportedOperationError;
  263. } else {
  264. return noErr;
  265. }
  266. }
  267. int JackCoreAudioDriver::Read()
  268. {
  269. if (fCaptureChannels > 0) { // Calling AudioUnitRender with no input returns a '????' error (callback setting issue ??), so hack to avoid it here...
  270. return (AudioUnitRender(fAUHAL, fActionFags, fCurrentTime, 1, fEngineControl->fBufferSize, fJackInputData) == noErr) ? 0 : -1;
  271. } else {
  272. return 0;
  273. }
  274. }
  275. int JackCoreAudioDriver::Write()
  276. {
  277. for (int i = 0; i < fPlaybackChannels; i++) {
  278. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[i]) > 0) {
  279. jack_default_audio_sample_t* buffer = GetOutputBuffer(i);
  280. int size = sizeof(jack_default_audio_sample_t) * fEngineControl->fBufferSize;
  281. memcpy((jack_default_audio_sample_t*)fDriverOutputData->mBuffers[i].mData, buffer, size);
  282. // Monitor ports
  283. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[i]) > 0) {
  284. memcpy(GetMonitorBuffer(i), buffer, size);
  285. }
  286. } else {
  287. memset((jack_default_audio_sample_t*)fDriverOutputData->mBuffers[i].mData, 0, sizeof(jack_default_audio_sample_t) * fEngineControl->fBufferSize);
  288. }
  289. }
  290. return 0;
  291. }
  292. OSStatus JackCoreAudioDriver::SRNotificationCallback(AudioDeviceID inDevice,
  293. UInt32 inChannel,
  294. Boolean isInput,
  295. AudioDevicePropertyID inPropertyID,
  296. void* inClientData)
  297. {
  298. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  299. switch (inPropertyID) {
  300. case kAudioDevicePropertyNominalSampleRate: {
  301. jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  302. // Check new sample rate
  303. Float64 tmp_sample_rate;
  304. UInt32 outSize = sizeof(Float64);
  305. OSStatus err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &tmp_sample_rate);
  306. if (err != noErr) {
  307. jack_error("Cannot get current sample rate");
  308. printError(err);
  309. } else {
  310. jack_log("JackCoreAudioDriver::SRNotificationCallback : checked sample rate = %f", tmp_sample_rate);
  311. }
  312. driver->fState = true;
  313. break;
  314. }
  315. }
  316. return noErr;
  317. }
  318. OSStatus JackCoreAudioDriver::BSNotificationCallback(AudioDeviceID inDevice,
  319. UInt32 inChannel,
  320. Boolean isInput,
  321. AudioDevicePropertyID inPropertyID,
  322. void* inClientData)
  323. {
  324. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  325. switch (inPropertyID) {
  326. case kAudioDevicePropertyBufferFrameSize: {
  327. jack_log("JackCoreAudioDriver::BSNotificationCallback kAudioDevicePropertyBufferFrameSize");
  328. // Check new buffer size
  329. UInt32 tmp_buffer_size;
  330. UInt32 outSize = sizeof(UInt32);
  331. OSStatus err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, &outSize, &tmp_buffer_size);
  332. if (err != noErr) {
  333. jack_error("Cannot get current buffer size");
  334. printError(err);
  335. } else {
  336. jack_log("JackCoreAudioDriver::BSNotificationCallback : checked buffer size = %d", tmp_buffer_size);
  337. }
  338. driver->fState = true;
  339. break;
  340. }
  341. }
  342. return noErr;
  343. }
  344. // A better implementation would possibly try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  345. OSStatus JackCoreAudioDriver::AudioHardwareNotificationCallback(AudioHardwarePropertyID inPropertyID, void* inClientData)
  346. {
  347. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  348. switch (inPropertyID) {
  349. case kAudioHardwarePropertyDevices: {
  350. jack_log("JackCoreAudioDriver::AudioHardwareNotificationCallback kAudioHardwarePropertyDevices");
  351. DisplayDeviceNames();
  352. AudioDeviceID captureID, playbackID;
  353. if (CheckAvailableDevice(driver->fDeviceID) ||
  354. (CheckAvailableDeviceName(driver->fCaptureUID, &captureID)
  355. && CheckAvailableDeviceName(driver->fPlaybackUID, &playbackID))) {
  356. }
  357. break;
  358. }
  359. }
  360. return noErr;
  361. }
  362. OSStatus JackCoreAudioDriver::DeviceNotificationCallback(AudioDeviceID inDevice,
  363. UInt32 inChannel,
  364. Boolean isInput,
  365. AudioDevicePropertyID inPropertyID,
  366. void* inClientData)
  367. {
  368. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  369. switch (inPropertyID) {
  370. case kAudioDevicePropertyDeviceIsRunning: {
  371. UInt32 isrunning = 0;
  372. UInt32 outsize = sizeof(UInt32);
  373. if (AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyDeviceIsRunning, &outsize, &isrunning) == noErr) {
  374. jack_log("JackCoreAudioDriver::DeviceNotificationCallback kAudioDevicePropertyDeviceIsRunning = %d", isrunning);
  375. }
  376. break;
  377. }
  378. case kAudioDevicePropertyDeviceIsAlive: {
  379. UInt32 isalive = 0;
  380. UInt32 outsize = sizeof(UInt32);
  381. if (AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyDeviceIsAlive, &outsize, &isalive) == noErr) {
  382. jack_log("JackCoreAudioDriver::DeviceNotificationCallback kAudioDevicePropertyDeviceIsAlive = %d", isalive);
  383. }
  384. break;
  385. }
  386. case kAudioDevicePropertyDeviceHasChanged: {
  387. UInt32 hachanged = 0;
  388. UInt32 outsize = sizeof(UInt32);
  389. if (AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyDeviceHasChanged, &outsize, &hachanged) == noErr) {
  390. jack_log("JackCoreAudioDriver::DeviceNotificationCallback kAudioDevicePropertyDeviceHasChanged = %d", hachanged);
  391. }
  392. break;
  393. }
  394. case kAudioDeviceProcessorOverload: {
  395. jack_error("JackCoreAudioDriver::DeviceNotificationCallback kAudioDeviceProcessorOverload");
  396. jack_time_t cur_time = GetMicroSeconds();
  397. driver->NotifyXRun(cur_time, float(cur_time - driver->fBeginDateUst)); // Better this value than nothing...
  398. break;
  399. }
  400. case kAudioDevicePropertyStreamConfiguration: {
  401. jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration : server will quit...");
  402. driver->NotifyFailure(JackBackendError, "Another application has changed the device configuration"); // Message length limited to JACK_MESSAGE_SIZE
  403. driver->CloseAUHAL();
  404. kill(JackTools::GetPID(), SIGINT);
  405. return kAudioHardwareUnsupportedOperationError;
  406. }
  407. case kAudioDevicePropertyNominalSampleRate: {
  408. Float64 sample_rate = 0;
  409. UInt32 outsize = sizeof(Float64);
  410. OSStatus err = AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outsize, &sample_rate);
  411. if (err != noErr) {
  412. return kAudioHardwareUnsupportedOperationError;
  413. }
  414. char device_name[256];
  415. const char* digidesign_name = "Digidesign";
  416. driver->GetDeviceNameFromID(driver->fDeviceID, device_name);
  417. if (sample_rate != driver->fEngineControl->fSampleRate) {
  418. // Digidesign hardware, so "special" code : change the SR again here
  419. if (strncmp(device_name, digidesign_name, 10) == 0) {
  420. jack_log("JackCoreAudioDriver::DeviceNotificationCallback Digidesign HW = %s", device_name);
  421. // Set sample rate again...
  422. sample_rate = driver->fEngineControl->fSampleRate;
  423. err = AudioDeviceSetProperty(driver->fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outsize, &sample_rate);
  424. if (err != noErr) {
  425. jack_error("Cannot set sample rate = %f", sample_rate);
  426. printError(err);
  427. } else {
  428. jack_log("JackCoreAudioDriver::DeviceNotificationCallback : set sample rate = %f", sample_rate);
  429. }
  430. // Check new sample rate again...
  431. outsize = sizeof(Float64);
  432. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outsize, &sample_rate);
  433. if (err != noErr) {
  434. jack_error("Cannot get current sample rate");
  435. printError(err);
  436. } else {
  437. jack_log("JackCoreAudioDriver::DeviceNotificationCallback : checked sample rate = %f", sample_rate);
  438. }
  439. return noErr;
  440. } else {
  441. driver->NotifyFailure(JackBackendError, "Another application has changed the sample rate"); // Message length limited to JACK_MESSAGE_SIZE
  442. driver->CloseAUHAL();
  443. kill(JackTools::GetPID(), SIGINT);
  444. return kAudioHardwareUnsupportedOperationError;
  445. }
  446. }
  447. }
  448. }
  449. return noErr;
  450. }
  451. OSStatus JackCoreAudioDriver::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  452. {
  453. UInt32 size = sizeof(AudioValueTranslation);
  454. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  455. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  456. if (inIUD == NULL) {
  457. return kAudioHardwareUnspecifiedError;
  458. } else {
  459. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  460. CFRelease(inIUD);
  461. jack_log("JackCoreAudioDriver::GetDeviceIDFromUID %s %ld", UID, *id);
  462. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  463. }
  464. }
  465. OSStatus JackCoreAudioDriver::GetDefaultDevice(AudioDeviceID* id)
  466. {
  467. OSStatus res;
  468. UInt32 theSize = sizeof(UInt32);
  469. AudioDeviceID inDefault;
  470. AudioDeviceID outDefault;
  471. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr) {
  472. return res;
  473. }
  474. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr) {
  475. return res;
  476. }
  477. jack_log("JackCoreAudioDriver::GetDefaultDevice : input = %ld output = %ld", inDefault, outDefault);
  478. // Get the device only if default input and output are the same
  479. if (inDefault != outDefault) {
  480. jack_error("Default input and output devices are not the same !!");
  481. return kAudioHardwareBadDeviceError;
  482. } else if (inDefault == 0) {
  483. jack_error("Default input and output devices are null !!");
  484. return kAudioHardwareBadDeviceError;
  485. } else {
  486. *id = inDefault;
  487. return noErr;
  488. }
  489. }
  490. OSStatus JackCoreAudioDriver::GetDefaultInputDevice(AudioDeviceID* id)
  491. {
  492. OSStatus res;
  493. UInt32 theSize = sizeof(UInt32);
  494. AudioDeviceID inDefault;
  495. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr) {
  496. return res;
  497. }
  498. if (inDefault == 0) {
  499. jack_error("Error: default input device is 0, please select a correct one !!");
  500. return -1;
  501. }
  502. jack_log("JackCoreAudioDriver::GetDefaultInputDevice : input = %ld ", inDefault);
  503. *id = inDefault;
  504. return noErr;
  505. }
  506. OSStatus JackCoreAudioDriver::GetDefaultOutputDevice(AudioDeviceID* id)
  507. {
  508. OSStatus res;
  509. UInt32 theSize = sizeof(UInt32);
  510. AudioDeviceID outDefault;
  511. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr) {
  512. return res;
  513. }
  514. if (outDefault == 0) {
  515. jack_error("Error: default output device is 0, please select a correct one !!");
  516. return -1;
  517. }
  518. jack_log("JackCoreAudioDriver::GetDefaultOutputDevice : output = %ld", outDefault);
  519. *id = outDefault;
  520. return noErr;
  521. }
  522. OSStatus JackCoreAudioDriver::GetDeviceNameFromID(AudioDeviceID id, char* name)
  523. {
  524. UInt32 size = 256;
  525. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  526. }
  527. OSStatus JackCoreAudioDriver::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  528. {
  529. OSStatus err = noErr;
  530. UInt32 outSize;
  531. Boolean outWritable;
  532. channelCount = 0;
  533. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  534. if (err == noErr) {
  535. int stream_count = outSize / sizeof(AudioBufferList);
  536. AudioBufferList bufferList[stream_count];
  537. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  538. if (err == noErr) {
  539. for (uint i = 0; i < bufferList->mNumberBuffers; i++) {
  540. channelCount += bufferList->mBuffers[i].mNumberChannels;
  541. //jack_info("GetTotalChannels stream = %d channels = %d", i, bufferList->mBuffers[i].mNumberChannels);
  542. }
  543. }
  544. }
  545. return err;
  546. }
  547. OSStatus JackCoreAudioDriver::GetStreamLatencies(AudioDeviceID device, bool isInput, vector<int>& latencies)
  548. {
  549. OSStatus err = noErr;
  550. UInt32 outSize1, outSize2, outSize3;
  551. Boolean outWritable;
  552. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, &outWritable);
  553. if (err == noErr) {
  554. int stream_count = outSize1 / sizeof(UInt32);
  555. AudioStreamID streamIDs[stream_count];
  556. AudioBufferList bufferList[stream_count];
  557. UInt32 streamLatency;
  558. outSize2 = sizeof(UInt32);
  559. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, streamIDs);
  560. if (err != noErr) {
  561. jack_error("GetStreamLatencies kAudioDevicePropertyStreams err = %d", err);
  562. return err;
  563. }
  564. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, &outWritable);
  565. if (err != noErr) {
  566. jack_error("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = %d", err);
  567. return err;
  568. }
  569. for (int i = 0; i < stream_count; i++) {
  570. err = AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &outSize2, &streamLatency);
  571. if (err != noErr) {
  572. jack_error("GetStreamLatencies kAudioStreamPropertyLatency err = %d", err);
  573. return err;
  574. }
  575. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, bufferList);
  576. if (err != noErr) {
  577. jack_error("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = %d", err);
  578. return err;
  579. }
  580. // Push 'channel' time the stream latency
  581. for (uint k = 0; k < bufferList->mBuffers[i].mNumberChannels; k++) {
  582. latencies.push_back(streamLatency);
  583. }
  584. }
  585. }
  586. return err;
  587. }
  588. JackCoreAudioDriver::JackCoreAudioDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
  589. : JackAudioDriver(name, alias, engine, table),
  590. fJackInputData(NULL),
  591. fDriverOutputData(NULL),
  592. fPluginID(0),
  593. fState(false),
  594. fHogged(false),
  595. fIOUsage(1.f),
  596. fComputationGrain(-1.f),
  597. fClockDriftCompensate(false)
  598. {}
  599. JackCoreAudioDriver::~JackCoreAudioDriver()
  600. {}
  601. OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
  602. {
  603. OSStatus osErr = noErr;
  604. AudioObjectPropertyAddress pluginAOPA;
  605. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  606. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  607. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  608. UInt32 outDataSize;
  609. if (fPluginID > 0) {
  610. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  611. if (osErr != noErr) {
  612. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  613. printError(osErr);
  614. return osErr;
  615. }
  616. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  617. if (osErr != noErr) {
  618. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  619. printError(osErr);
  620. return osErr;
  621. }
  622. }
  623. return noErr;
  624. }
  625. OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  626. {
  627. OSStatus err = noErr;
  628. AudioObjectID sub_device[32];
  629. UInt32 outSize = sizeof(sub_device);
  630. err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  631. vector<AudioDeviceID> captureDeviceIDArray;
  632. if (err != noErr) {
  633. jack_log("JackCoreAudioDriver::CreateAggregateDevice : input device does not have subdevices");
  634. captureDeviceIDArray.push_back(captureDeviceID);
  635. } else {
  636. int num_devices = outSize / sizeof(AudioObjectID);
  637. jack_log("JackCoreAudioDriver::CreateAggregateDevice :Input device has %d subdevices", num_devices);
  638. for (int i = 0; i < num_devices; i++) {
  639. captureDeviceIDArray.push_back(sub_device[i]);
  640. }
  641. }
  642. err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  643. vector<AudioDeviceID> playbackDeviceIDArray;
  644. if (err != noErr) {
  645. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output device does not have subdevices");
  646. playbackDeviceIDArray.push_back(playbackDeviceID);
  647. } else {
  648. int num_devices = outSize / sizeof(AudioObjectID);
  649. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output device has %d subdevices", num_devices);
  650. for (int i = 0; i < num_devices; i++) {
  651. playbackDeviceIDArray.push_back(sub_device[i]);
  652. }
  653. }
  654. return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
  655. }
  656. OSStatus JackCoreAudioDriver::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  657. {
  658. OSStatus osErr = noErr;
  659. UInt32 outSize;
  660. Boolean outWritable;
  661. // Prepare sub-devices for clock drift compensation
  662. // Workaround for bug in the HAL : until 10.6.2
  663. AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  664. AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  665. UInt32 theQualifierDataSize = sizeof(AudioObjectID);
  666. AudioClassID inClass = kAudioSubDeviceClassID;
  667. void* theQualifierData = &inClass;
  668. UInt32 subDevicesNum = 0;
  669. //---------------------------------------------------------------------------
  670. // Setup SR of both devices otherwise creating AD may fail...
  671. //---------------------------------------------------------------------------
  672. UInt32 keptclockdomain = 0;
  673. UInt32 clockdomain = 0;
  674. outSize = sizeof(UInt32);
  675. bool need_clock_drift_compensation = false;
  676. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  677. if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
  678. jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of input device");
  679. } else {
  680. // Check clock domain
  681. osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  682. if (osErr != 0) {
  683. jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  684. printError(osErr);
  685. } else {
  686. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  687. jack_log("JackCoreAudioDriver::CreateAggregateDevice : input clockdomain = %d", clockdomain);
  688. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  689. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  690. need_clock_drift_compensation = true;
  691. }
  692. }
  693. }
  694. }
  695. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  696. if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
  697. jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of output device");
  698. } else {
  699. // Check clock domain
  700. osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  701. if (osErr != 0) {
  702. jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  703. printError(osErr);
  704. } else {
  705. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  706. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output clockdomain = %d", clockdomain);
  707. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  708. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  709. need_clock_drift_compensation = true;
  710. }
  711. }
  712. }
  713. }
  714. // If no valid clock domain was found, then assume we have to compensate...
  715. if (keptclockdomain == 0) {
  716. need_clock_drift_compensation = true;
  717. }
  718. //---------------------------------------------------------------------------
  719. // Start to create a new aggregate by getting the base audio hardware plugin
  720. //---------------------------------------------------------------------------
  721. char device_name[256];
  722. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  723. GetDeviceNameFromID(captureDeviceID[i], device_name);
  724. jack_info("Separated input = '%s' ", device_name);
  725. }
  726. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  727. GetDeviceNameFromID(playbackDeviceID[i], device_name);
  728. jack_info("Separated output = '%s' ", device_name);
  729. }
  730. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  731. if (osErr != noErr) {
  732. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
  733. printError(osErr);
  734. return osErr;
  735. }
  736. AudioValueTranslation pluginAVT;
  737. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  738. pluginAVT.mInputData = &inBundleRef;
  739. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  740. pluginAVT.mOutputData = &fPluginID;
  741. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  742. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  743. if (osErr != noErr) {
  744. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
  745. printError(osErr);
  746. return osErr;
  747. }
  748. //-------------------------------------------------
  749. // Create a CFDictionary for our aggregate device
  750. //-------------------------------------------------
  751. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  752. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  753. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  754. // add the name of the device to the dictionary
  755. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  756. // add our choice of UID for the aggregate device to the dictionary
  757. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  758. // add a "private aggregate key" to the dictionary
  759. int value = 1;
  760. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  761. SInt32 system;
  762. Gestalt(gestaltSystemVersion, &system);
  763. jack_log("JackCoreAudioDriver::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
  764. // Starting with 10.5.4 systems, the AD can be internal... (better)
  765. if (system < 0x00001054) {
  766. jack_log("JackCoreAudioDriver::CreateAggregateDevice : public aggregate device....");
  767. } else {
  768. jack_log("JackCoreAudioDriver::CreateAggregateDevice : private aggregate device....");
  769. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  770. }
  771. // Prepare sub-devices for clock drift compensation
  772. CFMutableArrayRef subDevicesArrayClock = NULL;
  773. /*
  774. if (fClockDriftCompensate) {
  775. if (need_clock_drift_compensation) {
  776. jack_info("Clock drift compensation activated...");
  777. subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  778. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  779. CFStringRef UID = GetDeviceName(captureDeviceID[i]);
  780. if (UID) {
  781. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  782. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  783. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  784. //CFRelease(UID);
  785. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  786. }
  787. }
  788. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  789. CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
  790. if (UID) {
  791. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  792. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  793. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  794. //CFRelease(UID);
  795. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  796. }
  797. }
  798. // add sub-device clock array for the aggregate device to the dictionary
  799. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
  800. } else {
  801. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  802. }
  803. }
  804. */
  805. //-------------------------------------------------
  806. // Create a CFMutableArray for our sub-device list
  807. //-------------------------------------------------
  808. // we need to append the UID for each device to a CFMutableArray, so create one here
  809. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  810. vector<CFStringRef> captureDeviceUID;
  811. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  812. CFStringRef ref = GetDeviceName(captureDeviceID[i]);
  813. if (ref == NULL) {
  814. return -1;
  815. }
  816. captureDeviceUID.push_back(ref);
  817. // input sub-devices in this example, so append the sub-device's UID to the CFArray
  818. CFArrayAppendValue(subDevicesArray, ref);
  819. }
  820. vector<CFStringRef> playbackDeviceUID;
  821. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  822. CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
  823. if (ref == NULL) {
  824. return -1;
  825. }
  826. playbackDeviceUID.push_back(ref);
  827. // output sub-devices in this example, so append the sub-device's UID to the CFArray
  828. CFArrayAppendValue(subDevicesArray, ref);
  829. }
  830. //-----------------------------------------------------------------------
  831. // Feed the dictionary to the plugin, to create a blank aggregate device
  832. //-----------------------------------------------------------------------
  833. AudioObjectPropertyAddress pluginAOPA;
  834. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  835. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  836. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  837. UInt32 outDataSize;
  838. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  839. if (osErr != noErr) {
  840. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
  841. printError(osErr);
  842. goto error;
  843. }
  844. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  845. if (osErr != noErr) {
  846. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyData error");
  847. printError(osErr);
  848. goto error;
  849. }
  850. // pause for a bit to make sure that everything completed correctly
  851. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  852. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  853. //-------------------------
  854. // Set the sub-device list
  855. //-------------------------
  856. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  857. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  858. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  859. outDataSize = sizeof(CFMutableArrayRef);
  860. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  861. if (osErr != noErr) {
  862. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
  863. printError(osErr);
  864. goto error;
  865. }
  866. // pause again to give the changes time to take effect
  867. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  868. //-----------------------
  869. // Set the master device
  870. //-----------------------
  871. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  872. // pass in the UID of the device you want to use
  873. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  874. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  875. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  876. outDataSize = sizeof(CFStringRef);
  877. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
  878. if (osErr != noErr) {
  879. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
  880. printError(osErr);
  881. goto error;
  882. }
  883. // pause again to give the changes time to take effect
  884. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  885. // Prepare sub-devices for clock drift compensation
  886. // Workaround for bug in the HAL : until 10.6.2
  887. if (fClockDriftCompensate) {
  888. if (need_clock_drift_compensation) {
  889. jack_info("Clock drift compensation activated...");
  890. // Get the property data size
  891. osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
  892. if (osErr != noErr) {
  893. jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  894. printError(osErr);
  895. }
  896. // Calculate the number of object IDs
  897. subDevicesNum = outSize / sizeof(AudioObjectID);
  898. jack_info("JackCoreAudioDriver::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
  899. AudioObjectID subDevices[subDevicesNum];
  900. outSize = sizeof(subDevices);
  901. osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
  902. if (osErr != noErr) {
  903. jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  904. printError(osErr);
  905. }
  906. // Set kAudioSubDevicePropertyDriftCompensation property...
  907. for (UInt32 index = 0; index < subDevicesNum; ++index) {
  908. UInt32 theDriftCompensationValue = 1;
  909. osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
  910. if (osErr != noErr) {
  911. jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
  912. printError(osErr);
  913. }
  914. }
  915. } else {
  916. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  917. }
  918. }
  919. // pause again to give the changes time to take effect
  920. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  921. //----------
  922. // Clean up
  923. //----------
  924. // release the private AD key
  925. CFRelease(AggregateDeviceNumberRef);
  926. // release the CF objects we have created - we don't need them any more
  927. CFRelease(aggDeviceDict);
  928. CFRelease(subDevicesArray);
  929. if (subDevicesArrayClock) {
  930. CFRelease(subDevicesArrayClock);
  931. }
  932. // release the device UID
  933. for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
  934. CFRelease(captureDeviceUID[i]);
  935. }
  936. for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
  937. CFRelease(playbackDeviceUID[i]);
  938. }
  939. jack_log("JackCoreAudioDriver::CreateAggregateDeviceAux : new aggregate device %ld", *outAggregateDevice);
  940. return noErr;
  941. error:
  942. DestroyAggregateDevice();
  943. return -1;
  944. }
  945. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid,
  946. const char* playback_driver_uid,
  947. char* capture_driver_name,
  948. char* playback_driver_name,
  949. jack_nframes_t samplerate)
  950. {
  951. capture_driver_name[0] = 0;
  952. playback_driver_name[0] = 0;
  953. // Duplex
  954. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  955. jack_log("JackCoreAudioDriver::SetupDevices : duplex");
  956. // Same device for capture and playback...
  957. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  958. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  959. jack_log("JackCoreAudioDriver::SetupDevices : will take default in/out");
  960. if (GetDefaultDevice(&fDeviceID) != noErr) {
  961. jack_error("Cannot open default device");
  962. return -1;
  963. }
  964. }
  965. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  966. jack_error("Cannot get device name from device ID");
  967. return -1;
  968. }
  969. } else {
  970. // Creates aggregate device
  971. AudioDeviceID captureID, playbackID;
  972. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  973. jack_log("JackCoreAudioDriver::SetupDevices : will take default input");
  974. if (GetDefaultInputDevice(&captureID) != noErr) {
  975. jack_error("Cannot open default input device");
  976. return -1;
  977. }
  978. }
  979. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  980. jack_log("JackCoreAudioDriver::SetupDevices : will take default output");
  981. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  982. jack_error("Cannot open default output device");
  983. return -1;
  984. }
  985. }
  986. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
  987. return -1;
  988. }
  989. GetDeviceNameFromID(captureID, fCaptureUID);
  990. GetDeviceNameFromID(playbackID, fPlaybackUID);
  991. }
  992. // Capture only
  993. } else if (strcmp(capture_driver_uid, "") != 0) {
  994. jack_log("JackCoreAudioDriver::SetupDevices : capture only");
  995. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  996. jack_log("JackCoreAudioDriver::SetupDevices : will take default input");
  997. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  998. jack_error("Cannot open default input device");
  999. return -1;
  1000. }
  1001. }
  1002. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  1003. jack_error("Cannot get device name from device ID");
  1004. return -1;
  1005. }
  1006. // Playback only
  1007. } else if (strcmp(playback_driver_uid, "") != 0) {
  1008. jack_log("JackCoreAudioDriver::SetupDevices : playback only");
  1009. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  1010. jack_log("JackCoreAudioDriver::SetupDevices : will take default output");
  1011. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  1012. jack_error("Cannot open default output device");
  1013. return -1;
  1014. }
  1015. }
  1016. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  1017. jack_error("Cannot get device name from device ID");
  1018. return -1;
  1019. }
  1020. // Use default driver in duplex mode
  1021. } else {
  1022. jack_log("JackCoreAudioDriver::SetupDevices : default driver");
  1023. if (GetDefaultDevice(&fDeviceID) != noErr) {
  1024. jack_error("Cannot open default device in duplex mode, so aggregate default input and default output");
  1025. // Creates aggregate device
  1026. AudioDeviceID captureID, playbackID;
  1027. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  1028. jack_log("JackCoreAudioDriver::SetupDevices : will take default input");
  1029. if (GetDefaultInputDevice(&captureID) != noErr) {
  1030. jack_error("Cannot open default input device");
  1031. return -1;
  1032. }
  1033. }
  1034. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  1035. jack_log("JackCoreAudioDriver::SetupDevices : will take default output");
  1036. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  1037. jack_error("Cannot open default output device");
  1038. return -1;
  1039. }
  1040. }
  1041. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
  1042. return -1;
  1043. }
  1044. GetDeviceNameFromID(captureID, fCaptureUID);
  1045. GetDeviceNameFromID(playbackID, fPlaybackUID);
  1046. }
  1047. }
  1048. if (fHogged) {
  1049. if (TakeHog()) {
  1050. jack_info("Device = %ld has been hogged", fDeviceID);
  1051. }
  1052. }
  1053. return 0;
  1054. }
  1055. /*
  1056. Return the max possible input channels in in_nChannels and output channels in out_nChannels.
  1057. */
  1058. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
  1059. {
  1060. OSStatus err = noErr;
  1061. if (capturing) {
  1062. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  1063. if (err != noErr) {
  1064. jack_error("JackCoreAudioDriver::SetupChannels : cannot get input channel number");
  1065. printError(err);
  1066. return -1;
  1067. } else {
  1068. jack_log("JackCoreAudioDriver::SetupChannels : max input channels : %d", in_nChannels);
  1069. }
  1070. }
  1071. if (playing) {
  1072. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  1073. if (err != noErr) {
  1074. jack_error("Cannot get output channel number");
  1075. printError(err);
  1076. return -1;
  1077. } else {
  1078. jack_log("JackCoreAudioDriver::SetupChannels : max output channels : %d", out_nChannels);
  1079. }
  1080. }
  1081. if (inchannels > in_nChannels) {
  1082. jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
  1083. if (strict) {
  1084. return -1;
  1085. }
  1086. }
  1087. if (outchannels > out_nChannels) {
  1088. jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
  1089. if (strict) {
  1090. return -1;
  1091. }
  1092. }
  1093. if (inchannels == -1) {
  1094. jack_log("JackCoreAudioDriver::SetupChannels : setup max in channels = %d", in_nChannels);
  1095. inchannels = in_nChannels;
  1096. }
  1097. if (outchannels == -1) {
  1098. jack_log("JackCoreAudioDriver::SetupChannels : setup max out channels = %d", out_nChannels);
  1099. outchannels = out_nChannels;
  1100. }
  1101. return 0;
  1102. }
  1103. int JackCoreAudioDriver::SetupBufferSize(jack_nframes_t buffer_size)
  1104. {
  1105. // Setting buffer size
  1106. OSStatus err = noErr;
  1107. UInt32 tmp_buffer_size = buffer_size;
  1108. UInt32 outSize = sizeof(UInt32);
  1109. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, &outSize, &tmp_buffer_size);
  1110. if (err != noErr) {
  1111. jack_error("Cannot get buffer size %ld", buffer_size);
  1112. printError(err);
  1113. return -1;
  1114. } else {
  1115. jack_log("JackCoreAudioDriver::SetupBufferSize : current buffer size = %ld", tmp_buffer_size);
  1116. }
  1117. // If needed, set new buffer size
  1118. if (buffer_size != tmp_buffer_size) {
  1119. tmp_buffer_size = buffer_size;
  1120. // To get BS change notification
  1121. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyBufferFrameSize, BSNotificationCallback, this);
  1122. if (err != noErr) {
  1123. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyBufferFrameSize");
  1124. printError(err);
  1125. return -1;
  1126. }
  1127. // Waiting for BS change notification
  1128. int count = 0;
  1129. fState = false;
  1130. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, outSize, &tmp_buffer_size);
  1131. if (err != noErr) {
  1132. jack_error("JackCoreAudioDriver::SetupBufferSize : cannot set buffer size = %ld", tmp_buffer_size);
  1133. printError(err);
  1134. goto error;
  1135. }
  1136. while (!fState && count++ < WAIT_NOTIFICATION_COUNTER) {
  1137. usleep(100000);
  1138. jack_log("JackCoreAudioDriver::SetupBufferSize : wait count = %d", count);
  1139. }
  1140. if (count >= WAIT_NOTIFICATION_COUNTER) {
  1141. jack_error("Did not get buffer size notification...");
  1142. goto error;
  1143. }
  1144. // Check new buffer size
  1145. outSize = sizeof(UInt32);
  1146. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, &outSize, &tmp_buffer_size);
  1147. if (err != noErr) {
  1148. jack_error("Cannot get current buffer size");
  1149. printError(err);
  1150. } else {
  1151. jack_log("JackCoreAudioDriver::SetupBufferSize : checked buffer size = %ld", tmp_buffer_size);
  1152. }
  1153. // Remove BS change notification
  1154. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyBufferFrameSize, BSNotificationCallback);
  1155. }
  1156. return 0;
  1157. error:
  1158. // Remove SR change notification
  1159. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyBufferFrameSize, BSNotificationCallback);
  1160. return -1;
  1161. }
  1162. int JackCoreAudioDriver::SetupSampleRate(jack_nframes_t sample_rate)
  1163. {
  1164. return SetupSampleRateAux(fDeviceID, sample_rate);
  1165. }
  1166. int JackCoreAudioDriver::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t sample_rate)
  1167. {
  1168. OSStatus err = noErr;
  1169. UInt32 outSize;
  1170. Float64 tmp_sample_rate;
  1171. // Get sample rate
  1172. outSize = sizeof(Float64);
  1173. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &tmp_sample_rate);
  1174. if (err != noErr) {
  1175. jack_error("Cannot get current sample rate");
  1176. printError(err);
  1177. return -1;
  1178. } else {
  1179. jack_log("JackCoreAudioDriver::SetupSampleRateAux : current sample rate = %f", tmp_sample_rate);
  1180. }
  1181. // If needed, set new sample rate
  1182. if (sample_rate != (jack_nframes_t)tmp_sample_rate) {
  1183. tmp_sample_rate = (Float64)sample_rate;
  1184. // To get SR change notification
  1185. err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  1186. if (err != noErr) {
  1187. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  1188. printError(err);
  1189. return -1;
  1190. }
  1191. // Waiting for SR change notification
  1192. int count = 0;
  1193. fState = false;
  1194. err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &tmp_sample_rate);
  1195. if (err != noErr) {
  1196. jack_error("Cannot set sample rate = %ld", sample_rate);
  1197. printError(err);
  1198. goto error;
  1199. }
  1200. while (!fState && count++ < WAIT_NOTIFICATION_COUNTER) {
  1201. usleep(100000);
  1202. jack_log("JackCoreAudioDriver::SetupSampleRateAux : wait count = %d", count);
  1203. }
  1204. if (count >= WAIT_NOTIFICATION_COUNTER) {
  1205. jack_error("Did not get sample rate notification...");
  1206. goto error;
  1207. }
  1208. // Check new sample rate
  1209. outSize = sizeof(Float64);
  1210. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &tmp_sample_rate);
  1211. if (err != noErr) {
  1212. jack_error("Cannot get current sample rate");
  1213. printError(err);
  1214. } else {
  1215. jack_log("JackCoreAudioDriver::SetupSampleRateAux : checked sample rate = %f", tmp_sample_rate);
  1216. }
  1217. // Remove SR change notification
  1218. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  1219. }
  1220. return 0;
  1221. error:
  1222. // Remove SR change notification
  1223. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  1224. return -1;
  1225. }
  1226. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  1227. bool playing,
  1228. int inchannels,
  1229. int outchannels,
  1230. int in_nChannels,
  1231. int out_nChannels,
  1232. const vector<int>& chan_in_list,
  1233. const vector<int>& chan_out_list,
  1234. jack_nframes_t buffer_size,
  1235. jack_nframes_t sample_rate)
  1236. {
  1237. ComponentResult err1;
  1238. UInt32 enableIO;
  1239. AudioStreamBasicDescription srcFormat, dstFormat;
  1240. AudioDeviceID currAudioDeviceID;
  1241. UInt32 size;
  1242. jack_log("JackCoreAudioDriver::OpenAUHAL : capturing = %d playing = %d inchannels = %d outchannels = %d in_nChannels = %d out_nChannels = %d chan_in_list = %d chan_out_list = %d",
  1243. capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, chan_in_list.size(), chan_out_list.size());
  1244. if (inchannels == 0 && outchannels == 0) {
  1245. jack_error("No input and output channels...");
  1246. return -1;
  1247. }
  1248. // AUHAL
  1249. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  1250. Component HALOutput = FindNextComponent(NULL, &cd);
  1251. err1 = OpenAComponent(HALOutput, &fAUHAL);
  1252. if (err1 != noErr) {
  1253. jack_error("Error calling OpenAComponent");
  1254. printError(err1);
  1255. goto error;
  1256. }
  1257. err1 = AudioUnitInitialize(fAUHAL);
  1258. if (err1 != noErr) {
  1259. jack_error("Cannot initialize AUHAL unit");
  1260. printError(err1);
  1261. goto error;
  1262. }
  1263. // Start I/O
  1264. if (capturing && inchannels > 0) {
  1265. enableIO = 1;
  1266. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL input on");
  1267. } else {
  1268. enableIO = 0;
  1269. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL input off");
  1270. }
  1271. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  1272. if (err1 != noErr) {
  1273. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  1274. printError(err1);
  1275. goto error;
  1276. }
  1277. if (playing && outchannels > 0) {
  1278. enableIO = 1;
  1279. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL output on");
  1280. } else {
  1281. enableIO = 0;
  1282. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL output off");
  1283. }
  1284. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  1285. if (err1 != noErr) {
  1286. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  1287. printError(err1);
  1288. goto error;
  1289. }
  1290. size = sizeof(AudioDeviceID);
  1291. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  1292. if (err1 != noErr) {
  1293. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  1294. printError(err1);
  1295. goto error;
  1296. } else {
  1297. jack_log("JackCoreAudioDriver::OpenAUHAL : AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  1298. }
  1299. // Setup up choosen device, in both input and output cases
  1300. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  1301. if (err1 != noErr) {
  1302. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  1303. printError(err1);
  1304. goto error;
  1305. }
  1306. // Set buffer size
  1307. if (capturing && inchannels > 0) {
  1308. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  1309. if (err1 != noErr) {
  1310. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  1311. printError(err1);
  1312. goto error;
  1313. }
  1314. }
  1315. if (playing && outchannels > 0) {
  1316. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  1317. if (err1 != noErr) {
  1318. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  1319. printError(err1);
  1320. goto error;
  1321. }
  1322. }
  1323. // Setup input channel map
  1324. if (capturing && inchannels > 0 && inchannels <= in_nChannels) {
  1325. SInt32 chanArr[in_nChannels];
  1326. for (int i = 0; i < in_nChannels; i++) {
  1327. chanArr[i] = -1;
  1328. }
  1329. // Explicit mapping
  1330. if (chan_in_list.size() > 0) {
  1331. for (uint i = 0; i < chan_in_list.size(); i++) {
  1332. int chan = chan_in_list[i];
  1333. if (chan < out_nChannels) {
  1334. // The wanted JACK input index for the 'chan' channel value
  1335. chanArr[chan] = i;
  1336. jack_info("Input channel = %d ==> JACK input port = %d", chan, i);
  1337. } else {
  1338. jack_info("Error input channel number is incorrect : %d", chan);
  1339. goto error;
  1340. }
  1341. }
  1342. } else {
  1343. for (int i = 0; i < inchannels; i++) {
  1344. chanArr[i] = i;
  1345. jack_info("Input channel = %d ==> JACK input port = %d", chanArr[i], i);
  1346. }
  1347. }
  1348. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  1349. if (err1 != noErr) {
  1350. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap for input");
  1351. printError(err1);
  1352. goto error;
  1353. }
  1354. }
  1355. // Setup output channel map
  1356. if (playing && outchannels > 0 && outchannels <= out_nChannels) {
  1357. SInt32 chanArr[out_nChannels];
  1358. for (int i = 0; i < out_nChannels; i++) {
  1359. chanArr[i] = -1;
  1360. }
  1361. // Explicit mapping
  1362. if (chan_out_list.size() > 0) {
  1363. for (uint i = 0; i < chan_out_list.size(); i++) {
  1364. int chan = chan_out_list[i];
  1365. if (chan < out_nChannels) {
  1366. // The wanted JACK output index for the 'chan' channel value
  1367. chanArr[chan] = i;
  1368. jack_info("JACK output port = %d ==> output channel = %d", i, chan);
  1369. } else {
  1370. jack_info("Error output channel number is incorrect : %d", chan);
  1371. goto error;
  1372. }
  1373. }
  1374. } else {
  1375. for (int i = 0; i < outchannels; i++) {
  1376. chanArr[i] = i;
  1377. jack_info("JACK output port = %d ==> output channel = %d", i, chanArr[i]);
  1378. }
  1379. }
  1380. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  1381. if (err1 != noErr) {
  1382. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap for output");
  1383. printError(err1);
  1384. goto error;
  1385. }
  1386. }
  1387. // Setup stream converters
  1388. if (capturing && inchannels > 0) {
  1389. size = sizeof(AudioStreamBasicDescription);
  1390. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, &size);
  1391. if (err1 != noErr) {
  1392. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1393. printError(err1);
  1394. goto error;
  1395. }
  1396. PrintStreamDesc(&srcFormat);
  1397. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL input stream converter SR = %ld", sample_rate);
  1398. srcFormat.mSampleRate = sample_rate;
  1399. srcFormat.mFormatID = kAudioFormatLinearPCM;
  1400. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1401. srcFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  1402. srcFormat.mFramesPerPacket = 1;
  1403. srcFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  1404. srcFormat.mChannelsPerFrame = inchannels;
  1405. srcFormat.mBitsPerChannel = 32;
  1406. PrintStreamDesc(&srcFormat);
  1407. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
  1408. if (err1 != noErr) {
  1409. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1410. printError(err1);
  1411. goto error;
  1412. }
  1413. }
  1414. if (playing && outchannels > 0) {
  1415. size = sizeof(AudioStreamBasicDescription);
  1416. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, &size);
  1417. if (err1 != noErr) {
  1418. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  1419. printError(err1);
  1420. goto error;
  1421. }
  1422. PrintStreamDesc(&dstFormat);
  1423. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL output stream converter SR = %ld", sample_rate);
  1424. dstFormat.mSampleRate = sample_rate;
  1425. dstFormat.mFormatID = kAudioFormatLinearPCM;
  1426. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1427. dstFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  1428. dstFormat.mFramesPerPacket = 1;
  1429. dstFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  1430. dstFormat.mChannelsPerFrame = outchannels;
  1431. dstFormat.mBitsPerChannel = 32;
  1432. PrintStreamDesc(&dstFormat);
  1433. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
  1434. if (err1 != noErr) {
  1435. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  1436. printError(err1);
  1437. goto error;
  1438. }
  1439. }
  1440. // Setup callbacks
  1441. if (inchannels > 0 && outchannels == 0) {
  1442. AURenderCallbackStruct output;
  1443. output.inputProc = Render;
  1444. output.inputProcRefCon = this;
  1445. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  1446. if (err1 != noErr) {
  1447. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  1448. printError(err1);
  1449. goto error;
  1450. }
  1451. } else {
  1452. AURenderCallbackStruct output;
  1453. output.inputProc = Render;
  1454. output.inputProcRefCon = this;
  1455. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  1456. if (err1 != noErr) {
  1457. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  1458. printError(err1);
  1459. goto error;
  1460. }
  1461. }
  1462. return 0;
  1463. error:
  1464. CloseAUHAL();
  1465. return -1;
  1466. }
  1467. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  1468. {
  1469. // Prepare buffers
  1470. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  1471. fJackInputData->mNumberBuffers = inchannels;
  1472. for (int i = 0; i < inchannels; i++) {
  1473. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1474. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  1475. }
  1476. return 0;
  1477. }
  1478. void JackCoreAudioDriver::DisposeBuffers()
  1479. {
  1480. if (fJackInputData) {
  1481. free(fJackInputData);
  1482. fJackInputData = 0;
  1483. }
  1484. }
  1485. void JackCoreAudioDriver::CloseAUHAL()
  1486. {
  1487. AudioOutputUnitStop(fAUHAL);
  1488. AudioUnitUninitialize(fAUHAL);
  1489. CloseComponent(fAUHAL);
  1490. }
  1491. int JackCoreAudioDriver::AddListeners()
  1492. {
  1493. OSStatus err = noErr;
  1494. // Add listeners
  1495. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  1496. if (err != noErr) {
  1497. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  1498. printError(err);
  1499. return -1;
  1500. }
  1501. err = AudioHardwareAddPropertyListener(kAudioHardwarePropertyDevices, AudioHardwareNotificationCallback, this);
  1502. if (err != noErr) {
  1503. jack_error("Error calling AudioHardwareAddPropertyListener with kAudioHardwarePropertyDevices");
  1504. printError(err);
  1505. return -1;
  1506. }
  1507. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  1508. if (err != noErr) {
  1509. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  1510. printError(err);
  1511. return -1;
  1512. }
  1513. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  1514. if (err != noErr) {
  1515. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  1516. printError(err);
  1517. return -1;
  1518. }
  1519. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsAlive, DeviceNotificationCallback, this);
  1520. if (err != noErr) {
  1521. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsAlive");
  1522. printError(err);
  1523. return -1;
  1524. }
  1525. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceHasChanged, DeviceNotificationCallback, this);
  1526. if (err != noErr) {
  1527. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceHasChanged");
  1528. printError(err);
  1529. return -1;
  1530. }
  1531. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1532. if (err != noErr) {
  1533. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1534. printError(err);
  1535. return -1;
  1536. }
  1537. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1538. if (err != noErr) {
  1539. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1540. printError(err);
  1541. return -1;
  1542. }
  1543. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  1544. UInt32 outSize = sizeof(float);
  1545. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  1546. if (err != noErr) {
  1547. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  1548. printError(err);
  1549. }
  1550. }
  1551. return 0;
  1552. }
  1553. void JackCoreAudioDriver::RemoveListeners()
  1554. {
  1555. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  1556. AudioHardwareRemovePropertyListener(kAudioHardwarePropertyDevices, AudioHardwareNotificationCallback);
  1557. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  1558. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  1559. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsAlive, DeviceNotificationCallback);
  1560. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceHasChanged, DeviceNotificationCallback);
  1561. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1562. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1563. }
  1564. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  1565. jack_nframes_t sample_rate,
  1566. bool capturing,
  1567. bool playing,
  1568. int inchannels,
  1569. int outchannels,
  1570. const char* chan_in_list,
  1571. const char* chan_out_list,
  1572. bool monitor,
  1573. const char* capture_driver_uid,
  1574. const char* playback_driver_uid,
  1575. jack_nframes_t capture_latency,
  1576. jack_nframes_t playback_latency,
  1577. int async_output_latency,
  1578. int computation_grain,
  1579. bool hogged,
  1580. bool clock_drift)
  1581. {
  1582. int in_nChannels = 0;
  1583. int out_nChannels = 0;
  1584. char capture_driver_name[256];
  1585. char playback_driver_name[256];
  1586. fCaptureLatency = capture_latency;
  1587. fPlaybackLatency = playback_latency;
  1588. fIOUsage = float(async_output_latency) / 100.f;
  1589. fComputationGrain = float(computation_grain) / 100.f;
  1590. fHogged = hogged;
  1591. fClockDriftCompensate = clock_drift;
  1592. SInt32 major;
  1593. SInt32 minor;
  1594. Gestalt(gestaltSystemVersionMajor, &major);
  1595. Gestalt(gestaltSystemVersionMinor, &minor);
  1596. vector<int> parsed_chan_in_list;
  1597. vector<int> parsed_chan_out_list;
  1598. ParseChannelList(chan_in_list, parsed_chan_in_list);
  1599. if (parsed_chan_in_list.size() > 0) {
  1600. jack_info("Explicit input channel list size = %d", parsed_chan_in_list.size());
  1601. inchannels = parsed_chan_in_list.size();
  1602. }
  1603. ParseChannelList(chan_out_list, parsed_chan_out_list);
  1604. if (parsed_chan_out_list.size() > 0) {
  1605. jack_info("Explicit output channel list size = %d", parsed_chan_out_list.size());
  1606. outchannels = parsed_chan_out_list.size();
  1607. }
  1608. // Starting with 10.6 systems, the HAL notification thread is created internally
  1609. if (major == 10 && minor >= 6) {
  1610. CFRunLoopRef theRunLoop = NULL;
  1611. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1612. OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  1613. if (osErr != noErr) {
  1614. jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
  1615. printError(osErr);
  1616. }
  1617. }
  1618. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name, sample_rate) < 0) {
  1619. goto error;
  1620. }
  1621. // Generic JackAudioDriver Open
  1622. if (JackAudioDriver::Open(buffer_size, sample_rate,
  1623. capturing, playing,
  1624. inchannels, outchannels,
  1625. monitor,
  1626. capture_driver_name,
  1627. playback_driver_name,
  1628. capture_latency,
  1629. playback_latency) != 0) {
  1630. goto error;
  1631. }
  1632. if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0) {
  1633. goto error;
  1634. }
  1635. if (SetupBufferSize(buffer_size) < 0) {
  1636. goto error;
  1637. }
  1638. if (SetupSampleRate(sample_rate) < 0) {
  1639. goto error;
  1640. }
  1641. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, parsed_chan_in_list, parsed_chan_out_list, buffer_size, sample_rate) < 0) {
  1642. goto error;
  1643. }
  1644. if (capturing && inchannels > 0) {
  1645. if (SetupBuffers(inchannels) < 0) {
  1646. goto error;
  1647. }
  1648. }
  1649. if (AddListeners() < 0) {
  1650. goto error;
  1651. }
  1652. // Core driver may have changed the in/out values
  1653. fCaptureChannels = inchannels;
  1654. fPlaybackChannels = outchannels;
  1655. return noErr;
  1656. error:
  1657. Close();
  1658. return -1;
  1659. }
  1660. int JackCoreAudioDriver::Close()
  1661. {
  1662. jack_log("JackCoreAudioDriver::Close");
  1663. // Generic audio driver close
  1664. int res = JackAudioDriver::Close();
  1665. RemoveListeners();
  1666. DisposeBuffers();
  1667. CloseAUHAL();
  1668. DestroyAggregateDevice();
  1669. return res;
  1670. }
  1671. void JackCoreAudioDriver::UpdateLatencies()
  1672. {
  1673. UInt32 size;
  1674. OSStatus err;
  1675. jack_latency_range_t input_range;
  1676. jack_latency_range_t output_range;
  1677. jack_latency_range_t monitor_range;
  1678. // Get Input latency
  1679. size = sizeof(UInt32);
  1680. UInt32 value1 = 0;
  1681. UInt32 value2 = 0;
  1682. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1683. if (err != noErr) {
  1684. jack_error("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1685. }
  1686. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1687. if (err != noErr) {
  1688. jack_error("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1689. }
  1690. input_range.min = input_range.max = fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency;
  1691. // Get input stream latencies
  1692. vector<int> input_latencies;
  1693. err = GetStreamLatencies(fDeviceID, true, input_latencies);
  1694. for (int i = 0; i < fCaptureChannels; i++) {
  1695. if (err != noErr) {
  1696. input_range.min += input_latencies[i];
  1697. input_range.max += input_latencies[i];
  1698. }
  1699. fGraphManager->GetPort(fCapturePortList[i])->SetLatencyRange(JackCaptureLatency, &input_range);
  1700. }
  1701. // Get Output latency
  1702. size = sizeof(UInt32);
  1703. value1 = 0;
  1704. value2 = 0;
  1705. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1706. if (err != noErr) {
  1707. jack_error("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1708. }
  1709. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1710. if (err != noErr) {
  1711. jack_error("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1712. }
  1713. // Get output stream latencies
  1714. vector<int> output_latencies;
  1715. err = GetStreamLatencies(fDeviceID, false, output_latencies);
  1716. // Add more latency if "async" mode is used...
  1717. output_range.min = output_range.max = fEngineControl->fBufferSize + ((fEngineControl->fSyncMode)
  1718. ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency;
  1719. for (int i = 0; i < fPlaybackChannels; i++) {
  1720. if (err != noErr) {
  1721. output_range.min += output_latencies[i];
  1722. output_range.max += output_latencies[i];
  1723. }
  1724. fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &output_range);
  1725. // Monitor port
  1726. if (fWithMonitorPorts) {
  1727. monitor_range.min = monitor_range.max = fEngineControl->fBufferSize;
  1728. fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &monitor_range);
  1729. }
  1730. }
  1731. }
  1732. int JackCoreAudioDriver::Attach()
  1733. {
  1734. OSStatus err;
  1735. JackPort* port;
  1736. jack_port_id_t port_index;
  1737. UInt32 size;
  1738. Boolean isWritable;
  1739. char channel_name[64];
  1740. char name[REAL_JACK_PORT_NAME_SIZE];
  1741. char alias[REAL_JACK_PORT_NAME_SIZE];
  1742. jack_log("JackCoreAudioDriver::Attach : fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  1743. for (int i = 0; i < fCaptureChannels; i++) {
  1744. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  1745. if (err != noErr) {
  1746. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1747. }
  1748. if (err == noErr && size > 0) {
  1749. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1750. if (err != noErr) {
  1751. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1752. }
  1753. snprintf(alias, sizeof(alias), "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1754. } else {
  1755. snprintf(alias, sizeof(alias), "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1756. }
  1757. snprintf(name, sizeof(name), "%s:capture_%d", fClientControl.fName, i + 1);
  1758. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, CaptureDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
  1759. jack_error("Cannot register port for %s", name);
  1760. return -1;
  1761. }
  1762. port = fGraphManager->GetPort(port_index);
  1763. port->SetAlias(alias);
  1764. fCapturePortList[i] = port_index;
  1765. }
  1766. for (int i = 0; i < fPlaybackChannels; i++) {
  1767. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1768. if (err != noErr) {
  1769. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1770. }
  1771. if (err == noErr && size > 0) {
  1772. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1773. if (err != noErr) {
  1774. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1775. }
  1776. snprintf(alias, sizeof(alias), "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1777. } else {
  1778. snprintf(alias, sizeof(alias), "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1779. }
  1780. snprintf(name, sizeof(name), "%s:playback_%d", fClientControl.fName, i + 1);
  1781. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, PlaybackDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
  1782. jack_error("Cannot register port for %s", name);
  1783. return -1;
  1784. }
  1785. port = fGraphManager->GetPort(port_index);
  1786. port->SetAlias(alias);
  1787. fPlaybackPortList[i] = port_index;
  1788. // Monitor ports
  1789. if (fWithMonitorPorts) {
  1790. jack_log("JackCoreAudioDriver::Attach : create monitor port");
  1791. snprintf(name, sizeof(name), "%s:monitor_%u", fClientControl.fName, i + 1);
  1792. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, MonitorDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
  1793. jack_error("Cannot register monitor port for %s", name);
  1794. return -1;
  1795. } else {
  1796. fMonitorPortList[i] = port_index;
  1797. }
  1798. }
  1799. }
  1800. UpdateLatencies();
  1801. // Input buffers do no change : prepare them only once
  1802. for (int i = 0; i < fCaptureChannels; i++) {
  1803. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1804. }
  1805. return 0;
  1806. }
  1807. int JackCoreAudioDriver::Start()
  1808. {
  1809. jack_log("JackCoreAudioDriver::Start");
  1810. if (JackAudioDriver::Start() == 0) {
  1811. // Waiting for Render callback to be called (= driver has started)
  1812. fState = false;
  1813. int count = 0;
  1814. OSStatus err = AudioOutputUnitStart(fAUHAL);
  1815. if (err == noErr) {
  1816. while (!fState && count++ < WAIT_COUNTER) {
  1817. usleep(100000);
  1818. jack_log("JackCoreAudioDriver::Start : wait count = %d", count);
  1819. }
  1820. if (count < WAIT_COUNTER) {
  1821. jack_info("CoreAudio driver is running...");
  1822. return 0;
  1823. }
  1824. jack_error("CoreAudio driver cannot start...");
  1825. }
  1826. JackAudioDriver::Stop();
  1827. }
  1828. return -1;
  1829. }
  1830. int JackCoreAudioDriver::Stop()
  1831. {
  1832. jack_log("JackCoreAudioDriver::Stop");
  1833. int res = (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  1834. if (JackAudioDriver::Stop() < 0) {
  1835. res = -1;
  1836. }
  1837. return res;
  1838. }
  1839. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  1840. {
  1841. if (SetupBufferSize(buffer_size) < 0) {
  1842. return -1;
  1843. }
  1844. JackAudioDriver::SetBufferSize(buffer_size); // Generic change, never fails
  1845. // CoreAudio specific
  1846. UpdateLatencies();
  1847. // Input buffers do no change : prepare them only once
  1848. for (int i = 0; i < fCaptureChannels; i++) {
  1849. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1850. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  1851. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1852. }
  1853. return 0;
  1854. }
  1855. bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
  1856. {
  1857. pid_t hog_pid;
  1858. OSStatus err;
  1859. UInt32 propSize = sizeof(hog_pid);
  1860. err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  1861. if (err) {
  1862. jack_error("Cannot read hog state...");
  1863. printError(err);
  1864. }
  1865. if (hog_pid != getpid()) {
  1866. hog_pid = getpid();
  1867. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  1868. if (err != noErr) {
  1869. jack_error("Can't hog device = %d because it's being hogged by another program or cannot be hogged", deviceID);
  1870. return false;
  1871. }
  1872. }
  1873. return true;
  1874. }
  1875. bool JackCoreAudioDriver::TakeHog()
  1876. {
  1877. OSStatus err = noErr;
  1878. AudioObjectID sub_device[32];
  1879. UInt32 outSize = sizeof(sub_device);
  1880. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1881. if (err != noErr) {
  1882. jack_log("JackCoreAudioDriver::TakeHog : device does not have subdevices");
  1883. return TakeHogAux(fDeviceID, true);
  1884. } else {
  1885. int num_devices = outSize / sizeof(AudioObjectID);
  1886. jack_log("JackCoreAudioDriver::TakeHog : device does has %d subdevices", num_devices);
  1887. for (int i = 0; i < num_devices; i++) {
  1888. if (!TakeHogAux(sub_device[i], true)) {
  1889. return false;
  1890. }
  1891. }
  1892. return true;
  1893. }
  1894. }
  1895. bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
  1896. {
  1897. UInt32 deviceType, outSize = sizeof(UInt32);
  1898. OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
  1899. if (err != noErr) {
  1900. jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
  1901. return false;
  1902. } else {
  1903. return (deviceType == kAudioDeviceTransportTypeAggregate);
  1904. }
  1905. }
  1906. } // end of namespace
  1907. #ifdef __cplusplus
  1908. extern "C"
  1909. {
  1910. #endif
  1911. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1912. {
  1913. jack_driver_desc_t * desc;
  1914. jack_driver_desc_filler_t filler;
  1915. jack_driver_param_value_t value;
  1916. desc = jack_driver_descriptor_construct("coreaudio", JackDriverMaster, "Apple CoreAudio API based audio backend", &filler);
  1917. value.i = -1;
  1918. jack_driver_descriptor_add_parameter(desc, &filler, "channels", 'c', JackDriverParamInt, &value, NULL, "Maximum number of channels", "Maximum number of channels. If -1, max possible number of channels will be used");
  1919. jack_driver_descriptor_add_parameter(desc, &filler, "in-channels", 'i', JackDriverParamInt, &value, NULL, "Maximum number of input channels", "Maximum number of input channels. If -1, max possible number of input channels will be used");
  1920. jack_driver_descriptor_add_parameter(desc, &filler, "out-channels", 'o', JackDriverParamInt, &value, NULL, "Maximum number of output channels", "Maximum number of output channels. If -1, max possible number of output channels will be used");
  1921. value.str[0] = 0;
  1922. jack_driver_descriptor_add_parameter(desc, &filler, "input-list", 'n', JackDriverParamString, &value, NULL, "Input channel list", "List of input channel number to be opened");
  1923. jack_driver_descriptor_add_parameter(desc, &filler, "output-list", 'N', JackDriverParamString, &value, NULL, "Output channel list", "List of output channel number to be opened");
  1924. value.str[0] = 0;
  1925. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Input CoreAudio device name", NULL);
  1926. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Output CoreAudio device name", NULL);
  1927. value.i = 0;
  1928. jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);
  1929. value.i = TRUE;
  1930. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  1931. value.ui = 44100U;
  1932. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  1933. value.ui = 256U;
  1934. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  1935. value.str[0] = 0;
  1936. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "CoreAudio device name", NULL);
  1937. value.ui = 0;
  1938. jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency (frames)", NULL);
  1939. jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency (frames)", NULL);
  1940. value.i = FALSE;
  1941. jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available CoreAudio devices", NULL);
  1942. value.i = FALSE;
  1943. jack_driver_descriptor_add_parameter(desc, &filler, "hog", 'H', JackDriverParamBool, &value, NULL, "Take exclusive access of the audio device", NULL);
  1944. value.ui = 100;
  1945. jack_driver_descriptor_add_parameter(desc, &filler, "async-latency", 'L', JackDriverParamUInt, &value, NULL, "Extra output latency in asynchronous mode (percent)", NULL);
  1946. value.ui = 100;
  1947. jack_driver_descriptor_add_parameter(desc, &filler, "grain", 'G', JackDriverParamUInt, &value, NULL, "Computation grain in RT thread (percent)", NULL);
  1948. value.i = FALSE;
  1949. jack_driver_descriptor_add_parameter(desc, &filler, "clock-drift", 's', JackDriverParamBool, &value, NULL, "Clock drift compensation", "Whether to compensate clock drift in dynamically created aggregate device");
  1950. return desc;
  1951. }
  1952. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1953. {
  1954. jack_nframes_t srate = 44100;
  1955. jack_nframes_t frames_per_interrupt = 256;
  1956. bool capture = false;
  1957. bool playback = false;
  1958. int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
  1959. int chan_out = -1; // Default: if not explicitely set, then max possible will be used...
  1960. const char* chan_in_list = "";
  1961. const char* chan_out_list = "";
  1962. bool monitor = false;
  1963. const char* capture_driver_uid = "";
  1964. const char* playback_driver_uid = "";
  1965. const JSList *node;
  1966. const jack_driver_param_t *param;
  1967. jack_nframes_t systemic_input_latency = 0;
  1968. jack_nframes_t systemic_output_latency = 0;
  1969. int async_output_latency = 100;
  1970. int computation_grain = -1;
  1971. bool hogged = false;
  1972. bool clock_drift = false;
  1973. for (node = params; node; node = jack_slist_next(node)) {
  1974. param = (const jack_driver_param_t *) node->data;
  1975. switch (param->character) {
  1976. case 'd':
  1977. capture_driver_uid = param->value.str;
  1978. playback_driver_uid = param->value.str;
  1979. break;
  1980. case 'D':
  1981. capture = true;
  1982. playback = true;
  1983. break;
  1984. case 'c':
  1985. chan_in = chan_out = param->value.i;
  1986. break;
  1987. case 'i':
  1988. chan_in = param->value.i;
  1989. break;
  1990. case 'o':
  1991. chan_out = param->value.i;
  1992. break;
  1993. case 'n':
  1994. chan_in_list = param->value.str;
  1995. break;
  1996. case 'N':
  1997. chan_out_list = param->value.str;
  1998. break;
  1999. case 'C':
  2000. capture = true;
  2001. if (strcmp(param->value.str, "none") != 0) {
  2002. capture_driver_uid = param->value.str;
  2003. }
  2004. break;
  2005. case 'P':
  2006. playback = true;
  2007. if (strcmp(param->value.str, "none") != 0) {
  2008. playback_driver_uid = param->value.str;
  2009. }
  2010. break;
  2011. case 'm':
  2012. monitor = param->value.i;
  2013. break;
  2014. case 'r':
  2015. srate = param->value.ui;
  2016. break;
  2017. case 'p':
  2018. frames_per_interrupt = (unsigned int)param->value.ui;
  2019. break;
  2020. case 'I':
  2021. systemic_input_latency = param->value.ui;
  2022. break;
  2023. case 'O':
  2024. systemic_output_latency = param->value.ui;
  2025. break;
  2026. case 'l':
  2027. Jack::DisplayDeviceNames();
  2028. // Stops the server in this case
  2029. return NULL;
  2030. case 'H':
  2031. hogged = true;
  2032. break;
  2033. case 'L':
  2034. async_output_latency = param->value.ui;
  2035. break;
  2036. case 'G':
  2037. computation_grain = param->value.ui;
  2038. break;
  2039. case 's':
  2040. clock_drift = true;
  2041. break;
  2042. }
  2043. }
  2044. /* duplex is the default */
  2045. if (!capture && !playback) {
  2046. capture = true;
  2047. playback = true;
  2048. }
  2049. if (strcmp(chan_in_list, "") != 0 && chan_in >= 0) {
  2050. printf("Input channel list and in channels are both specified, input channel list will take over...\n");
  2051. }
  2052. if (strcmp(chan_out_list, "") != 0 && chan_out >= 0) {
  2053. printf("Output channel list and out channels are both specified, output channel list will take over...\n");
  2054. }
  2055. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  2056. if (driver->Open(frames_per_interrupt,
  2057. srate, capture,
  2058. playback, chan_in,
  2059. chan_out, chan_in_list,
  2060. chan_out_list, monitor,
  2061. capture_driver_uid,
  2062. playback_driver_uid,
  2063. systemic_input_latency,
  2064. systemic_output_latency,
  2065. async_output_latency,
  2066. computation_grain,
  2067. hogged, clock_drift) == 0) {
  2068. return driver;
  2069. } else {
  2070. delete driver;
  2071. return NULL;
  2072. }
  2073. }
  2074. #ifdef __cplusplus
  2075. }
  2076. #endif