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.

2701 lines
105KB

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