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.

1232 lines
39KB

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