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.

1425 lines
53KB

  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 "JackCompilerDeps.h"
  24. #include <iostream>
  25. namespace Jack
  26. {
  27. static void Print4CharCode(char* msg, long c)
  28. {
  29. UInt32 __4CC_number = (c);
  30. char __4CC_string[5];
  31. *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
  32. __4CC_string[4] = 0;
  33. jack_log("%s'%s'", (msg), __4CC_string);
  34. }
  35. static void printError(OSStatus err)
  36. {
  37. switch (err) {
  38. case kAudioHardwareNoError:
  39. jack_log("error code : kAudioHardwareNoError");
  40. break;
  41. case kAudioConverterErr_FormatNotSupported:
  42. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  43. break;
  44. case kAudioConverterErr_OperationNotSupported:
  45. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  46. break;
  47. case kAudioConverterErr_PropertyNotSupported:
  48. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  49. break;
  50. case kAudioConverterErr_InvalidInputSize:
  51. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  52. break;
  53. case kAudioConverterErr_InvalidOutputSize:
  54. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  55. break;
  56. case kAudioConverterErr_UnspecifiedError:
  57. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  58. break;
  59. case kAudioConverterErr_BadPropertySizeError:
  60. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  61. break;
  62. case kAudioConverterErr_RequiresPacketDescriptionsError:
  63. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  64. break;
  65. case kAudioConverterErr_InputSampleRateOutOfRange:
  66. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  67. break;
  68. case kAudioConverterErr_OutputSampleRateOutOfRange:
  69. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  70. break;
  71. case kAudioHardwareNotRunningError:
  72. jack_log("error code : kAudioHardwareNotRunningError");
  73. break;
  74. case kAudioHardwareUnknownPropertyError:
  75. jack_log("error code : kAudioHardwareUnknownPropertyError");
  76. break;
  77. case kAudioHardwareIllegalOperationError:
  78. jack_log("error code : kAudioHardwareIllegalOperationError");
  79. break;
  80. case kAudioHardwareBadDeviceError:
  81. jack_log("error code : kAudioHardwareBadDeviceError");
  82. break;
  83. case kAudioHardwareBadStreamError:
  84. jack_log("error code : kAudioHardwareBadStreamError");
  85. break;
  86. case kAudioDeviceUnsupportedFormatError:
  87. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  88. break;
  89. case kAudioDevicePermissionsError:
  90. jack_log("error code : kAudioDevicePermissionsError");
  91. break;
  92. case kAudioHardwareBadObjectError:
  93. jack_log("error code : kAudioHardwareBadObjectError");
  94. break;
  95. case kAudioHardwareUnsupportedOperationError:
  96. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  97. break;
  98. default:
  99. Print4CharCode("error code : unknown", err);
  100. break;
  101. }
  102. }
  103. static OSStatus DisplayDeviceNames()
  104. {
  105. UInt32 size;
  106. Boolean isWritable;
  107. int i, deviceNum;
  108. OSStatus err;
  109. CFStringRef UIname;
  110. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  111. if (err != noErr)
  112. return err;
  113. deviceNum = size / sizeof(AudioDeviceID);
  114. AudioDeviceID devices[deviceNum];
  115. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  116. if (err != noErr)
  117. return err;
  118. for (i = 0; i < deviceNum; i++) {
  119. char device_name[256];
  120. char internal_name[256];
  121. size = sizeof(CFStringRef);
  122. UIname = NULL;
  123. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  124. if (err == noErr) {
  125. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  126. } else {
  127. goto error;
  128. }
  129. size = 256;
  130. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  131. if (err != noErr)
  132. return err;
  133. jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
  134. }
  135. return noErr;
  136. error:
  137. if (UIname != NULL)
  138. CFRelease(UIname);
  139. return err;
  140. }
  141. OSStatus JackCoreAudioDriver::Render(void *inRefCon,
  142. AudioUnitRenderActionFlags *ioActionFlags,
  143. const AudioTimeStamp *inTimeStamp,
  144. UInt32 inBusNumber,
  145. UInt32 inNumberFrames,
  146. AudioBufferList *ioData)
  147. {
  148. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inRefCon;
  149. driver->fActionFags = ioActionFlags;
  150. driver->fCurrentTime = (AudioTimeStamp *)inTimeStamp;
  151. driver->fDriverOutputData = ioData;
  152. driver->CycleTakeBeginTime();
  153. return driver->Process();
  154. }
  155. int JackCoreAudioDriver::Read()
  156. {
  157. AudioUnitRender(fAUHAL, fActionFags, fCurrentTime, 1, fEngineControl->fBufferSize, fJackInputData);
  158. return 0;
  159. }
  160. int JackCoreAudioDriver::Write()
  161. {
  162. for (int i = 0; i < fPlaybackChannels; i++) {
  163. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[i]) > 0) {
  164. float* buffer = GetOutputBuffer(i);
  165. int size = sizeof(float) * fEngineControl->fBufferSize;
  166. memcpy((float*)fDriverOutputData->mBuffers[i].mData, buffer, size);
  167. // Monitor ports
  168. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[i]) > 0)
  169. memcpy(GetMonitorBuffer(i), buffer, size);
  170. } else {
  171. memset((float*)fDriverOutputData->mBuffers[i].mData, 0, sizeof(float) * fEngineControl->fBufferSize);
  172. }
  173. }
  174. return 0;
  175. }
  176. // Will run only once
  177. OSStatus JackCoreAudioDriver::MeasureCallback(AudioDeviceID inDevice,
  178. const AudioTimeStamp* inNow,
  179. const AudioBufferList* inInputData,
  180. const AudioTimeStamp* inInputTime,
  181. AudioBufferList* outOutputData,
  182. const AudioTimeStamp* inOutputTime,
  183. void* inClientData)
  184. {
  185. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  186. AudioDeviceStop(driver->fDeviceID, MeasureCallback);
  187. jack_log("JackCoreAudioDriver::MeasureCallback called");
  188. JackMachThread::GetParams(&driver->fEngineControl->fPeriod, &driver->fEngineControl->fComputation, &driver->fEngineControl->fConstraint);
  189. // Setup threadded based log function
  190. set_threaded_log_function();
  191. return noErr;
  192. }
  193. OSStatus JackCoreAudioDriver::SRNotificationCallback(AudioDeviceID inDevice,
  194. UInt32 inChannel,
  195. Boolean isInput,
  196. AudioDevicePropertyID inPropertyID,
  197. void* inClientData)
  198. {
  199. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  200. switch (inPropertyID) {
  201. case kAudioDevicePropertyNominalSampleRate: {
  202. jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  203. driver->fState = true;
  204. break;
  205. }
  206. }
  207. return noErr;
  208. }
  209. // A better implementation would try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  210. OSStatus JackCoreAudioDriver::DeviceNotificationCallback(AudioDeviceID inDevice,
  211. UInt32 inChannel,
  212. Boolean isInput,
  213. AudioDevicePropertyID inPropertyID,
  214. void* inClientData)
  215. {
  216. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  217. switch (inPropertyID) {
  218. case kAudioDeviceProcessorOverload:
  219. jack_error("JackCoreAudioDriver::DeviceNotificationCallback kAudioDeviceProcessorOverload");
  220. jack_time_t cur_time = GetMicroSeconds();
  221. driver->NotifyXRun(cur_time, float(cur_time - driver->fBeginDateUst)); // Better this value than nothing...
  222. break;
  223. case kAudioDevicePropertyStreamConfiguration:
  224. jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration : server may not work correctly anymore...");
  225. return kAudioHardwareUnsupportedOperationError;
  226. case kAudioDevicePropertyNominalSampleRate:
  227. jack_error("Cannot handle kAudioDevicePropertyNominalSampleRate : server may not work correctly anymore...");
  228. return kAudioHardwareUnsupportedOperationError;
  229. /*
  230. case kAudioDevicePropertyNominalSampleRate: {
  231. UInt32 outSize = sizeof(Float64);
  232. Float64 sampleRate;
  233. int in_nChannels = 0;
  234. int out_nChannels = 0;
  235. char capture_driver_name[256];
  236. char playback_driver_name[256];
  237. CFStringRef ref;
  238. // Stop and restart
  239. driver->Stop();
  240. driver->RemoveListeners();
  241. driver->CloseAUHAL();
  242. OSStatus err = AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  243. if (err != noErr) {
  244. jack_error("Cannot get current sample rate");
  245. printError(err);
  246. }
  247. jack_log("JackCoreAudioDriver::DeviceNotificationCallback kAudioDevicePropertyNominalSampleRate %ld", long(sampleRate));
  248. if (driver->SetupDevices(driver->fCaptureUID, driver->fPlaybackUID, capture_driver_name, playback_driver_name) < 0)
  249. return -1;
  250. if (driver->SetupChannels(driver->fCapturing, driver->fPlaying, driver->fInChannels, driver->fOutChannels, in_nChannels, out_nChannels, false) < 0)
  251. return -1;
  252. if (driver->SetupBufferSizeAndSampleRate(driver->fEngineControl->fBufferSize, sampleRate) < 0)
  253. return -1;
  254. if (driver->OpenAUHAL(driver->fCapturing,
  255. driver->fPlaying,
  256. driver->fInChannels,
  257. driver->fOutChannels,
  258. in_nChannels,
  259. out_nChannels,
  260. driver->fEngineControl->fBufferSize,
  261. sampleRate,
  262. false) < 0)
  263. goto error;
  264. if (driver->AddListeners() < 0)
  265. goto error;
  266. driver->Start();
  267. // Send notification to be used in JackPilot or JackRouter plugin
  268. jack_error("Device restart...");
  269. ref = CFStringCreateWithCString(NULL, driver->fEngineControl->fServerName, kCFStringEncodingMacRoman);
  270. CFNotificationCenterPostNotificationWithOptions(CFNotificationCenterGetDistributedCenter(),
  271. CFSTR("com.grame.jackserver.restart"),
  272. ref,
  273. NULL,
  274. kCFNotificationDeliverImmediately | kCFNotificationPostToAllSessions);
  275. CFRelease(ref);
  276. return noErr;
  277. error:
  278. driver->CloseAUHAL();
  279. break;
  280. }
  281. */
  282. }
  283. return noErr;
  284. }
  285. OSStatus JackCoreAudioDriver::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  286. {
  287. UInt32 size = sizeof(AudioValueTranslation);
  288. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  289. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  290. if (inIUD == NULL) {
  291. return kAudioHardwareUnspecifiedError;
  292. } else {
  293. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  294. CFRelease(inIUD);
  295. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  296. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  297. }
  298. }
  299. OSStatus JackCoreAudioDriver::GetDefaultDevice(AudioDeviceID* id)
  300. {
  301. OSStatus res;
  302. UInt32 theSize = sizeof(UInt32);
  303. AudioDeviceID inDefault;
  304. AudioDeviceID outDefault;
  305. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  306. return res;
  307. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  308. return res;
  309. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  310. // Get the device only if default input and ouput are the same
  311. if (inDefault == outDefault) {
  312. *id = inDefault;
  313. return noErr;
  314. } else {
  315. jack_error("Default input and output devices are not the same !!");
  316. return kAudioHardwareBadDeviceError;
  317. }
  318. }
  319. OSStatus JackCoreAudioDriver::GetDefaultInputDevice(AudioDeviceID* id)
  320. {
  321. OSStatus res;
  322. UInt32 theSize = sizeof(UInt32);
  323. AudioDeviceID inDefault;
  324. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  325. return res;
  326. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  327. *id = inDefault;
  328. return noErr;
  329. }
  330. OSStatus JackCoreAudioDriver::GetDefaultOutputDevice(AudioDeviceID* id)
  331. {
  332. OSStatus res;
  333. UInt32 theSize = sizeof(UInt32);
  334. AudioDeviceID outDefault;
  335. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  336. return res;
  337. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  338. *id = outDefault;
  339. return noErr;
  340. }
  341. OSStatus JackCoreAudioDriver::GetDeviceNameFromID(AudioDeviceID id, char* name)
  342. {
  343. UInt32 size = 256;
  344. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  345. }
  346. OSStatus JackCoreAudioDriver::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  347. {
  348. OSStatus err = noErr;
  349. UInt32 outSize;
  350. Boolean outWritable;
  351. AudioBufferList* bufferList = 0;
  352. channelCount = 0;
  353. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  354. if (err == noErr) {
  355. bufferList = (AudioBufferList*)malloc(outSize);
  356. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  357. if (err == noErr) {
  358. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  359. channelCount += bufferList->mBuffers[i].mNumberChannels;
  360. }
  361. if (bufferList)
  362. free(bufferList);
  363. }
  364. return err;
  365. }
  366. JackCoreAudioDriver::JackCoreAudioDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
  367. : JackAudioDriver(name, alias, engine, table), fJackInputData(NULL), fDriverOutputData(NULL), fState(false), fIOUsage(1.f)
  368. {}
  369. JackCoreAudioDriver::~JackCoreAudioDriver()
  370. {}
  371. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid, const char* playback_driver_uid, char* capture_driver_name, char* playback_driver_name)
  372. {
  373. capture_driver_name[0] = 0;
  374. playback_driver_name[0] = 0;
  375. // Duplex
  376. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  377. jack_log("JackCoreAudioDriver::Open duplex");
  378. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  379. jack_log("Will take default in/out");
  380. if (GetDefaultDevice(&fDeviceID) != noErr) {
  381. jack_error("Cannot open default device");
  382. return -1;
  383. }
  384. }
  385. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  386. jack_error("Cannot get device name from device ID");
  387. return -1;
  388. }
  389. // Capture only
  390. } else if (strcmp(capture_driver_uid, "") != 0) {
  391. jack_log("JackCoreAudioDriver::Open capture only");
  392. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  393. jack_log("Will take default input");
  394. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  395. jack_error("Cannot open default device");
  396. return -1;
  397. }
  398. }
  399. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  400. jack_error("Cannot get device name from device ID");
  401. return -1;
  402. }
  403. // Playback only
  404. } else if (strcmp(playback_driver_uid, "") != 0) {
  405. jack_log("JackCoreAudioDriver::Open playback only");
  406. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  407. jack_log("Will take default output");
  408. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  409. jack_error("Cannot open default device");
  410. return -1;
  411. }
  412. }
  413. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  414. jack_error("Cannot get device name from device ID");
  415. return -1;
  416. }
  417. // Use default driver in duplex mode
  418. } else {
  419. jack_log("JackCoreAudioDriver::Open default driver");
  420. if (GetDefaultDevice(&fDeviceID) != noErr) {
  421. jack_error("Cannot open default device");
  422. return -1;
  423. }
  424. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  425. jack_error("Cannot get device name from device ID");
  426. return -1;
  427. }
  428. }
  429. return 0;
  430. }
  431. /*
  432. Return the max possible input channels in in_nChannels and output channels in out_nChannels.
  433. */
  434. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
  435. {
  436. OSStatus err = noErr;
  437. if (capturing) {
  438. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  439. if (err != noErr) {
  440. jack_error("Cannot get input channel number");
  441. printError(err);
  442. return -1;
  443. } else {
  444. jack_log("Max input channels : %d", in_nChannels);
  445. }
  446. }
  447. if (playing) {
  448. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  449. if (err != noErr) {
  450. jack_error("Cannot get output channel number");
  451. printError(err);
  452. return -1;
  453. } else {
  454. jack_log("Max output channels : %d", out_nChannels);
  455. }
  456. }
  457. if (inchannels > in_nChannels) {
  458. jack_error("This device hasn't required input channels inchannels = %ld in_nChannels = %ld", inchannels, in_nChannels);
  459. if (strict)
  460. return -1;
  461. }
  462. if (outchannels > out_nChannels) {
  463. jack_error("This device hasn't required output channels outchannels = %ld out_nChannels = %ld", outchannels, out_nChannels);
  464. if (strict)
  465. return -1;
  466. }
  467. if (inchannels == 0) {
  468. jack_log("Setup max in channels = %ld", in_nChannels);
  469. inchannels = in_nChannels;
  470. }
  471. if (outchannels == 0) {
  472. jack_log("Setup max out channels = %ld", out_nChannels);
  473. outchannels = out_nChannels;
  474. }
  475. return 0;
  476. }
  477. int JackCoreAudioDriver::SetupBufferSizeAndSampleRate(jack_nframes_t buffer_size, jack_nframes_t samplerate)
  478. {
  479. OSStatus err = noErr;
  480. UInt32 outSize;
  481. Float64 sampleRate;
  482. // Setting buffer size
  483. outSize = sizeof(UInt32);
  484. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  485. if (err != noErr) {
  486. jack_error("Cannot set buffer size %ld", buffer_size);
  487. printError(err);
  488. return -1;
  489. }
  490. // Get sample rate
  491. outSize = sizeof(Float64);
  492. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  493. if (err != noErr) {
  494. jack_error("Cannot get current sample rate");
  495. printError(err);
  496. return -1;
  497. }
  498. // If needed, set new sample rate
  499. if (samplerate != (jack_nframes_t)sampleRate) {
  500. sampleRate = (Float64)samplerate;
  501. // To get SR change notification
  502. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  503. if (err != noErr) {
  504. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  505. printError(err);
  506. return -1;
  507. }
  508. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  509. if (err != noErr) {
  510. jack_error("Cannot set sample rate = %ld", samplerate);
  511. printError(err);
  512. return -1;
  513. }
  514. // Waiting for SR change notification
  515. int count = 0;
  516. while (!fState && count++ < 100) {
  517. usleep(100000);
  518. jack_log("Wait count = %ld", count);
  519. }
  520. // Remove SR change notification
  521. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  522. }
  523. return 0;
  524. }
  525. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  526. bool playing,
  527. int inchannels,
  528. int outchannels,
  529. int in_nChannels,
  530. int out_nChannels,
  531. jack_nframes_t buffer_size,
  532. jack_nframes_t samplerate,
  533. bool strict)
  534. {
  535. ComponentResult err1;
  536. UInt32 enableIO;
  537. AudioStreamBasicDescription srcFormat, dstFormat;
  538. jack_log("OpenAUHAL capturing = %ld playing = %ld inchannels = %ld outchannels = %ld in_nChannels = %ld out_nChannels = %ld ", capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels);
  539. if (inchannels == 0 && outchannels == 0) {
  540. jack_error("No input and output channels...");
  541. return -1;
  542. }
  543. // AUHAL
  544. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  545. Component HALOutput = FindNextComponent(NULL, &cd);
  546. err1 = OpenAComponent(HALOutput, &fAUHAL);
  547. if (err1 != noErr) {
  548. jack_error("Error calling OpenAComponent");
  549. printError(err1);
  550. return -1;
  551. }
  552. err1 = AudioUnitInitialize(fAUHAL);
  553. if (err1 != noErr) {
  554. jack_error("Cannot initialize AUHAL unit");
  555. printError(err1);
  556. return -1;
  557. }
  558. // Start I/O
  559. if (capturing && inchannels > 0) {
  560. enableIO = 1;
  561. jack_log("Setup AUHAL input on");
  562. } else {
  563. enableIO = 0;
  564. jack_log("Setup AUHAL input off");
  565. }
  566. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  567. if (err1 != noErr) {
  568. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  569. printError(err1);
  570. if (strict)
  571. return -1;
  572. }
  573. if (playing && outchannels > 0) {
  574. enableIO = 1;
  575. jack_log("Setup AUHAL output on");
  576. } else {
  577. enableIO = 0;
  578. jack_log("Setup AUHAL output off");
  579. }
  580. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  581. if (err1 != noErr) {
  582. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  583. printError(err1);
  584. if (strict)
  585. return -1;
  586. }
  587. AudioDeviceID currAudioDeviceID;
  588. UInt32 size = sizeof(AudioDeviceID);
  589. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  590. if (err1 != noErr) {
  591. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  592. printError(err1);
  593. if (strict)
  594. return -1;
  595. } else {
  596. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  597. }
  598. // Setup up choosen device, in both input and output cases
  599. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  600. if (err1 != noErr) {
  601. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  602. printError(err1);
  603. if (strict)
  604. return -1;
  605. }
  606. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  607. if (err1 != noErr) {
  608. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  609. printError(err1);
  610. if (strict)
  611. return -1;
  612. } else {
  613. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  614. }
  615. // Set buffer size
  616. if (capturing && inchannels > 0) {
  617. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  618. if (err1 != noErr) {
  619. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  620. printError(err1);
  621. if (strict)
  622. return -1;
  623. }
  624. }
  625. if (playing && outchannels > 0) {
  626. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  627. if (err1 != noErr) {
  628. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  629. printError(err1);
  630. if (strict)
  631. return -1;
  632. }
  633. }
  634. // Setup channel map
  635. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  636. SInt32 chanArr[in_nChannels];
  637. for (int i = 0; i < in_nChannels; i++) {
  638. chanArr[i] = -1;
  639. }
  640. for (int i = 0; i < inchannels; i++) {
  641. chanArr[i] = i;
  642. }
  643. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  644. if (err1 != noErr) {
  645. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  646. printError(err1);
  647. }
  648. }
  649. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  650. SInt32 chanArr[out_nChannels];
  651. for (int i = 0; i < out_nChannels; i++) {
  652. chanArr[i] = -1;
  653. }
  654. for (int i = 0; i < outchannels; i++) {
  655. chanArr[i] = i;
  656. }
  657. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  658. if (err1 != noErr) {
  659. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  660. printError(err1);
  661. }
  662. }
  663. // Setup stream converters
  664. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  665. srcFormat.mSampleRate = samplerate;
  666. srcFormat.mFormatID = kAudioFormatLinearPCM;
  667. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  668. srcFormat.mBytesPerPacket = sizeof(float);
  669. srcFormat.mFramesPerPacket = 1;
  670. srcFormat.mBytesPerFrame = sizeof(float);
  671. srcFormat.mChannelsPerFrame = outchannels;
  672. srcFormat.mBitsPerChannel = 32;
  673. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &srcFormat, sizeof(AudioStreamBasicDescription));
  674. if (err1 != noErr) {
  675. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  676. printError(err1);
  677. }
  678. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  679. dstFormat.mSampleRate = samplerate;
  680. dstFormat.mFormatID = kAudioFormatLinearPCM;
  681. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  682. dstFormat.mBytesPerPacket = sizeof(float);
  683. dstFormat.mFramesPerPacket = 1;
  684. dstFormat.mBytesPerFrame = sizeof(float);
  685. dstFormat.mChannelsPerFrame = inchannels;
  686. dstFormat.mBitsPerChannel = 32;
  687. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &dstFormat, sizeof(AudioStreamBasicDescription));
  688. if (err1 != noErr) {
  689. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  690. printError(err1);
  691. }
  692. // Setup callbacks
  693. if (inchannels > 0 && outchannels == 0) {
  694. AURenderCallbackStruct output;
  695. output.inputProc = Render;
  696. output.inputProcRefCon = this;
  697. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  698. if (err1 != noErr) {
  699. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  700. printError(err1);
  701. return -1;
  702. }
  703. } else {
  704. AURenderCallbackStruct output;
  705. output.inputProc = Render;
  706. output.inputProcRefCon = this;
  707. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  708. if (err1 != noErr) {
  709. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  710. printError(err1);
  711. return -1;
  712. }
  713. }
  714. return 0;
  715. }
  716. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  717. {
  718. // Prepare buffers
  719. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  720. if (fJackInputData == 0) {
  721. jack_error("Cannot allocate memory for input buffers");
  722. return -1;
  723. }
  724. fJackInputData->mNumberBuffers = inchannels;
  725. for (int i = 0; i < fCaptureChannels; i++) {
  726. fJackInputData->mBuffers[i].mNumberChannels = 1;
  727. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  728. }
  729. return 0;
  730. }
  731. void JackCoreAudioDriver::DisposeBuffers()
  732. {
  733. if (fJackInputData) {
  734. free(fJackInputData);
  735. fJackInputData = 0;
  736. }
  737. }
  738. void JackCoreAudioDriver::CloseAUHAL()
  739. {
  740. AudioUnitUninitialize(fAUHAL);
  741. CloseComponent(fAUHAL);
  742. }
  743. int JackCoreAudioDriver::AddListeners()
  744. {
  745. OSStatus err = noErr;
  746. // Add listeners
  747. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  748. if (err != noErr) {
  749. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  750. printError(err);
  751. return -1;
  752. }
  753. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  754. if (err != noErr) {
  755. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  756. printError(err);
  757. return -1;
  758. }
  759. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  760. if (err != noErr) {
  761. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  762. printError(err);
  763. return -1;
  764. }
  765. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  766. if (err != noErr) {
  767. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  768. printError(err);
  769. return -1;
  770. }
  771. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  772. if (err != noErr) {
  773. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  774. printError(err);
  775. return -1;
  776. }
  777. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  778. if (err != noErr) {
  779. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  780. printError(err);
  781. return -1;
  782. }
  783. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  784. UInt32 outSize = sizeof(float);
  785. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  786. if (err != noErr) {
  787. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  788. printError(err);
  789. }
  790. }
  791. return 0;
  792. }
  793. void JackCoreAudioDriver::RemoveListeners()
  794. {
  795. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  796. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  797. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  798. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  799. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  800. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  801. }
  802. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  803. jack_nframes_t samplerate,
  804. bool capturing,
  805. bool playing,
  806. int inchannels,
  807. int outchannels,
  808. bool monitor,
  809. const char* capture_driver_uid,
  810. const char* playback_driver_uid,
  811. jack_nframes_t capture_latency,
  812. jack_nframes_t playback_latency,
  813. int async_output_latency)
  814. {
  815. int in_nChannels = 0;
  816. int out_nChannels = 0;
  817. char capture_driver_name[256];
  818. char playback_driver_name[256];
  819. // Keep initial state
  820. fCapturing = capturing;
  821. fPlaying = playing;
  822. fInChannels = inchannels;
  823. fOutChannels = outchannels;
  824. fMonitor = monitor;
  825. strcpy(fCaptureUID, capture_driver_uid);
  826. strcpy(fPlaybackUID, playback_driver_uid);
  827. fCaptureLatency = capture_latency;
  828. fPlaybackLatency = playback_latency;
  829. fIOUsage = float(async_output_latency)/ 100.f;
  830. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name) < 0)
  831. return -1;
  832. // Generic JackAudioDriver Open
  833. if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
  834. return -1;
  835. if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
  836. return -1;
  837. if (SetupBufferSizeAndSampleRate(buffer_size, samplerate) < 0)
  838. return -1;
  839. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate, true) < 0)
  840. goto error;
  841. if (capturing && inchannels > 0)
  842. if (SetupBuffers(inchannels) < 0)
  843. goto error;
  844. if (AddListeners() < 0)
  845. goto error;
  846. // Core driver may have changed the in/out values
  847. fCaptureChannels = inchannels;
  848. fPlaybackChannels = outchannels;
  849. return noErr;
  850. error:
  851. Close();
  852. return -1;
  853. }
  854. int JackCoreAudioDriver::Close()
  855. {
  856. jack_log("JackCoreAudioDriver::Close");
  857. Stop();
  858. JackAudioDriver::Close();
  859. RemoveListeners();
  860. DisposeBuffers();
  861. CloseAUHAL();
  862. return 0;
  863. }
  864. int JackCoreAudioDriver::Attach()
  865. {
  866. OSStatus err;
  867. JackPort* port;
  868. jack_port_id_t port_index;
  869. UInt32 size;
  870. Boolean isWritable;
  871. char channel_name[64];
  872. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  873. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  874. unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  875. jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  876. for (int i = 0; i < fCaptureChannels; i++) {
  877. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  878. if (err != noErr)
  879. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  880. if (err == noErr && size > 0) {
  881. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  882. if (err != noErr)
  883. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  884. snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  885. } else {
  886. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  887. }
  888. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  889. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  890. jack_error("Cannot register port for %s", name);
  891. return -1;
  892. }
  893. size = sizeof(UInt32);
  894. UInt32 value1 = 0;
  895. UInt32 value2 = 0;
  896. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  897. if (err != noErr)
  898. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  899. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  900. if (err != noErr)
  901. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  902. port = fGraphManager->GetPort(port_index);
  903. port->SetAlias(alias);
  904. port->SetLatency(fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency);
  905. fCapturePortList[i] = port_index;
  906. }
  907. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  908. for (int i = 0; i < fPlaybackChannels; i++) {
  909. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  910. if (err != noErr)
  911. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  912. if (err == noErr && size > 0) {
  913. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  914. if (err != noErr)
  915. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  916. snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  917. } else {
  918. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  919. }
  920. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  921. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  922. jack_error("Cannot register port for %s", name);
  923. return -1;
  924. }
  925. size = sizeof(UInt32);
  926. UInt32 value1 = 0;
  927. UInt32 value2 = 0;
  928. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  929. if (err != noErr)
  930. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  931. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  932. if (err != noErr)
  933. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  934. port = fGraphManager->GetPort(port_index);
  935. port->SetAlias(alias);
  936. // Add more latency if "async" mode is used...
  937. port->SetLatency(fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency);
  938. fPlaybackPortList[i] = port_index;
  939. // Monitor ports
  940. if (fWithMonitorPorts) {
  941. jack_log("Create monitor port ");
  942. snprintf(name, sizeof(name) - 1, "%s:%s:monitor_%u", fAliasName, fPlaybackDriverName, i + 1);
  943. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, fEngineControl->fBufferSize)) == NO_PORT) {
  944. jack_error("Cannot register monitor port for %s", name);
  945. return -1;
  946. } else {
  947. port = fGraphManager->GetPort(port_index);
  948. port->SetLatency(fEngineControl->fBufferSize);
  949. fMonitorPortList[i] = port_index;
  950. }
  951. }
  952. }
  953. // Input buffers do no change : prepare them only once
  954. for (int i = 0; i < fCaptureChannels; i++) {
  955. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  956. }
  957. return 0;
  958. }
  959. int JackCoreAudioDriver::Start()
  960. {
  961. jack_log("JackCoreAudioDriver::Start");
  962. JackAudioDriver::Start();
  963. /*
  964. #ifdef MAC_OS_X_VERSION_10_5
  965. OSStatus err = AudioDeviceCreateIOProcID(fDeviceID, MeasureCallback, this, &fMesureCallbackID);
  966. #else
  967. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  968. #endif
  969. */
  970. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  971. if (err != noErr)
  972. return -1;
  973. err = AudioOutputUnitStart(fAUHAL);
  974. if (err != noErr)
  975. return -1;
  976. if ((err = AudioDeviceStart(fDeviceID, MeasureCallback)) != noErr) {
  977. jack_error("Cannot start MeasureCallback");
  978. printError(err);
  979. return -1;
  980. }
  981. return 0;
  982. }
  983. int JackCoreAudioDriver::Stop()
  984. {
  985. jack_log("JackCoreAudioDriver::Stop");
  986. AudioDeviceStop(fDeviceID, MeasureCallback);
  987. /*
  988. #ifdef MAC_OS_X_VERSION_10_5
  989. AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
  990. #else
  991. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  992. #endif
  993. */
  994. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  995. return (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  996. }
  997. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  998. {
  999. OSStatus err;
  1000. UInt32 outSize = sizeof(UInt32);
  1001. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  1002. if (err != noErr) {
  1003. jack_error("Cannot set buffer size %ld", buffer_size);
  1004. printError(err);
  1005. return -1;
  1006. }
  1007. JackAudioDriver::SetBufferSize(buffer_size); // never fails
  1008. // Input buffers do no change : prepare them only once
  1009. for (int i = 0; i < fCaptureChannels; i++) {
  1010. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1011. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  1012. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1013. }
  1014. return 0;
  1015. }
  1016. } // end of namespace
  1017. #ifdef __cplusplus
  1018. extern "C"
  1019. {
  1020. #endif
  1021. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1022. {
  1023. jack_driver_desc_t *desc;
  1024. unsigned int i;
  1025. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  1026. strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  1027. strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  1028. desc->nparams = 14;
  1029. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  1030. i = 0;
  1031. strcpy(desc->params[i].name, "channels");
  1032. desc->params[i].character = 'c';
  1033. desc->params[i].type = JackDriverParamInt;
  1034. desc->params[i].value.ui = 0;
  1035. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  1036. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1037. i++;
  1038. strcpy(desc->params[i].name, "inchannels");
  1039. desc->params[i].character = 'i';
  1040. desc->params[i].type = JackDriverParamInt;
  1041. desc->params[i].value.ui = 0;
  1042. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  1043. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1044. i++;
  1045. strcpy(desc->params[i].name, "outchannels");
  1046. desc->params[i].character = 'o';
  1047. desc->params[i].type = JackDriverParamInt;
  1048. desc->params[i].value.ui = 0;
  1049. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  1050. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1051. i++;
  1052. strcpy(desc->params[i].name, "capture");
  1053. desc->params[i].character = 'C';
  1054. desc->params[i].type = JackDriverParamString;
  1055. strcpy(desc->params[i].value.str, "will take default CoreAudio input device");
  1056. strcpy(desc->params[i].short_desc, "Provide capture ports. Optionally set CoreAudio device name");
  1057. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1058. i++;
  1059. strcpy(desc->params[i].name, "playback");
  1060. desc->params[i].character = 'P';
  1061. desc->params[i].type = JackDriverParamString;
  1062. strcpy(desc->params[i].value.str, "will take default CoreAudio output device");
  1063. strcpy(desc->params[i].short_desc, "Provide playback ports. Optionally set CoreAudio device name");
  1064. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1065. i++;
  1066. strcpy (desc->params[i].name, "monitor");
  1067. desc->params[i].character = 'm';
  1068. desc->params[i].type = JackDriverParamBool;
  1069. desc->params[i].value.i = 0;
  1070. strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
  1071. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1072. i++;
  1073. strcpy(desc->params[i].name, "duplex");
  1074. desc->params[i].character = 'D';
  1075. desc->params[i].type = JackDriverParamBool;
  1076. desc->params[i].value.i = TRUE;
  1077. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  1078. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1079. i++;
  1080. strcpy(desc->params[i].name, "rate");
  1081. desc->params[i].character = 'r';
  1082. desc->params[i].type = JackDriverParamUInt;
  1083. desc->params[i].value.ui = 44100U;
  1084. strcpy(desc->params[i].short_desc, "Sample rate");
  1085. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1086. i++;
  1087. strcpy(desc->params[i].name, "period");
  1088. desc->params[i].character = 'p';
  1089. desc->params[i].type = JackDriverParamUInt;
  1090. desc->params[i].value.ui = 128U;
  1091. strcpy(desc->params[i].short_desc, "Frames per period");
  1092. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1093. i++;
  1094. strcpy(desc->params[i].name, "device");
  1095. desc->params[i].character = 'd';
  1096. desc->params[i].type = JackDriverParamString;
  1097. strcpy(desc->params[i].value.str, "will take default CoreAudio device name");
  1098. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  1099. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1100. i++;
  1101. strcpy(desc->params[i].name, "input-latency");
  1102. desc->params[i].character = 'I';
  1103. desc->params[i].type = JackDriverParamUInt;
  1104. desc->params[i].value.i = 0;
  1105. strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
  1106. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1107. i++;
  1108. strcpy(desc->params[i].name, "output-latency");
  1109. desc->params[i].character = 'O';
  1110. desc->params[i].type = JackDriverParamUInt;
  1111. desc->params[i].value.i = 0;
  1112. strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
  1113. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1114. i++;
  1115. strcpy(desc->params[i].name, "list-devices");
  1116. desc->params[i].character = 'l';
  1117. desc->params[i].type = JackDriverParamBool;
  1118. desc->params[i].value.i = TRUE;
  1119. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  1120. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1121. i++;
  1122. strcpy(desc->params[i].name, "async-latency");
  1123. desc->params[i].character = 'L';
  1124. desc->params[i].type = JackDriverParamUInt;
  1125. desc->params[i].value.i = 100;
  1126. strcpy(desc->params[i].short_desc, "Extra output latency in aynchronous mode (percent)");
  1127. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1128. return desc;
  1129. }
  1130. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1131. {
  1132. jack_nframes_t srate = 44100;
  1133. jack_nframes_t frames_per_interrupt = 128;
  1134. int capture = FALSE;
  1135. int playback = FALSE;
  1136. int chan_in = 0;
  1137. int chan_out = 0;
  1138. bool monitor = false;
  1139. const char* capture_driver_uid = "";
  1140. const char* playback_driver_uid = "";
  1141. const JSList *node;
  1142. const jack_driver_param_t *param;
  1143. jack_nframes_t systemic_input_latency = 0;
  1144. jack_nframes_t systemic_output_latency = 0;
  1145. int async_output_latency = 100;
  1146. for (node = params; node; node = jack_slist_next(node)) {
  1147. param = (const jack_driver_param_t *) node->data;
  1148. switch (param->character) {
  1149. case 'd':
  1150. capture_driver_uid = strdup(param->value.str);
  1151. playback_driver_uid = strdup(param->value.str);
  1152. break;
  1153. case 'D':
  1154. capture = TRUE;
  1155. playback = TRUE;
  1156. break;
  1157. case 'c':
  1158. chan_in = chan_out = (int) param->value.ui;
  1159. break;
  1160. case 'i':
  1161. chan_in = (int) param->value.ui;
  1162. break;
  1163. case 'o':
  1164. chan_out = (int) param->value.ui;
  1165. break;
  1166. case 'C':
  1167. capture = TRUE;
  1168. if (strcmp(param->value.str, "none") != 0) {
  1169. capture_driver_uid = strdup(param->value.str);
  1170. }
  1171. break;
  1172. case 'P':
  1173. playback = TRUE;
  1174. if (strcmp(param->value.str, "none") != 0) {
  1175. playback_driver_uid = strdup(param->value.str);
  1176. }
  1177. break;
  1178. case 'm':
  1179. monitor = param->value.i;
  1180. break;
  1181. case 'r':
  1182. srate = param->value.ui;
  1183. break;
  1184. case 'p':
  1185. frames_per_interrupt = (unsigned int) param->value.ui;
  1186. break;
  1187. case 'I':
  1188. systemic_input_latency = param->value.ui;
  1189. break;
  1190. case 'O':
  1191. systemic_output_latency = param->value.ui;
  1192. break;
  1193. case 'l':
  1194. Jack::DisplayDeviceNames();
  1195. break;
  1196. case 'L':
  1197. async_output_latency = param->value.ui;
  1198. break;
  1199. }
  1200. }
  1201. /* duplex is the default */
  1202. if (!capture && !playback) {
  1203. capture = TRUE;
  1204. playback = TRUE;
  1205. }
  1206. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  1207. if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
  1208. playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency) == 0) {
  1209. return driver;
  1210. } else {
  1211. delete driver;
  1212. return NULL;
  1213. }
  1214. }
  1215. #ifdef __cplusplus
  1216. }
  1217. #endif