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.

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