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.

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