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.

2634 lines
102KB

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