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.

1003 lines
32KB

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