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.

1112 lines
35KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include <iostream>
  16. #include <fstream>
  17. #include <set>
  18. #include <assert.h>
  19. #include "JackSystemDeps.h"
  20. #include "JackLockedEngine.h"
  21. #include "JackExternalClient.h"
  22. #include "JackInternalClient.h"
  23. #include "JackEngineControl.h"
  24. #include "JackClientControl.h"
  25. #include "JackServerGlobals.h"
  26. #include "JackGlobals.h"
  27. #include "JackChannel.h"
  28. #include "JackError.h"
  29. namespace Jack
  30. {
  31. JackEngine::JackEngine(JackGraphManager* manager,
  32. JackSynchro* table,
  33. JackEngineControl* control)
  34. {
  35. fGraphManager = manager;
  36. fSynchroTable = table;
  37. fEngineControl = control;
  38. for (int i = 0; i < CLIENT_NUM; i++)
  39. fClientTable[i] = NULL;
  40. fLastSwitchUsecs = 0;
  41. fMaxUUID = 0;
  42. fSessionPendingReplies = 0;
  43. fSessionTransaction = NULL;
  44. fSessionResult = NULL;
  45. }
  46. JackEngine::~JackEngine()
  47. {}
  48. int JackEngine::Open()
  49. {
  50. jack_log("JackEngine::Open");
  51. // Open audio thread => request thread communication channel
  52. if (fChannel.Open(fEngineControl->fServerName) < 0) {
  53. jack_error("Cannot connect to server");
  54. return -1;
  55. } else {
  56. return 0;
  57. }
  58. }
  59. int JackEngine::Close()
  60. {
  61. jack_log("JackEngine::Close");
  62. fChannel.Close();
  63. // Close remaining clients (RT is stopped)
  64. for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
  65. if (JackLoadableInternalClient* loadable_client = dynamic_cast<JackLoadableInternalClient*>(fClientTable[i])) {
  66. jack_log("JackEngine::Close loadable client = %s", loadable_client->GetClientControl()->fName);
  67. loadable_client->Close();
  68. fClientTable[i] = NULL;
  69. delete loadable_client;
  70. } else if (JackExternalClient* external_client = dynamic_cast<JackExternalClient*>(fClientTable[i])) {
  71. jack_log("JackEngine::Close external client = %s", external_client->GetClientControl()->fName);
  72. external_client->Close();
  73. fClientTable[i] = NULL;
  74. delete external_client;
  75. }
  76. }
  77. return 0;
  78. }
  79. void JackEngine::ShutDown()
  80. {
  81. jack_log("JackEngine::ShutDown");
  82. // Shutdown remaining clients (RT is stopped)
  83. for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
  84. if (JackLoadableInternalClient* loadable_client = dynamic_cast<JackLoadableInternalClient*>(fClientTable[i])) {
  85. jack_log("JackEngine::ShutDown loadable client = %s", loadable_client->GetClientControl()->fName);
  86. loadable_client->ShutDown();
  87. }
  88. }
  89. }
  90. void JackEngine::NotifyQuit()
  91. {
  92. fChannel.NotifyQuit();
  93. }
  94. //-----------------------------
  95. // Client ressource management
  96. //-----------------------------
  97. int JackEngine::AllocateRefnum()
  98. {
  99. for (int i = 0; i < CLIENT_NUM; i++) {
  100. if (!fClientTable[i]) {
  101. jack_log("JackEngine::AllocateRefNum ref = %ld", i);
  102. return i;
  103. }
  104. }
  105. return -1;
  106. }
  107. void JackEngine::ReleaseRefnum(int ref)
  108. {
  109. fClientTable[ref] = NULL;
  110. if (fEngineControl->fTemporary) {
  111. int i;
  112. for (i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
  113. if (fClientTable[i])
  114. break;
  115. }
  116. if (i == CLIENT_NUM) {
  117. // last client and temporay case: quit the server
  118. jack_log("JackEngine::ReleaseRefnum server quit");
  119. fEngineControl->fTemporary = false;
  120. throw JackTemporaryException();
  121. }
  122. }
  123. }
  124. //------------------
  125. // Graph management
  126. //------------------
  127. void JackEngine::ProcessNext(jack_time_t cur_cycle_begin)
  128. {
  129. fLastSwitchUsecs = cur_cycle_begin;
  130. if (fGraphManager->RunNextGraph()) { // True if the graph actually switched to a new state
  131. fChannel.Notify(ALL_CLIENTS, kGraphOrderCallback, 0);
  132. }
  133. fSignal.Signal(); // Signal for threads waiting for next cycle
  134. }
  135. void JackEngine::ProcessCurrent(jack_time_t cur_cycle_begin)
  136. {
  137. if (cur_cycle_begin < fLastSwitchUsecs + 2 * fEngineControl->fPeriodUsecs) // Signal XRun only for the first failing cycle
  138. CheckXRun(cur_cycle_begin);
  139. fGraphManager->RunCurrentGraph();
  140. }
  141. bool JackEngine::Process(jack_time_t cur_cycle_begin, jack_time_t prev_cycle_end)
  142. {
  143. bool res = true;
  144. // Cycle begin
  145. fEngineControl->CycleBegin(fClientTable, fGraphManager, cur_cycle_begin, prev_cycle_end);
  146. // Graph
  147. if (fGraphManager->IsFinishedGraph()) {
  148. ProcessNext(cur_cycle_begin);
  149. res = true;
  150. } else {
  151. jack_log("Process: graph not finished!");
  152. if (cur_cycle_begin > fLastSwitchUsecs + fEngineControl->fTimeOutUsecs) {
  153. jack_log("Process: switch to next state delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
  154. ProcessNext(cur_cycle_begin);
  155. res = true;
  156. } else {
  157. jack_log("Process: waiting to switch delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
  158. ProcessCurrent(cur_cycle_begin);
  159. res = false;
  160. }
  161. }
  162. // Cycle end
  163. fEngineControl->CycleEnd(fClientTable);
  164. return res;
  165. }
  166. /*
  167. Client that finish *after* the callback date are considered late even if their output buffers may have been
  168. correctly mixed in the time window: callbackUsecs <==> Read <==> Write.
  169. */
  170. void JackEngine::CheckXRun(jack_time_t callback_usecs) // REVOIR les conditions de fin
  171. {
  172. for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
  173. JackClientInterface* client = fClientTable[i];
  174. if (client && client->GetClientControl()->fActive) {
  175. JackClientTiming* timing = fGraphManager->GetClientTiming(i);
  176. jack_client_state_t status = timing->fStatus;
  177. jack_time_t finished_date = timing->fFinishedAt;
  178. if (status != NotTriggered && status != Finished) {
  179. jack_error("JackEngine::XRun: client = %s was not run: state = %ld", client->GetClientControl()->fName, status);
  180. fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
  181. }
  182. if (status == Finished && (long)(finished_date - callback_usecs) > 0) {
  183. jack_error("JackEngine::XRun: client %s finished after current callback", client->GetClientControl()->fName);
  184. fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
  185. }
  186. }
  187. }
  188. }
  189. int JackEngine::ComputeTotalLatencies()
  190. {
  191. std::vector<jack_int_t> sorted;
  192. std::vector<jack_int_t>::iterator it;
  193. std::vector<jack_int_t>::reverse_iterator rit;
  194. fGraphManager->TopologicalSort(sorted);
  195. /* iterate over all clients in graph order, and emit
  196. * capture latency callback.
  197. */
  198. for (it = sorted.begin(); it != sorted.end(); it++) {
  199. NotifyClient(*it, kLatencyCallback, true, "", 0, 0);
  200. }
  201. /* now issue playback latency callbacks in reverse graph order.
  202. */
  203. for (rit = sorted.rbegin(); rit != sorted.rend(); rit++) {
  204. NotifyClient(*rit, kLatencyCallback, true, "", 1, 0);
  205. }
  206. return 0;
  207. }
  208. //---------------
  209. // Notifications
  210. //---------------
  211. void JackEngine::NotifyClient(int refnum, int event, int sync, const char* message, int value1, int value2)
  212. {
  213. JackClientInterface* client = fClientTable[refnum];
  214. // The client may be notified by the RT thread while closing
  215. if (client) {
  216. if (client->GetClientControl()->fCallback[event]) {
  217. /*
  218. Important for internal clients : unlock before calling the notification callbacks.
  219. */
  220. bool res = Unlock();
  221. if (client->ClientNotify(refnum, client->GetClientControl()->fName, event, sync, message, value1, value2) < 0)
  222. jack_error("NotifyClient fails name = %s event = %ld val1 = %ld val2 = %ld", client->GetClientControl()->fName, event, value1, value2);
  223. if (res)
  224. Lock();
  225. } else {
  226. jack_log("JackEngine::NotifyClient: no callback for event = %ld", event);
  227. }
  228. }
  229. }
  230. void JackEngine::NotifyClients(int event, int sync, const char* message, int value1, int value2)
  231. {
  232. for (int i = 0; i < CLIENT_NUM; i++) {
  233. NotifyClient(i, event, sync, message, value1, value2);
  234. }
  235. }
  236. int JackEngine::NotifyAddClient(JackClientInterface* new_client, const char* name, int refnum)
  237. {
  238. jack_log("JackEngine::NotifyAddClient: name = %s", name);
  239. // Notify existing clients of the new client and new client of existing clients.
  240. for (int i = 0; i < CLIENT_NUM; i++) {
  241. JackClientInterface* old_client = fClientTable[i];
  242. if (old_client && old_client != new_client) {
  243. if (old_client->ClientNotify(refnum, name, kAddClient, false, "", 0, 0) < 0) {
  244. jack_error("NotifyAddClient old_client fails name = %s", old_client->GetClientControl()->fName);
  245. // Not considered as a failure...
  246. }
  247. if (new_client->ClientNotify(i, old_client->GetClientControl()->fName, kAddClient, true, "", 0, 0) < 0) {
  248. jack_error("NotifyAddClient new_client fails name = %s", name);
  249. return -1;
  250. }
  251. }
  252. }
  253. return 0;
  254. }
  255. void JackEngine::NotifyRemoveClient(const char* name, int refnum)
  256. {
  257. // Notify existing clients (including the one beeing suppressed) of the removed client
  258. for (int i = 0; i < CLIENT_NUM; i++) {
  259. JackClientInterface* client = fClientTable[i];
  260. if (client) {
  261. client->ClientNotify(refnum, name, kRemoveClient, false, "", 0, 0);
  262. }
  263. }
  264. }
  265. // Coming from the driver
  266. void JackEngine::NotifyXRun(jack_time_t callback_usecs, float delayed_usecs)
  267. {
  268. // Use the audio thread => request thread communication channel
  269. fEngineControl->NotifyXRun(callback_usecs, delayed_usecs);
  270. fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0);
  271. }
  272. void JackEngine::NotifyXRun(int refnum)
  273. {
  274. if (refnum == ALL_CLIENTS) {
  275. NotifyClients(kXRunCallback, false, "", 0, 0);
  276. } else {
  277. NotifyClient(refnum, kXRunCallback, false, "", 0, 0);
  278. }
  279. }
  280. void JackEngine::NotifyGraphReorder()
  281. {
  282. NotifyClients(kGraphOrderCallback, false, "", 0, 0);
  283. ComputeTotalLatencies();
  284. }
  285. void JackEngine::NotifyBufferSize(jack_nframes_t buffer_size)
  286. {
  287. NotifyClients(kBufferSizeCallback, true, "", buffer_size, 0);
  288. }
  289. void JackEngine::NotifySampleRate(jack_nframes_t sample_rate)
  290. {
  291. NotifyClients(kSampleRateCallback, true, "", sample_rate, 0);
  292. }
  293. void JackEngine::NotifyFailure(int code, const char* reason)
  294. {
  295. NotifyClients(kShutDownCallback, false, reason, code, 0);
  296. }
  297. void JackEngine::NotifyFreewheel(bool onoff)
  298. {
  299. if (onoff) {
  300. // Save RT state
  301. fEngineControl->fSavedRealTime = fEngineControl->fRealTime;
  302. fEngineControl->fRealTime = false;
  303. } else {
  304. // Restore RT state
  305. fEngineControl->fRealTime = fEngineControl->fSavedRealTime;
  306. fEngineControl->fSavedRealTime = false;
  307. }
  308. NotifyClients((onoff ? kStartFreewheelCallback : kStopFreewheelCallback), true, "", 0, 0);
  309. }
  310. void JackEngine::NotifyPortRegistation(jack_port_id_t port_index, bool onoff)
  311. {
  312. NotifyClients((onoff ? kPortRegistrationOnCallback : kPortRegistrationOffCallback), false, "", port_index, 0);
  313. }
  314. void JackEngine::NotifyPortRename(jack_port_id_t port, const char* old_name)
  315. {
  316. NotifyClients(kPortRenameCallback, false, old_name, port, 0);
  317. }
  318. void JackEngine::NotifyPortConnect(jack_port_id_t src, jack_port_id_t dst, bool onoff)
  319. {
  320. NotifyClients((onoff ? kPortConnectCallback : kPortDisconnectCallback), false, "", src, dst);
  321. }
  322. void JackEngine::NotifyActivate(int refnum)
  323. {
  324. NotifyClient(refnum, kActivateClient, true, "", 0, 0);
  325. }
  326. //----------------------------
  327. // Loadable client management
  328. //----------------------------
  329. int JackEngine::GetInternalClientName(int refnum, char* name_res)
  330. {
  331. JackClientInterface* client = fClientTable[refnum];
  332. strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
  333. return 0;
  334. }
  335. int JackEngine::InternalClientHandle(const char* client_name, int* status, int* int_ref)
  336. {
  337. // Clear status
  338. *status = 0;
  339. for (int i = 0; i < CLIENT_NUM; i++) {
  340. JackClientInterface* client = fClientTable[i];
  341. if (client && dynamic_cast<JackLoadableInternalClient*>(client) && (strcmp(client->GetClientControl()->fName, client_name) == 0)) {
  342. jack_log("InternalClientHandle found client name = %s ref = %ld", client_name, i);
  343. *int_ref = i;
  344. return 0;
  345. }
  346. }
  347. *status |= (JackNoSuchClient | JackFailure);
  348. return -1;
  349. }
  350. int JackEngine::InternalClientUnload(int refnum, int* status)
  351. {
  352. JackClientInterface* client = fClientTable[refnum];
  353. if (client) {
  354. int res = client->Close();
  355. delete client;
  356. *status = 0;
  357. return res;
  358. } else {
  359. *status = (JackNoSuchClient | JackFailure);
  360. return -1;
  361. }
  362. }
  363. //-------------------
  364. // Client management
  365. //-------------------
  366. int JackEngine::ClientCheck(const char* name, int uuid, char* name_res, int protocol, int options, int* status)
  367. {
  368. // Clear status
  369. *status = 0;
  370. strcpy(name_res, name);
  371. jack_log("Check protocol client = %ld server = %ld", protocol, JACK_PROTOCOL_VERSION);
  372. if (protocol != JACK_PROTOCOL_VERSION) {
  373. *status |= (JackFailure | JackVersionError);
  374. jack_error("JACK protocol mismatch (%d vs %d)", protocol, JACK_PROTOCOL_VERSION);
  375. return -1;
  376. }
  377. std::map<int,std::string>::iterator res = fReservationMap.find(uuid);
  378. if (res != fReservationMap.end()) {
  379. strncpy(name_res, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
  380. } else if (ClientCheckName(name)) {
  381. *status |= JackNameNotUnique;
  382. if (options & JackUseExactName) {
  383. jack_error("cannot create new client; %s already exists", name);
  384. *status |= JackFailure;
  385. return -1;
  386. }
  387. if (GenerateUniqueName(name_res)) {
  388. *status |= JackFailure;
  389. return -1;
  390. }
  391. }
  392. return 0;
  393. }
  394. bool JackEngine::GenerateUniqueName(char* name)
  395. {
  396. int tens, ones;
  397. int length = strlen(name);
  398. if (length > JACK_CLIENT_NAME_SIZE - 4) {
  399. jack_error("%s exists and is too long to make unique", name);
  400. return true; /* failure */
  401. }
  402. /* generate a unique name by appending "-01".."-99" */
  403. name[length++] = '-';
  404. tens = length++;
  405. ones = length++;
  406. name[tens] = '0';
  407. name[ones] = '1';
  408. name[length] = '\0';
  409. while (ClientCheckName(name)) {
  410. if (name[ones] == '9') {
  411. if (name[tens] == '9') {
  412. jack_error("client %s has 99 extra instances already", name);
  413. return true; /* give up */
  414. }
  415. name[tens]++;
  416. name[ones] = '0';
  417. } else {
  418. name[ones]++;
  419. }
  420. }
  421. return false;
  422. }
  423. bool JackEngine::ClientCheckName(const char* name)
  424. {
  425. for (int i = 0; i < CLIENT_NUM; i++) {
  426. JackClientInterface* client = fClientTable[i];
  427. if (client && (strcmp(client->GetClientControl()->fName, name) == 0))
  428. return true;
  429. }
  430. for (std::map<int,std::string>::iterator i = fReservationMap.begin(); i != fReservationMap.end(); i++) {
  431. if (i->second == name)
  432. return true;
  433. }
  434. return false;
  435. }
  436. int JackEngine::GetNewUUID()
  437. {
  438. return fMaxUUID++;
  439. }
  440. void JackEngine::EnsureUUID(int uuid)
  441. {
  442. if (uuid > fMaxUUID)
  443. fMaxUUID = uuid+1;
  444. for (int i = 0; i < CLIENT_NUM; i++) {
  445. JackClientInterface* client = fClientTable[i];
  446. if (client && (client->GetClientControl()->fSessionID == uuid)) {
  447. client->GetClientControl()->fSessionID = GetNewUUID();
  448. }
  449. }
  450. }
  451. int JackEngine::GetClientPID(const char* name)
  452. {
  453. for (int i = 0; i < CLIENT_NUM; i++) {
  454. JackClientInterface* client = fClientTable[i];
  455. if (client && (strcmp(client->GetClientControl()->fName, name) == 0))
  456. return client->GetClientControl()->fPID;
  457. }
  458. return 0;
  459. }
  460. int JackEngine::GetClientRefNum(const char* name)
  461. {
  462. for (int i = 0; i < CLIENT_NUM; i++) {
  463. JackClientInterface* client = fClientTable[i];
  464. if (client && (strcmp(client->GetClientControl()->fName, name) == 0))
  465. return client->GetClientControl()->fRefNum;
  466. }
  467. return -1;
  468. }
  469. // Used for external clients
  470. int JackEngine::ClientExternalOpen(const char* name, int pid, int uuid, int* ref, int* shared_engine, int* shared_client, int* shared_graph_manager)
  471. {
  472. char real_name[JACK_CLIENT_NAME_SIZE + 1];
  473. if (uuid < 0) {
  474. uuid = GetNewUUID();
  475. strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
  476. } else {
  477. std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
  478. if (res != fReservationMap.end()) {
  479. strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
  480. fReservationMap.erase(uuid);
  481. } else {
  482. strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
  483. }
  484. EnsureUUID(uuid);
  485. }
  486. jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s ", uuid, real_name);
  487. int refnum = AllocateRefnum();
  488. if (refnum < 0) {
  489. jack_error("No more refnum available");
  490. return -1;
  491. }
  492. JackExternalClient* client = new JackExternalClient();
  493. if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
  494. jack_error("Cannot allocate synchro");
  495. goto error;
  496. }
  497. if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
  498. jack_error("Cannot open client");
  499. goto error;
  500. }
  501. if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
  502. // Failure if RT thread is not running (problem with the driver...)
  503. jack_error("Driver is not running");
  504. goto error;
  505. }
  506. fClientTable[refnum] = client;
  507. if (NotifyAddClient(client, real_name, refnum) < 0) {
  508. jack_error("Cannot notify add client");
  509. goto error;
  510. }
  511. fGraphManager->InitRefNum(refnum);
  512. fEngineControl->ResetRollingUsecs();
  513. *shared_engine = fEngineControl->GetShmIndex();
  514. *shared_graph_manager = fGraphManager->GetShmIndex();
  515. *ref = refnum;
  516. return 0;
  517. error:
  518. // Cleanup...
  519. fSynchroTable[refnum].Destroy();
  520. fClientTable[refnum] = 0;
  521. client->Close();
  522. delete client;
  523. return -1;
  524. }
  525. // Used for server driver clients
  526. int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
  527. {
  528. jack_log("JackEngine::ClientInternalOpen: name = %s", name);
  529. int refnum = AllocateRefnum();
  530. if (refnum < 0) {
  531. jack_error("No more refnum available");
  532. goto error;
  533. }
  534. if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
  535. jack_error("Cannot allocate synchro");
  536. goto error;
  537. }
  538. if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
  539. // Failure if RT thread is not running (problem with the driver...)
  540. jack_error("Driver is not running");
  541. goto error;
  542. }
  543. fClientTable[refnum] = client;
  544. if (NotifyAddClient(client, name, refnum) < 0) {
  545. jack_error("Cannot notify add client");
  546. goto error;
  547. }
  548. fGraphManager->InitRefNum(refnum);
  549. fEngineControl->ResetRollingUsecs();
  550. *shared_engine = fEngineControl;
  551. *shared_manager = fGraphManager;
  552. *ref = refnum;
  553. return 0;
  554. error:
  555. // Cleanup...
  556. fSynchroTable[refnum].Destroy();
  557. fClientTable[refnum] = 0;
  558. return -1;
  559. }
  560. // Used for external clients
  561. int JackEngine::ClientExternalClose(int refnum)
  562. {
  563. jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
  564. JackClientInterface* client = fClientTable[refnum];
  565. fEngineControl->fTransport.ResetTimebase(refnum);
  566. int res = ClientCloseAux(refnum, client, true);
  567. client->Close();
  568. delete client;
  569. return res;
  570. }
  571. // Used for server internal clients or drivers when the RT thread is stopped
  572. int JackEngine::ClientInternalClose(int refnum, bool wait)
  573. {
  574. jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
  575. JackClientInterface* client = fClientTable[refnum];
  576. fEngineControl->fTransport.ResetTimebase(refnum);
  577. return ClientCloseAux(refnum, client, wait);
  578. }
  579. int JackEngine::ClientCloseAux(int refnum, JackClientInterface* client, bool wait)
  580. {
  581. jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
  582. // Unregister all ports ==> notifications are sent
  583. jack_int_t ports[PORT_NUM_FOR_CLIENT];
  584. int i;
  585. fGraphManager->GetInputPorts(refnum, ports);
  586. for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
  587. PortUnRegister(refnum, ports[i]);
  588. }
  589. fGraphManager->GetOutputPorts(refnum, ports);
  590. for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
  591. PortUnRegister(refnum, ports[i]);
  592. }
  593. // Remove the client from the table
  594. ReleaseRefnum(refnum);
  595. // Remove all ports
  596. fGraphManager->RemoveAllPorts(refnum);
  597. // Wait until next cycle to be sure client is not used anymore
  598. if (wait) {
  599. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
  600. jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
  601. }
  602. }
  603. // Notify running clients
  604. NotifyRemoveClient(client->GetClientControl()->fName, client->GetClientControl()->fRefNum);
  605. // Cleanup...
  606. fSynchroTable[refnum].Destroy();
  607. fEngineControl->ResetRollingUsecs();
  608. return 0;
  609. }
  610. int JackEngine::ClientActivate(int refnum, bool is_real_time)
  611. {
  612. JackClientInterface* client = fClientTable[refnum];
  613. jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  614. if (is_real_time)
  615. fGraphManager->Activate(refnum);
  616. // Wait for graph state change to be effective
  617. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  618. jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  619. return -1;
  620. } else {
  621. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  622. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  623. fGraphManager->GetInputPorts(refnum, input_ports);
  624. fGraphManager->GetOutputPorts(refnum, output_ports);
  625. // Notify client
  626. NotifyActivate(refnum);
  627. // Then issue port registration notification
  628. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  629. NotifyPortRegistation(input_ports[i], true);
  630. }
  631. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  632. NotifyPortRegistation(output_ports[i], true);
  633. }
  634. return 0;
  635. }
  636. }
  637. // May be called without client
  638. int JackEngine::ClientDeactivate(int refnum)
  639. {
  640. JackClientInterface* client = fClientTable[refnum];
  641. jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  642. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  643. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  644. fGraphManager->GetInputPorts(refnum, input_ports);
  645. fGraphManager->GetOutputPorts(refnum, output_ports);
  646. // First disconnect all ports
  647. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  648. PortDisconnect(refnum, input_ports[i], ALL_PORTS);
  649. }
  650. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  651. PortDisconnect(refnum, output_ports[i], ALL_PORTS);
  652. }
  653. // Then issue port registration notification
  654. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  655. NotifyPortRegistation(input_ports[i], false);
  656. }
  657. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  658. NotifyPortRegistation(output_ports[i], false);
  659. }
  660. fGraphManager->Deactivate(refnum);
  661. fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
  662. // Wait for graph state change to be effective
  663. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  664. jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  665. return -1;
  666. } else {
  667. return 0;
  668. }
  669. }
  670. //-----------------
  671. // Port management
  672. //-----------------
  673. int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
  674. {
  675. jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
  676. JackClientInterface* client = fClientTable[refnum];
  677. // Check if port name already exists
  678. if (fGraphManager->GetPort(name) != NO_PORT) {
  679. jack_error("port_name \"%s\" already exists", name);
  680. return -1;
  681. }
  682. // buffer_size is actually ignored...
  683. *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
  684. if (*port_index != NO_PORT) {
  685. if (client->GetClientControl()->fActive)
  686. NotifyPortRegistation(*port_index, true);
  687. return 0;
  688. } else {
  689. return -1;
  690. }
  691. }
  692. int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
  693. {
  694. jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
  695. JackClientInterface* client = fClientTable[refnum];
  696. // Disconnect port ==> notification is sent
  697. PortDisconnect(refnum, port_index, ALL_PORTS);
  698. if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
  699. if (client->GetClientControl()->fActive)
  700. NotifyPortRegistation(port_index, false);
  701. return 0;
  702. } else {
  703. return -1;
  704. }
  705. }
  706. int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
  707. {
  708. jack_log("JackEngine::PortConnect src = %s dst = %s", src, dst);
  709. jack_port_id_t port_src, port_dst;
  710. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  711. ? -1
  712. : PortConnect(refnum, port_src, port_dst);
  713. }
  714. int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  715. {
  716. jack_log("JackEngine::PortConnect src = %d dst = %d", src, dst);
  717. JackClientInterface* client;
  718. int ref;
  719. if (fGraphManager->CheckPorts(src, dst) < 0)
  720. return -1;
  721. ref = fGraphManager->GetOutputRefNum(src);
  722. assert(ref >= 0);
  723. client = fClientTable[ref];
  724. assert(client);
  725. if (!client->GetClientControl()->fActive) {
  726. jack_error("Cannot connect ports owned by inactive clients:"
  727. " \"%s\" is not active", client->GetClientControl()->fName);
  728. return -1;
  729. }
  730. ref = fGraphManager->GetInputRefNum(dst);
  731. assert(ref >= 0);
  732. client = fClientTable[ref];
  733. assert(client);
  734. if (!client->GetClientControl()->fActive) {
  735. jack_error("Cannot connect ports owned by inactive clients:"
  736. " \"%s\" is not active", client->GetClientControl()->fName);
  737. return -1;
  738. }
  739. int res = fGraphManager->Connect(src, dst);
  740. if (res == 0)
  741. NotifyPortConnect(src, dst, true);
  742. return res;
  743. }
  744. int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
  745. {
  746. jack_log("JackEngine::PortDisconnect src = %s dst = %s", src, dst);
  747. jack_port_id_t port_src, port_dst;
  748. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  749. ? -1
  750. : PortDisconnect(refnum, port_src, port_dst);
  751. }
  752. int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  753. {
  754. jack_log("JackEngine::PortDisconnect src = %d dst = %d", src, dst);
  755. if (dst == ALL_PORTS) {
  756. jack_int_t connections[CONNECTION_NUM_FOR_PORT];
  757. fGraphManager->GetConnections(src, connections);
  758. JackPort* port = fGraphManager->GetPort(src);
  759. int ret = 0;
  760. if (port->GetFlags() & JackPortIsOutput) {
  761. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  762. if (PortDisconnect(refnum, src, connections[i]) != 0) {
  763. ret = -1;
  764. }
  765. }
  766. } else {
  767. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  768. if (PortDisconnect(refnum, connections[i], src) != 0) {
  769. ret = -1;
  770. }
  771. }
  772. }
  773. return ret;
  774. } else if (fGraphManager->CheckPorts(src, dst) < 0) {
  775. return -1;
  776. } else if (fGraphManager->Disconnect(src, dst) == 0) {
  777. // Notifications
  778. NotifyPortConnect(src, dst, false);
  779. return 0;
  780. } else {
  781. return -1;
  782. }
  783. }
  784. int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
  785. {
  786. char old_name[REAL_JACK_PORT_NAME_SIZE];
  787. strcpy(old_name, fGraphManager->GetPort(port)->GetName());
  788. fGraphManager->GetPort(port)->SetName(name);
  789. NotifyPortRename(port, old_name);
  790. return 0;
  791. }
  792. //--------------------
  793. // Session management
  794. //--------------------
  795. void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
  796. {
  797. if (fSessionPendingReplies != 0) {
  798. JackSessionNotifyResult res(-1);
  799. res.Write(socket);
  800. jack_log("JackEngine::SessionNotify ... busy");
  801. if (result != NULL) {
  802. *result = NULL;
  803. }
  804. return;
  805. }
  806. for (int i = 0; i < CLIENT_NUM; i++) {
  807. JackClientInterface* client = fClientTable[i];
  808. if (client && (client->GetClientControl()->fSessionID < 0)) {
  809. client->GetClientControl()->fSessionID = GetNewUUID();
  810. }
  811. }
  812. fSessionResult = new JackSessionNotifyResult();
  813. for (int i = 0; i < CLIENT_NUM; i++) {
  814. JackClientInterface* client = fClientTable[i];
  815. if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
  816. // check if this is a notification to a specific client.
  817. if (target != NULL && strlen(target) != 0) {
  818. if (strcmp(target, client->GetClientControl()->fName)) {
  819. continue;
  820. }
  821. }
  822. char path_buf[JACK_PORT_NAME_SIZE];
  823. snprintf(path_buf, sizeof(path_buf), "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
  824. int res = JackTools::MkDir(path_buf);
  825. if (res)
  826. jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
  827. int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
  828. if (result == kPendingSessionReply) {
  829. fSessionPendingReplies += 1;
  830. } else if (result == kImmediateSessionReply) {
  831. char uuid_buf[JACK_UUID_SIZE];
  832. snprintf(uuid_buf, sizeof(uuid_buf), "%d", client->GetClientControl()->fSessionID);
  833. fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
  834. client->GetClientControl()->fName,
  835. client->GetClientControl()->fSessionCommand,
  836. client->GetClientControl()->fSessionFlags));
  837. }
  838. }
  839. }
  840. if (result != NULL) {
  841. *result = fSessionResult;
  842. }
  843. if (fSessionPendingReplies == 0) {
  844. fSessionResult->Write(socket);
  845. if (result == NULL) {
  846. delete fSessionResult;
  847. }
  848. fSessionResult = NULL;
  849. } else {
  850. fSessionTransaction = socket;
  851. }
  852. }
  853. int JackEngine::SessionReply(int refnum)
  854. {
  855. JackClientInterface* client = fClientTable[refnum];
  856. char uuid_buf[JACK_UUID_SIZE];
  857. snprintf(uuid_buf, sizeof(uuid_buf), "%d", client->GetClientControl()->fSessionID);
  858. fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
  859. client->GetClientControl()->fName,
  860. client->GetClientControl()->fSessionCommand,
  861. client->GetClientControl()->fSessionFlags));
  862. fSessionPendingReplies -= 1;
  863. if (fSessionPendingReplies == 0) {
  864. fSessionResult->Write(fSessionTransaction);
  865. if (fSessionTransaction != NULL)
  866. {
  867. delete fSessionResult;
  868. }
  869. fSessionResult = NULL;
  870. }
  871. return 0;
  872. }
  873. int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
  874. {
  875. for (int i = 0; i < CLIENT_NUM; i++) {
  876. JackClientInterface* client = fClientTable[i];
  877. if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
  878. snprintf(uuid_res, JACK_UUID_SIZE, "%d", client->GetClientControl()->fSessionID);
  879. return 0;
  880. }
  881. }
  882. // Did not find name.
  883. return -1;
  884. }
  885. int JackEngine::GetClientNameForUUID(const char *uuid, char *name_res)
  886. {
  887. for (int i = 0; i < CLIENT_NUM; i++) {
  888. JackClientInterface* client = fClientTable[i];
  889. if (!client) {
  890. continue;
  891. }
  892. char uuid_buf[JACK_UUID_SIZE];
  893. snprintf(uuid_buf, JACK_UUID_SIZE, "%d", client->GetClientControl()->fSessionID);
  894. if (strcmp(uuid,uuid_buf) == 0) {
  895. strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
  896. return 0;
  897. }
  898. }
  899. // Did not find uuid.
  900. return -1;
  901. }
  902. int JackEngine::ReserveClientName(const char *name, const char *uuid)
  903. {
  904. jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuid);
  905. if (ClientCheckName(name)) {
  906. jack_log("name already taken");
  907. return -1;
  908. }
  909. EnsureUUID(atoi(uuid));
  910. fReservationMap[atoi(uuid)] = name;
  911. return 0;
  912. }
  913. int JackEngine::ClientHasSessionCallback(const char *name)
  914. {
  915. JackClientInterface* client = NULL;
  916. for (int i = 0; i < CLIENT_NUM; i++) {
  917. client = fClientTable[i];
  918. if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
  919. break;
  920. }
  921. }
  922. if (client) {
  923. return client->GetClientControl()->fCallback[kSessionCallback];
  924. } else {
  925. return -1;
  926. }
  927. }
  928. } // end of namespace