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.

2695 lines
104KB

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