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.

2088 lines
82KB

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