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.

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