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.

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