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.

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