Merge branch 'develop' of github.com:jackaudio/jack2 into develop
[jack2.git] / common / JackEngine.cpp
blobbac1d876a6c1c26244fae3bd5a38da67d66f0972
1 /*
2 Copyright (C) 2004-2008 Grame
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include <iostream>
21 #include <fstream>
22 #include <set>
23 #include <assert.h>
24 #include <ctype.h>
26 #include "JackSystemDeps.h"
27 #include "JackLockedEngine.h"
28 #include "JackExternalClient.h"
29 #include "JackInternalClient.h"
30 #include "JackEngineControl.h"
31 #include "JackClientControl.h"
32 #include "JackServerGlobals.h"
33 #include "JackGlobals.h"
34 #include "JackChannel.h"
35 #include "JackError.h"
37 namespace Jack
40 JackEngine::JackEngine(JackGraphManager* manager,
41 JackSynchro* table,
42 JackEngineControl* control,
43 char self_connect_mode)
44 : JackLockAble(control->fServerName),
45 fSignal(control->fServerName),
46 fMetadata(NULL) // FIXME use control->fServerName?
48 fGraphManager = manager;
49 fSynchroTable = table;
50 fEngineControl = control;
51 fSelfConnectMode = self_connect_mode;
52 for (int i = 0; i < CLIENT_NUM; i++) {
53 fClientTable[i] = NULL;
55 fLastSwitchUsecs = 0;
56 fSessionPendingReplies = 0;
57 fSessionTransaction = NULL;
58 fSessionResult = NULL;
61 JackEngine::~JackEngine()
64 int JackEngine::Open()
66 jack_log("JackEngine::Open");
68 // Open audio thread => request thread communication channel
69 if (fChannel.Open(fEngineControl->fServerName) < 0) {
70 jack_error("Cannot connect to server");
71 return -1;
72 } else {
73 return 0;
77 int JackEngine::Close()
79 jack_log("JackEngine::Close");
80 fChannel.Close();
82 // Close remaining clients (RT is stopped)
83 for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
84 if (JackLoadableInternalClient* loadable_client = dynamic_cast<JackLoadableInternalClient*>(fClientTable[i])) {
85 jack_log("JackEngine::Close loadable client = %s", loadable_client->GetClientControl()->fName);
86 loadable_client->Close();
87 fClientTable[i] = NULL;
88 delete loadable_client;
89 } else if (JackExternalClient* external_client = dynamic_cast<JackExternalClient*>(fClientTable[i])) {
90 jack_log("JackEngine::Close external client = %s", external_client->GetClientControl()->fName);
91 external_client->Close();
92 fClientTable[i] = NULL;
93 delete external_client;
97 return 0;
100 void JackEngine::NotifyQuit()
102 fChannel.NotifyQuit();
106 //-----------------------------
107 // Client ressource management
108 //-----------------------------
110 int JackEngine::AllocateRefnum()
112 for (int i = 0; i < CLIENT_NUM; i++) {
113 if (!fClientTable[i]) {
114 jack_log("JackEngine::AllocateRefNum ref = %ld", i);
115 return i;
118 return -1;
121 void JackEngine::ReleaseRefnum(int refnum)
123 fClientTable[refnum] = NULL;
125 if (fEngineControl->fTemporary) {
126 int i;
127 for (i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
128 if (fClientTable[i]) {
129 break;
132 if (i == CLIENT_NUM) {
133 // Last client and temporay case: quit the server
134 jack_log("JackEngine::ReleaseRefnum server quit");
135 fEngineControl->fTemporary = false;
136 throw JackTemporaryException();
141 //------------------
142 // Graph management
143 //------------------
145 void JackEngine::ProcessNext(jack_time_t cur_cycle_begin)
147 fLastSwitchUsecs = cur_cycle_begin;
148 if (fGraphManager->RunNextGraph()) { // True if the graph actually switched to a new state
149 fChannel.Notify(ALL_CLIENTS, kGraphOrderCallback, 0);
151 fSignal.Signal(); // Signal for threads waiting for next cycle
154 void JackEngine::ProcessCurrent(jack_time_t cur_cycle_begin)
156 if (cur_cycle_begin < fLastSwitchUsecs + 2 * fEngineControl->fPeriodUsecs) { // Signal XRun only for the first failing cycle
157 CheckXRun(cur_cycle_begin);
159 fGraphManager->RunCurrentGraph();
162 bool JackEngine::Process(jack_time_t cur_cycle_begin, jack_time_t prev_cycle_end)
164 bool res = true;
166 // Cycle begin
167 fEngineControl->CycleBegin(fClientTable, fGraphManager, cur_cycle_begin, prev_cycle_end);
169 // Graph
170 if (fGraphManager->IsFinishedGraph()) {
171 ProcessNext(cur_cycle_begin);
172 res = true;
173 } else {
174 jack_log("Process: graph not finished!");
175 if (cur_cycle_begin > fLastSwitchUsecs + fEngineControl->fTimeOutUsecs) {
176 jack_log("Process: switch to next state delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
177 ProcessNext(cur_cycle_begin);
178 res = true;
179 } else {
180 jack_log("Process: waiting to switch delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
181 ProcessCurrent(cur_cycle_begin);
182 res = false;
186 // Cycle end
187 fEngineControl->CycleEnd(fClientTable);
188 return res;
192 Client that finish *after* the callback date are considered late even if their output buffers may have been
193 correctly mixed in the time window: callbackUsecs <==> Read <==> Write.
196 static const char* State2String(jack_client_state_t state)
198 switch (state) {
199 case NotTriggered:
200 return "NotTriggered";
201 case Triggered:
202 return "Triggered";
203 case Running:
204 return "Running";
205 case Finished:
206 return "Finished";
207 default:
208 return "";
212 void JackEngine::CheckXRun(jack_time_t callback_usecs) // REVOIR les conditions de fin
214 for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
215 JackClientInterface* client = fClientTable[i];
216 if (client && client->GetClientControl()->fActive) {
217 JackClientTiming* timing = fGraphManager->GetClientTiming(i);
218 jack_client_state_t status = timing->fStatus;
219 jack_time_t finished_date = timing->fFinishedAt;
221 if (status != NotTriggered && status != Finished) {
222 jack_error("JackEngine::XRun: client = %s was not finished, state = %s", client->GetClientControl()->fName, State2String(status));
223 fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
226 if (status == Finished && (long)(finished_date - callback_usecs) > 0) {
227 jack_error("JackEngine::XRun: client %s finished after current callback", client->GetClientControl()->fName);
228 fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
234 int JackEngine::ComputeTotalLatencies()
236 std::vector<jack_int_t> sorted;
237 std::vector<jack_int_t>::iterator it;
238 std::vector<jack_int_t>::reverse_iterator rit;
240 fGraphManager->TopologicalSort(sorted);
242 /* iterate over all clients in graph order, and emit
243 * capture latency callback.
246 for (it = sorted.begin(); it != sorted.end(); it++) {
247 NotifyClient(*it, kLatencyCallback, true, "", 0, 0);
250 /* now issue playback latency callbacks in reverse graph order.
252 for (rit = sorted.rbegin(); rit != sorted.rend(); rit++) {
253 NotifyClient(*rit, kLatencyCallback, true, "", 1, 0);
256 return 0;
259 //--------------
260 // Metadata API
261 //--------------
263 int JackEngine::PropertyChangeNotify(jack_uuid_t subject, const char* key, jack_property_change_t change)
265 jack_log("JackEngine::PropertyChangeNotify: subject = %x key = %s change = %x", subject, key, change);
267 for (int i = 0; i < CLIENT_NUM; i++) {
268 JackClientInterface* client = fClientTable[i];
269 if (client) {
270 char buf[JACK_UUID_STRING_SIZE];
271 jack_uuid_unparse(subject, buf);
272 client->ClientNotify(i, buf, kPropertyChangeCallback, false, key, change, 0);
276 return 0;
279 //---------------
280 // Notifications
281 //---------------
283 int JackEngine::ClientNotify(JackClientInterface* client, int refnum, const char* name, int notify, int sync, const char* message, int value1, int value2)
285 // Check if notification is needed
286 if (!client->GetClientControl()->fCallback[notify]) {
287 jack_log("JackEngine::ClientNotify: no callback for notification = %ld", notify);
288 return 0;
291 int res1;
293 // External client
294 if (dynamic_cast<JackExternalClient*>(client)) {
295 res1 = client->ClientNotify(refnum, name, notify, sync, message, value1, value2);
296 // Important for internal client : unlock before calling the notification callbacks
297 } else {
298 bool res2 = Unlock();
299 res1 = client->ClientNotify(refnum, name, notify, sync, message, value1, value2);
300 if (res2) {
301 Lock();
305 if (res1 < 0) {
306 jack_error("ClientNotify fails name = %s notification = %ld val1 = %ld val2 = %ld", name, notify, value1, value2);
308 return res1;
311 void JackEngine::NotifyClient(int refnum, int event, int sync, const char* message, int value1, int value2)
313 JackClientInterface* client = fClientTable[refnum];
314 if (client) {
315 ClientNotify(client, refnum, client->GetClientControl()->fName, event, sync, message, value1, value2);
319 void JackEngine::NotifyClients(int event, int sync, const char* message, int value1, int value2)
321 for (int i = 0; i < CLIENT_NUM; i++) {
322 NotifyClient(i, event, sync, message, value1, value2);
326 int JackEngine::NotifyAddClient(JackClientInterface* new_client, const char* new_name, int refnum)
328 jack_log("JackEngine::NotifyAddClient: name = %s", new_name);
330 // Notify existing clients of the new client and new client of existing clients.
331 for (int i = 0; i < CLIENT_NUM; i++) {
332 JackClientInterface* old_client = fClientTable[i];
333 if (old_client && old_client != new_client) {
334 char* old_name = old_client->GetClientControl()->fName;
335 if (ClientNotify(old_client, refnum, new_name, kAddClient, false, "", 0, 0) < 0) {
336 jack_error("NotifyAddClient old_client fails name = %s", old_name);
337 // Not considered as a failure...
339 if (ClientNotify(new_client, i, old_name, kAddClient, true, "", 0, 0) < 0) {
340 jack_error("NotifyAddClient new_client fails name = %s", new_name);
341 return -1;
346 return 0;
349 void JackEngine::NotifyRemoveClient(const char* name, int refnum)
351 // Notify existing clients (including the one beeing suppressed) of the removed client
352 for (int i = 0; i < CLIENT_NUM; i++) {
353 JackClientInterface* client = fClientTable[i];
354 if (client) {
355 ClientNotify(client, refnum, name, kRemoveClient, false, "", 0, 0);
360 // Coming from the driver
361 void JackEngine::NotifyDriverXRun()
363 // Use the audio thread => request thread communication channel
364 fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0);
367 void JackEngine::NotifyClientXRun(int refnum)
369 if (refnum == ALL_CLIENTS) {
370 NotifyClients(kXRunCallback, false, "", 0, 0);
371 } else {
372 NotifyClient(refnum, kXRunCallback, false, "", 0, 0);
376 void JackEngine::NotifyGraphReorder()
378 ComputeTotalLatencies();
379 NotifyClients(kGraphOrderCallback, false, "", 0, 0);
382 void JackEngine::NotifyBufferSize(jack_nframes_t buffer_size)
384 NotifyClients(kBufferSizeCallback, true, "", buffer_size, 0);
387 void JackEngine::NotifySampleRate(jack_nframes_t sample_rate)
389 NotifyClients(kSampleRateCallback, true, "", sample_rate, 0);
392 void JackEngine::NotifyFailure(int code, const char* reason)
394 NotifyClients(kShutDownCallback, false, reason, code, 0);
397 void JackEngine::NotifyFreewheel(bool onoff)
399 if (onoff) {
400 // Save RT state
401 fEngineControl->fSavedRealTime = fEngineControl->fRealTime;
402 fEngineControl->fRealTime = false;
403 } else {
404 // Restore RT state
405 fEngineControl->fRealTime = fEngineControl->fSavedRealTime;
406 fEngineControl->fSavedRealTime = false;
408 NotifyClients((onoff ? kStartFreewheelCallback : kStopFreewheelCallback), true, "", 0, 0);
411 void JackEngine::NotifyPortRegistation(jack_port_id_t port_index, bool onoff)
413 NotifyClients((onoff ? kPortRegistrationOnCallback : kPortRegistrationOffCallback), false, "", port_index, 0);
416 void JackEngine::NotifyPortRename(jack_port_id_t port, const char* old_name)
418 NotifyClients(kPortRenameCallback, false, old_name, port, 0);
421 void JackEngine::NotifyPortConnect(jack_port_id_t src, jack_port_id_t dst, bool onoff)
423 NotifyClients((onoff ? kPortConnectCallback : kPortDisconnectCallback), false, "", src, dst);
426 void JackEngine::NotifyActivate(int refnum)
428 NotifyClient(refnum, kActivateClient, true, "", 0, 0);
431 //----------------------------
432 // Loadable client management
433 //----------------------------
435 int JackEngine::GetInternalClientName(int refnum, char* name_res)
437 JackClientInterface* client = fClientTable[refnum];
438 assert(client);
439 strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
440 return 0;
443 int JackEngine::InternalClientHandle(const char* client_name, int* status, int* int_ref)
445 // Clear status
446 *status = 0;
448 for (int i = 0; i < CLIENT_NUM; i++) {
449 JackClientInterface* client = fClientTable[i];
450 if (client && dynamic_cast<JackLoadableInternalClient*>(client) && (strcmp(client->GetClientControl()->fName, client_name) == 0)) {
451 jack_log("InternalClientHandle found client name = %s ref = %ld", client_name, i);
452 *int_ref = i;
453 return 0;
457 *status |= (JackNoSuchClient | JackFailure);
458 return -1;
461 int JackEngine::InternalClientUnload(int refnum, int* status)
463 JackClientInterface* client = fClientTable[refnum];
464 if (client) {
465 int res = client->Close();
466 delete client;
467 *status = 0;
468 return res;
469 } else {
470 *status = (JackNoSuchClient | JackFailure);
471 return -1;
475 //-------------------
476 // Client management
477 //-------------------
479 int JackEngine::ClientCheck(const char* name, jack_uuid_t uuid, char* name_res, int protocol, int options, int* status)
481 // Clear status
482 *status = 0;
483 strcpy(name_res, name);
485 jack_log("Check protocol client = %ld server = %ld", protocol, JACK_PROTOCOL_VERSION);
487 if (protocol != JACK_PROTOCOL_VERSION) {
488 *status |= (JackFailure | JackVersionError);
489 jack_error("JACK protocol mismatch (%d vs %d)", protocol, JACK_PROTOCOL_VERSION);
490 return -1;
493 std::map<int,std::string>::iterator res = fReservationMap.find(uuid);
495 if (res != fReservationMap.end()) {
496 strncpy(name_res, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
497 } else if (ClientCheckName(name)) {
499 *status |= JackNameNotUnique;
501 if (options & JackUseExactName) {
502 jack_error("cannot create new client; %s already exists", name);
503 *status |= JackFailure;
504 return -1;
507 if (GenerateUniqueName(name_res)) {
508 *status |= JackFailure;
509 return -1;
513 return 0;
516 bool JackEngine::GenerateUniqueName(char* name)
518 int tens, ones;
519 int length = strlen(name);
521 if (length > JACK_CLIENT_NAME_SIZE - 4) {
522 jack_error("%s exists and is too long to make unique", name);
523 return true; /* failure */
526 /* generate a unique name by appending "-01".."-99" */
527 name[length++] = '-';
528 tens = length++;
529 ones = length++;
530 name[tens] = '0';
531 name[ones] = '1';
532 name[length] = '\0';
534 while (ClientCheckName(name)) {
535 if (name[ones] == '9') {
536 if (name[tens] == '9') {
537 jack_error("client %s has 99 extra instances already", name);
538 return true; /* give up */
540 name[tens]++;
541 name[ones] = '0';
542 } else {
543 name[ones]++;
546 return false;
549 bool JackEngine::ClientCheckName(const char* name)
551 for (int i = 0; i < CLIENT_NUM; i++) {
552 JackClientInterface* client = fClientTable[i];
553 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
554 return true;
558 for (std::map<int,std::string>::iterator i = fReservationMap.begin(); i != fReservationMap.end(); i++) {
559 if (i->second == name) {
560 return true;
564 return false;
567 void JackEngine::EnsureUUID(jack_uuid_t uuid)
569 if (jack_uuid_empty(uuid))
570 return;
572 for (int i = 0; i < CLIENT_NUM; i++) {
573 JackClientInterface* client = fClientTable[i];
574 if (client && jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
575 // FIXME? this code does nothing, but jack1 has it like this too..
576 jack_uuid_clear (&uuid);
577 // client->GetClientControl()->fSessionID = jack_client_uuid_generate();
582 int JackEngine::GetClientPID(const char* name)
584 for (int i = 0; i < CLIENT_NUM; i++) {
585 JackClientInterface* client = fClientTable[i];
586 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
587 return client->GetClientControl()->fPID;
591 return 0;
594 int JackEngine::GetClientRefNum(const char* name)
596 for (int i = 0; i < CLIENT_NUM; i++) {
597 JackClientInterface* client = fClientTable[i];
598 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
599 return client->GetClientControl()->fRefNum;
603 return -1;
606 // Used for external clients
607 int JackEngine::ClientExternalOpen(const char* name, int pid, jack_uuid_t uuid, int* ref, int* shared_engine, int* shared_client, int* shared_graph_manager)
609 char real_name[JACK_CLIENT_NAME_SIZE + 1];
611 <<<<<<< HEAD
612 if (uuid < 0) {
613 =======
614 if (jack_uuid_empty(uuid)) {
615 >>>>>>> f7f2244b07ee0a723853e838de85e25471b8903f
616 uuid = jack_client_uuid_generate();
617 strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
618 } else {
619 std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
620 if (res != fReservationMap.end()) {
621 strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
622 fReservationMap.erase(uuid);
623 } else {
624 strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
626 EnsureUUID(uuid);
629 jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s", uuid, real_name);
631 int refnum = AllocateRefnum();
632 if (refnum < 0) {
633 jack_error("No more refnum available");
634 return -1;
637 JackExternalClient* client = new JackExternalClient();
639 if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
640 jack_error("Cannot allocate synchro");
641 goto error;
644 if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
645 jack_error("Cannot open client");
646 goto error;
649 if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
650 // Failure if RT thread is not running (problem with the driver...)
651 jack_error("Driver is not running");
652 goto error;
655 fClientTable[refnum] = client;
657 if (NotifyAddClient(client, real_name, refnum) < 0) {
658 jack_error("Cannot notify add client");
659 goto error;
662 fGraphManager->InitRefNum(refnum);
663 fEngineControl->ResetRollingUsecs();
664 *shared_engine = fEngineControl->GetShmIndex();
665 *shared_graph_manager = fGraphManager->GetShmIndex();
666 *ref = refnum;
667 return 0;
669 error:
670 // Cleanup...
671 fSynchroTable[refnum].Destroy();
672 fClientTable[refnum] = 0;
673 client->Close();
674 delete client;
675 return -1;
678 // Used for server driver clients
679 int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
681 jack_log("JackEngine::ClientInternalOpen: name = %s", name);
683 int refnum = AllocateRefnum();
684 if (refnum < 0) {
685 jack_error("No more refnum available");
686 goto error;
689 if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
690 jack_error("Cannot allocate synchro");
691 goto error;
694 if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
695 // Failure if RT thread is not running (problem with the driver...)
696 jack_error("Driver is not running");
697 goto error;
700 fClientTable[refnum] = client;
702 if (NotifyAddClient(client, name, refnum) < 0) {
703 jack_error("Cannot notify add client");
704 goto error;
707 fGraphManager->InitRefNum(refnum);
708 fEngineControl->ResetRollingUsecs();
709 *shared_engine = fEngineControl;
710 *shared_manager = fGraphManager;
711 *ref = refnum;
712 return 0;
714 error:
715 // Cleanup...
716 fSynchroTable[refnum].Destroy();
717 fClientTable[refnum] = 0;
718 return -1;
721 // Used for external clients
722 int JackEngine::ClientExternalClose(int refnum)
724 jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
725 JackClientInterface* client = fClientTable[refnum];
726 assert(client);
727 int res = ClientCloseAux(refnum, true);
728 client->Close();
729 delete client;
730 return res;
733 // Used for server internal clients or drivers when the RT thread is stopped
734 int JackEngine::ClientInternalClose(int refnum, bool wait)
736 jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
737 return ClientCloseAux(refnum, wait);
740 int JackEngine::ClientCloseAux(int refnum, bool wait)
742 jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
744 JackClientInterface* client = fClientTable[refnum];
745 fEngineControl->fTransport.ResetTimebase(refnum);
747 jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
748 jack_uuid_copy (&uuid, client->GetClientControl()->fSessionID);
750 // Unregister all ports ==> notifications are sent
751 jack_int_t ports[PORT_NUM_FOR_CLIENT];
752 int i;
754 fGraphManager->GetInputPorts(refnum, ports);
755 for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
756 PortUnRegister(refnum, ports[i]);
759 fGraphManager->GetOutputPorts(refnum, ports);
760 for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
761 PortUnRegister(refnum, ports[i]);
764 // Remove the client from the table
765 ReleaseRefnum(refnum);
767 // Remove all ports
768 fGraphManager->RemoveAllPorts(refnum);
770 // Wait until next cycle to be sure client is not used anymore
771 if (wait) {
772 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
773 jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
777 // Notify running clients
778 NotifyRemoveClient(client->GetClientControl()->fName, refnum);
780 fMetadata.RemoveProperties(NULL, uuid);
781 /* have to do the notification ourselves, since the client argument
782 to fMetadata->RemoveProperties() was NULL
784 PropertyChangeNotify(uuid, NULL, PropertyDeleted);
786 // Cleanup...
787 fSynchroTable[refnum].Destroy();
788 fEngineControl->ResetRollingUsecs();
789 return 0;
792 int JackEngine::ClientActivate(int refnum, bool is_real_time)
794 JackClientInterface* client = fClientTable[refnum];
795 jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
797 if (is_real_time) {
798 fGraphManager->Activate(refnum);
801 // Wait for graph state change to be effective
802 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
803 jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
804 return -1;
805 } else {
806 jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
807 jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
808 fGraphManager->GetInputPorts(refnum, input_ports);
809 fGraphManager->GetOutputPorts(refnum, output_ports);
811 // Notify client
812 NotifyActivate(refnum);
814 // Then issue port registration notification
815 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
816 NotifyPortRegistation(input_ports[i], true);
818 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
819 NotifyPortRegistation(output_ports[i], true);
822 return 0;
826 // May be called without client
827 int JackEngine::ClientDeactivate(int refnum)
829 JackClientInterface* client = fClientTable[refnum];
830 jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
832 jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
833 jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
834 fGraphManager->GetInputPorts(refnum, input_ports);
835 fGraphManager->GetOutputPorts(refnum, output_ports);
837 // First disconnect all ports
838 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
839 PortDisconnect(-1, input_ports[i], ALL_PORTS);
841 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
842 PortDisconnect(-1, output_ports[i], ALL_PORTS);
845 // Then issue port registration notification
846 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
847 NotifyPortRegistation(input_ports[i], false);
849 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
850 NotifyPortRegistation(output_ports[i], false);
853 fGraphManager->Deactivate(refnum);
854 fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
856 // Wait for graph state change to be effective
857 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
858 jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
859 return -1;
860 } else {
861 return 0;
865 void JackEngine::ClientKill(int refnum)
867 jack_log("JackEngine::ClientKill ref = %ld", refnum);
868 if (ClientDeactivate(refnum) < 0) {
869 jack_error("JackEngine::ClientKill ref = %ld cannot be removed from the graph !!", refnum);
871 if (ClientExternalClose(refnum) < 0) {
872 jack_error("JackEngine::ClientKill ref = %ld cannot be closed", refnum);
876 //-----------------
877 // Port management
878 //-----------------
880 int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
882 jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
883 JackClientInterface* client = fClientTable[refnum];
885 // Check if port name already exists
886 if (fGraphManager->GetPort(name) != NO_PORT) {
887 jack_error("port_name \"%s\" already exists", name);
888 return -1;
891 // buffer_size is actually ignored...
892 *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
893 if (*port_index != NO_PORT) {
894 if (client->GetClientControl()->fActive) {
895 NotifyPortRegistation(*port_index, true);
897 return 0;
898 } else {
899 return -1;
903 int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
905 jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
906 JackClientInterface* client = fClientTable[refnum];
907 assert(client);
909 // Disconnect port ==> notification is sent
910 PortDisconnect(-1, port_index, ALL_PORTS);
912 if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
913 if (client->GetClientControl()->fActive) {
914 NotifyPortRegistation(port_index, false);
916 return 0;
917 } else {
918 return -1;
922 // this check is to prevent apps to self connect to other apps
923 // TODO: make this work with multiple clients per app
924 int JackEngine::CheckPortsConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
926 if (fSelfConnectMode == ' ') return 1;
928 JackPort* src_port = fGraphManager->GetPort(src);
929 JackPort* dst_port = fGraphManager->GetPort(dst);
931 jack_log("JackEngine::CheckPortsConnect(ref = %d, src = %d, dst = %d)", refnum, src_port->GetRefNum(), dst_port->GetRefNum());
933 //jack_log("%s -> %s", src_port->GetName(), dst_port->GetName());
934 //jack_log("mode = '%c'", fSelfConnectMode);
936 int src_self = src_port->GetRefNum() == refnum ? 1 : 0;
937 int dst_self = dst_port->GetRefNum() == refnum ? 1 : 0;
939 //jack_log("src_self is %s", src_self ? "true" : "false");
940 //jack_log("dst_self is %s", dst_self ? "true" : "false");
942 // 0 means client is connecting other client ports (control app patchbay functionality)
943 // 1 means client is connecting its own port to port of other client (e.g. self connecting into "system" client)
944 // 2 means client is connecting its own ports (for app internal functionality)
945 int sum = src_self + dst_self;
946 //jack_log("sum = %d", sum);
947 if (sum == 0) return 1;
948 char lmode = tolower(fSelfConnectMode);
949 //jack_log("lmode = '%c'", lmode);
950 if (sum == 2 && lmode == 'e') return 1;
951 bool fail = lmode != fSelfConnectMode; // fail modes are upper case
952 //jack_log("fail = %d", (int)fail);
954 jack_info(
955 "%s port self connect request%s (%s -> %s)",
956 fail ? "rejecting" : "ignoring",
957 sum == 1 ? " to external port" : "",
958 src_port->GetName(),
959 dst_port->GetName());
961 return fail ? -1 : 0;
964 int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
966 jack_log("JackEngine::PortConnect ref = %d src = %s dst = %s", refnum, src, dst);
967 jack_port_id_t port_src, port_dst;
969 return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
970 ? -1
971 : PortConnect(refnum, port_src, port_dst);
974 int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
976 jack_log("JackEngine::PortConnect ref = %d src = %d dst = %d", refnum, src, dst);
977 JackClientInterface* client;
978 int ref;
980 if (fGraphManager->CheckPorts(src, dst) < 0) {
981 return -1;
984 ref = fGraphManager->GetOutputRefNum(src);
985 assert(ref >= 0);
986 client = fClientTable[ref];
987 assert(client);
988 if (!client->GetClientControl()->fActive) {
989 jack_error("Cannot connect ports owned by inactive clients:"
990 " \"%s\" is not active", client->GetClientControl()->fName);
991 return -1;
994 ref = fGraphManager->GetInputRefNum(dst);
995 assert(ref >= 0);
996 client = fClientTable[ref];
997 assert(client);
998 if (!client->GetClientControl()->fActive) {
999 jack_error("Cannot connect ports owned by inactive clients:"
1000 " \"%s\" is not active", client->GetClientControl()->fName);
1001 return -1;
1004 int res = CheckPortsConnect(refnum, src, dst);
1005 if (res != 1) {
1006 return res;
1009 res = fGraphManager->Connect(src, dst);
1010 if (res == 0) {
1011 NotifyPortConnect(src, dst, true);
1013 return res;
1016 int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
1018 jack_log("JackEngine::PortDisconnect ref = %d src = %s dst = %s", refnum, src, dst);
1019 jack_port_id_t port_src, port_dst;
1021 return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
1022 ? -1
1023 : PortDisconnect(refnum, port_src, port_dst);
1026 int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
1028 jack_log("JackEngine::PortDisconnect ref = %d src = %d dst = %d", refnum, src, dst);
1030 if (dst == ALL_PORTS) {
1032 jack_int_t connections[CONNECTION_NUM_FOR_PORT];
1033 fGraphManager->GetConnections(src, connections);
1035 JackPort* port = fGraphManager->GetPort(src);
1036 int res = 0;
1037 if (port->GetFlags() & JackPortIsOutput) {
1038 for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
1039 if (PortDisconnect(refnum, src, connections[i]) != 0) {
1040 res = -1;
1043 } else {
1044 for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
1045 if (PortDisconnect(refnum, connections[i], src) != 0) {
1046 res = -1;
1051 return res;
1054 if (fGraphManager->CheckPorts(src, dst) < 0) {
1055 return -1;
1058 int res = CheckPortsConnect(refnum, src, dst);
1059 if (res != 1) {
1060 return res;
1063 res = fGraphManager->Disconnect(src, dst);
1064 if (res == 0)
1065 NotifyPortConnect(src, dst, false);
1066 return res;
1069 int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
1071 char old_name[REAL_JACK_PORT_NAME_SIZE+1];
1072 strcpy(old_name, fGraphManager->GetPort(port)->GetName());
1073 fGraphManager->GetPort(port)->SetName(name);
1074 NotifyPortRename(port, old_name);
1075 return 0;
1078 //--------------------
1079 // Session management
1080 //--------------------
1082 void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
1084 if (fSessionPendingReplies != 0) {
1085 JackSessionNotifyResult res(-1);
1086 res.Write(socket);
1087 jack_log("JackEngine::SessionNotify ... busy");
1088 if (result != NULL) *result = NULL;
1089 return;
1092 for (int i = 0; i < CLIENT_NUM; i++) {
1093 JackClientInterface* client = fClientTable[i];
1094 <<<<<<< HEAD
1095 if (client && (client->GetClientControl()->fSessionID < 0)) {
1096 =======
1097 if (client && jack_uuid_empty(client->GetClientControl()->fSessionID)) {
1098 >>>>>>> f7f2244b07ee0a723853e838de85e25471b8903f
1099 client->GetClientControl()->fSessionID = jack_client_uuid_generate();
1102 fSessionResult = new JackSessionNotifyResult();
1104 for (int i = 0; i < CLIENT_NUM; i++) {
1105 JackClientInterface* client = fClientTable[i];
1106 if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
1108 // check if this is a notification to a specific client.
1109 if (target != NULL && strlen(target) != 0) {
1110 if (strcmp(target, client->GetClientControl()->fName)) {
1111 continue;
1115 char path_buf[JACK_PORT_NAME_SIZE];
1116 if (path[strlen(path) - 1] == DIR_SEPARATOR) {
1117 snprintf(path_buf, sizeof path_buf, "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
1118 } else {
1119 snprintf(path_buf, sizeof path_buf, "%s%c%s%c", path, DIR_SEPARATOR, client->GetClientControl()->fName, DIR_SEPARATOR);
1122 int res = JackTools::MkDir(path_buf);
1123 if (res) jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
1125 int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
1127 if (result == kPendingSessionReply) {
1128 fSessionPendingReplies += 1;
1129 } else if (result == kImmediateSessionReply) {
1130 char uuid_buf[JACK_UUID_STRING_SIZE];
1131 jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
1132 fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1133 client->GetClientControl()->fName,
1134 client->GetClientControl()->fSessionCommand,
1135 client->GetClientControl()->fSessionFlags));
1140 if (result != NULL) *result = fSessionResult;
1142 if (fSessionPendingReplies == 0) {
1143 fSessionResult->Write(socket);
1144 if (result == NULL) delete fSessionResult;
1145 fSessionResult = NULL;
1146 } else {
1147 fSessionTransaction = socket;
1151 int JackEngine::SessionReply(int refnum)
1153 JackClientInterface* client = fClientTable[refnum];
1154 assert(client);
1155 char uuid_buf[JACK_UUID_STRING_SIZE];
1156 jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
1157 fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1158 client->GetClientControl()->fName,
1159 client->GetClientControl()->fSessionCommand,
1160 client->GetClientControl()->fSessionFlags));
1161 fSessionPendingReplies -= 1;
1163 if (fSessionPendingReplies == 0) {
1164 fSessionResult->Write(fSessionTransaction);
1165 if (fSessionTransaction != NULL) {
1166 delete fSessionResult;
1168 fSessionResult = NULL;
1171 return 0;
1174 int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
1176 for (int i = 0; i < CLIENT_NUM; i++) {
1177 JackClientInterface* client = fClientTable[i];
1179 if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
1180 jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_res);
1181 return 0;
1184 // Did not find name.
1185 return -1;
1188 int JackEngine::GetClientNameForUUID(const char *uuid_buf, char *name_res)
1190 jack_uuid_t uuid;
1191 if (jack_uuid_parse(uuid_buf, &uuid) != 0)
1192 return -1;
1194 for (int i = 0; i < CLIENT_NUM; i++) {
1195 JackClientInterface* client = fClientTable[i];
1197 if (!client) {
1198 continue;
1201 if (jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
1202 strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
1203 return 0;
1206 // Did not find uuid.
1207 return -1;
1210 int JackEngine::ReserveClientName(const char *name, const char *uuidstr)
1212 jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuidstr);
1214 if (ClientCheckName(name)) {
1215 jack_log("name already taken");
1216 return -1;
1219 jack_uuid_t uuid;
1220 if (jack_uuid_parse(uuidstr, &uuid) != 0) {
1221 jack_error("JackEngine::ReserveClientName invalid uuid %s", uuidstr);
1222 return -1;
1225 EnsureUUID(uuid);
1226 fReservationMap[uuid] = name;
1227 return 0;
1230 int JackEngine::ClientHasSessionCallback(const char *name)
1232 JackClientInterface* client = NULL;
1233 for (int i = 0; i < CLIENT_NUM; i++) {
1234 client = fClientTable[i];
1235 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
1236 break;
1240 if (client) {
1241 return client->GetClientControl()->fCallback[kSessionCallback];
1242 } else {
1243 return -1;
1247 } // end of namespace