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.

2699 lines
104KB

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