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.

1251 lines
39KB

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