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.

2029 lines
79KB

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