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.

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