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.

1224 lines
38KB

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