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.

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