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.

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