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.

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