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.

1140 lines
35KB

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