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.

2540 lines
99KB

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