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.

2022 lines
78KB

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