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.

1245 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. 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. fMetadata(NULL) // FIXME use control->fServerName?
  39. {
  40. fGraphManager = manager;
  41. fSynchroTable = table;
  42. fEngineControl = control;
  43. fSelfConnectMode = self_connect_mode;
  44. for (int i = 0; i < CLIENT_NUM; i++) {
  45. fClientTable[i] = NULL;
  46. }
  47. fLastSwitchUsecs = 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, jack_uuid_t 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. void JackEngine::EnsureUUID(jack_uuid_t uuid)
  480. {
  481. if (jack_uuid_empty(uuid))
  482. return;
  483. for (int i = 0; i < CLIENT_NUM; i++) {
  484. JackClientInterface* client = fClientTable[i];
  485. if (client && jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
  486. // FIXME? this code does nothing, but jack1 has it like this too..
  487. jack_uuid_clear (&uuid);
  488. // client->GetClientControl()->fSessionID = jack_client_uuid_generate();
  489. }
  490. }
  491. }
  492. int JackEngine::GetClientPID(const char* name)
  493. {
  494. for (int i = 0; i < CLIENT_NUM; i++) {
  495. JackClientInterface* client = fClientTable[i];
  496. if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
  497. return client->GetClientControl()->fPID;
  498. }
  499. }
  500. return 0;
  501. }
  502. int JackEngine::GetClientRefNum(const char* name)
  503. {
  504. for (int i = 0; i < CLIENT_NUM; i++) {
  505. JackClientInterface* client = fClientTable[i];
  506. if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
  507. return client->GetClientControl()->fRefNum;
  508. }
  509. }
  510. return -1;
  511. }
  512. // Used for external clients
  513. int JackEngine::ClientExternalOpen(const char* name, int pid, jack_uuid_t uuid, int* ref, int* shared_engine, int* shared_client, int* shared_graph_manager)
  514. {
  515. char real_name[JACK_CLIENT_NAME_SIZE + 1];
  516. if (jack_uuid_empty(uuid)) {
  517. uuid = jack_client_uuid_generate();
  518. strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
  519. } else {
  520. std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
  521. if (res != fReservationMap.end()) {
  522. strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
  523. fReservationMap.erase(uuid);
  524. } else {
  525. strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
  526. }
  527. EnsureUUID(uuid);
  528. }
  529. jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s", uuid, real_name);
  530. int refnum = AllocateRefnum();
  531. if (refnum < 0) {
  532. jack_error("No more refnum available");
  533. return -1;
  534. }
  535. JackExternalClient* client = new JackExternalClient();
  536. if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
  537. jack_error("Cannot allocate synchro");
  538. goto error;
  539. }
  540. if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
  541. jack_error("Cannot open client");
  542. goto error;
  543. }
  544. if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
  545. // Failure if RT thread is not running (problem with the driver...)
  546. jack_error("Driver is not running");
  547. goto error;
  548. }
  549. fClientTable[refnum] = client;
  550. if (NotifyAddClient(client, real_name, refnum) < 0) {
  551. jack_error("Cannot notify add client");
  552. goto error;
  553. }
  554. fGraphManager->InitRefNum(refnum);
  555. fEngineControl->ResetRollingUsecs();
  556. *shared_engine = fEngineControl->GetShmIndex();
  557. *shared_graph_manager = fGraphManager->GetShmIndex();
  558. *ref = refnum;
  559. return 0;
  560. error:
  561. // Cleanup...
  562. fSynchroTable[refnum].Destroy();
  563. fClientTable[refnum] = 0;
  564. client->Close();
  565. delete client;
  566. return -1;
  567. }
  568. // Used for server driver clients
  569. int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
  570. {
  571. jack_log("JackEngine::ClientInternalOpen: name = %s", name);
  572. int refnum = AllocateRefnum();
  573. if (refnum < 0) {
  574. jack_error("No more refnum available");
  575. goto error;
  576. }
  577. if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
  578. jack_error("Cannot allocate synchro");
  579. goto error;
  580. }
  581. if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
  582. // Failure if RT thread is not running (problem with the driver...)
  583. jack_error("Driver is not running");
  584. goto error;
  585. }
  586. fClientTable[refnum] = client;
  587. if (NotifyAddClient(client, name, refnum) < 0) {
  588. jack_error("Cannot notify add client");
  589. goto error;
  590. }
  591. fGraphManager->InitRefNum(refnum);
  592. fEngineControl->ResetRollingUsecs();
  593. *shared_engine = fEngineControl;
  594. *shared_manager = fGraphManager;
  595. *ref = refnum;
  596. return 0;
  597. error:
  598. // Cleanup...
  599. fSynchroTable[refnum].Destroy();
  600. fClientTable[refnum] = 0;
  601. return -1;
  602. }
  603. // Used for external clients
  604. int JackEngine::ClientExternalClose(int refnum)
  605. {
  606. jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
  607. JackClientInterface* client = fClientTable[refnum];
  608. assert(client);
  609. int res = ClientCloseAux(refnum, true);
  610. client->Close();
  611. delete client;
  612. return res;
  613. }
  614. // Used for server internal clients or drivers when the RT thread is stopped
  615. int JackEngine::ClientInternalClose(int refnum, bool wait)
  616. {
  617. jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
  618. return ClientCloseAux(refnum, wait);
  619. }
  620. int JackEngine::ClientCloseAux(int refnum, bool wait)
  621. {
  622. jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
  623. JackClientInterface* client = fClientTable[refnum];
  624. fEngineControl->fTransport.ResetTimebase(refnum);
  625. jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
  626. jack_uuid_copy (&uuid, client->GetClientControl()->fSessionID);
  627. // Unregister all ports ==> notifications are sent
  628. jack_int_t ports[PORT_NUM_FOR_CLIENT];
  629. int i;
  630. fGraphManager->GetInputPorts(refnum, ports);
  631. for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
  632. PortUnRegister(refnum, ports[i]);
  633. }
  634. fGraphManager->GetOutputPorts(refnum, ports);
  635. for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
  636. PortUnRegister(refnum, ports[i]);
  637. }
  638. // Remove the client from the table
  639. ReleaseRefnum(refnum);
  640. // Remove all ports
  641. fGraphManager->RemoveAllPorts(refnum);
  642. // Wait until next cycle to be sure client is not used anymore
  643. if (wait) {
  644. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
  645. jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
  646. }
  647. }
  648. // Notify running clients
  649. NotifyRemoveClient(client->GetClientControl()->fName, refnum);
  650. fMetadata.RemoveProperties(NULL, uuid);
  651. /* have to do the notification ourselves, since the client argument
  652. to fMetadata->RemoveProperties() was NULL
  653. */
  654. PropertyChangeNotify(uuid, NULL, PropertyDeleted);
  655. // Cleanup...
  656. fSynchroTable[refnum].Destroy();
  657. fEngineControl->ResetRollingUsecs();
  658. return 0;
  659. }
  660. int JackEngine::ClientActivate(int refnum, bool is_real_time)
  661. {
  662. JackClientInterface* client = fClientTable[refnum];
  663. jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  664. if (is_real_time) {
  665. fGraphManager->Activate(refnum);
  666. }
  667. // Wait for graph state change to be effective
  668. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  669. jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  670. return -1;
  671. } else {
  672. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  673. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  674. fGraphManager->GetInputPorts(refnum, input_ports);
  675. fGraphManager->GetOutputPorts(refnum, output_ports);
  676. // Notify client
  677. NotifyActivate(refnum);
  678. // Then issue port registration notification
  679. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  680. NotifyPortRegistation(input_ports[i], true);
  681. }
  682. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  683. NotifyPortRegistation(output_ports[i], true);
  684. }
  685. return 0;
  686. }
  687. }
  688. // May be called without client
  689. int JackEngine::ClientDeactivate(int refnum)
  690. {
  691. JackClientInterface* client = fClientTable[refnum];
  692. jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  693. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  694. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  695. fGraphManager->GetInputPorts(refnum, input_ports);
  696. fGraphManager->GetOutputPorts(refnum, output_ports);
  697. // First disconnect all ports
  698. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  699. PortDisconnect(-1, input_ports[i], ALL_PORTS);
  700. }
  701. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  702. PortDisconnect(-1, output_ports[i], ALL_PORTS);
  703. }
  704. // Then issue port registration notification
  705. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  706. NotifyPortRegistation(input_ports[i], false);
  707. }
  708. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  709. NotifyPortRegistation(output_ports[i], false);
  710. }
  711. fGraphManager->Deactivate(refnum);
  712. fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
  713. // Wait for graph state change to be effective
  714. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  715. jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  716. return -1;
  717. } else {
  718. return 0;
  719. }
  720. }
  721. void JackEngine::ClientKill(int refnum)
  722. {
  723. jack_log("JackEngine::ClientKill ref = %ld", refnum);
  724. if (ClientDeactivate(refnum) < 0) {
  725. jack_error("JackEngine::ClientKill ref = %ld cannot be removed from the graph !!", refnum);
  726. }
  727. if (ClientExternalClose(refnum) < 0) {
  728. jack_error("JackEngine::ClientKill ref = %ld cannot be closed", refnum);
  729. }
  730. }
  731. //-----------------
  732. // Port management
  733. //-----------------
  734. int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
  735. {
  736. jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
  737. JackClientInterface* client = fClientTable[refnum];
  738. // Check if port name already exists
  739. if (fGraphManager->GetPort(name) != NO_PORT) {
  740. jack_error("port_name \"%s\" already exists", name);
  741. return -1;
  742. }
  743. // buffer_size is actually ignored...
  744. *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
  745. if (*port_index != NO_PORT) {
  746. if (client->GetClientControl()->fActive) {
  747. NotifyPortRegistation(*port_index, true);
  748. }
  749. return 0;
  750. } else {
  751. return -1;
  752. }
  753. }
  754. int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
  755. {
  756. jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
  757. JackClientInterface* client = fClientTable[refnum];
  758. assert(client);
  759. // Disconnect port ==> notification is sent
  760. PortDisconnect(-1, port_index, ALL_PORTS);
  761. if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
  762. if (client->GetClientControl()->fActive) {
  763. NotifyPortRegistation(port_index, false);
  764. }
  765. return 0;
  766. } else {
  767. return -1;
  768. }
  769. }
  770. // this check is to prevent apps to self connect to other apps
  771. // TODO: make this work with multiple clients per app
  772. int JackEngine::CheckPortsConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  773. {
  774. if (fSelfConnectMode == ' ') return 1;
  775. JackPort* src_port = fGraphManager->GetPort(src);
  776. JackPort* dst_port = fGraphManager->GetPort(dst);
  777. jack_log("JackEngine::CheckPortsConnect(ref = %d, src = %d, dst = %d)", refnum, src_port->GetRefNum(), dst_port->GetRefNum());
  778. //jack_log("%s -> %s", src_port->GetName(), dst_port->GetName());
  779. //jack_log("mode = '%c'", fSelfConnectMode);
  780. int src_self = src_port->GetRefNum() == refnum ? 1 : 0;
  781. int dst_self = dst_port->GetRefNum() == refnum ? 1 : 0;
  782. //jack_log("src_self is %s", src_self ? "true" : "false");
  783. //jack_log("dst_self is %s", dst_self ? "true" : "false");
  784. // 0 means client is connecting other client ports (control app patchbay functionality)
  785. // 1 means client is connecting its own port to port of other client (e.g. self connecting into "system" client)
  786. // 2 means client is connecting its own ports (for app internal functionality)
  787. int sum = src_self + dst_self;
  788. //jack_log("sum = %d", sum);
  789. if (sum == 0) return 1;
  790. char lmode = tolower(fSelfConnectMode);
  791. //jack_log("lmode = '%c'", lmode);
  792. if (sum == 2 && lmode == 'e') return 1;
  793. bool fail = lmode != fSelfConnectMode; // fail modes are upper case
  794. //jack_log("fail = %d", (int)fail);
  795. jack_info(
  796. "%s port self connect request%s (%s -> %s)",
  797. fail ? "rejecting" : "ignoring",
  798. sum == 1 ? " to external port" : "",
  799. src_port->GetName(),
  800. dst_port->GetName());
  801. return fail ? -1 : 0;
  802. }
  803. int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
  804. {
  805. jack_log("JackEngine::PortConnect ref = %d src = %s dst = %s", refnum, src, dst);
  806. jack_port_id_t port_src, port_dst;
  807. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  808. ? -1
  809. : PortConnect(refnum, port_src, port_dst);
  810. }
  811. int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  812. {
  813. jack_log("JackEngine::PortConnect ref = %d src = %d dst = %d", refnum, src, dst);
  814. JackClientInterface* client;
  815. int ref;
  816. if (fGraphManager->CheckPorts(src, dst) < 0) {
  817. return -1;
  818. }
  819. ref = fGraphManager->GetOutputRefNum(src);
  820. assert(ref >= 0);
  821. client = fClientTable[ref];
  822. assert(client);
  823. if (!client->GetClientControl()->fActive) {
  824. jack_error("Cannot connect ports owned by inactive clients:"
  825. " \"%s\" is not active", client->GetClientControl()->fName);
  826. return -1;
  827. }
  828. ref = fGraphManager->GetInputRefNum(dst);
  829. assert(ref >= 0);
  830. client = fClientTable[ref];
  831. assert(client);
  832. if (!client->GetClientControl()->fActive) {
  833. jack_error("Cannot connect ports owned by inactive clients:"
  834. " \"%s\" is not active", client->GetClientControl()->fName);
  835. return -1;
  836. }
  837. int res = CheckPortsConnect(refnum, src, dst);
  838. if (res != 1) {
  839. return res;
  840. }
  841. res = fGraphManager->Connect(src, dst);
  842. if (res == 0) {
  843. NotifyPortConnect(src, dst, true);
  844. }
  845. return res;
  846. }
  847. int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
  848. {
  849. jack_log("JackEngine::PortDisconnect ref = %d src = %s dst = %s", refnum, src, dst);
  850. jack_port_id_t port_src, port_dst;
  851. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  852. ? -1
  853. : PortDisconnect(refnum, port_src, port_dst);
  854. }
  855. int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  856. {
  857. jack_log("JackEngine::PortDisconnect ref = %d src = %d dst = %d", refnum, src, dst);
  858. if (dst == ALL_PORTS) {
  859. jack_int_t connections[CONNECTION_NUM_FOR_PORT];
  860. fGraphManager->GetConnections(src, connections);
  861. JackPort* port = fGraphManager->GetPort(src);
  862. int res = 0;
  863. if (port->GetFlags() & JackPortIsOutput) {
  864. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  865. if (PortDisconnect(refnum, src, connections[i]) != 0) {
  866. res = -1;
  867. }
  868. }
  869. } else {
  870. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  871. if (PortDisconnect(refnum, connections[i], src) != 0) {
  872. res = -1;
  873. }
  874. }
  875. }
  876. return res;
  877. }
  878. if (fGraphManager->CheckPorts(src, dst) < 0) {
  879. return -1;
  880. }
  881. int res = CheckPortsConnect(refnum, src, dst);
  882. if (res != 1) {
  883. return res;
  884. }
  885. res = fGraphManager->Disconnect(src, dst);
  886. if (res == 0)
  887. NotifyPortConnect(src, dst, false);
  888. return res;
  889. }
  890. int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
  891. {
  892. char old_name[REAL_JACK_PORT_NAME_SIZE+1];
  893. strcpy(old_name, fGraphManager->GetPort(port)->GetName());
  894. fGraphManager->GetPort(port)->SetName(name);
  895. NotifyPortRename(port, old_name);
  896. return 0;
  897. }
  898. //--------------------
  899. // Session management
  900. //--------------------
  901. void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
  902. {
  903. if (fSessionPendingReplies != 0) {
  904. JackSessionNotifyResult res(-1);
  905. res.Write(socket);
  906. jack_log("JackEngine::SessionNotify ... busy");
  907. if (result != NULL) *result = NULL;
  908. return;
  909. }
  910. for (int i = 0; i < CLIENT_NUM; i++) {
  911. JackClientInterface* client = fClientTable[i];
  912. <<<<<<< HEAD
  913. if (client && (client->GetClientControl()->fSessionID < 0)) {
  914. =======
  915. if (client && jack_uuid_empty(client->GetClientControl()->fSessionID)) {
  916. >>>>>>> f7f2244b07ee0a723853e838de85e25471b8903f
  917. client->GetClientControl()->fSessionID = jack_client_uuid_generate();
  918. }
  919. }
  920. fSessionResult = new JackSessionNotifyResult();
  921. for (int i = 0; i < CLIENT_NUM; i++) {
  922. JackClientInterface* client = fClientTable[i];
  923. if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
  924. // check if this is a notification to a specific client.
  925. if (target != NULL && strlen(target) != 0) {
  926. if (strcmp(target, client->GetClientControl()->fName)) {
  927. continue;
  928. }
  929. }
  930. char path_buf[JACK_PORT_NAME_SIZE];
  931. if (path[strlen(path) - 1] == DIR_SEPARATOR) {
  932. snprintf(path_buf, sizeof path_buf, "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
  933. } else {
  934. snprintf(path_buf, sizeof path_buf, "%s%c%s%c", path, DIR_SEPARATOR, client->GetClientControl()->fName, DIR_SEPARATOR);
  935. }
  936. int res = JackTools::MkDir(path_buf);
  937. if (res) jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
  938. int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
  939. if (result == kPendingSessionReply) {
  940. fSessionPendingReplies += 1;
  941. } else if (result == kImmediateSessionReply) {
  942. char uuid_buf[JACK_UUID_STRING_SIZE];
  943. jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
  944. fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
  945. client->GetClientControl()->fName,
  946. client->GetClientControl()->fSessionCommand,
  947. client->GetClientControl()->fSessionFlags));
  948. }
  949. }
  950. }
  951. if (result != NULL) *result = fSessionResult;
  952. if (fSessionPendingReplies == 0) {
  953. fSessionResult->Write(socket);
  954. if (result == NULL) delete fSessionResult;
  955. fSessionResult = NULL;
  956. } else {
  957. fSessionTransaction = socket;
  958. }
  959. }
  960. int JackEngine::SessionReply(int refnum)
  961. {
  962. JackClientInterface* client = fClientTable[refnum];
  963. assert(client);
  964. char uuid_buf[JACK_UUID_STRING_SIZE];
  965. jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
  966. fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
  967. client->GetClientControl()->fName,
  968. client->GetClientControl()->fSessionCommand,
  969. client->GetClientControl()->fSessionFlags));
  970. fSessionPendingReplies -= 1;
  971. if (fSessionPendingReplies == 0) {
  972. fSessionResult->Write(fSessionTransaction);
  973. if (fSessionTransaction != NULL) {
  974. delete fSessionResult;
  975. }
  976. fSessionResult = NULL;
  977. }
  978. return 0;
  979. }
  980. int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
  981. {
  982. for (int i = 0; i < CLIENT_NUM; i++) {
  983. JackClientInterface* client = fClientTable[i];
  984. if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
  985. jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_res);
  986. return 0;
  987. }
  988. }
  989. // Did not find name.
  990. return -1;
  991. }
  992. int JackEngine::GetClientNameForUUID(const char *uuid_buf, char *name_res)
  993. {
  994. jack_uuid_t uuid;
  995. if (jack_uuid_parse(uuid_buf, &uuid) != 0)
  996. return -1;
  997. for (int i = 0; i < CLIENT_NUM; i++) {
  998. JackClientInterface* client = fClientTable[i];
  999. if (!client) {
  1000. continue;
  1001. }
  1002. if (jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
  1003. strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
  1004. return 0;
  1005. }
  1006. }
  1007. // Did not find uuid.
  1008. return -1;
  1009. }
  1010. int JackEngine::ReserveClientName(const char *name, const char *uuidstr)
  1011. {
  1012. jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuidstr);
  1013. if (ClientCheckName(name)) {
  1014. jack_log("name already taken");
  1015. return -1;
  1016. }
  1017. jack_uuid_t uuid;
  1018. if (jack_uuid_parse(uuidstr, &uuid) != 0) {
  1019. jack_error("JackEngine::ReserveClientName invalid uuid %s", uuidstr);
  1020. return -1;
  1021. }
  1022. EnsureUUID(uuid);
  1023. fReservationMap[uuid] = name;
  1024. return 0;
  1025. }
  1026. int JackEngine::ClientHasSessionCallback(const char *name)
  1027. {
  1028. JackClientInterface* client = NULL;
  1029. for (int i = 0; i < CLIENT_NUM; i++) {
  1030. client = fClientTable[i];
  1031. if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
  1032. break;
  1033. }
  1034. }
  1035. if (client) {
  1036. return client->GetClientControl()->fCallback[kSessionCallback];
  1037. } else {
  1038. return -1;
  1039. }
  1040. }
  1041. } // end of namespace