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.

1263 lines
39KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include <iostream>
  16. #include <fstream>
  17. #include <set>
  18. #include <assert.h>
  19. #include <ctype.h>
  20. #include "JackSystemDeps.h"
  21. #include "JackLockedEngine.h"
  22. #include "JackExternalClient.h"
  23. #include "JackInternalClient.h"
  24. #include "JackEngineControl.h"
  25. #include "JackClientControl.h"
  26. #include "JackServerGlobals.h"
  27. #include "JackGlobals.h"
  28. #include "JackChannel.h"
  29. #include "JackError.h"
  30. extern const char* JACK_METADATA_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(NULL) // FIXME use control->fServerName?
  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 ressource 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 temporay 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 beeing 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. // Notify running clients
  651. NotifyRemoveClient(client->GetClientControl()->fName, refnum);
  652. fMetadata.RemoveProperties(NULL, uuid);
  653. /* have to do the notification ourselves, since the client argument
  654. to fMetadata->RemoveProperties() was NULL
  655. */
  656. PropertyChangeNotify(uuid, NULL, PropertyDeleted);
  657. // Cleanup...
  658. fSynchroTable[refnum].Destroy();
  659. fEngineControl->ResetRollingUsecs();
  660. return 0;
  661. }
  662. int JackEngine::ClientActivate(int refnum, bool is_real_time)
  663. {
  664. JackClientInterface* client = fClientTable[refnum];
  665. jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  666. if (is_real_time) {
  667. fGraphManager->Activate(refnum);
  668. }
  669. // Wait for graph state change to be effective
  670. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  671. jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  672. return -1;
  673. } else {
  674. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  675. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  676. fGraphManager->GetInputPorts(refnum, input_ports);
  677. fGraphManager->GetOutputPorts(refnum, output_ports);
  678. // Notify client
  679. NotifyActivate(refnum);
  680. // Then issue port registration notification
  681. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  682. NotifyPortRegistation(input_ports[i], true);
  683. }
  684. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  685. NotifyPortRegistation(output_ports[i], true);
  686. }
  687. return 0;
  688. }
  689. }
  690. // May be called without client
  691. int JackEngine::ClientDeactivate(int refnum)
  692. {
  693. JackClientInterface* client = fClientTable[refnum];
  694. jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  695. jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
  696. jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
  697. fGraphManager->GetInputPorts(refnum, input_ports);
  698. fGraphManager->GetOutputPorts(refnum, output_ports);
  699. // First disconnect all ports
  700. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  701. PortDisconnect(-1, input_ports[i], ALL_PORTS);
  702. }
  703. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  704. PortDisconnect(-1, output_ports[i], ALL_PORTS);
  705. }
  706. // Then issue port registration notification
  707. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
  708. NotifyPortRegistation(input_ports[i], false);
  709. }
  710. for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
  711. NotifyPortRegistation(output_ports[i], false);
  712. }
  713. fGraphManager->Deactivate(refnum);
  714. fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
  715. // Wait for graph state change to be effective
  716. if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
  717. jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
  718. return -1;
  719. } else {
  720. return 0;
  721. }
  722. }
  723. void JackEngine::ClientKill(int refnum)
  724. {
  725. jack_log("JackEngine::ClientKill ref = %ld", refnum);
  726. if (ClientDeactivate(refnum) < 0) {
  727. jack_error("JackEngine::ClientKill ref = %ld cannot be removed from the graph !!", refnum);
  728. }
  729. if (ClientExternalClose(refnum) < 0) {
  730. jack_error("JackEngine::ClientKill ref = %ld cannot be closed", refnum);
  731. }
  732. }
  733. //-----------------
  734. // Port management
  735. //-----------------
  736. int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
  737. {
  738. jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
  739. JackClientInterface* client = fClientTable[refnum];
  740. // Check if port name already exists
  741. if (fGraphManager->GetPort(name) != NO_PORT) {
  742. jack_error("port_name \"%s\" already exists", name);
  743. return -1;
  744. }
  745. // buffer_size is actually ignored...
  746. *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
  747. if (*port_index != NO_PORT) {
  748. if (client->GetClientControl()->fActive) {
  749. NotifyPortRegistation(*port_index, true);
  750. }
  751. return 0;
  752. } else {
  753. return -1;
  754. }
  755. }
  756. int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
  757. {
  758. jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
  759. JackClientInterface* client = fClientTable[refnum];
  760. assert(client);
  761. // Disconnect port ==> notification is sent
  762. PortDisconnect(-1, port_index, ALL_PORTS);
  763. if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
  764. if (client->GetClientControl()->fActive) {
  765. NotifyPortRegistation(port_index, false);
  766. }
  767. return 0;
  768. } else {
  769. return -1;
  770. }
  771. }
  772. // this check is to prevent apps to self connect to other apps
  773. // TODO: make this work with multiple clients per app
  774. int JackEngine::CheckPortsConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  775. {
  776. if (fSelfConnectMode == ' ') return 1;
  777. JackPort* src_port = fGraphManager->GetPort(src);
  778. JackPort* dst_port = fGraphManager->GetPort(dst);
  779. jack_log("JackEngine::CheckPortsConnect(ref = %d, src = %d, dst = %d)", refnum, src_port->GetRefNum(), dst_port->GetRefNum());
  780. //jack_log("%s -> %s", src_port->GetName(), dst_port->GetName());
  781. //jack_log("mode = '%c'", fSelfConnectMode);
  782. int src_self = src_port->GetRefNum() == refnum ? 1 : 0;
  783. int dst_self = dst_port->GetRefNum() == refnum ? 1 : 0;
  784. //jack_log("src_self is %s", src_self ? "true" : "false");
  785. //jack_log("dst_self is %s", dst_self ? "true" : "false");
  786. // 0 means client is connecting other client ports (control app patchbay functionality)
  787. // 1 means client is connecting its own port to port of other client (e.g. self connecting into "system" client)
  788. // 2 means client is connecting its own ports (for app internal functionality)
  789. int sum = src_self + dst_self;
  790. //jack_log("sum = %d", sum);
  791. if (sum == 0) return 1;
  792. char lmode = tolower(fSelfConnectMode);
  793. //jack_log("lmode = '%c'", lmode);
  794. if (sum == 2 && lmode == 'e') return 1;
  795. bool fail = lmode != fSelfConnectMode; // fail modes are upper case
  796. //jack_log("fail = %d", (int)fail);
  797. jack_info(
  798. "%s port self connect request%s (%s -> %s)",
  799. fail ? "rejecting" : "ignoring",
  800. sum == 1 ? " to external port" : "",
  801. src_port->GetName(),
  802. dst_port->GetName());
  803. return fail ? -1 : 0;
  804. }
  805. int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
  806. {
  807. jack_log("JackEngine::PortConnect ref = %d src = %s dst = %s", refnum, src, dst);
  808. jack_port_id_t port_src, port_dst;
  809. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  810. ? -1
  811. : PortConnect(refnum, port_src, port_dst);
  812. }
  813. int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  814. {
  815. jack_log("JackEngine::PortConnect ref = %d src = %d dst = %d", refnum, src, dst);
  816. JackClientInterface* client;
  817. int ref;
  818. if (fGraphManager->CheckPorts(src, dst) < 0) {
  819. return -1;
  820. }
  821. ref = fGraphManager->GetOutputRefNum(src);
  822. assert(ref >= 0);
  823. client = fClientTable[ref];
  824. assert(client);
  825. if (!client->GetClientControl()->fActive) {
  826. jack_error("Cannot connect ports owned by inactive clients:"
  827. " \"%s\" is not active", client->GetClientControl()->fName);
  828. return -1;
  829. }
  830. ref = fGraphManager->GetInputRefNum(dst);
  831. assert(ref >= 0);
  832. client = fClientTable[ref];
  833. assert(client);
  834. if (!client->GetClientControl()->fActive) {
  835. jack_error("Cannot connect ports owned by inactive clients:"
  836. " \"%s\" is not active", client->GetClientControl()->fName);
  837. return -1;
  838. }
  839. int res = CheckPortsConnect(refnum, src, dst);
  840. if (res != 1) {
  841. return res;
  842. }
  843. res = fGraphManager->Connect(src, dst);
  844. if (res == 0) {
  845. NotifyPortConnect(src, dst, true);
  846. }
  847. return res;
  848. }
  849. int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
  850. {
  851. jack_log("JackEngine::PortDisconnect ref = %d src = %s dst = %s", refnum, src, dst);
  852. jack_port_id_t port_src, port_dst;
  853. return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
  854. ? -1
  855. : PortDisconnect(refnum, port_src, port_dst);
  856. }
  857. int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
  858. {
  859. jack_log("JackEngine::PortDisconnect ref = %d src = %d dst = %d", refnum, src, dst);
  860. if (dst == ALL_PORTS) {
  861. jack_int_t connections[CONNECTION_NUM_FOR_PORT];
  862. fGraphManager->GetConnections(src, connections);
  863. JackPort* port = fGraphManager->GetPort(src);
  864. int res = 0;
  865. if (port->GetFlags() & JackPortIsOutput) {
  866. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  867. if (PortDisconnect(refnum, src, connections[i]) != 0) {
  868. res = -1;
  869. }
  870. }
  871. } else {
  872. for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
  873. if (PortDisconnect(refnum, connections[i], src) != 0) {
  874. res = -1;
  875. }
  876. }
  877. }
  878. return res;
  879. }
  880. if (fGraphManager->CheckPorts(src, dst) < 0) {
  881. return -1;
  882. }
  883. int res = CheckPortsConnect(refnum, src, dst);
  884. if (res != 1) {
  885. return res;
  886. }
  887. res = fGraphManager->Disconnect(src, dst);
  888. if (res == 0)
  889. NotifyPortConnect(src, dst, false);
  890. return res;
  891. }
  892. int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
  893. {
  894. char old_name[REAL_JACK_PORT_NAME_SIZE+1];
  895. strcpy(old_name, fGraphManager->GetPort(port)->GetName());
  896. fGraphManager->GetPort(port)->SetName(name);
  897. NotifyPortRename(port, old_name);
  898. return 0;
  899. }
  900. int JackEngine::PortSetDeviceMetadata(jack_port_id_t port, const char* pretty_name)
  901. {
  902. static const char* type = "text/plain";
  903. jack_uuid_t uuid = jack_port_uuid_generate(port);
  904. int res = fMetadata.SetProperty(NULL, uuid, JACK_METADATA_HARDWARE, pretty_name, type);
  905. if (res == -1) {
  906. return -1;
  907. }
  908. char *v, *t;
  909. res = fMetadata.GetProperty(uuid, JACK_METADATA_PRETTY_NAME, &v, &t);
  910. if (res == -1) {
  911. res = fMetadata.SetProperty(NULL, uuid, JACK_METADATA_PRETTY_NAME, pretty_name, type);
  912. }
  913. return res;
  914. }
  915. //--------------------
  916. // Session management
  917. //--------------------
  918. void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
  919. {
  920. if (fSessionPendingReplies != 0) {
  921. JackSessionNotifyResult res(-1);
  922. res.Write(socket);
  923. jack_log("JackEngine::SessionNotify ... busy");
  924. if (result != NULL) *result = NULL;
  925. return;
  926. }
  927. for (int i = 0; i < CLIENT_NUM; i++) {
  928. JackClientInterface* client = fClientTable[i];
  929. if (client && jack_uuid_empty(client->GetClientControl()->fSessionID)) {
  930. client->GetClientControl()->fSessionID = jack_client_uuid_generate();
  931. }
  932. }
  933. fSessionResult = new JackSessionNotifyResult();
  934. for (int i = 0; i < CLIENT_NUM; i++) {
  935. JackClientInterface* client = fClientTable[i];
  936. if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
  937. // check if this is a notification to a specific client.
  938. if (target != NULL && strlen(target) != 0) {
  939. if (strcmp(target, client->GetClientControl()->fName)) {
  940. continue;
  941. }
  942. }
  943. char path_buf[JACK_PORT_NAME_SIZE];
  944. if (path[strlen(path) - 1] == DIR_SEPARATOR) {
  945. snprintf(path_buf, sizeof path_buf, "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
  946. } else {
  947. snprintf(path_buf, sizeof path_buf, "%s%c%s%c", path, DIR_SEPARATOR, client->GetClientControl()->fName, DIR_SEPARATOR);
  948. }
  949. int res = JackTools::MkDir(path_buf);
  950. if (res) jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
  951. int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
  952. if (result == kPendingSessionReply) {
  953. fSessionPendingReplies += 1;
  954. } else if (result == kImmediateSessionReply) {
  955. char uuid_buf[JACK_UUID_STRING_SIZE];
  956. jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
  957. fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
  958. client->GetClientControl()->fName,
  959. client->GetClientControl()->fSessionCommand,
  960. client->GetClientControl()->fSessionFlags));
  961. }
  962. }
  963. }
  964. if (result != NULL) *result = fSessionResult;
  965. if (fSessionPendingReplies == 0) {
  966. fSessionResult->Write(socket);
  967. if (result == NULL) delete fSessionResult;
  968. fSessionResult = NULL;
  969. } else {
  970. fSessionTransaction = socket;
  971. }
  972. }
  973. int JackEngine::SessionReply(int refnum)
  974. {
  975. JackClientInterface* client = fClientTable[refnum];
  976. assert(client);
  977. char uuid_buf[JACK_UUID_STRING_SIZE];
  978. jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
  979. fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
  980. client->GetClientControl()->fName,
  981. client->GetClientControl()->fSessionCommand,
  982. client->GetClientControl()->fSessionFlags));
  983. fSessionPendingReplies -= 1;
  984. if (fSessionPendingReplies == 0) {
  985. fSessionResult->Write(fSessionTransaction);
  986. if (fSessionTransaction != NULL) {
  987. delete fSessionResult;
  988. }
  989. fSessionResult = NULL;
  990. }
  991. return 0;
  992. }
  993. int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
  994. {
  995. for (int i = 0; i < CLIENT_NUM; i++) {
  996. JackClientInterface* client = fClientTable[i];
  997. if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
  998. jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_res);
  999. return 0;
  1000. }
  1001. }
  1002. // Did not find name.
  1003. return -1;
  1004. }
  1005. int JackEngine::GetClientNameForUUID(const char *uuid_buf, char *name_res)
  1006. {
  1007. jack_uuid_t uuid;
  1008. if (jack_uuid_parse(uuid_buf, &uuid) != 0)
  1009. return -1;
  1010. for (int i = 0; i < CLIENT_NUM; i++) {
  1011. JackClientInterface* client = fClientTable[i];
  1012. if (!client) {
  1013. continue;
  1014. }
  1015. if (jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
  1016. strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
  1017. return 0;
  1018. }
  1019. }
  1020. // Did not find uuid.
  1021. return -1;
  1022. }
  1023. int JackEngine::ReserveClientName(const char *name, const char *uuidstr)
  1024. {
  1025. jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuidstr);
  1026. if (ClientCheckName(name)) {
  1027. jack_log("name already taken");
  1028. return -1;
  1029. }
  1030. jack_uuid_t uuid;
  1031. if (jack_uuid_parse(uuidstr, &uuid) != 0) {
  1032. jack_error("JackEngine::ReserveClientName invalid uuid %s", uuidstr);
  1033. return -1;
  1034. }
  1035. EnsureUUID(uuid);
  1036. fReservationMap[uuid] = name;
  1037. return 0;
  1038. }
  1039. int JackEngine::ClientHasSessionCallback(const char *name)
  1040. {
  1041. JackClientInterface* client = NULL;
  1042. for (int i = 0; i < CLIENT_NUM; i++) {
  1043. client = fClientTable[i];
  1044. if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
  1045. break;
  1046. }
  1047. }
  1048. if (client) {
  1049. return client->GetClientControl()->fCallback[kSessionCallback];
  1050. } else {
  1051. return -1;
  1052. }
  1053. }
  1054. } // end of namespace