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.

1231 lines
38KB

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