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.

1093 lines
34KB

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