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.

1275 lines
40KB

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