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.

1172 lines
37KB

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