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.

1161 lines
36KB

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