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.

2716 lines
105KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include "JackCoreAudioDriver.h"
  16. #include "JackEngineControl.h"
  17. #include "JackMachThread.h"
  18. #include "JackGraphManager.h"
  19. #include "JackError.h"
  20. #include "JackClientControl.h"
  21. #include "JackDriverLoader.h"
  22. #include "JackGlobals.h"
  23. #include "JackTools.h"
  24. #include "JackLockedEngine.h"
  25. #include "JackAC3Encoder.h"
  26. #include <sstream>
  27. #include <iostream>
  28. #include <CoreServices/CoreServices.h>
  29. #include <CoreFoundation/CFNumber.h>
  30. namespace Jack
  31. {
  32. static void Print4CharCode(const char* msg, long c)
  33. {
  34. UInt32 __4CC_number = (c);
  35. char __4CC_string[5];
  36. *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
  37. __4CC_string[4] = 0;
  38. jack_log("%s'%s'", (msg), __4CC_string);
  39. }
  40. static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
  41. {
  42. jack_log("- - - - - - - - - - - - - - - - - - - -");
  43. jack_log(" Sample Rate:%f", inDesc->mSampleRate);
  44. jack_log(" Format ID:%.*s", (int)sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
  45. jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
  46. jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
  47. jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
  48. jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
  49. jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
  50. jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
  51. jack_log("- - - - - - - - - - - - - - - - - - - -");
  52. }
  53. static void printError(OSStatus err)
  54. {
  55. switch (err) {
  56. case kAudioHardwareNoError:
  57. jack_log("error code : kAudioHardwareNoError");
  58. break;
  59. case kAudioConverterErr_FormatNotSupported:
  60. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  61. break;
  62. case kAudioConverterErr_OperationNotSupported:
  63. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  64. break;
  65. case kAudioConverterErr_PropertyNotSupported:
  66. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  67. break;
  68. case kAudioConverterErr_InvalidInputSize:
  69. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  70. break;
  71. case kAudioConverterErr_InvalidOutputSize:
  72. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  73. break;
  74. case kAudioConverterErr_UnspecifiedError:
  75. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  76. break;
  77. case kAudioConverterErr_BadPropertySizeError:
  78. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  79. break;
  80. case kAudioConverterErr_RequiresPacketDescriptionsError:
  81. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  82. break;
  83. case kAudioConverterErr_InputSampleRateOutOfRange:
  84. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  85. break;
  86. case kAudioConverterErr_OutputSampleRateOutOfRange:
  87. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  88. break;
  89. case kAudioHardwareNotRunningError:
  90. jack_log("error code : kAudioHardwareNotRunningError");
  91. break;
  92. case kAudioHardwareUnknownPropertyError:
  93. jack_log("error code : kAudioHardwareUnknownPropertyError");
  94. break;
  95. case kAudioHardwareIllegalOperationError:
  96. jack_log("error code : kAudioHardwareIllegalOperationError");
  97. break;
  98. case kAudioHardwareBadDeviceError:
  99. jack_log("error code : kAudioHardwareBadDeviceError");
  100. break;
  101. case kAudioHardwareBadStreamError:
  102. jack_log("error code : kAudioHardwareBadStreamError");
  103. break;
  104. case kAudioDeviceUnsupportedFormatError:
  105. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  106. break;
  107. case kAudioDevicePermissionsError:
  108. jack_log("error code : kAudioDevicePermissionsError");
  109. break;
  110. case kAudioHardwareBadObjectError:
  111. jack_log("error code : kAudioHardwareBadObjectError");
  112. break;
  113. case kAudioHardwareUnsupportedOperationError:
  114. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  115. break;
  116. default:
  117. Print4CharCode("error code : unknown ", err);
  118. break;
  119. }
  120. }
  121. static bool CheckAvailableDeviceName(const char* device_name, AudioDeviceID* device_id)
  122. {
  123. UInt32 size;
  124. Boolean isWritable;
  125. int i, deviceNum;
  126. OSStatus err;
  127. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  128. if (err != noErr) {
  129. return false;
  130. }
  131. deviceNum = size / sizeof(AudioDeviceID);
  132. AudioDeviceID devices[deviceNum];
  133. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  134. if (err != noErr) {
  135. return false;
  136. }
  137. for (i = 0; i < deviceNum; i++) {
  138. char device_name_aux[256];
  139. size = 256;
  140. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name_aux);
  141. if (err != noErr) {
  142. return false;
  143. }
  144. if (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. if (err != noErr) {
  727. jack_log("JackCoreAudioDriver::CreateAggregateDevice : input device does not have subdevices");
  728. captureDeviceIDArray.push_back(captureDeviceID);
  729. } else {
  730. int num_devices = outSize / sizeof(AudioObjectID);
  731. jack_log("JackCoreAudioDriver::CreateAggregateDevice :Input device has %d subdevices", num_devices);
  732. for (int i = 0; i < num_devices; i++) {
  733. captureDeviceIDArray.push_back(sub_device[i]);
  734. }
  735. }
  736. err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  737. vector<AudioDeviceID> playbackDeviceIDArray;
  738. if (err != noErr) {
  739. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output device does not have subdevices");
  740. playbackDeviceIDArray.push_back(playbackDeviceID);
  741. } else {
  742. int num_devices = outSize / sizeof(AudioObjectID);
  743. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output device has %d subdevices", num_devices);
  744. for (int i = 0; i < num_devices; i++) {
  745. playbackDeviceIDArray.push_back(sub_device[i]);
  746. }
  747. }
  748. return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
  749. }
  750. OSStatus JackCoreAudioDriver::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  751. {
  752. OSStatus osErr = noErr;
  753. UInt32 outSize;
  754. Boolean outWritable;
  755. // Prepare sub-devices for clock drift compensation
  756. // Workaround for bug in the HAL : until 10.6.2
  757. AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  758. AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  759. UInt32 theQualifierDataSize = sizeof(AudioObjectID);
  760. AudioClassID inClass = kAudioSubDeviceClassID;
  761. void* theQualifierData = &inClass;
  762. UInt32 subDevicesNum = 0;
  763. //---------------------------------------------------------------------------
  764. // Setup SR of both devices otherwise creating AD may fail...
  765. //---------------------------------------------------------------------------
  766. UInt32 keptclockdomain = 0;
  767. UInt32 clockdomain = 0;
  768. outSize = sizeof(UInt32);
  769. bool need_clock_drift_compensation = false;
  770. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  771. if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
  772. jack_error("CreateAggregateDevice : cannot set SR of input device");
  773. } else {
  774. // Check clock domain
  775. osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  776. if (osErr != 0) {
  777. jack_error("CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  778. printError(osErr);
  779. } else {
  780. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  781. jack_log("JackCoreAudioDriver::CreateAggregateDevice : input clockdomain = %d", clockdomain);
  782. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  783. jack_error("CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  784. need_clock_drift_compensation = true;
  785. }
  786. }
  787. }
  788. }
  789. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  790. if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
  791. jack_error("CreateAggregateDevice : cannot set SR of output device");
  792. } else {
  793. // Check clock domain
  794. osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  795. if (osErr != 0) {
  796. jack_error("CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  797. printError(osErr);
  798. } else {
  799. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  800. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output clockdomain = %d", clockdomain);
  801. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  802. jack_error("CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  803. need_clock_drift_compensation = true;
  804. }
  805. }
  806. }
  807. }
  808. // If no valid clock domain was found, then assume we have to compensate...
  809. if (keptclockdomain == 0) {
  810. need_clock_drift_compensation = true;
  811. }
  812. //---------------------------------------------------------------------------
  813. // Start to create a new aggregate by getting the base audio hardware plugin
  814. //---------------------------------------------------------------------------
  815. char device_name[256];
  816. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  817. GetDeviceNameFromID(captureDeviceID[i], device_name);
  818. jack_info("Separated input = '%s' ", device_name);
  819. }
  820. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  821. GetDeviceNameFromID(playbackDeviceID[i], device_name);
  822. jack_info("Separated output = '%s' ", device_name);
  823. }
  824. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  825. if (osErr != noErr) {
  826. jack_error("CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
  827. printError(osErr);
  828. return osErr;
  829. }
  830. AudioValueTranslation pluginAVT;
  831. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  832. pluginAVT.mInputData = &inBundleRef;
  833. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  834. pluginAVT.mOutputData = &fPluginID;
  835. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  836. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  837. if (osErr != noErr) {
  838. jack_error("CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
  839. printError(osErr);
  840. return osErr;
  841. }
  842. //-------------------------------------------------
  843. // Create a CFDictionary for our aggregate device
  844. //-------------------------------------------------
  845. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  846. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  847. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  848. // add the name of the device to the dictionary
  849. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  850. // add our choice of UID for the aggregate device to the dictionary
  851. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  852. // add a "private aggregate key" to the dictionary
  853. int value = 1;
  854. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  855. SInt32 system;
  856. Gestalt(gestaltSystemVersion, &system);
  857. jack_log("JackCoreAudioDriver::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
  858. // Starting with 10.5.4 systems, the AD can be internal... (better)
  859. if (system < 0x00001054) {
  860. jack_log("JackCoreAudioDriver::CreateAggregateDevice : public aggregate device....");
  861. } else {
  862. jack_log("JackCoreAudioDriver::CreateAggregateDevice : private aggregate device....");
  863. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  864. }
  865. // Prepare sub-devices for clock drift compensation
  866. CFMutableArrayRef subDevicesArrayClock = NULL;
  867. /*
  868. if (fClockDriftCompensate) {
  869. if (need_clock_drift_compensation) {
  870. jack_info("Clock drift compensation activated...");
  871. subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  872. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  873. CFStringRef UID = GetDeviceName(captureDeviceID[i]);
  874. if (UID) {
  875. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  876. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  877. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  878. //CFRelease(UID);
  879. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  880. }
  881. }
  882. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  883. CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
  884. if (UID) {
  885. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  886. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  887. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  888. //CFRelease(UID);
  889. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  890. }
  891. }
  892. // add sub-device clock array for the aggregate device to the dictionary
  893. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
  894. } else {
  895. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  896. }
  897. }
  898. */
  899. //-------------------------------------------------
  900. // Create a CFMutableArray for our sub-device list
  901. //-------------------------------------------------
  902. // we need to append the UID for each device to a CFMutableArray, so create one here
  903. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  904. vector<CFStringRef> captureDeviceUID;
  905. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  906. CFStringRef ref = GetDeviceName(captureDeviceID[i]);
  907. if (ref == NULL) {
  908. return -1;
  909. }
  910. captureDeviceUID.push_back(ref);
  911. // input sub-devices in this example, so append the sub-device's UID to the CFArray
  912. CFArrayAppendValue(subDevicesArray, ref);
  913. }
  914. vector<CFStringRef> playbackDeviceUID;
  915. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  916. CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
  917. if (ref == NULL) {
  918. return -1;
  919. }
  920. playbackDeviceUID.push_back(ref);
  921. // output sub-devices in this example, so append the sub-device's UID to the CFArray
  922. CFArrayAppendValue(subDevicesArray, ref);
  923. }
  924. //-----------------------------------------------------------------------
  925. // Feed the dictionary to the plugin, to create a blank aggregate device
  926. //-----------------------------------------------------------------------
  927. AudioObjectPropertyAddress pluginAOPA;
  928. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  929. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  930. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  931. UInt32 outDataSize;
  932. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  933. if (osErr != noErr) {
  934. jack_error("CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
  935. printError(osErr);
  936. goto error;
  937. }
  938. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  939. if (osErr != noErr) {
  940. jack_error("CreateAggregateDevice : AudioObjectGetPropertyData error");
  941. printError(osErr);
  942. goto error;
  943. }
  944. // pause for a bit to make sure that everything completed correctly
  945. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  946. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  947. //-------------------------
  948. // Set the sub-device list
  949. //-------------------------
  950. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  951. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  952. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  953. outDataSize = sizeof(CFMutableArrayRef);
  954. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  955. if (osErr != noErr) {
  956. jack_error("CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
  957. printError(osErr);
  958. goto error;
  959. }
  960. // pause again to give the changes time to take effect
  961. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  962. //-----------------------
  963. // Set the master device
  964. //-----------------------
  965. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  966. // pass in the UID of the device you want to use
  967. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  968. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  969. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  970. outDataSize = sizeof(CFStringRef);
  971. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
  972. if (osErr != noErr) {
  973. jack_error("CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
  974. printError(osErr);
  975. goto error;
  976. }
  977. // pause again to give the changes time to take effect
  978. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  979. // Prepare sub-devices for clock drift compensation
  980. // Workaround for bug in the HAL : until 10.6.2
  981. if (fClockDriftCompensate) {
  982. if (need_clock_drift_compensation) {
  983. jack_info("Clock drift compensation activated...");
  984. // Get the property data size
  985. osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
  986. if (osErr != noErr) {
  987. jack_error("CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  988. printError(osErr);
  989. }
  990. // Calculate the number of object IDs
  991. subDevicesNum = outSize / sizeof(AudioObjectID);
  992. jack_info("JackCoreAudioDriver::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
  993. AudioObjectID subDevices[subDevicesNum];
  994. outSize = sizeof(subDevices);
  995. osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
  996. if (osErr != noErr) {
  997. jack_error("CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  998. printError(osErr);
  999. }
  1000. // Set kAudioSubDevicePropertyDriftCompensation property...
  1001. for (UInt32 index = 0; index < subDevicesNum; ++index) {
  1002. UInt32 theDriftCompensationValue = 1;
  1003. osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
  1004. if (osErr != noErr) {
  1005. jack_error("CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
  1006. printError(osErr);
  1007. }
  1008. }
  1009. } else {
  1010. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  1011. }
  1012. }
  1013. // pause again to give the changes time to take effect
  1014. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1015. //----------
  1016. // Clean up
  1017. //----------
  1018. // release the private AD key
  1019. CFRelease(AggregateDeviceNumberRef);
  1020. // release the CF objects we have created - we don't need them any more
  1021. CFRelease(aggDeviceDict);
  1022. CFRelease(subDevicesArray);
  1023. if (subDevicesArrayClock) {
  1024. CFRelease(subDevicesArrayClock);
  1025. }
  1026. // release the device UID
  1027. for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
  1028. CFRelease(captureDeviceUID[i]);
  1029. }
  1030. for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
  1031. CFRelease(playbackDeviceUID[i]);
  1032. }
  1033. jack_log("JackCoreAudioDriver::CreateAggregateDeviceAux : new aggregate device %ld", *outAggregateDevice);
  1034. return noErr;
  1035. error:
  1036. DestroyAggregateDevice();
  1037. return -1;
  1038. }
  1039. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid,
  1040. const char* playback_driver_uid,
  1041. char* capture_driver_name,
  1042. char* playback_driver_name,
  1043. jack_nframes_t samplerate,
  1044. bool ac3_encoding)
  1045. {
  1046. capture_driver_name[0] = 0;
  1047. playback_driver_name[0] = 0;
  1048. // Duplex
  1049. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  1050. jack_log("JackCoreAudioDriver::SetupDevices : duplex");
  1051. // Same device for capture and playback...
  1052. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  1053. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  1054. jack_log("JackCoreAudioDriver::SetupDevices : will take default in/out");
  1055. if (GetDefaultDevice(&fDeviceID) != noErr) {
  1056. jack_error("Cannot open default device");
  1057. return -1;
  1058. }
  1059. }
  1060. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  1061. jack_error("Cannot get device name from device ID");
  1062. return -1;
  1063. }
  1064. if (fHogged) {
  1065. if (!TakeHogAux(fDeviceID, false)) {
  1066. jack_error("Cannot take hog mode");
  1067. }
  1068. if (ac3_encoding) {
  1069. fDigitalPlayback = IsDigitalDevice(fDeviceID);
  1070. }
  1071. }
  1072. } else {
  1073. // Creates aggregate device
  1074. AudioDeviceID captureID = -1;
  1075. AudioDeviceID playbackID = -1;
  1076. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  1077. jack_log("JackCoreAudioDriver::SetupDevices : will take default input");
  1078. if (GetDefaultInputDevice(&captureID) != noErr) {
  1079. jack_error("Cannot open default input device");
  1080. return -1;
  1081. }
  1082. }
  1083. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  1084. jack_log("JackCoreAudioDriver::SetupDevices : will take default output");
  1085. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  1086. jack_error("Cannot open default output device");
  1087. return -1;
  1088. }
  1089. }
  1090. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
  1091. return -1;
  1092. }
  1093. GetDeviceNameFromID(captureID, fCaptureUID);
  1094. GetDeviceNameFromID(playbackID, fPlaybackUID);
  1095. if (fHogged) {
  1096. if (!TakeHogAux(captureID, true)) {
  1097. jack_error("Cannot take hog mode for capture device");
  1098. }
  1099. if (!TakeHogAux(playbackID, false)) {
  1100. jack_error("Cannot take hog mode for playback device");
  1101. }
  1102. if (ac3_encoding) {
  1103. fDigitalPlayback = IsDigitalDevice(playbackID);
  1104. }
  1105. }
  1106. }
  1107. // Capture only
  1108. } else if (strcmp(capture_driver_uid, "") != 0) {
  1109. jack_log("JackCoreAudioDriver::SetupDevices : capture only");
  1110. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  1111. jack_log("JackCoreAudioDriver::SetupDevices : will take default input");
  1112. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  1113. jack_error("Cannot open default input device");
  1114. return -1;
  1115. }
  1116. }
  1117. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  1118. jack_error("Cannot get device name from device ID");
  1119. return -1;
  1120. }
  1121. if (fHogged) {
  1122. if (!TakeHogAux(fDeviceID, true)) {
  1123. jack_error("Cannot take hog mode for capture device");
  1124. }
  1125. }
  1126. // Playback only
  1127. } else if (strcmp(playback_driver_uid, "") != 0) {
  1128. jack_log("JackCoreAudioDriver::SetupDevices : playback only");
  1129. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  1130. jack_log("JackCoreAudioDriver::SetupDevices : will take default output");
  1131. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  1132. jack_error("Cannot open default output device");
  1133. return -1;
  1134. }
  1135. }
  1136. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  1137. jack_error("Cannot get device name from device ID");
  1138. return -1;
  1139. }
  1140. if (fHogged) {
  1141. if (!TakeHogAux(fDeviceID, false)) {
  1142. jack_error("Cannot take hog mode for playback device");
  1143. }
  1144. if (ac3_encoding) {
  1145. fDigitalPlayback = IsDigitalDevice(fDeviceID);
  1146. }
  1147. }
  1148. // Use default driver in duplex mode
  1149. } else {
  1150. jack_log("JackCoreAudioDriver::SetupDevices : default driver");
  1151. if (GetDefaultDevice(&fDeviceID) != noErr) {
  1152. jack_error("Cannot open default device in duplex mode, so aggregate default input and default output");
  1153. // Creates aggregate device
  1154. AudioDeviceID captureID = -1;
  1155. AudioDeviceID playbackID = -1;
  1156. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  1157. jack_log("JackCoreAudioDriver::SetupDevices : will take default input");
  1158. if (GetDefaultInputDevice(&captureID) != noErr) {
  1159. jack_error("Cannot open default input device");
  1160. return -1;
  1161. }
  1162. }
  1163. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  1164. jack_log("JackCoreAudioDriver::SetupDevices : will take default output");
  1165. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  1166. jack_error("Cannot open default output device");
  1167. return -1;
  1168. }
  1169. }
  1170. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
  1171. return -1;
  1172. }
  1173. GetDeviceNameFromID(captureID, fCaptureUID);
  1174. GetDeviceNameFromID(playbackID, fPlaybackUID);
  1175. if (fHogged) {
  1176. if (!TakeHogAux(captureID, true)) {
  1177. jack_error("Cannot take hog mode for capture device");
  1178. }
  1179. if (!TakeHogAux(playbackID, false)) {
  1180. jack_error("Cannot take hog mode for playback device");
  1181. }
  1182. if (ac3_encoding) {
  1183. fDigitalPlayback = IsDigitalDevice(playbackID);
  1184. }
  1185. }
  1186. }
  1187. }
  1188. return 0;
  1189. }
  1190. /*
  1191. Return the max possible input channels in in_maxChannels and output channels in out_maxChannels.
  1192. */
  1193. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_maxChannels, int& out_maxChannels, bool strict)
  1194. {
  1195. OSStatus err = noErr;
  1196. if (capturing) {
  1197. err = GetTotalChannels(fDeviceID, in_maxChannels, true);
  1198. if (err != noErr) {
  1199. jack_error("SetupChannels : cannot get input channel number");
  1200. printError(err);
  1201. return -1;
  1202. } else {
  1203. jack_log("JackCoreAudioDriver::SetupChannels : max input channels : %d", in_maxChannels);
  1204. }
  1205. }
  1206. if (playing) {
  1207. err = GetTotalChannels(fDeviceID, out_maxChannels, false);
  1208. if (err != noErr) {
  1209. jack_error("Cannot get output channel number");
  1210. printError(err);
  1211. return -1;
  1212. } else {
  1213. jack_log("JackCoreAudioDriver::SetupChannels : max output channels : %d", out_maxChannels);
  1214. }
  1215. }
  1216. if (inchannels > in_maxChannels) {
  1217. jack_error("This device hasn't required input channels inchannels = %d in_maxChannels = %d", inchannels, in_maxChannels);
  1218. if (strict) {
  1219. return -1;
  1220. }
  1221. }
  1222. if (outchannels > out_maxChannels) {
  1223. jack_error("This device hasn't required output channels outchannels = %d out_maxChannels = %d", outchannels, out_maxChannels);
  1224. if (strict) {
  1225. return -1;
  1226. }
  1227. }
  1228. if (inchannels == -1) {
  1229. jack_log("JackCoreAudioDriver::SetupChannels : setup max in channels = %d", in_maxChannels);
  1230. inchannels = in_maxChannels;
  1231. }
  1232. if (outchannels == -1) {
  1233. jack_log("JackCoreAudioDriver::SetupChannels : setup max out channels = %d", out_maxChannels);
  1234. outchannels = out_maxChannels;
  1235. }
  1236. return 0;
  1237. }
  1238. int JackCoreAudioDriver::SetupBufferSize(jack_nframes_t buffer_size)
  1239. {
  1240. // Setting buffer size
  1241. OSStatus err = noErr;
  1242. UInt32 tmp_buffer_size = buffer_size;
  1243. UInt32 outSize = sizeof(UInt32);
  1244. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, &outSize, &tmp_buffer_size);
  1245. if (err != noErr) {
  1246. jack_error("Cannot get buffer size %ld", buffer_size);
  1247. printError(err);
  1248. return -1;
  1249. } else {
  1250. jack_log("JackCoreAudioDriver::SetupBufferSize : current buffer size = %ld", tmp_buffer_size);
  1251. }
  1252. // If needed, set new buffer size
  1253. if (buffer_size != tmp_buffer_size) {
  1254. tmp_buffer_size = buffer_size;
  1255. // To get BS change notification
  1256. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyBufferFrameSize, BSNotificationCallback, this);
  1257. if (err != noErr) {
  1258. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyBufferFrameSize");
  1259. printError(err);
  1260. return -1;
  1261. }
  1262. // Waiting for BS change notification
  1263. int count = 0;
  1264. fState = false;
  1265. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, outSize, &tmp_buffer_size);
  1266. if (err != noErr) {
  1267. jack_error("SetupBufferSize : cannot set buffer size = %ld", tmp_buffer_size);
  1268. printError(err);
  1269. goto error;
  1270. }
  1271. while (!fState && count++ < WAIT_NOTIFICATION_COUNTER) {
  1272. usleep(100000);
  1273. jack_log("JackCoreAudioDriver::SetupBufferSize : wait count = %d", count);
  1274. }
  1275. if (count >= WAIT_NOTIFICATION_COUNTER) {
  1276. jack_error("Did not get buffer size notification...");
  1277. goto error;
  1278. }
  1279. // Check new buffer size
  1280. outSize = sizeof(UInt32);
  1281. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyBufferFrameSize, &outSize, &tmp_buffer_size);
  1282. if (err != noErr) {
  1283. jack_error("Cannot get current buffer size");
  1284. printError(err);
  1285. } else {
  1286. jack_log("JackCoreAudioDriver::SetupBufferSize : checked buffer size = %ld", tmp_buffer_size);
  1287. }
  1288. // Remove BS change notification
  1289. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyBufferFrameSize, BSNotificationCallback);
  1290. }
  1291. return 0;
  1292. error:
  1293. // Remove BS change notification
  1294. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyBufferFrameSize, BSNotificationCallback);
  1295. return -1;
  1296. }
  1297. int JackCoreAudioDriver::SetupSampleRate(jack_nframes_t sample_rate)
  1298. {
  1299. return SetupSampleRateAux(fDeviceID, sample_rate);
  1300. }
  1301. int JackCoreAudioDriver::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t sample_rate)
  1302. {
  1303. OSStatus err = noErr;
  1304. UInt32 outSize;
  1305. Float64 tmp_sample_rate;
  1306. // Get sample rate
  1307. outSize = sizeof(Float64);
  1308. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &tmp_sample_rate);
  1309. if (err != noErr) {
  1310. jack_error("Cannot get current sample rate");
  1311. printError(err);
  1312. return -1;
  1313. } else {
  1314. jack_log("JackCoreAudioDriver::SetupSampleRateAux : current sample rate = %f", tmp_sample_rate);
  1315. }
  1316. // If needed, set new sample rate
  1317. if (sample_rate != (jack_nframes_t)tmp_sample_rate) {
  1318. tmp_sample_rate = (Float64)sample_rate;
  1319. // To get SR change notification
  1320. err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  1321. if (err != noErr) {
  1322. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  1323. printError(err);
  1324. return -1;
  1325. }
  1326. // Waiting for SR change notification
  1327. int count = 0;
  1328. fState = false;
  1329. err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &tmp_sample_rate);
  1330. if (err != noErr) {
  1331. jack_error("Cannot set sample rate = %ld", sample_rate);
  1332. printError(err);
  1333. goto error;
  1334. }
  1335. while (!fState && count++ < WAIT_NOTIFICATION_COUNTER) {
  1336. usleep(100000);
  1337. jack_log("JackCoreAudioDriver::SetupSampleRateAux : wait count = %d", count);
  1338. }
  1339. if (count >= WAIT_NOTIFICATION_COUNTER) {
  1340. jack_error("Did not get sample rate notification...");
  1341. goto error;
  1342. }
  1343. // Check new sample rate
  1344. outSize = sizeof(Float64);
  1345. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &tmp_sample_rate);
  1346. if (err != noErr) {
  1347. jack_error("Cannot get current sample rate");
  1348. printError(err);
  1349. } else {
  1350. jack_log("JackCoreAudioDriver::SetupSampleRateAux : checked sample rate = %f", tmp_sample_rate);
  1351. }
  1352. // Remove SR change notification
  1353. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  1354. }
  1355. return 0;
  1356. error:
  1357. // Remove SR change notification
  1358. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  1359. return -1;
  1360. }
  1361. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  1362. bool playing,
  1363. int inchannels,
  1364. int outchannels,
  1365. int in_maxChannels,
  1366. int out_maxChannels,
  1367. const vector<int>& chan_in_list,
  1368. const vector<int>& chan_out_list,
  1369. jack_nframes_t buffer_size,
  1370. jack_nframes_t sample_rate)
  1371. {
  1372. ComponentResult err1;
  1373. UInt32 enableIO;
  1374. AudioStreamBasicDescription srcFormat, dstFormat;
  1375. AudioDeviceID currAudioDeviceID;
  1376. UInt32 size;
  1377. 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",
  1378. capturing, playing, inchannels, outchannels, in_maxChannels, out_maxChannels, chan_in_list.size(), chan_out_list.size());
  1379. if (inchannels == 0 && outchannels == 0) {
  1380. jack_error("No input and output channels...");
  1381. return -1;
  1382. }
  1383. // AUHAL
  1384. #ifdef MAC_OS_X_VERSION_10_5
  1385. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  1386. Component HALOutput = FindNextComponent(NULL, &cd);
  1387. err1 = OpenAComponent(HALOutput, &fAUHAL);
  1388. if (err1 != noErr) {
  1389. jack_error("Error calling OpenAComponent");
  1390. printError(err1);
  1391. goto error;
  1392. }
  1393. #else
  1394. AudioComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  1395. AudioComponent HALOutput = AudioComponentFindNext(NULL, &cd);
  1396. err1 = AudioComponentInstanceNew(HALOutput, &fAUHAL);
  1397. if (err1 != noErr) {
  1398. jack_error("Error calling AudioComponentInstanceNew");
  1399. printError(err1);
  1400. goto error;
  1401. }
  1402. #endif
  1403. err1 = AudioUnitInitialize(fAUHAL);
  1404. if (err1 != noErr) {
  1405. jack_error("Cannot initialize AUHAL unit");
  1406. printError(err1);
  1407. goto error;
  1408. }
  1409. // Start I/O
  1410. if (capturing && inchannels > 0) {
  1411. enableIO = 1;
  1412. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL input on");
  1413. } else {
  1414. enableIO = 0;
  1415. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL input off");
  1416. }
  1417. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  1418. if (err1 != noErr) {
  1419. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  1420. printError(err1);
  1421. goto error;
  1422. }
  1423. if (playing && outchannels > 0) {
  1424. enableIO = 1;
  1425. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL output on");
  1426. } else {
  1427. enableIO = 0;
  1428. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL output off");
  1429. }
  1430. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  1431. if (err1 != noErr) {
  1432. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  1433. printError(err1);
  1434. goto error;
  1435. }
  1436. size = sizeof(AudioDeviceID);
  1437. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  1438. if (err1 != noErr) {
  1439. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  1440. printError(err1);
  1441. goto error;
  1442. } else {
  1443. jack_log("JackCoreAudioDriver::OpenAUHAL : AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  1444. }
  1445. // Setup up choosen device, in both input and output cases
  1446. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  1447. if (err1 != noErr) {
  1448. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  1449. printError(err1);
  1450. goto error;
  1451. }
  1452. // Set buffer size
  1453. if (capturing && inchannels > 0) {
  1454. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  1455. if (err1 != noErr) {
  1456. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  1457. printError(err1);
  1458. goto error;
  1459. }
  1460. }
  1461. if (playing && outchannels > 0) {
  1462. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  1463. if (err1 != noErr) {
  1464. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  1465. printError(err1);
  1466. goto error;
  1467. }
  1468. }
  1469. // Setup input channel map
  1470. if (capturing && inchannels > 0 && inchannels <= in_maxChannels) {
  1471. SInt32 chanArr[in_maxChannels];
  1472. for (int i = 0; i < in_maxChannels; i++) {
  1473. chanArr[i] = -1;
  1474. }
  1475. // Explicit mapping
  1476. if (chan_in_list.size() > 0) {
  1477. for (uint i = 0; i < chan_in_list.size(); i++) {
  1478. int chan = chan_in_list[i];
  1479. if (chan < in_maxChannels) {
  1480. // The wanted JACK input index for the 'chan' channel value
  1481. chanArr[chan] = i;
  1482. jack_info("Input channel = %d ==> JACK input port = %d", chan, i);
  1483. } else {
  1484. jack_info("Error input channel number is incorrect : %d", chan);
  1485. goto error;
  1486. }
  1487. }
  1488. } else {
  1489. for (int i = 0; i < inchannels; i++) {
  1490. chanArr[i] = i;
  1491. jack_info("Input channel = %d ==> JACK input port = %d", chanArr[i], i);
  1492. }
  1493. }
  1494. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_maxChannels);
  1495. if (err1 != noErr) {
  1496. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap for input");
  1497. printError(err1);
  1498. goto error;
  1499. }
  1500. }
  1501. // Setup output channel map
  1502. if (playing && outchannels > 0 && outchannels <= out_maxChannels) {
  1503. SInt32 chanArr[out_maxChannels];
  1504. for (int i = 0; i < out_maxChannels; i++) {
  1505. chanArr[i] = -1;
  1506. }
  1507. // Explicit mapping
  1508. if (chan_out_list.size() > 0) {
  1509. for (uint i = 0; i < chan_out_list.size(); i++) {
  1510. int chan = chan_out_list[i];
  1511. if (chan < out_maxChannels) {
  1512. // The wanted JACK output index for the 'chan' channel value
  1513. chanArr[chan] = i;
  1514. jack_info("JACK output port = %d ==> output channel = %d", i, chan);
  1515. } else {
  1516. jack_info("Error output channel number is incorrect : %d", chan);
  1517. goto error;
  1518. }
  1519. }
  1520. } else {
  1521. for (int i = 0; i < outchannels; i++) {
  1522. chanArr[i] = i;
  1523. jack_info("JACK output port = %d ==> output channel = %d", i, chanArr[i]);
  1524. }
  1525. }
  1526. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_maxChannels);
  1527. if (err1 != noErr) {
  1528. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap for output");
  1529. printError(err1);
  1530. goto error;
  1531. }
  1532. }
  1533. // Setup stream converters
  1534. if (capturing && inchannels > 0) {
  1535. size = sizeof(AudioStreamBasicDescription);
  1536. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, &size);
  1537. if (err1 != noErr) {
  1538. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1539. printError(err1);
  1540. goto error;
  1541. }
  1542. PrintStreamDesc(&srcFormat);
  1543. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL input stream converter SR = %ld", sample_rate);
  1544. srcFormat.mSampleRate = sample_rate;
  1545. srcFormat.mFormatID = kAudioFormatLinearPCM;
  1546. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1547. srcFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  1548. srcFormat.mFramesPerPacket = 1;
  1549. srcFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  1550. srcFormat.mChannelsPerFrame = inchannels;
  1551. srcFormat.mBitsPerChannel = 32;
  1552. PrintStreamDesc(&srcFormat);
  1553. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
  1554. if (err1 != noErr) {
  1555. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1556. printError(err1);
  1557. goto error;
  1558. }
  1559. }
  1560. if (playing && outchannels > 0) {
  1561. size = sizeof(AudioStreamBasicDescription);
  1562. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, &size);
  1563. if (err1 != noErr) {
  1564. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  1565. printError(err1);
  1566. goto error;
  1567. }
  1568. PrintStreamDesc(&dstFormat);
  1569. jack_log("JackCoreAudioDriver::OpenAUHAL : setup AUHAL output stream converter SR = %ld", sample_rate);
  1570. dstFormat.mSampleRate = sample_rate;
  1571. dstFormat.mFormatID = kAudioFormatLinearPCM;
  1572. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1573. dstFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  1574. dstFormat.mFramesPerPacket = 1;
  1575. dstFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  1576. dstFormat.mChannelsPerFrame = outchannels;
  1577. dstFormat.mBitsPerChannel = 32;
  1578. PrintStreamDesc(&dstFormat);
  1579. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
  1580. if (err1 != noErr) {
  1581. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  1582. printError(err1);
  1583. goto error;
  1584. }
  1585. }
  1586. // Setup callbacks
  1587. if (inchannels > 0 && outchannels == 0) {
  1588. AURenderCallbackStruct output;
  1589. output.inputProc = Render;
  1590. output.inputProcRefCon = this;
  1591. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  1592. if (err1 != noErr) {
  1593. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  1594. printError(err1);
  1595. goto error;
  1596. }
  1597. } else {
  1598. AURenderCallbackStruct output;
  1599. output.inputProc = Render;
  1600. output.inputProcRefCon = this;
  1601. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  1602. if (err1 != noErr) {
  1603. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  1604. printError(err1);
  1605. goto error;
  1606. }
  1607. }
  1608. return 0;
  1609. error:
  1610. CloseAUHAL();
  1611. return -1;
  1612. }
  1613. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  1614. {
  1615. // Prepare buffers
  1616. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  1617. fJackInputData->mNumberBuffers = inchannels;
  1618. for (int i = 0; i < inchannels; i++) {
  1619. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1620. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  1621. }
  1622. return 0;
  1623. }
  1624. void JackCoreAudioDriver::DisposeBuffers()
  1625. {
  1626. if (fJackInputData) {
  1627. free(fJackInputData);
  1628. fJackInputData = 0;
  1629. }
  1630. }
  1631. void JackCoreAudioDriver::CloseAUHAL()
  1632. {
  1633. AudioOutputUnitStop(fAUHAL);
  1634. AudioUnitUninitialize(fAUHAL);
  1635. CloseComponent(fAUHAL);
  1636. }
  1637. int JackCoreAudioDriver::AddListeners()
  1638. {
  1639. OSStatus err = noErr;
  1640. // Add listeners
  1641. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  1642. if (err != noErr) {
  1643. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  1644. printError(err);
  1645. return -1;
  1646. }
  1647. err = AudioHardwareAddPropertyListener(kAudioHardwarePropertyDevices, AudioHardwareNotificationCallback, this);
  1648. if (err != noErr) {
  1649. jack_error("Error calling AudioHardwareAddPropertyListener with kAudioHardwarePropertyDevices");
  1650. printError(err);
  1651. return -1;
  1652. }
  1653. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  1654. if (err != noErr) {
  1655. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  1656. printError(err);
  1657. return -1;
  1658. }
  1659. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  1660. if (err != noErr) {
  1661. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  1662. printError(err);
  1663. return -1;
  1664. }
  1665. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsAlive, DeviceNotificationCallback, this);
  1666. if (err != noErr) {
  1667. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsAlive");
  1668. printError(err);
  1669. return -1;
  1670. }
  1671. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceHasChanged, DeviceNotificationCallback, this);
  1672. if (err != noErr) {
  1673. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceHasChanged");
  1674. printError(err);
  1675. return -1;
  1676. }
  1677. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1678. if (err != noErr) {
  1679. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1680. printError(err);
  1681. return -1;
  1682. }
  1683. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1684. if (err != noErr) {
  1685. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1686. printError(err);
  1687. return -1;
  1688. }
  1689. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  1690. UInt32 outSize = sizeof(float);
  1691. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  1692. if (err != noErr) {
  1693. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  1694. printError(err);
  1695. }
  1696. }
  1697. return 0;
  1698. }
  1699. void JackCoreAudioDriver::RemoveListeners()
  1700. {
  1701. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  1702. AudioHardwareRemovePropertyListener(kAudioHardwarePropertyDevices, AudioHardwareNotificationCallback);
  1703. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  1704. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  1705. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsAlive, DeviceNotificationCallback);
  1706. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceHasChanged, DeviceNotificationCallback);
  1707. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1708. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1709. }
  1710. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  1711. jack_nframes_t sample_rate,
  1712. bool capturing,
  1713. bool playing,
  1714. int inchannels,
  1715. int outchannels,
  1716. const char* chan_in_list,
  1717. const char* chan_out_list,
  1718. bool monitor,
  1719. const char* capture_driver_uid,
  1720. const char* playback_driver_uid,
  1721. jack_nframes_t capture_latency,
  1722. jack_nframes_t playback_latency,
  1723. int async_output_latency,
  1724. int computation_grain,
  1725. bool hogged,
  1726. bool clock_drift,
  1727. bool ac3_encoding,
  1728. int ac3_bitrate,
  1729. bool ac3_lfe)
  1730. {
  1731. int in_maxChannels = 0;
  1732. int out_maxChannels = 0;
  1733. char capture_driver_name[256];
  1734. char playback_driver_name[256];
  1735. fCaptureLatency = capture_latency;
  1736. fPlaybackLatency = playback_latency;
  1737. fIOUsage = float(async_output_latency) / 100.f;
  1738. fComputationGrain = float(computation_grain) / 100.f;
  1739. fHogged = hogged;
  1740. fClockDriftCompensate = clock_drift;
  1741. SInt32 major;
  1742. SInt32 minor;
  1743. Gestalt(gestaltSystemVersionMajor, &major);
  1744. Gestalt(gestaltSystemVersionMinor, &minor);
  1745. vector<int> parsed_chan_in_list;
  1746. vector<int> parsed_chan_out_list;
  1747. // Starting with 10.6 systems, the HAL notification thread is created internally
  1748. if (major == 10 && minor >= 6) {
  1749. CFRunLoopRef theRunLoop = NULL;
  1750. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1751. OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  1752. if (osErr != noErr) {
  1753. jack_error("Open kAudioHardwarePropertyRunLoop error");
  1754. printError(osErr);
  1755. }
  1756. }
  1757. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name, sample_rate, ac3_encoding) < 0) {
  1758. goto error;
  1759. }
  1760. // Generic JackAudioDriver Open
  1761. if (JackAudioDriver::Open(buffer_size, sample_rate,
  1762. capturing, playing,
  1763. inchannels, outchannels,
  1764. monitor,
  1765. capture_driver_name,
  1766. playback_driver_name,
  1767. capture_latency,
  1768. playback_latency) != 0) {
  1769. goto error;
  1770. }
  1771. if (SetupChannels(capturing, playing, inchannels, outchannels, in_maxChannels, out_maxChannels, !ac3_encoding) < 0) {
  1772. goto error;
  1773. }
  1774. ParseChannelList(chan_in_list, parsed_chan_in_list, in_maxChannels);
  1775. if (parsed_chan_in_list.size() > 0) {
  1776. jack_info("Explicit input channel list size = %d", parsed_chan_in_list.size());
  1777. inchannels = parsed_chan_in_list.size();
  1778. }
  1779. ParseChannelList(chan_out_list, parsed_chan_out_list, out_maxChannels);
  1780. if (parsed_chan_out_list.size() > 0) {
  1781. jack_info("Explicit output channel list size = %d", parsed_chan_out_list.size());
  1782. outchannels = parsed_chan_out_list.size();
  1783. }
  1784. if (SetupBufferSize(buffer_size) < 0) {
  1785. goto error;
  1786. }
  1787. if (SetupSampleRate(sample_rate) < 0) {
  1788. goto error;
  1789. }
  1790. if (ac3_encoding) {
  1791. if (!fDigitalPlayback) {
  1792. jack_error("AC3 encoding can only be used with a digital device");
  1793. goto error;
  1794. }
  1795. JackAC3EncoderParams params;
  1796. memset(&params, 0, sizeof(JackAC3EncoderParams));
  1797. params.bitrate = ac3_bitrate;
  1798. params.channels = outchannels;
  1799. params.sample_rate = sample_rate;
  1800. params.lfe = ac3_lfe;
  1801. fAC3Encoder = new JackAC3Encoder(params);
  1802. if (!fAC3Encoder || !fAC3Encoder->Init(sample_rate)) {
  1803. jack_error("Cannot allocate or init AC3 encoder");
  1804. goto error;
  1805. }
  1806. // Setup AC3 channel number
  1807. fPlaybackChannels = outchannels;
  1808. if (ac3_lfe) {
  1809. fPlaybackChannels++;
  1810. }
  1811. if (fPlaybackChannels < 2 || fPlaybackChannels > 6) {
  1812. jack_error("AC3 encoder channels must be between 2 and 6");
  1813. goto error;
  1814. }
  1815. // Force real output channel number to 2
  1816. outchannels = out_maxChannels = 2;
  1817. } else {
  1818. fPlaybackChannels = outchannels;
  1819. }
  1820. // Core driver may have changed the in/out values
  1821. fCaptureChannels = inchannels;
  1822. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_maxChannels, out_maxChannels, parsed_chan_in_list, parsed_chan_out_list, buffer_size, sample_rate) < 0) {
  1823. goto error;
  1824. }
  1825. if (capturing && inchannels > 0) {
  1826. if (SetupBuffers(inchannels) < 0) {
  1827. goto error;
  1828. }
  1829. }
  1830. if (AddListeners() < 0) {
  1831. goto error;
  1832. }
  1833. return noErr;
  1834. error:
  1835. Close();
  1836. return -1;
  1837. }
  1838. int JackCoreAudioDriver::Close()
  1839. {
  1840. jack_log("JackCoreAudioDriver::Close");
  1841. // Generic audio driver close
  1842. int res = JackAudioDriver::Close();
  1843. RemoveListeners();
  1844. DisposeBuffers();
  1845. CloseAUHAL();
  1846. DestroyAggregateDevice();
  1847. return res;
  1848. }
  1849. void JackCoreAudioDriver::UpdateLatencies()
  1850. {
  1851. UInt32 size;
  1852. OSStatus err;
  1853. jack_latency_range_t input_range;
  1854. jack_latency_range_t output_range;
  1855. jack_latency_range_t monitor_range;
  1856. // Get Input latency
  1857. size = sizeof(UInt32);
  1858. UInt32 value1 = 0;
  1859. UInt32 value2 = 0;
  1860. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1861. if (err != noErr) {
  1862. jack_error("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1863. }
  1864. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1865. if (err != noErr) {
  1866. jack_error("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1867. }
  1868. input_range.min = input_range.max = fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency;
  1869. // Get input stream latencies
  1870. vector<int> input_latencies;
  1871. err = GetStreamLatencies(fDeviceID, true, input_latencies);
  1872. for (int i = 0; i < fCaptureChannels; i++) {
  1873. if (err != noErr) {
  1874. input_range.min += input_latencies[i];
  1875. input_range.max += input_latencies[i];
  1876. }
  1877. fGraphManager->GetPort(fCapturePortList[i])->SetLatencyRange(JackCaptureLatency, &input_range);
  1878. }
  1879. // Get Output latency
  1880. size = sizeof(UInt32);
  1881. value1 = 0;
  1882. value2 = 0;
  1883. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1884. if (err != noErr) {
  1885. jack_error("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1886. }
  1887. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1888. if (err != noErr) {
  1889. jack_error("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1890. }
  1891. // Get output stream latencies
  1892. vector<int> output_latencies;
  1893. err = GetStreamLatencies(fDeviceID, false, output_latencies);
  1894. // Add more latency if "async" mode is used...
  1895. output_range.min = output_range.max = fEngineControl->fBufferSize + ((fEngineControl->fSyncMode)
  1896. ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency;
  1897. for (int i = 0; i < fPlaybackChannels; i++) {
  1898. if (err != noErr) {
  1899. output_range.min += output_latencies[i];
  1900. output_range.max += output_latencies[i];
  1901. }
  1902. fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &output_range);
  1903. // Monitor port
  1904. if (fWithMonitorPorts) {
  1905. monitor_range.min = monitor_range.max = fEngineControl->fBufferSize;
  1906. fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &monitor_range);
  1907. }
  1908. }
  1909. }
  1910. int JackCoreAudioDriver::Attach()
  1911. {
  1912. OSStatus err;
  1913. JackPort* port;
  1914. jack_port_id_t port_index;
  1915. UInt32 size;
  1916. Boolean isWritable;
  1917. char channel_name[64];
  1918. char name[REAL_JACK_PORT_NAME_SIZE];
  1919. char alias[REAL_JACK_PORT_NAME_SIZE];
  1920. jack_log("JackCoreAudioDriver::Attach : fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  1921. for (int i = 0; i < fCaptureChannels; i++) {
  1922. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  1923. if (err != noErr) {
  1924. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1925. }
  1926. if (err == noErr && size > 0) {
  1927. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1928. if (err != noErr) {
  1929. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1930. }
  1931. snprintf(alias, sizeof(alias), "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1932. } else {
  1933. snprintf(alias, sizeof(alias), "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1934. }
  1935. snprintf(name, sizeof(name), "%s:capture_%d", fClientControl.fName, i + 1);
  1936. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, CaptureDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
  1937. jack_error("Cannot register port for %s", name);
  1938. return -1;
  1939. }
  1940. port = fGraphManager->GetPort(port_index);
  1941. port->SetAlias(alias);
  1942. fCapturePortList[i] = port_index;
  1943. }
  1944. for (int i = 0; i < fPlaybackChannels; i++) {
  1945. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1946. if (err != noErr) {
  1947. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1948. }
  1949. if (err == noErr && size > 0) {
  1950. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1951. if (err != noErr) {
  1952. jack_log("JackCoreAudioDriver::Attach : AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1953. }
  1954. snprintf(alias, sizeof(alias), "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1955. } else {
  1956. snprintf(alias, sizeof(alias), "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1957. }
  1958. snprintf(name, sizeof(name), "%s:playback_%d", fClientControl.fName, i + 1);
  1959. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, PlaybackDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
  1960. jack_error("Cannot register port for %s", name);
  1961. return -1;
  1962. }
  1963. port = fGraphManager->GetPort(port_index);
  1964. port->SetAlias(alias);
  1965. fPlaybackPortList[i] = port_index;
  1966. // Monitor ports
  1967. if (fWithMonitorPorts) {
  1968. jack_log("JackCoreAudioDriver::Attach : create monitor port");
  1969. snprintf(name, sizeof(name), "%s:monitor_%u", fClientControl.fName, i + 1);
  1970. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, MonitorDriverFlags, fEngineControl->fBufferSize, &port_index) < 0) {
  1971. jack_error("Cannot register monitor port for %s", name);
  1972. return -1;
  1973. } else {
  1974. fMonitorPortList[i] = port_index;
  1975. }
  1976. }
  1977. }
  1978. if (fAC3Encoder) {
  1979. // Setup specific AC3 channels names
  1980. for (int i = 0; i < fPlaybackChannels; i++) {
  1981. fAC3Encoder->GetChannelName("coreaudio", "", alias, i);
  1982. port = fGraphManager->GetPort(fPlaybackPortList[i]);
  1983. port->SetAlias(alias);
  1984. }
  1985. }
  1986. UpdateLatencies();
  1987. // Input buffers do no change : prepare them only once
  1988. for (int i = 0; i < fCaptureChannels; i++) {
  1989. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1990. }
  1991. return 0;
  1992. }
  1993. int JackCoreAudioDriver::Start()
  1994. {
  1995. jack_log("JackCoreAudioDriver::Start");
  1996. if (JackAudioDriver::Start() == 0) {
  1997. // Waiting for Render callback to be called (= driver has started)
  1998. fState = false;
  1999. int count = 0;
  2000. if (AudioOutputUnitStart(fAUHAL) == noErr) {
  2001. while (!fState && count++ < WAIT_COUNTER) {
  2002. usleep(100000);
  2003. jack_log("JackCoreAudioDriver::Start : wait count = %d", count);
  2004. }
  2005. if (count < WAIT_COUNTER) {
  2006. jack_info("CoreAudio driver is running...");
  2007. return 0;
  2008. }
  2009. jack_error("CoreAudio driver cannot start...");
  2010. }
  2011. JackAudioDriver::Stop();
  2012. }
  2013. return -1;
  2014. }
  2015. int JackCoreAudioDriver::Stop()
  2016. {
  2017. jack_log("JackCoreAudioDriver::Stop");
  2018. int res = (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  2019. if (JackAudioDriver::Stop() < 0) {
  2020. res = -1;
  2021. }
  2022. return res;
  2023. }
  2024. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  2025. {
  2026. if (SetupBufferSize(buffer_size) < 0) {
  2027. return -1;
  2028. }
  2029. JackAudioDriver::SetBufferSize(buffer_size); // Generic change, never fails
  2030. // CoreAudio specific
  2031. UpdateLatencies();
  2032. // Input buffers do no change : prepare them only once
  2033. for (int i = 0; i < fCaptureChannels; i++) {
  2034. fJackInputData->mBuffers[i].mNumberChannels = 1;
  2035. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  2036. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  2037. }
  2038. return 0;
  2039. }
  2040. bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
  2041. {
  2042. pid_t hog_pid;
  2043. UInt32 propSize = sizeof(hog_pid);
  2044. OSStatus err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  2045. if (err) {
  2046. jack_error("Cannot read hog state...");
  2047. printError(err);
  2048. }
  2049. jack_log("JackCoreAudioDriver::TakeHogAux : deviceID = %d", deviceID);
  2050. if (hog_pid != getpid()) {
  2051. hog_pid = getpid();
  2052. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  2053. if (err != noErr) {
  2054. jack_error("Can't hog device = %d because it's being hogged by another program or cannot be hogged", deviceID);
  2055. return false;
  2056. }
  2057. }
  2058. return true;
  2059. }
  2060. bool JackCoreAudioDriver::TakeHog()
  2061. {
  2062. OSStatus err = noErr;
  2063. AudioObjectID sub_device[32];
  2064. UInt32 outSize = sizeof(sub_device);
  2065. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  2066. if (err != noErr) {
  2067. jack_log("JackCoreAudioDriver::TakeHog : device does not have subdevices");
  2068. return TakeHogAux(fDeviceID, true);
  2069. } else {
  2070. int num_devices = outSize / sizeof(AudioObjectID);
  2071. jack_log("JackCoreAudioDriver::TakeHog : device does has %d subdevices", num_devices);
  2072. for (int i = 0; i < num_devices; i++) {
  2073. if (!TakeHogAux(sub_device[i], true)) {
  2074. return false;
  2075. }
  2076. }
  2077. return true;
  2078. }
  2079. }
  2080. bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
  2081. {
  2082. UInt32 deviceType, outSize = sizeof(UInt32);
  2083. OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
  2084. if (err != noErr) {
  2085. jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
  2086. return false;
  2087. } else {
  2088. return (deviceType == kAudioDeviceTransportTypeAggregate);
  2089. }
  2090. }
  2091. } // end of namespace
  2092. #ifdef __cplusplus
  2093. extern "C"
  2094. {
  2095. #endif
  2096. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  2097. {
  2098. jack_driver_desc_t * desc;
  2099. jack_driver_desc_filler_t filler;
  2100. jack_driver_param_value_t value;
  2101. desc = jack_driver_descriptor_construct("coreaudio", JackDriverMaster, "Apple CoreAudio API based audio backend", &filler);
  2102. value.i = -1;
  2103. 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");
  2104. 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");
  2105. 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");
  2106. value.str[0] = 0;
  2107. 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\")");
  2108. 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\")");
  2109. value.str[0] = 0;
  2110. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Input CoreAudio device name", NULL);
  2111. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Output CoreAudio device name", NULL);
  2112. value.i = 0;
  2113. jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);
  2114. #ifndef __ppc__
  2115. value.i = 0;
  2116. jack_driver_descriptor_add_parameter(desc, &filler, "AC3-encoding", 'a', JackDriverParamBool, &value, NULL, "AC3 multi-channels encoding", NULL);
  2117. value.i = 448;
  2118. jack_driver_descriptor_add_parameter(desc, &filler, "AC3-bitrate", 'b', JackDriverParamUInt, &value, NULL, "AC3 bitrate", NULL);
  2119. value.i = 0;
  2120. jack_driver_descriptor_add_parameter(desc, &filler, "AC3-LFE", 'f', JackDriverParamBool, &value, NULL, "AC3 LFE channel", NULL);
  2121. #endif
  2122. value.i = true;
  2123. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  2124. value.ui = 44100U;
  2125. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  2126. value.ui = 256U;
  2127. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  2128. value.str[0] = 0;
  2129. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "CoreAudio device name", NULL);
  2130. value.ui = 0;
  2131. jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency (frames)", NULL);
  2132. jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency (frames)", NULL);
  2133. value.i = false;
  2134. jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available CoreAudio devices", NULL);
  2135. value.i = false;
  2136. jack_driver_descriptor_add_parameter(desc, &filler, "hog", 'H', JackDriverParamBool, &value, NULL, "Take exclusive access of the audio device", NULL);
  2137. value.ui = 100;
  2138. jack_driver_descriptor_add_parameter(desc, &filler, "async-latency", 'L', JackDriverParamUInt, &value, NULL, "Extra output latency in asynchronous mode (percent)", NULL);
  2139. value.ui = 100;
  2140. jack_driver_descriptor_add_parameter(desc, &filler, "grain", 'G', JackDriverParamUInt, &value, NULL, "Computation grain in RT thread (percent)", NULL);
  2141. value.i = false;
  2142. 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");
  2143. return desc;
  2144. }
  2145. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  2146. {
  2147. jack_nframes_t srate = 44100;
  2148. jack_nframes_t frames_per_interrupt = 256;
  2149. bool capture = false;
  2150. bool playback = false;
  2151. int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
  2152. int chan_out = -1; // Default: if not explicitely set, then max possible will be used...
  2153. const char* chan_in_list = "";
  2154. const char* chan_out_list = "";
  2155. bool monitor = false;
  2156. const char* capture_driver_uid = "";
  2157. const char* playback_driver_uid = "";
  2158. const JSList *node;
  2159. const jack_driver_param_t *param;
  2160. jack_nframes_t systemic_input_latency = 0;
  2161. jack_nframes_t systemic_output_latency = 0;
  2162. int async_output_latency = 100;
  2163. int computation_grain = -1;
  2164. bool hogged = false;
  2165. bool clock_drift = false;
  2166. bool ac3_encoding = false;
  2167. int ac3_bitrate = 448;
  2168. bool ac3_lfe = false;
  2169. for (node = params; node; node = jack_slist_next(node)) {
  2170. param = (const jack_driver_param_t *) node->data;
  2171. switch (param->character) {
  2172. case 'd':
  2173. capture_driver_uid = param->value.str;
  2174. playback_driver_uid = param->value.str;
  2175. break;
  2176. case 'D':
  2177. capture = true;
  2178. playback = true;
  2179. break;
  2180. case 'c':
  2181. chan_in = chan_out = param->value.i;
  2182. break;
  2183. case 'i':
  2184. chan_in = param->value.i;
  2185. break;
  2186. case 'o':
  2187. chan_out = param->value.i;
  2188. break;
  2189. case 'n':
  2190. chan_in_list = param->value.str;
  2191. break;
  2192. case 'N':
  2193. chan_out_list = param->value.str;
  2194. break;
  2195. case 'C':
  2196. capture = true;
  2197. if (strcmp(param->value.str, "none") != 0) {
  2198. capture_driver_uid = param->value.str;
  2199. }
  2200. break;
  2201. case 'P':
  2202. playback = true;
  2203. if (strcmp(param->value.str, "none") != 0) {
  2204. playback_driver_uid = param->value.str;
  2205. }
  2206. break;
  2207. case 'm':
  2208. monitor = param->value.i;
  2209. break;
  2210. #ifndef __ppc__
  2211. case 'a':
  2212. ac3_encoding = param->value.i;
  2213. break;
  2214. case 'b':
  2215. ac3_bitrate = param->value.i;
  2216. break;
  2217. case 'f':
  2218. ac3_lfe = param->value.i;
  2219. break;
  2220. #endif
  2221. case 'r':
  2222. srate = param->value.ui;
  2223. break;
  2224. case 'p':
  2225. frames_per_interrupt = (unsigned int)param->value.ui;
  2226. break;
  2227. case 'I':
  2228. systemic_input_latency = param->value.ui;
  2229. break;
  2230. case 'O':
  2231. systemic_output_latency = param->value.ui;
  2232. break;
  2233. case 'l':
  2234. Jack::DisplayDeviceNames();
  2235. // Stops the server in this case
  2236. return NULL;
  2237. case 'H':
  2238. hogged = true;
  2239. break;
  2240. case 'L':
  2241. async_output_latency = param->value.ui;
  2242. break;
  2243. case 'G':
  2244. computation_grain = param->value.ui;
  2245. break;
  2246. case 's':
  2247. clock_drift = true;
  2248. break;
  2249. }
  2250. }
  2251. /* duplex is the default */
  2252. if (!capture && !playback) {
  2253. capture = true;
  2254. playback = true;
  2255. }
  2256. if (strcmp(chan_in_list, "") != 0 && chan_in >= 0) {
  2257. printf("Input channel list and in channels are both specified, input channel list will take over...\n");
  2258. }
  2259. if (strcmp(chan_out_list, "") != 0 && chan_out >= 0) {
  2260. printf("Output channel list and out channels are both specified, output channel list will take over...\n");
  2261. }
  2262. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  2263. if (driver->Open(frames_per_interrupt,
  2264. srate, capture,
  2265. playback, chan_in,
  2266. chan_out, chan_in_list,
  2267. chan_out_list, monitor,
  2268. capture_driver_uid,
  2269. playback_driver_uid,
  2270. systemic_input_latency,
  2271. systemic_output_latency,
  2272. async_output_latency,
  2273. computation_grain,
  2274. hogged, clock_drift,
  2275. ac3_encoding, ac3_bitrate, ac3_lfe) == 0) {
  2276. return driver;
  2277. } else {
  2278. delete driver;
  2279. return NULL;
  2280. }
  2281. }
  2282. #ifdef __cplusplus
  2283. }
  2284. #endif