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.

1249 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. <<<<<<< HEAD
  517. if (uuid < 0) {
  518. =======
  519. if (jack_uuid_empty(uuid)) {
  520. >>>>>>> f7f2244b07ee0a723853e838de85e25471b8903f
  521. uuid = jack_client_uuid_generate();
  522. strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
  523. } else {
  524. std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
  525. if (res != fReservationMap.end()) {
  526. strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
  527. fReservationMap.erase(uuid);
  528. } else {
  529. strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
  530. }
  531. EnsureUUID(uuid);
  532. }
  533. jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s", uuid, real_name);
  534. int refnum = AllocateRefnum();
  535. if (refnum < 0) {
  536. jack_error("No more refnum available");
  537. return -1;
  538. }
  539. JackExternalClient* client = new JackExternalClient();
  540. if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
  541. jack_error("Cannot allocate synchro");
  542. goto error;
  543. }
  544. if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
  545. jack_error("Cannot open client");
  546. goto error;
  547. }
  548. if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
  549. // Failure if RT thread is not running (problem with the driver...)
  550. jack_error("Driver is not running");
  551. goto error;
  552. }
  553. fClientTable[refnum] = client;
  554. if (NotifyAddClient(client, real_name, refnum) < 0) {
  555. jack_error("Cannot notify add client");
  556. goto error;
  557. }
  558. fGraphManager->InitRefNum(refnum);
  559. fEngineControl->ResetRollingUsecs();
  560. *shared_engine = fEngineControl->GetShmIndex();
  561. *shared_graph_manager = fGraphManager->GetShmIndex();
  562. *ref = refnum;
  563. return 0;
  564. error:
  565. // Cleanup...
  566. fSynchroTable[refnum].Destroy();
  567. fClientTable[refnum] = 0;
  568. client->Close();
  569. delete client;
  570. return -1;
  571. }
  572. // Used for server driver clients
  573. int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
  574. {
  575. jack_log("JackEngine::ClientInternalOpen: name = %s", name);
  576. int refnum = AllocateRefnum();
  577. if (refnum < 0) {
  578. jack_error("No more refnum available");
  579. goto error;
  580. }
  581. if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
  582. jack_error("Cannot allocate synchro");
  583. goto error;
  584. }
  585. if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
  586. // Failure if RT thread is not running (problem with the driver...)
  587. jack_error("Driver is not running");
  588. goto error;
  589. }
  590. fClientTable[refnum] = client;
  591. if (NotifyAddClient(client, name, refnum) < 0) {
  592. jack_error("Cannot notify add client");
  593. goto error;
  594. }
  595. fGraphManager->InitRefNum(refnum);
  596. fEngineControl->ResetRollingUsecs();
  597. *shared_engine = fEngineControl;
  598. *shared_manager = fGraphManager;
  599. *ref = refnum;
  600. return 0;
  601. error:
  602. // Cleanup...
  603. fSynchroTable[refnum].Destroy();
  604. fClientTable[refnum] = 0;
  605. return -1;
  606. }
  607. // Used for external clients
  608. int JackEngine::ClientExternalClose(int refnum)
  609. {
  610. jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
  611. JackClientInterface* client = fClientTable[refnum];
  612. assert(client);
  613. int res = ClientCloseAux(refnum, true);
  614. client->Close();
  615. delete client;
  616. return res;
  617. }
  618. // Used for server internal clients or drivers when the RT thread is stopped
  619. int JackEngine::ClientInternalClose(int refnum, bool wait)
  620. {
  621. jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
  622. return ClientCloseAux(refnum, wait);
  623. }
  624. int JackEngine::ClientCloseAux(int refnum, bool wait)
  625. {
  626. jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
  627. JackClientInterface* client = fClientTable[refnum];
  628. fEngineControl->fTransport.ResetTimebase(refnum);
  629. jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
  630. jack_uuid_copy (&uuid, client->GetClientControl()->fSessionID);
  631. // Unregister all ports ==> notifications are sent
  632. jack_int_t ports[PORT_NUM_FOR_CLIENT];
  633. int i;
  634. fGraphManager->GetInputPorts(refnum, ports);
  635. for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
  636. PortUnRegister(refnum, ports[i]);
  637. }
  638. fGraphManager->GetOutputPorts(refnum, ports);
  639. for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
  640. PortUnRegister(refnum, ports[i]);
  641. }
  642. // Remove the client from the table
  643. ReleaseRefnum(refnum);
  644. // Remove all ports
  645. fGraphManager->RemoveAllPorts(refnum);
  646. // Wait until next cycle to be sure client is not used anymore
  647. if (wait) {
  648. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
  649. jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
  650. }
  651. }
  652. // Notify running clients
  653. NotifyRemoveClient(client->GetClientControl()->fName, refnum);
  654. fMetadata.RemoveProperties(NULL, uuid);
  655. /* have to do the notification ourselves, since the client argument
  656. to fMetadata->RemoveProperties() was NULL
  657. */
  658. PropertyChangeNotify(uuid, NULL, PropertyDeleted);
  659. // Cleanup...
  660. fSynchroTable[refnum].Destroy();
  661. fEngineControl->ResetRollingUsecs();
  662. return 0;
  663. }
  664. int JackEngine::ClientActivate(int refnum, bool is_real_time)
  665. {
  666. JackClientInterface* client = fClientTable[refnum];
  667. jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  668. if (is_real_time) {
  669. fGraphManager->Activate(refnum);
  670. }
  671. // Wait for graph state change to be effective
  672. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  673. jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  674. return -1;
  675. } else {
  676. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  677. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  678. fGraphManager->GetInputPorts(refnum, input_ports);
  679. fGraphManager->GetOutputPorts(refnum, output_ports);
  680. // Notify client
  681. NotifyActivate(refnum);
  682. // Then issue port registration notification
  683. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  684. NotifyPortRegistation(input_ports[i], true);
  685. }
  686. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  687. NotifyPortRegistation(output_ports[i], true);
  688. }
  689. return 0;
  690. }
  691. }
  692. // May be called without client
  693. int JackEngine::ClientDeactivate(int refnum)
  694. {
  695. JackClientInterface* client = fClientTable[refnum];
  696. jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  697. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  698. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  699. fGraphManager->GetInputPorts(refnum, input_ports);
  700. fGraphManager->GetOutputPorts(refnum, output_ports);
  701. // First disconnect all ports
  702. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  703. PortDisconnect(-1, input_ports[i], ALL_PORTS);
  704. }
  705. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  706. PortDisconnect(-1, output_ports[i], ALL_PORTS);
  707. }
  708. // Then issue port registration notification
  709. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  710. NotifyPortRegistation(input_ports[i], false);
  711. }
  712. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  713. NotifyPortRegistation(output_ports[i], false);
  714. }
  715. fGraphManager->Deactivate(refnum);
  716. fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
  717. // Wait for graph state change to be effective
  718. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  719. jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  720. return -1;
  721. } else {
  722. return 0;
  723. }
  724. }
  725. void JackEngine::ClientKill(int refnum)
  726. {
  727. jack_log("JackEngine::ClientKill ref = %ld", refnum);
  728. if (ClientDeactivate(refnum) < 0) {
  729. jack_error("JackEngine::ClientKill ref = %ld cannot be removed from the graph !!", refnum);
  730. }
  731. if (ClientExternalClose(refnum) < 0) {
  732. jack_error("JackEngine::ClientKill ref = %ld cannot be closed", refnum);
  733. }
  734. }
  735. //-----------------
  736. // Port management
  737. //-----------------
  738. int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
  739. {
  740. jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
  741. JackClientInterface* client = fClientTable[refnum];
  742. // Check if port name already exists
  743. if (fGraphManager->GetPort(name) != NO_PORT) {
  744. jack_error("port_name \"%s\" already exists", name);
  745. return -1;
  746. }
  747. // buffer_size is actually ignored...
  748. *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
  749. if (*port_index != NO_PORT) {
  750. if (client->GetClientControl()->fActive) {
  751. NotifyPortRegistation(*port_index, true);
  752. }
  753. return 0;
  754. } else {
  755. return -1;
  756. }
  757. }
  758. int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
  759. {
  760. jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
  761. JackClientInterface* client = fClientTable[refnum];
  762. assert(client);
  763. // Disconnect port ==> notification is sent
  764. PortDisconnect(-1, port_index, ALL_PORTS);
  765. if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
  766. if (client->GetClientControl()->fActive) {
  767. NotifyPortRegistation(port_index, false);
  768. }
  769. return 0;
  770. } else {
  771. return -1;
  772. }
  773. }
  774. // this check is to prevent apps to self connect to other apps
  775. // TODO: make this work with multiple clients per app
  776. int JackEngine::CheckPortsConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  777. {
  778. if (fSelfConnectMode == ' ') return 1;
  779. JackPort* src_port = fGraphManager->GetPort(src);
  780. JackPort* dst_port = fGraphManager->GetPort(dst);
  781. jack_log("JackEngine::CheckPortsConnect(ref = %d, src = %d, dst = %d)", refnum, src_port->GetRefNum(), dst_port->GetRefNum());
  782. //jack_log("%s -> %s", src_port->GetName(), dst_port->GetName());
  783. //jack_log("mode = '%c'", fSelfConnectMode);
  784. int src_self = src_port->GetRefNum() == refnum ? 1 : 0;
  785. int dst_self = dst_port->GetRefNum() == refnum ? 1 : 0;
  786. //jack_log("src_self is %s", src_self ? "true" : "false");
  787. //jack_log("dst_self is %s", dst_self ? "true" : "false");
  788. // 0 means client is connecting other client ports (control app patchbay functionality)
  789. // 1 means client is connecting its own port to port of other client (e.g. self connecting into "system" client)
  790. // 2 means client is connecting its own ports (for app internal functionality)
  791. int sum = src_self + dst_self;
  792. //jack_log("sum = %d", sum);
  793. if (sum == 0) return 1;
  794. char lmode = tolower(fSelfConnectMode);
  795. //jack_log("lmode = '%c'", lmode);
  796. if (sum == 2 && lmode == 'e') return 1;
  797. bool fail = lmode != fSelfConnectMode; // fail modes are upper case
  798. //jack_log("fail = %d", (int)fail);
  799. jack_info(
  800. "%s port self connect request%s (%s -> %s)",
  801. fail ? "rejecting" : "ignoring",
  802. sum == 1 ? " to external port" : "",
  803. src_port->GetName(),
  804. dst_port->GetName());
  805. return fail ? -1 : 0;
  806. }
  807. int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
  808. {
  809. jack_log("JackEngine::PortConnect ref = %d src = %s dst = %s", refnum, src, dst);
  810. jack_port_id_t port_src, port_dst;
  811. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  812. ? -1
  813. : PortConnect(refnum, port_src, port_dst);
  814. }
  815. int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  816. {
  817. jack_log("JackEngine::PortConnect ref = %d src = %d dst = %d", refnum, src, dst);
  818. JackClientInterface* client;
  819. int ref;
  820. if (fGraphManager->CheckPorts(src, dst) < 0) {
  821. return -1;
  822. }
  823. ref = fGraphManager->GetOutputRefNum(src);
  824. assert(ref >= 0);
  825. client = fClientTable[ref];
  826. assert(client);
  827. if (!client->GetClientControl()->fActive) {
  828. jack_error("Cannot connect ports owned by inactive clients:"
  829. " \"%s\" is not active", client->GetClientControl()->fName);
  830. return -1;
  831. }
  832. ref = fGraphManager->GetInputRefNum(dst);
  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. int res = CheckPortsConnect(refnum, src, dst);
  842. if (res != 1) {
  843. return res;
  844. }
  845. res = fGraphManager->Connect(src, dst);
  846. if (res == 0) {
  847. NotifyPortConnect(src, dst, true);
  848. }
  849. return res;
  850. }
  851. int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
  852. {
  853. jack_log("JackEngine::PortDisconnect ref = %d src = %s dst = %s", refnum, src, dst);
  854. jack_port_id_t port_src, port_dst;
  855. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  856. ? -1
  857. : PortDisconnect(refnum, port_src, port_dst);
  858. }
  859. int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  860. {
  861. jack_log("JackEngine::PortDisconnect ref = %d src = %d dst = %d", refnum, src, dst);
  862. if (dst == ALL_PORTS) {
  863. jack_int_t connections[CONNECTION_NUM_FOR_PORT];
  864. fGraphManager->GetConnections(src, connections);
  865. JackPort* port = fGraphManager->GetPort(src);
  866. int res = 0;
  867. if (port->GetFlags() & JackPortIsOutput) {
  868. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  869. if (PortDisconnect(refnum, src, connections[i]) != 0) {
  870. res = -1;
  871. }
  872. }
  873. } else {
  874. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  875. if (PortDisconnect(refnum, connections[i], src) != 0) {
  876. res = -1;
  877. }
  878. }
  879. }
  880. return res;
  881. }
  882. if (fGraphManager->CheckPorts(src, dst) < 0) {
  883. return -1;
  884. }
  885. int res = CheckPortsConnect(refnum, src, dst);
  886. if (res != 1) {
  887. return res;
  888. }
  889. res = fGraphManager->Disconnect(src, dst);
  890. if (res == 0)
  891. NotifyPortConnect(src, dst, false);
  892. return res;
  893. }
  894. int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
  895. {
  896. char old_name[REAL_JACK_PORT_NAME_SIZE+1];
  897. strcpy(old_name, fGraphManager->GetPort(port)->GetName());
  898. fGraphManager->GetPort(port)->SetName(name);
  899. NotifyPortRename(port, old_name);
  900. return 0;
  901. }
  902. //--------------------
  903. // Session management
  904. //--------------------
  905. void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
  906. {
  907. if (fSessionPendingReplies != 0) {
  908. JackSessionNotifyResult res(-1);
  909. res.Write(socket);
  910. jack_log("JackEngine::SessionNotify ... busy");
  911. if (result != NULL) *result = NULL;
  912. return;
  913. }
  914. for (int i = 0; i < CLIENT_NUM; i++) {
  915. JackClientInterface* client = fClientTable[i];
  916. <<<<<<< HEAD
  917. if (client && (client->GetClientControl()->fSessionID < 0)) {
  918. =======
  919. if (client && jack_uuid_empty(client->GetClientControl()->fSessionID)) {
  920. >>>>>>> f7f2244b07ee0a723853e838de85e25471b8903f
  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