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.

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