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.

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