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.

1124 lines
35KB

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