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.

866 lines
26KB

  1. /*
  2. Copyright (C) 2006-2011 Grame
  3. Permission is hereby granted, free of charge, to any person obtaining
  4. a copy of this software and associated documentation files
  5. (the "Software"), to deal in the Software without restriction,
  6. including without limitation the rights to use, copy, modify, merge,
  7. publish, distribute, sublicense, and/or sell copies of the Software,
  8. and to permit persons to whom the Software is furnished to do so,
  9. subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  15. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  16. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  17. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  18. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  19. */
  20. #ifdef WIN32
  21. #pragma warning (disable : 4786)
  22. #endif
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <assert.h>
  26. #include <process.h>
  27. #include "JackRouter.h"
  28. #include "profport.h"
  29. /*
  30. 08/07/2007 SL : Use jack_client_open instead of jack_client_new (automatic client renaming).
  31. 09/08/2007 SL : Add JackRouter.ini parameter file.
  32. 09/20/2007 SL : Better error report in DllRegisterServer (for Vista).
  33. 09/27/2007 SL : Add AUDO_CONNECT property in JackRouter.ini file.
  34. 10/10/2007 SL : Use ASIOSTInt32LSB instead of ASIOSTInt16LSB.
  35. 12/04/2011 SL : Compilation on Windows 64.
  36. 12/04/2011 SL : Dynamic port allocation. Correct JACK port naming.
  37. */
  38. //------------------------------------------------------------------------------------------
  39. // extern
  40. void getNanoSeconds(ASIOTimeStamp *time);
  41. // local
  42. double AsioSamples2double (ASIOSamples* samples);
  43. static const double twoRaisedTo32 = 4294967296.;
  44. static const double twoRaisedTo32Reciprocal = 1. / twoRaisedTo32;
  45. //------------------------------------------------------------------------------------------
  46. // on windows, we do the COM stuff.
  47. #if WINDOWS
  48. #include "windows.h"
  49. #include "mmsystem.h"
  50. #ifdef _WIN64
  51. #define JACK_ROUTER "JackRouter.dll"
  52. #include <psapi.h>
  53. #else
  54. #define JACK_ROUTER "JackRouter.dll"
  55. #include "./psapi.h"
  56. #endif
  57. using namespace std;
  58. // class id.
  59. // {838FE50A-C1AB-4b77-B9B6-0A40788B53F3}
  60. CLSID IID_ASIO_DRIVER = { 0x838fe50a, 0xc1ab, 0x4b77, { 0xb9, 0xb6, 0xa, 0x40, 0x78, 0x8b, 0x53, 0xf3 } };
  61. CFactoryTemplate g_Templates[1] = {
  62. {L"ASIOJACK", &IID_ASIO_DRIVER, JackRouter::CreateInstance}
  63. };
  64. int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);
  65. CUnknown* JackRouter::CreateInstance(LPUNKNOWN pUnk, HRESULT *phr)
  66. {
  67. return (CUnknown*)new JackRouter(pUnk,phr);
  68. };
  69. STDMETHODIMP JackRouter::NonDelegatingQueryInterface(REFIID riid, void ** ppv)
  70. {
  71. if (riid == IID_ASIO_DRIVER) {
  72. return GetInterface(this, ppv);
  73. }
  74. return CUnknown::NonDelegatingQueryInterface(riid, ppv);
  75. }
  76. // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  77. // Register ASIO Driver
  78. // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  79. extern LONG RegisterAsioDriver(CLSID,char *,char *,char *,char *);
  80. extern LONG UnregisterAsioDriver(CLSID,char *,char *);
  81. //
  82. // Server registration, called on REGSVR32.EXE "the dllname.dll"
  83. //
  84. HRESULT _stdcall DllRegisterServer()
  85. {
  86. LONG rc;
  87. char errstr[128];
  88. rc = RegisterAsioDriver (IID_ASIO_DRIVER, JACK_ROUTER,"JackRouter","JackRouter","Apartment");
  89. if (rc) {
  90. memset(errstr,0,128);
  91. sprintf(errstr,"Register Server failed ! (%d)", rc);
  92. MessageBox(0,(LPCTSTR)errstr,(LPCTSTR)"JackRouter",MB_OK);
  93. return -1;
  94. }
  95. return S_OK;
  96. }
  97. //
  98. // Server unregistration
  99. //
  100. HRESULT _stdcall DllUnregisterServer()
  101. {
  102. LONG rc;
  103. char errstr[128];
  104. rc = UnregisterAsioDriver (IID_ASIO_DRIVER,JACK_ROUTER,"JackRouter");
  105. if (rc) {
  106. memset(errstr,0,128);
  107. sprintf(errstr,"Unregister Server failed ! (%d)",rc);
  108. MessageBox(0,(LPCTSTR)errstr,(LPCTSTR)"JackRouter",MB_OK);
  109. return -1;
  110. }
  111. return S_OK;
  112. }
  113. // Globals
  114. list<pair<string, string> > JackRouter::fConnections;
  115. bool JackRouter::fFirstActivate = true;
  116. //------------------------------------------------------------------------------------------
  117. //------------------------------------------------------------------------------------------
  118. JackRouter::JackRouter (LPUNKNOWN pUnk, HRESULT *phr)
  119. : CUnknown("ASIOJACK", pUnk, phr)
  120. //------------------------------------------------------------------------------------------
  121. #else
  122. // when not on windows, we derive from AsioDriver
  123. JackRouter::JackRouter() : AsioDriver()
  124. #endif
  125. {
  126. long i;
  127. fSamplePosition = 0;
  128. fActive = false;
  129. fStarted = false;
  130. fTimeInfoMode = false;
  131. fTcRead = false;
  132. fClient = NULL;
  133. fAutoConnectIn = true;
  134. fAutoConnectOut = true;
  135. fCallbacks = 0;
  136. fActiveInputs = fActiveOutputs = 0;
  137. fToggle = 0;
  138. fBufferSize = 512;
  139. fSampleRate = 44100;
  140. printf("Constructor\n");
  141. // Use "jackrouter.ini" parameters if available
  142. HMODULE handle = LoadLibrary(JACK_ROUTER);
  143. if (handle) {
  144. // Get JackRouter.dll path
  145. char dllName[512];
  146. string confPath;
  147. DWORD res = GetModuleFileName(handle, dllName, 512);
  148. // Compute .ini file path
  149. string fullPath = dllName;
  150. int lastPos = fullPath.find_last_of(PATH_SEP);
  151. string dllFolder = fullPath.substr(0, lastPos);
  152. confPath = dllFolder + PATH_SEP + "JackRouter.ini";
  153. // Get parameters
  154. kNumInputs = get_private_profile_int("IO", "input", 2, confPath.c_str());
  155. kNumOutputs = get_private_profile_int("IO", "output", 2, confPath.c_str());
  156. fAutoConnectIn = get_private_profile_int("AUTO_CONNECT", "input", 1, confPath.c_str());
  157. fAutoConnectOut = get_private_profile_int("AUTO_CONNECT", "output", 1, confPath.c_str());
  158. FreeLibrary(handle);
  159. } else {
  160. printf("LoadLibrary error\n");
  161. }
  162. #ifdef LONG_SAMPLE
  163. fInputBuffers = new long*[kNumInputs];
  164. fOutputBuffers = new long*[kNumOutputs];
  165. #else
  166. fInputBuffers = new float*[kNumInputs];
  167. fOutputBuffers = new float*[kNumOutputs];
  168. #endif
  169. fInMap = new long[kNumInputs];
  170. fOutMap = new long[kNumOutputs];
  171. fInputPorts = new jack_port_t*[kNumInputs];
  172. fOutputPorts = new jack_port_t*[kNumOutputs];
  173. for (i = 0; i < kNumInputs; i++) {
  174. fInputBuffers[i] = 0;
  175. fInputPorts[i] = 0;
  176. fInMap[i] = 0;
  177. }
  178. for (i = 0; i < kNumOutputs; i++) {
  179. fOutputBuffers[i] = 0;
  180. fOutputPorts[i] = 0;
  181. fOutMap[i] = 0;
  182. }
  183. }
  184. //------------------------------------------------------------------------------------------
  185. JackRouter::~JackRouter()
  186. {
  187. printf("Destructor\n");
  188. stop ();
  189. disposeBuffers ();
  190. jack_client_close(fClient);
  191. delete[] fInputBuffers;
  192. delete[] fOutputBuffers;
  193. delete[] fInputPorts;
  194. delete[] fOutputPorts;
  195. delete[] fInMap;
  196. delete[] fOutMap;
  197. }
  198. //------------------------------------------------------------------------------------------
  199. static bool GetEXEName(DWORD dwProcessID, char* name)
  200. {
  201. DWORD aProcesses [1024], cbNeeded, cProcesses;
  202. unsigned int i;
  203. // Enumerate all processes
  204. if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
  205. return false;
  206. // Calculate how many process identifiers were returned.
  207. cProcesses = cbNeeded / sizeof(DWORD);
  208. TCHAR szEXEName[MAX_PATH];
  209. // Loop through all process to find the one that matches
  210. // the one we are looking for
  211. for (i = 0; i < cProcesses; i++) {
  212. if (aProcesses [i] == dwProcessID) {
  213. // Get a handle to the process
  214. HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
  215. PROCESS_VM_READ, FALSE, dwProcessID);
  216. // Get the process name
  217. if (NULL != hProcess) {
  218. HMODULE hMod;
  219. DWORD cbNeeded;
  220. if (EnumProcessModules(hProcess, &hMod,
  221. sizeof(hMod), &cbNeeded)) {
  222. //Get the name of the exe file
  223. GetModuleBaseName(hProcess, hMod, szEXEName,
  224. sizeof(szEXEName)/sizeof(TCHAR));
  225. int len = strlen((char*)szEXEName) - 4; // remove ".exe"
  226. strncpy(name, (char*)szEXEName, len);
  227. name[len] = '\0';
  228. return true;
  229. }
  230. }
  231. }
  232. }
  233. return false;
  234. }
  235. //------------------------------------------------------------------------------------------
  236. static inline jack_default_audio_sample_t ClipFloat(jack_default_audio_sample_t sample)
  237. {
  238. return (sample < jack_default_audio_sample_t(-1.0)) ? jack_default_audio_sample_t(-1.0) : (sample > jack_default_audio_sample_t(1.0)) ? jack_default_audio_sample_t(1.0) : sample;
  239. }
  240. //------------------------------------------------------------------------------------------
  241. void JackRouter::shutdown(void* arg)
  242. {
  243. JackRouter* driver = (JackRouter*)arg;
  244. /*
  245. //exit(1);
  246. char errstr[128];
  247. memset(errstr,0,128);
  248. sprintf(errstr,"JACK server has quitted");
  249. MessageBox(0,(LPCTSTR)errstr,(LPCTSTR)"JackRouter",MB_OK);
  250. */
  251. }
  252. //------------------------------------------------------------------------------------------
  253. int JackRouter::process(jack_nframes_t nframes, void* arg)
  254. {
  255. JackRouter* driver = (JackRouter*)arg;
  256. int i,j;
  257. int pos = (driver->fToggle) ? 0 : driver->fBufferSize ;
  258. for (i = 0; i < driver->fActiveInputs; i++) {
  259. #ifdef LONG_SAMPLE
  260. jack_default_audio_sample_t* buffer = (jack_default_audio_sample_t*)jack_port_get_buffer(driver->fInputPorts[i], nframes);
  261. long* in = driver->fInputBuffers[i] + pos;
  262. for (j = 0; j < nframes; j++) {
  263. in[j] = buffer[j] * jack_default_audio_sample_t(0x7fffffff);
  264. }
  265. #else
  266. memcpy(driver->fInputBuffers[i] + pos,
  267. jack_port_get_buffer(driver->fInputPorts[i], nframes),
  268. nframes * sizeof(jack_default_audio_sample_t));
  269. #endif
  270. }
  271. driver->bufferSwitch();
  272. for (i = 0; i < driver->fActiveOutputs; i++) {
  273. #ifdef LONG_SAMPLE
  274. jack_default_audio_sample_t* buffer = (jack_default_audio_sample_t*)jack_port_get_buffer(driver->fOutputPorts[i], nframes);
  275. long* out = driver->fOutputBuffers[i] + pos;
  276. jack_default_audio_sample_t gain = jack_default_audio_sample_t(1)/jack_default_audio_sample_t(0x7fffffff);
  277. for (j = 0; j < nframes; j++) {
  278. buffer[j] = out[j] * gain;
  279. }
  280. #else
  281. memcpy(jack_port_get_buffer(driver->fOutputPorts[i], nframes),
  282. driver->fOutputBuffers[i] + pos,
  283. nframes * sizeof(jack_default_audio_sample_t));
  284. #endif
  285. }
  286. return 0;
  287. }
  288. //------------------------------------------------------------------------------------------
  289. void JackRouter::getDriverName(char *name)
  290. {
  291. strcpy (name, "JackRouter");
  292. }
  293. //------------------------------------------------------------------------------------------
  294. long JackRouter::getDriverVersion()
  295. {
  296. return 0x00000001L;
  297. }
  298. //------------------------------------------------------------------------------------------
  299. void JackRouter::getErrorMessage(char *string)
  300. {
  301. strcpy (string, fErrorMessage);
  302. }
  303. //------------------------------------------------------------------------------------------
  304. ASIOBool JackRouter::init(void* sysRef)
  305. {
  306. char name[MAX_PATH];
  307. sysRef = sysRef;
  308. if (fActive)
  309. return true;
  310. HANDLE win = (HANDLE)sysRef;
  311. int my_pid = _getpid();
  312. if (!GetEXEName(my_pid, name)) { // If getting the .exe name fails, takes a generic one.
  313. _snprintf(name, sizeof(name) - 1, "JackRouter_%d", my_pid);
  314. }
  315. if (fClient) {
  316. printf("Error: jack client still present...\n");
  317. return true;
  318. }
  319. fClient = jack_client_open(name, JackNullOption, NULL);
  320. if (fClient == NULL) {
  321. strcpy (fErrorMessage, "Open error: is jack server running?");
  322. printf("Open error: is jack server running?\n");
  323. return false;
  324. }
  325. fBufferSize = jack_get_buffer_size(fClient);
  326. fSampleRate = jack_get_sample_rate(fClient);
  327. jack_set_process_callback(fClient, process, this);
  328. jack_on_shutdown(fClient, shutdown, this);
  329. fInputLatency = fBufferSize; // typically
  330. fOutputLatency = fBufferSize * 2;
  331. fMilliSeconds = (long)((double)(fBufferSize * 1000) / fSampleRate);
  332. // Typically fBufferSize * 2; try to get 1 by offering direct buffer
  333. // access, and using asioPostOutput for lower latency
  334. printf("Init ASIO Jack\n");
  335. fActive = true;
  336. return true;
  337. }
  338. //------------------------------------------------------------------------------------------
  339. ASIOError JackRouter::start()
  340. {
  341. if (fCallbacks) {
  342. fSamplePosition = 0;
  343. fTheSystemTime.lo = fTheSystemTime.hi = 0;
  344. fToggle = 0;
  345. fStarted = true;
  346. printf("Start ASIO Jack\n");
  347. if (jack_activate(fClient) == 0) {
  348. if (fFirstActivate) {
  349. AutoConnect();
  350. fFirstActivate = false;
  351. } else {
  352. RestoreConnections();
  353. }
  354. return ASE_OK;
  355. } else {
  356. return ASE_NotPresent;
  357. }
  358. }
  359. return ASE_NotPresent;
  360. }
  361. //------------------------------------------------------------------------------------------
  362. ASIOError JackRouter::stop()
  363. {
  364. printf("Stop ASIO Jack\n");
  365. fStarted = false;
  366. SaveConnections();
  367. jack_deactivate(fClient);
  368. return ASE_OK;
  369. }
  370. //------------------------------------------------------------------------------------------
  371. ASIOError JackRouter::getChannels(long *numInputChannels, long *numOutputChannels)
  372. {
  373. *numInputChannels = kNumInputs;
  374. *numOutputChannels = kNumOutputs;
  375. return ASE_OK;
  376. }
  377. //------------------------------------------------------------------------------------------
  378. ASIOError JackRouter::getLatencies(long *_inputLatency, long *_outputLatency)
  379. {
  380. *_inputLatency = fInputLatency;
  381. *_outputLatency = fOutputLatency;
  382. return ASE_OK;
  383. }
  384. //------------------------------------------------------------------------------------------
  385. ASIOError JackRouter::getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity)
  386. {
  387. *minSize = *maxSize = *preferredSize = fBufferSize; // Allows this size only
  388. *granularity = 0;
  389. return ASE_OK;
  390. }
  391. //------------------------------------------------------------------------------------------
  392. ASIOError JackRouter::canSampleRate(ASIOSampleRate sampleRate)
  393. {
  394. return (sampleRate == fSampleRate) ? ASE_OK : ASE_NoClock;
  395. }
  396. //------------------------------------------------------------------------------------------
  397. ASIOError JackRouter::getSampleRate(ASIOSampleRate *sampleRate)
  398. {
  399. *sampleRate = fSampleRate;
  400. return ASE_OK;
  401. }
  402. //------------------------------------------------------------------------------------------
  403. ASIOError JackRouter::setSampleRate(ASIOSampleRate sampleRate)
  404. {
  405. return (sampleRate == fSampleRate) ? ASE_OK : ASE_NoClock;
  406. }
  407. //------------------------------------------------------------------------------------------
  408. ASIOError JackRouter::getClockSources(ASIOClockSource *clocks, long *numSources)
  409. {
  410. // Internal
  411. if (clocks && numSources) {
  412. clocks->index = 0;
  413. clocks->associatedChannel = -1;
  414. clocks->associatedGroup = -1;
  415. clocks->isCurrentSource = ASIOTrue;
  416. strcpy(clocks->name, "Internal");
  417. *numSources = 1;
  418. return ASE_OK;
  419. } else {
  420. return ASE_InvalidParameter;
  421. }
  422. }
  423. //------------------------------------------------------------------------------------------
  424. ASIOError JackRouter::setClockSource(long index)
  425. {
  426. if (!index) {
  427. fAsioTime.timeInfo.flags |= kClockSourceChanged;
  428. return ASE_OK;
  429. } else {
  430. return ASE_NotPresent;
  431. }
  432. }
  433. //------------------------------------------------------------------------------------------
  434. ASIOError JackRouter::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp)
  435. {
  436. tStamp->lo = fTheSystemTime.lo;
  437. tStamp->hi = fTheSystemTime.hi;
  438. if (fSamplePosition >= twoRaisedTo32) {
  439. sPos->hi = (unsigned long)(fSamplePosition * twoRaisedTo32Reciprocal);
  440. sPos->lo = (unsigned long)(fSamplePosition - (sPos->hi * twoRaisedTo32));
  441. } else {
  442. sPos->hi = 0;
  443. sPos->lo = (unsigned long)fSamplePosition;
  444. }
  445. return ASE_OK;
  446. }
  447. //------------------------------------------------------------------------------------------
  448. ASIOError JackRouter::getChannelInfo(ASIOChannelInfo *info)
  449. {
  450. if (info->channel < 0 || (info->isInput ? info->channel >= kNumInputs : info->channel >= kNumOutputs))
  451. return ASE_InvalidParameter;
  452. #ifdef LONG_SAMPLE
  453. info->type = ASIOSTInt32LSB;
  454. #else
  455. info->type = ASIOSTFloat32LSB;
  456. #endif
  457. info->channelGroup = 0;
  458. info->isActive = ASIOFalse;
  459. long i;
  460. char buf[32];
  461. if (info->isInput) {
  462. for (i = 0; i < fActiveInputs; i++) {
  463. if (fInMap[i] == info->channel) {
  464. info->isActive = ASIOTrue;
  465. //_snprintf(buf, sizeof(buf) - 1, "Jack::In%d ", info->channel);
  466. //strcpy(info->name, buf);
  467. //strcpy(info->name, jack_port_name(fInputPorts[i]));
  468. break;
  469. }
  470. }
  471. _snprintf(buf, sizeof(buf) - 1, "In%d ", info->channel);
  472. strcpy(info->name, buf);
  473. } else {
  474. for (i = 0; i < fActiveOutputs; i++) {
  475. if (fOutMap[i] == info->channel) { //NOT USED !!
  476. info->isActive = ASIOTrue;
  477. //_snprintf(buf, sizeof(buf) - 1, "Jack::Out%d ", info->channel);
  478. //strcpy(info->name, buf);
  479. //strcpy(info->name, jack_port_name(fOutputPorts[i]));
  480. break;
  481. }
  482. }
  483. _snprintf(buf, sizeof(buf) - 1, "Out%d ", info->channel);
  484. strcpy(info->name, buf);
  485. }
  486. return ASE_OK;
  487. }
  488. //------------------------------------------------------------------------------------------
  489. ASIOError JackRouter::createBuffers(ASIOBufferInfo *bufferInfos, long numChannels,
  490. long bufferSize, ASIOCallbacks *callbacks)
  491. {
  492. ASIOBufferInfo *info = bufferInfos;
  493. long i;
  494. bool notEnoughMem = false;
  495. char buf[256];
  496. fActiveInputs = 0;
  497. fActiveOutputs = 0;
  498. for (i = 0; i < numChannels; i++, info++) {
  499. if (info->isInput) {
  500. if (info->channelNum < 0 || info->channelNum >= kNumInputs)
  501. goto error;
  502. fInMap[fActiveInputs] = info->channelNum;
  503. #ifdef LONG_SAMPLE
  504. fInputBuffers[fActiveInputs] = new long[fBufferSize * 2]; // double buffer
  505. #else
  506. fInputBuffers[fActiveInputs] = new jack_default_audio_sample_t[fBufferSize * 2]; // double buffer
  507. #endif
  508. if (fInputBuffers[fActiveInputs]) {
  509. info->buffers[0] = fInputBuffers[fActiveInputs];
  510. info->buffers[1] = fInputBuffers[fActiveInputs] + fBufferSize;
  511. } else {
  512. info->buffers[0] = info->buffers[1] = 0;
  513. notEnoughMem = true;
  514. }
  515. _snprintf(buf, sizeof(buf) - 1, "in%d", info->channelNum + 1);
  516. fInputPorts[fActiveInputs]
  517. = jack_port_register(fClient, buf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput,0);
  518. if (fInputPorts[fActiveInputs] == NULL)
  519. goto error;
  520. fActiveInputs++;
  521. if (fActiveInputs > kNumInputs) {
  522. error:
  523. disposeBuffers();
  524. return ASE_InvalidParameter;
  525. }
  526. } else { // output
  527. if (info->channelNum < 0 || info->channelNum >= kNumOutputs)
  528. goto error;
  529. fOutMap[fActiveOutputs] = info->channelNum;
  530. #ifdef LONG_SAMPLE
  531. fOutputBuffers[fActiveOutputs] = new long[fBufferSize * 2]; // double buffer
  532. #else
  533. fOutputBuffers[fActiveOutputs] = new jack_default_audio_sample_t[fBufferSize * 2]; // double buffer
  534. #endif
  535. if (fOutputBuffers[fActiveOutputs]) {
  536. info->buffers[0] = fOutputBuffers[fActiveOutputs];
  537. info->buffers[1] = fOutputBuffers[fActiveOutputs] + fBufferSize;
  538. } else {
  539. info->buffers[0] = info->buffers[1] = 0;
  540. notEnoughMem = true;
  541. }
  542. _snprintf(buf, sizeof(buf) - 1, "out%d", info->channelNum + 1);
  543. fOutputPorts[fActiveOutputs]
  544. = jack_port_register(fClient, buf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput,0);
  545. if (fOutputPorts[fActiveOutputs] == NULL)
  546. goto error;
  547. fActiveOutputs++;
  548. if (fActiveOutputs > kNumOutputs) {
  549. fActiveOutputs--;
  550. disposeBuffers();
  551. return ASE_InvalidParameter;
  552. }
  553. }
  554. }
  555. if (notEnoughMem) {
  556. disposeBuffers();
  557. return ASE_NoMemory;
  558. }
  559. this->fCallbacks = callbacks;
  560. if (callbacks->asioMessage (kAsioSupportsTimeInfo, 0, 0, 0)) {
  561. fTimeInfoMode = true;
  562. fAsioTime.timeInfo.speed = 1.;
  563. fAsioTime.timeInfo.systemTime.hi = fAsioTime.timeInfo.systemTime.lo = 0;
  564. fAsioTime.timeInfo.samplePosition.hi = fAsioTime.timeInfo.samplePosition.lo = 0;
  565. fAsioTime.timeInfo.sampleRate = fSampleRate;
  566. fAsioTime.timeInfo.flags = kSystemTimeValid | kSamplePositionValid | kSampleRateValid;
  567. fAsioTime.timeCode.speed = 1.;
  568. fAsioTime.timeCode.timeCodeSamples.lo = fAsioTime.timeCode.timeCodeSamples.hi = 0;
  569. fAsioTime.timeCode.flags = kTcValid | kTcRunning ;
  570. } else {
  571. fTimeInfoMode = false;
  572. }
  573. return ASE_OK;
  574. }
  575. //---------------------------------------------------------------------------------------------
  576. ASIOError JackRouter::disposeBuffers()
  577. {
  578. long i;
  579. fCallbacks = 0;
  580. stop();
  581. for (i = 0; i < fActiveInputs; i++) {
  582. delete[] fInputBuffers[i];
  583. jack_port_unregister(fClient, fInputPorts[i]);
  584. }
  585. fActiveInputs = 0;
  586. for (i = 0; i < fActiveOutputs; i++) {
  587. delete[] fOutputBuffers[i];
  588. jack_port_unregister(fClient, fOutputPorts[i]);
  589. }
  590. fActiveOutputs = 0;
  591. return ASE_OK;
  592. }
  593. //---------------------------------------------------------------------------------------------
  594. ASIOError JackRouter::controlPanel()
  595. {
  596. return ASE_NotPresent;
  597. }
  598. //---------------------------------------------------------------------------------------------
  599. ASIOError JackRouter::future(long selector, void* opt) // !!! check properties
  600. {
  601. ASIOTransportParameters* tp = (ASIOTransportParameters*)opt;
  602. switch (selector)
  603. {
  604. case kAsioEnableTimeCodeRead: fTcRead = true; return ASE_SUCCESS;
  605. case kAsioDisableTimeCodeRead: fTcRead = false; return ASE_SUCCESS;
  606. case kAsioSetInputMonitor: return ASE_SUCCESS; // for testing!!!
  607. case kAsioCanInputMonitor: return ASE_SUCCESS; // for testing!!!
  608. case kAsioCanTimeInfo: return ASE_SUCCESS;
  609. case kAsioCanTimeCode: return ASE_SUCCESS;
  610. }
  611. return ASE_NotPresent;
  612. }
  613. //--------------------------------------------------------------------------------------------------------
  614. // private methods
  615. //--------------------------------------------------------------------------------------------------------
  616. //---------------------------------------------------------------------------------------------
  617. void JackRouter::bufferSwitch()
  618. {
  619. if (fStarted && fCallbacks) {
  620. getNanoSeconds(&fTheSystemTime); // latch system time
  621. fSamplePosition += fBufferSize;
  622. if (fTimeInfoMode) {
  623. bufferSwitchX ();
  624. } else {
  625. fCallbacks->bufferSwitch (fToggle, ASIOFalse);
  626. }
  627. fToggle = fToggle ? 0 : 1;
  628. }
  629. }
  630. //---------------------------------------------------------------------------------------------
  631. // asio2 buffer switch
  632. void JackRouter::bufferSwitchX ()
  633. {
  634. getSamplePosition (&fAsioTime.timeInfo.samplePosition, &fAsioTime.timeInfo.systemTime);
  635. long offset = fToggle ? fBufferSize : 0;
  636. if (fTcRead) {
  637. // Create a fake time code, which is 10 minutes ahead of the card's sample position
  638. // Please note that for simplicity here time code will wrap after 32 bit are reached
  639. fAsioTime.timeCode.timeCodeSamples.lo = fAsioTime.timeInfo.samplePosition.lo + 600.0 * fSampleRate;
  640. fAsioTime.timeCode.timeCodeSamples.hi = 0;
  641. }
  642. fCallbacks->bufferSwitchTimeInfo (&fAsioTime, fToggle, ASIOFalse);
  643. fAsioTime.timeInfo.flags &= ~(kSampleRateChanged | kClockSourceChanged);
  644. }
  645. //---------------------------------------------------------------------------------------------
  646. ASIOError JackRouter::outputReady()
  647. {
  648. return ASE_NotPresent;
  649. }
  650. //---------------------------------------------------------------------------------------------
  651. double AsioSamples2double(ASIOSamples* samples)
  652. {
  653. double a = (double)(samples->lo);
  654. if (samples->hi)
  655. a += (double)(samples->hi) * twoRaisedTo32;
  656. return a;
  657. }
  658. //---------------------------------------------------------------------------------------------
  659. void getNanoSeconds(ASIOTimeStamp* ts)
  660. {
  661. double nanoSeconds = (double)((unsigned long)timeGetTime ()) * 1000000.;
  662. ts->hi = (unsigned long)(nanoSeconds / twoRaisedTo32);
  663. ts->lo = (unsigned long)(nanoSeconds - (ts->hi * twoRaisedTo32));
  664. }
  665. //------------------------------------------------------------------------
  666. void JackRouter::SaveConnections()
  667. {
  668. const char** connections;
  669. int i;
  670. for (i = 0; i < fActiveInputs; ++i) {
  671. if (fInputPorts[i] && (connections = jack_port_get_connections(fInputPorts[i])) != 0) {
  672. for (int j = 0; connections[j]; j++) {
  673. fConnections.push_back(make_pair(connections[j], jack_port_name(fInputPorts[i])));
  674. }
  675. jack_free(connections);
  676. }
  677. }
  678. for (i = 0; i < fActiveOutputs; ++i) {
  679. if (fOutputPorts[i] && (connections = jack_port_get_connections(fOutputPorts[i])) != 0) {
  680. for (int j = 0; connections[j]; j++) {
  681. fConnections.push_back(make_pair(jack_port_name(fOutputPorts[i]), connections[j]));
  682. }
  683. jack_free(connections);
  684. }
  685. }
  686. }
  687. //------------------------------------------------------------------------
  688. void JackRouter::RestoreConnections()
  689. {
  690. list<pair<string, string> >::const_iterator it;
  691. for (it = fConnections.begin(); it != fConnections.end(); it++) {
  692. pair<string, string> connection = *it;
  693. jack_connect(fClient, connection.first.c_str(), connection.second.c_str());
  694. }
  695. fConnections.clear();
  696. }
  697. //------------------------------------------------------------------------------------------
  698. void JackRouter::AutoConnect()
  699. {
  700. const char** ports;
  701. if ((ports = jack_get_ports(fClient, NULL, NULL, JackPortIsPhysical | JackPortIsOutput)) == NULL) {
  702. printf("Cannot find any physical capture ports\n");
  703. } else {
  704. if (fAutoConnectIn) {
  705. for (int i = 0; i < fActiveInputs; i++) {
  706. if (!ports[i]) {
  707. printf("source port is null i = %ld\n", i);
  708. break;
  709. } else if (jack_connect(fClient, ports[i], jack_port_name(fInputPorts[i])) != 0) {
  710. printf("Cannot connect input ports\n");
  711. }
  712. }
  713. }
  714. jack_free(ports);
  715. }
  716. if ((ports = jack_get_ports(fClient, NULL, NULL, JackPortIsPhysical | JackPortIsInput)) == NULL) {
  717. printf("Cannot find any physical playback ports");
  718. } else {
  719. if (fAutoConnectOut) {
  720. for (int i = 0; i < fActiveOutputs; i++) {
  721. if (!ports[i]){
  722. printf("destination port is null i = %ld\n", i);
  723. break;
  724. } else if (jack_connect(fClient, jack_port_name(fOutputPorts[i]), ports[i]) != 0) {
  725. printf("Cannot connect output ports\n");
  726. }
  727. }
  728. }
  729. jack_free(ports);
  730. }
  731. }