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.

2066 lines
81KB

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