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.

945 lines
30KB

  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. //------------------------------------------------------------------------------------------
  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. fCallbacks = 0;
  135. fActiveInputs = fActiveOutputs = 0;
  136. fToggle = 0;
  137. fBufferSize = 512;
  138. fSampleRate = 44100;
  139. fFloatSample = true; // float by default
  140. fFirstActivate = true;
  141. printf("Constructor\n");
  142. // Use "jackrouter.ini" parameters if available
  143. HMODULE handle = LoadLibrary(JACK_ROUTER);
  144. if (handle) {
  145. // Get JackRouter.dll path
  146. char dllName[512];
  147. string confPath;
  148. DWORD res = GetModuleFileName(handle, dllName, 512);
  149. // Compute .ini file path
  150. string fullPath = dllName;
  151. int lastPos = fullPath.find_last_of(PATH_SEP);
  152. string dllFolder = fullPath.substr(0, lastPos);
  153. confPath = dllFolder + PATH_SEP + "JackRouter.ini";
  154. // Get parameters
  155. kNumInputs = get_private_profile_int("IO", "input", 2, confPath.c_str());
  156. kNumOutputs = get_private_profile_int("IO", "output", 2, confPath.c_str());
  157. fAutoConnectIn = get_private_profile_int("AUTO_CONNECT", "input", 1, confPath.c_str());
  158. fAutoConnectOut = get_private_profile_int("AUTO_CONNECT", "output", 1, confPath.c_str());
  159. fFloatSample = get_private_profile_int("IO", "float-sample", 0, confPath.c_str());
  160. fAliasSystem = get_private_profile_int("AUTO_CONNECT", "alias", 0, confPath.c_str());
  161. FreeLibrary(handle);
  162. } else {
  163. printf("LoadLibrary error\n");
  164. }
  165. if (!fFloatSample) {
  166. fInputBuffers = (void**)new long*[kNumInputs];
  167. fOutputBuffers = (void**)new long*[kNumOutputs];
  168. } else {
  169. fInputBuffers = (void**)new float*[kNumInputs];
  170. fOutputBuffers = (void**)new float*[kNumOutputs];
  171. }
  172. fInMap = new long[kNumInputs];
  173. fOutMap = new long[kNumOutputs];
  174. fInputPorts = new jack_port_t*[kNumInputs];
  175. fOutputPorts = new jack_port_t*[kNumOutputs];
  176. for (i = 0; i < kNumInputs; i++) {
  177. fInputBuffers[i] = 0;
  178. fInputPorts[i] = 0;
  179. fInMap[i] = 0;
  180. }
  181. for (i = 0; i < kNumOutputs; i++) {
  182. fOutputBuffers[i] = 0;
  183. fOutputPorts[i] = 0;
  184. fOutMap[i] = 0;
  185. }
  186. }
  187. //------------------------------------------------------------------------------------------
  188. JackRouter::~JackRouter()
  189. {
  190. printf("Destructor\n");
  191. stop ();
  192. disposeBuffers ();
  193. jack_client_close(fClient);
  194. delete[] fInputBuffers;
  195. delete[] fOutputBuffers;
  196. delete[] fInputPorts;
  197. delete[] fOutputPorts;
  198. delete[] fInMap;
  199. delete[] fOutMap;
  200. }
  201. //------------------------------------------------------------------------------------------
  202. static bool GetEXEName(DWORD dwProcessID, char* name)
  203. {
  204. DWORD aProcesses [1024], cbNeeded, cProcesses;
  205. unsigned int i;
  206. // Enumerate all processes
  207. if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
  208. return false;
  209. // Calculate how many process identifiers were returned.
  210. cProcesses = cbNeeded / sizeof(DWORD);
  211. TCHAR szEXEName[MAX_PATH];
  212. // Loop through all process to find the one that matches
  213. // the one we are looking for
  214. for (i = 0; i < cProcesses; i++) {
  215. if (aProcesses [i] == dwProcessID) {
  216. // Get a handle to the process
  217. HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
  218. PROCESS_VM_READ, FALSE, dwProcessID);
  219. // Get the process name
  220. if (NULL != hProcess) {
  221. HMODULE hMod;
  222. DWORD cbNeeded;
  223. if (EnumProcessModules(hProcess, &hMod,
  224. sizeof(hMod), &cbNeeded)) {
  225. //Get the name of the exe file
  226. GetModuleBaseName(hProcess, hMod, szEXEName,
  227. sizeof(szEXEName)/sizeof(TCHAR));
  228. int len = strlen((char*)szEXEName) - 4; // remove ".exe"
  229. strncpy(name, (char*)szEXEName, len);
  230. name[len] = '\0';
  231. return true;
  232. }
  233. }
  234. }
  235. }
  236. return false;
  237. }
  238. //------------------------------------------------------------------------------------------
  239. static inline jack_default_audio_sample_t ClipFloat(jack_default_audio_sample_t sample)
  240. {
  241. 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;
  242. }
  243. //------------------------------------------------------------------------------------------
  244. void JackRouter::connectCallback(jack_port_id_t a, jack_port_id_t b, int connect, void* arg)
  245. {
  246. JackRouter* driver = (JackRouter*)arg;
  247. }
  248. //------------------------------------------------------------------------------------------
  249. void JackRouter::shutdownCallback(void* arg)
  250. {
  251. JackRouter* driver = (JackRouter*)arg;
  252. /*
  253. char errstr[128];
  254. memset(errstr,0,128);
  255. sprintf(errstr,"JACK server has quitted");
  256. MessageBox(0,(LPCTSTR)errstr,(LPCTSTR)"JackRouter",MB_OK);
  257. */
  258. }
  259. //------------------------------------------------------------------------------------------
  260. int JackRouter::processCallback(jack_nframes_t nframes, void* arg)
  261. {
  262. JackRouter* driver = (JackRouter*)arg;
  263. int i,j;
  264. int pos = (driver->fToggle) ? 0 : driver->fBufferSize ;
  265. for (i = 0; i < driver->fActiveInputs; i++) {
  266. if (!driver->fFloatSample) {
  267. jack_default_audio_sample_t* buffer = (jack_default_audio_sample_t*)jack_port_get_buffer(driver->fInputPorts[i], nframes);
  268. long* in = (long*)driver->fInputBuffers[i] + pos;
  269. for (j = 0; j < nframes; j++) {
  270. in[j] = buffer[j] * jack_default_audio_sample_t(0x7fffffff);
  271. }
  272. } else {
  273. memcpy((float*)driver->fInputBuffers[i] + pos,
  274. jack_port_get_buffer(driver->fInputPorts[i], nframes),
  275. nframes * sizeof(jack_default_audio_sample_t));
  276. }
  277. }
  278. driver->bufferSwitch();
  279. for (i = 0; i < driver->fActiveOutputs; i++) {
  280. if (!driver->fFloatSample) {
  281. jack_default_audio_sample_t* buffer = (jack_default_audio_sample_t*)jack_port_get_buffer(driver->fOutputPorts[i], nframes);
  282. long* out = (long*)driver->fOutputBuffers[i] + pos;
  283. jack_default_audio_sample_t gain = jack_default_audio_sample_t(1)/jack_default_audio_sample_t(0x7fffffff);
  284. for (j = 0; j < nframes; j++) {
  285. buffer[j] = out[j] * gain;
  286. }
  287. } else {
  288. memcpy(jack_port_get_buffer(driver->fOutputPorts[i], nframes),
  289. (float*)driver->fOutputBuffers[i] + pos,
  290. nframes * sizeof(jack_default_audio_sample_t));
  291. }
  292. }
  293. return 0;
  294. }
  295. //------------------------------------------------------------------------------------------
  296. void JackRouter::getDriverName(char *name)
  297. {
  298. strcpy (name, "JackRouter");
  299. }
  300. //------------------------------------------------------------------------------------------
  301. long JackRouter::getDriverVersion()
  302. {
  303. return 0x00000001L;
  304. }
  305. //------------------------------------------------------------------------------------------
  306. void JackRouter::getErrorMessage(char *string)
  307. {
  308. strcpy (string, fErrorMessage);
  309. }
  310. //------------------------------------------------------------------------------------------
  311. ASIOBool JackRouter::init(void* sysRef)
  312. {
  313. char name[MAX_PATH];
  314. sysRef = sysRef;
  315. if (fActive)
  316. return true;
  317. HANDLE win = (HANDLE)sysRef;
  318. int my_pid = _getpid();
  319. if (!GetEXEName(my_pid, name)) { // If getting the .exe name fails, takes a generic one.
  320. _snprintf(name, sizeof(name) - 1, "JackRouter_%d", my_pid);
  321. }
  322. if (fClient) {
  323. printf("Error: JACK client still present...\n");
  324. return true;
  325. }
  326. fClient = jack_client_open(name, JackNullOption, NULL);
  327. if (fClient == NULL) {
  328. strcpy(fErrorMessage, "Open error: is JACK server running?");
  329. printf("Open error: is JACK server running?\n");
  330. return false;
  331. }
  332. fBufferSize = jack_get_buffer_size(fClient);
  333. fSampleRate = jack_get_sample_rate(fClient);
  334. jack_set_process_callback(fClient, processCallback, this);
  335. jack_on_shutdown(fClient, shutdownCallback, this);
  336. jack_set_port_connect_callback(fClient, connectCallback, this);
  337. fInputLatency = fBufferSize; // typically
  338. fOutputLatency = fBufferSize * 2;
  339. fMilliSeconds = (long)((double)(fBufferSize * 1000) / fSampleRate);
  340. // Typically fBufferSize * 2; try to get 1 by offering direct buffer
  341. // access, and using asioPostOutput for lower latency
  342. printf("Init ASIO JACK\n");
  343. fActive = true;
  344. return true;
  345. }
  346. //------------------------------------------------------------------------------------------
  347. ASIOError JackRouter::start()
  348. {
  349. if (fCallbacks) {
  350. fSamplePosition = 0;
  351. fTheSystemTime.lo = fTheSystemTime.hi = 0;
  352. fToggle = 0;
  353. fStarted = true;
  354. printf("Start ASIO JACK\n");
  355. if (jack_activate(fClient) == 0) {
  356. if (fFirstActivate) {
  357. AutoConnect();
  358. fFirstActivate = false;
  359. } else {
  360. RestoreConnections();
  361. }
  362. return ASE_OK;
  363. } else {
  364. return ASE_NotPresent;
  365. }
  366. }
  367. return ASE_NotPresent;
  368. }
  369. //------------------------------------------------------------------------------------------
  370. ASIOError JackRouter::stop()
  371. {
  372. printf("Stop ASIO JACK\n");
  373. fStarted = false;
  374. SaveConnections();
  375. jack_deactivate(fClient);
  376. return ASE_OK;
  377. }
  378. //------------------------------------------------------------------------------------------
  379. ASIOError JackRouter::getChannels(long *numInputChannels, long *numOutputChannels)
  380. {
  381. *numInputChannels = kNumInputs;
  382. *numOutputChannels = kNumOutputs;
  383. return ASE_OK;
  384. }
  385. //------------------------------------------------------------------------------------------
  386. ASIOError JackRouter::getLatencies(long *_inputLatency, long *_outputLatency)
  387. {
  388. *_inputLatency = fInputLatency;
  389. *_outputLatency = fOutputLatency;
  390. return ASE_OK;
  391. }
  392. //------------------------------------------------------------------------------------------
  393. ASIOError JackRouter::getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity)
  394. {
  395. *minSize = *maxSize = *preferredSize = fBufferSize; // Allows this size only
  396. *granularity = 0;
  397. return ASE_OK;
  398. }
  399. //------------------------------------------------------------------------------------------
  400. ASIOError JackRouter::canSampleRate(ASIOSampleRate sampleRate)
  401. {
  402. return (sampleRate == fSampleRate) ? ASE_OK : ASE_NoClock;
  403. }
  404. //------------------------------------------------------------------------------------------
  405. ASIOError JackRouter::getSampleRate(ASIOSampleRate *sampleRate)
  406. {
  407. *sampleRate = fSampleRate;
  408. return ASE_OK;
  409. }
  410. //------------------------------------------------------------------------------------------
  411. ASIOError JackRouter::setSampleRate(ASIOSampleRate sampleRate)
  412. {
  413. return (sampleRate == fSampleRate) ? ASE_OK : ASE_NoClock;
  414. }
  415. //------------------------------------------------------------------------------------------
  416. ASIOError JackRouter::getClockSources(ASIOClockSource *clocks, long *numSources)
  417. {
  418. // Internal
  419. if (clocks && numSources) {
  420. clocks->index = 0;
  421. clocks->associatedChannel = -1;
  422. clocks->associatedGroup = -1;
  423. clocks->isCurrentSource = ASIOTrue;
  424. strcpy(clocks->name, "Internal");
  425. *numSources = 1;
  426. return ASE_OK;
  427. } else {
  428. return ASE_InvalidParameter;
  429. }
  430. }
  431. //------------------------------------------------------------------------------------------
  432. ASIOError JackRouter::setClockSource(long index)
  433. {
  434. if (!index) {
  435. fAsioTime.timeInfo.flags |= kClockSourceChanged;
  436. return ASE_OK;
  437. } else {
  438. return ASE_NotPresent;
  439. }
  440. }
  441. //------------------------------------------------------------------------------------------
  442. ASIOError JackRouter::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp)
  443. {
  444. tStamp->lo = fTheSystemTime.lo;
  445. tStamp->hi = fTheSystemTime.hi;
  446. if (fSamplePosition >= twoRaisedTo32) {
  447. sPos->hi = (unsigned long)(fSamplePosition * twoRaisedTo32Reciprocal);
  448. sPos->lo = (unsigned long)(fSamplePosition - (sPos->hi * twoRaisedTo32));
  449. } else {
  450. sPos->hi = 0;
  451. sPos->lo = (unsigned long)fSamplePosition;
  452. }
  453. return ASE_OK;
  454. }
  455. //------------------------------------------------------------------------------------------
  456. ASIOError JackRouter::getChannelInfo(ASIOChannelInfo *info)
  457. {
  458. if (info->channel < 0 || (info->isInput ? info->channel >= kNumInputs : info->channel >= kNumOutputs)) {
  459. return ASE_InvalidParameter;
  460. }
  461. if (!fFloatSample) {
  462. info->type = ASIOSTInt32LSB;
  463. } else {
  464. info->type = ASIOSTFloat32LSB;
  465. }
  466. info->channelGroup = 0;
  467. info->isActive = ASIOFalse;
  468. long i;
  469. char buf[32];
  470. char* aliases[2];
  471. aliases[0] = (char*)malloc(jack_port_name_size());
  472. aliases[1] = (char*)malloc(jack_port_name_size());
  473. if (!aliases[0] || !aliases[1])
  474. return ASE_NoMemory;
  475. if (info->isInput) {
  476. for (i = 0; i < fActiveInputs; i++) {
  477. if (fInMap[i] == info->channel) {
  478. info->isActive = ASIOTrue;
  479. break;
  480. }
  481. }
  482. jack_port_t* port = fInputPorts[i];
  483. // A alias on system is wanted
  484. if (fAliasSystem && jack_port_get_aliases(port, aliases) == 1) {
  485. strncpy(info->name, aliases[0], 32);
  486. //strcpy(info->name, "toto");
  487. } else {
  488. _snprintf(buf, sizeof(buf) - 1, "In%d", info->channel);
  489. strcpy(info->name, buf);
  490. }
  491. } else {
  492. for (i = 0; i < fActiveOutputs; i++) {
  493. if (fOutMap[i] == info->channel) {
  494. info->isActive = ASIOTrue;
  495. break;
  496. }
  497. }
  498. jack_port_t* port = fOutputPorts[i];
  499. // A alias on system is wanted
  500. if (fAliasSystem && jack_port_get_aliases(port, aliases) == 1) {
  501. strncpy(info->name, aliases[0], 32);
  502. //strcpy(info->name, "toto");
  503. } else {
  504. _snprintf(buf, sizeof(buf) - 1, "Out%d", info->channel);
  505. strcpy(info->name, buf);
  506. }
  507. }
  508. free(aliases[0]);
  509. free(aliases[1]);
  510. return ASE_OK;
  511. }
  512. //------------------------------------------------------------------------------------------
  513. ASIOError JackRouter::createBuffers(ASIOBufferInfo *bufferInfos, long numChannels,
  514. long bufferSize, ASIOCallbacks *callbacks)
  515. {
  516. ASIOBufferInfo *info = bufferInfos;
  517. long i;
  518. bool notEnoughMem = false;
  519. char buf[256];
  520. fActiveInputs = 0;
  521. fActiveOutputs = 0;
  522. for (i = 0; i < numChannels; i++, info++) {
  523. if (info->isInput) {
  524. if (info->channelNum < 0 || info->channelNum >= kNumInputs)
  525. goto error;
  526. fInMap[fActiveInputs] = info->channelNum;
  527. if (!fFloatSample) {
  528. fInputBuffers[fActiveInputs] = new long[fBufferSize * 2]; // double buffer
  529. } else {
  530. fInputBuffers[fActiveInputs] = new jack_default_audio_sample_t[fBufferSize * 2]; // double buffer
  531. }
  532. if (fInputBuffers[fActiveInputs]) {
  533. info->buffers[0] = fInputBuffers[fActiveInputs];
  534. info->buffers[1] = (fFloatSample) ? (void*)((float*)fInputBuffers[fActiveInputs] + fBufferSize) : (void*)((long*)fInputBuffers[fActiveInputs] + fBufferSize);
  535. } else {
  536. info->buffers[0] = info->buffers[1] = 0;
  537. notEnoughMem = true;
  538. }
  539. _snprintf(buf, sizeof(buf) - 1, "in%d", info->channelNum + 1);
  540. fInputPorts[fActiveInputs]
  541. = jack_port_register(fClient, buf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput,0);
  542. if (fInputPorts[fActiveInputs] == NULL)
  543. goto error;
  544. fActiveInputs++;
  545. if (fActiveInputs > kNumInputs) {
  546. error:
  547. disposeBuffers();
  548. return ASE_InvalidParameter;
  549. }
  550. } else { // output
  551. if (info->channelNum < 0 || info->channelNum >= kNumOutputs)
  552. goto error;
  553. fOutMap[fActiveOutputs] = info->channelNum;
  554. if (!fFloatSample) {
  555. fOutputBuffers[fActiveOutputs] = new long[fBufferSize * 2]; // double buffer
  556. } else {
  557. fOutputBuffers[fActiveOutputs] = new jack_default_audio_sample_t[fBufferSize * 2]; // double buffer
  558. }
  559. if (fOutputBuffers[fActiveOutputs]) {
  560. info->buffers[0] = fOutputBuffers[fActiveOutputs];
  561. info->buffers[1] = (fFloatSample) ? (void*)((float*)fOutputBuffers[fActiveOutputs] + fBufferSize) : (void*)((long*)fOutputBuffers[fActiveOutputs] + fBufferSize);
  562. } else {
  563. info->buffers[0] = info->buffers[1] = 0;
  564. notEnoughMem = true;
  565. }
  566. _snprintf(buf, sizeof(buf) - 1, "out%d", info->channelNum + 1);
  567. fOutputPorts[fActiveOutputs]
  568. = jack_port_register(fClient, buf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput,0);
  569. if (fOutputPorts[fActiveOutputs] == NULL)
  570. goto error;
  571. fActiveOutputs++;
  572. if (fActiveOutputs > kNumOutputs) {
  573. fActiveOutputs--;
  574. disposeBuffers();
  575. return ASE_InvalidParameter;
  576. }
  577. }
  578. }
  579. if (notEnoughMem) {
  580. disposeBuffers();
  581. return ASE_NoMemory;
  582. }
  583. this->fCallbacks = callbacks;
  584. if (callbacks->asioMessage (kAsioSupportsTimeInfo, 0, 0, 0)) {
  585. fTimeInfoMode = true;
  586. fAsioTime.timeInfo.speed = 1.;
  587. fAsioTime.timeInfo.systemTime.hi = fAsioTime.timeInfo.systemTime.lo = 0;
  588. fAsioTime.timeInfo.samplePosition.hi = fAsioTime.timeInfo.samplePosition.lo = 0;
  589. fAsioTime.timeInfo.sampleRate = fSampleRate;
  590. fAsioTime.timeInfo.flags = kSystemTimeValid | kSamplePositionValid | kSampleRateValid;
  591. fAsioTime.timeCode.speed = 1.;
  592. fAsioTime.timeCode.timeCodeSamples.lo = fAsioTime.timeCode.timeCodeSamples.hi = 0;
  593. fAsioTime.timeCode.flags = kTcValid | kTcRunning ;
  594. } else {
  595. fTimeInfoMode = false;
  596. }
  597. return ASE_OK;
  598. }
  599. //---------------------------------------------------------------------------------------------
  600. ASIOError JackRouter::disposeBuffers()
  601. {
  602. long i;
  603. fCallbacks = 0;
  604. stop();
  605. for (i = 0; i < fActiveInputs; i++) {
  606. delete[] fInputBuffers[i];
  607. jack_port_unregister(fClient, fInputPorts[i]);
  608. }
  609. fActiveInputs = 0;
  610. for (i = 0; i < fActiveOutputs; i++) {
  611. delete[] fOutputBuffers[i];
  612. jack_port_unregister(fClient, fOutputPorts[i]);
  613. }
  614. fActiveOutputs = 0;
  615. return ASE_OK;
  616. }
  617. //---------------------------------------------------------------------------------------------
  618. ASIOError JackRouter::controlPanel()
  619. {
  620. return ASE_NotPresent;
  621. }
  622. //---------------------------------------------------------------------------------------------
  623. ASIOError JackRouter::future(long selector, void* opt) // !!! check properties
  624. {
  625. ASIOTransportParameters* tp = (ASIOTransportParameters*)opt;
  626. switch (selector) {
  627. case kAsioEnableTimeCodeRead: fTcRead = true; return ASE_SUCCESS;
  628. case kAsioDisableTimeCodeRead: fTcRead = false; return ASE_SUCCESS;
  629. case kAsioSetInputMonitor: return ASE_SUCCESS; // for testing!!!
  630. case kAsioCanInputMonitor: return ASE_SUCCESS; // for testing!!!
  631. case kAsioCanTimeInfo: return ASE_SUCCESS;
  632. case kAsioCanTimeCode: return ASE_SUCCESS;
  633. }
  634. return ASE_NotPresent;
  635. }
  636. //--------------------------------------------------------------------------------------------------------
  637. // private methods
  638. //--------------------------------------------------------------------------------------------------------
  639. //---------------------------------------------------------------------------------------------
  640. void JackRouter::bufferSwitch()
  641. {
  642. if (fStarted && fCallbacks) {
  643. getNanoSeconds(&fTheSystemTime); // latch system time
  644. fSamplePosition += fBufferSize;
  645. if (fTimeInfoMode) {
  646. bufferSwitchX ();
  647. } else {
  648. fCallbacks->bufferSwitch (fToggle, ASIOFalse);
  649. }
  650. fToggle = fToggle ? 0 : 1;
  651. }
  652. }
  653. //---------------------------------------------------------------------------------------------
  654. // asio2 buffer switch
  655. void JackRouter::bufferSwitchX()
  656. {
  657. getSamplePosition (&fAsioTime.timeInfo.samplePosition, &fAsioTime.timeInfo.systemTime);
  658. long offset = fToggle ? fBufferSize : 0;
  659. if (fTcRead) {
  660. // Create a fake time code, which is 10 minutes ahead of the card's sample position
  661. // Please note that for simplicity here time code will wrap after 32 bit are reached
  662. fAsioTime.timeCode.timeCodeSamples.lo = fAsioTime.timeInfo.samplePosition.lo + 600.0 * fSampleRate;
  663. fAsioTime.timeCode.timeCodeSamples.hi = 0;
  664. }
  665. fCallbacks->bufferSwitchTimeInfo (&fAsioTime, fToggle, ASIOFalse);
  666. fAsioTime.timeInfo.flags &= ~(kSampleRateChanged | kClockSourceChanged);
  667. }
  668. //---------------------------------------------------------------------------------------------
  669. ASIOError JackRouter::outputReady()
  670. {
  671. return ASE_NotPresent;
  672. }
  673. //---------------------------------------------------------------------------------------------
  674. double AsioSamples2double(ASIOSamples* samples)
  675. {
  676. double a = (double)(samples->lo);
  677. if (samples->hi)
  678. a += (double)(samples->hi) * twoRaisedTo32;
  679. return a;
  680. }
  681. //---------------------------------------------------------------------------------------------
  682. void getNanoSeconds(ASIOTimeStamp* ts)
  683. {
  684. double nanoSeconds = (double)((unsigned long)timeGetTime ()) * 1000000.;
  685. ts->hi = (unsigned long)(nanoSeconds / twoRaisedTo32);
  686. ts->lo = (unsigned long)(nanoSeconds - (ts->hi * twoRaisedTo32));
  687. }
  688. //------------------------------------------------------------------------
  689. void JackRouter::SaveConnections()
  690. {
  691. const char** connections;
  692. int i;
  693. for (i = 0; i < fActiveInputs; ++i) {
  694. if (fInputPorts[i] && (connections = jack_port_get_connections(fInputPorts[i])) != 0) {
  695. for (int j = 0; connections[j]; j++) {
  696. fConnections.push_back(make_pair(connections[j], jack_port_name(fInputPorts[i])));
  697. }
  698. jack_free(connections);
  699. }
  700. }
  701. for (i = 0; i < fActiveOutputs; ++i) {
  702. if (fOutputPorts[i] && (connections = jack_port_get_connections(fOutputPorts[i])) != 0) {
  703. for (int j = 0; connections[j]; j++) {
  704. fConnections.push_back(make_pair(jack_port_name(fOutputPorts[i]), connections[j]));
  705. }
  706. jack_free(connections);
  707. }
  708. }
  709. }
  710. //------------------------------------------------------------------------
  711. void JackRouter::RestoreConnections()
  712. {
  713. list<pair<string, string> >::const_iterator it;
  714. for (it = fConnections.begin(); it != fConnections.end(); it++) {
  715. pair<string, string> connection = *it;
  716. jack_connect(fClient, connection.first.c_str(), connection.second.c_str());
  717. }
  718. fConnections.clear();
  719. }
  720. //------------------------------------------------------------------------------------------
  721. void JackRouter::AutoConnect()
  722. {
  723. const char** ports;
  724. char* aliases[2];
  725. aliases[0] = (char*)malloc(jack_port_name_size());
  726. aliases[1] = (char*)malloc(jack_port_name_size());
  727. if (!aliases[0] || !aliases[1])
  728. return;
  729. if ((ports = jack_get_ports(fClient, NULL, NULL, JackPortIsPhysical | JackPortIsOutput)) == NULL) {
  730. printf("Cannot find any physical capture ports\n");
  731. } else {
  732. if (fAutoConnectIn) {
  733. for (int i = 0; i < fActiveInputs; i++) {
  734. /*
  735. if (!ports[i]) {
  736. printf("source port is null i = %ld\n", i);
  737. break;
  738. } else if (jack_connect(fClient, ports[i], jack_port_name(fInputPorts[i])) != 0) {
  739. printf("Cannot connect input ports\n");
  740. }
  741. */
  742. long ASIO_channel = fInMap[i];
  743. if (!ports[ASIO_channel]) {
  744. printf("source port is null ASIO_channel = %ld\n", ASIO_channel);
  745. break;
  746. } else if (jack_connect(fClient, ports[ASIO_channel], jack_port_name(fInputPorts[i])) != 0) {
  747. printf("Cannot connect input ports\n");
  748. } else if (fAliasSystem) {
  749. jack_port_t* input_port = jack_port_by_name(fClient, ports[ASIO_channel]);
  750. if (input_port) {
  751. if (jack_port_get_aliases(input_port, aliases) == 2) {
  752. jack_port_set_alias(fInputPorts[i], aliases[1]);
  753. }
  754. }
  755. }
  756. }
  757. }
  758. jack_free(ports);
  759. }
  760. if ((ports = jack_get_ports(fClient, NULL, NULL, JackPortIsPhysical | JackPortIsInput)) == NULL) {
  761. printf("Cannot find any physical playback ports");
  762. } else {
  763. if (fAutoConnectOut) {
  764. for (int i = 0; i < fActiveOutputs; i++) {
  765. /*
  766. if (!ports[i]){
  767. printf("destination port is null i = %ld\n", i);
  768. break;
  769. } else if (jack_connect(fClient, jack_port_name(fOutputPorts[i]), ports[i]) != 0) {
  770. printf("Cannot connect output ports\n");
  771. }
  772. */
  773. long ASIO_channel = fOutMap[i];
  774. if (!ports[ASIO_channel]){
  775. printf("destination port is null ASIO_channel = %ld\n", ASIO_channel);
  776. break;
  777. } else if (jack_connect(fClient, jack_port_name(fOutputPorts[i]), ports[ASIO_channel]) != 0) {
  778. printf("Cannot connect output ports\n");
  779. } else if (fAliasSystem) {
  780. jack_port_t* output_port = jack_port_by_name(fClient, ports[ASIO_channel]);
  781. if (output_port) {
  782. if (jack_port_get_aliases(output_port, aliases) == 2) {
  783. jack_port_set_alias(fOutputPorts[i], aliases[1]);
  784. }
  785. }
  786. }
  787. }
  788. }
  789. free(aliases[0]);
  790. free(aliases[1]);
  791. jack_free(ports);
  792. }
  793. }