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.

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