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.

2725 lines
106KB

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