Fix yet another merge conflict
[jack2.git] / common / JackEngine.cpp
blobbe87c977fb3e80ee157ebf126e34e2e0285caf59
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 if (jack_uuid_empty(uuid)) {
612 uuid = jack_client_uuid_generate();
613 strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
614 } else {
615 std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
616 if (res != fReservationMap.end()) {
617 strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
618 fReservationMap.erase(uuid);
619 } else {
620 strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
622 EnsureUUID(uuid);
625 jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s", uuid, real_name);
627 int refnum = AllocateRefnum();
628 if (refnum < 0) {
629 jack_error("No more refnum available");
630 return -1;
633 JackExternalClient* client = new JackExternalClient();
635 if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
636 jack_error("Cannot allocate synchro");
637 goto error;
640 if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
641 jack_error("Cannot open client");
642 goto error;
645 if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
646 // Failure if RT thread is not running (problem with the driver...)
647 jack_error("Driver is not running");
648 goto error;
651 fClientTable[refnum] = client;
653 if (NotifyAddClient(client, real_name, refnum) < 0) {
654 jack_error("Cannot notify add client");
655 goto error;
658 fGraphManager->InitRefNum(refnum);
659 fEngineControl->ResetRollingUsecs();
660 *shared_engine = fEngineControl->GetShmIndex();
661 *shared_graph_manager = fGraphManager->GetShmIndex();
662 *ref = refnum;
663 return 0;
665 error:
666 // Cleanup...
667 fSynchroTable[refnum].Destroy();
668 fClientTable[refnum] = 0;
669 client->Close();
670 delete client;
671 return -1;
674 // Used for server driver clients
675 int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
677 jack_log("JackEngine::ClientInternalOpen: name = %s", name);
679 int refnum = AllocateRefnum();
680 if (refnum < 0) {
681 jack_error("No more refnum available");
682 goto error;
685 if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
686 jack_error("Cannot allocate synchro");
687 goto error;
690 if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
691 // Failure if RT thread is not running (problem with the driver...)
692 jack_error("Driver is not running");
693 goto error;
696 fClientTable[refnum] = client;
698 if (NotifyAddClient(client, name, refnum) < 0) {
699 jack_error("Cannot notify add client");
700 goto error;
703 fGraphManager->InitRefNum(refnum);
704 fEngineControl->ResetRollingUsecs();
705 *shared_engine = fEngineControl;
706 *shared_manager = fGraphManager;
707 *ref = refnum;
708 return 0;
710 error:
711 // Cleanup...
712 fSynchroTable[refnum].Destroy();
713 fClientTable[refnum] = 0;
714 return -1;
717 // Used for external clients
718 int JackEngine::ClientExternalClose(int refnum)
720 jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
721 JackClientInterface* client = fClientTable[refnum];
722 assert(client);
723 int res = ClientCloseAux(refnum, true);
724 client->Close();
725 delete client;
726 return res;
729 // Used for server internal clients or drivers when the RT thread is stopped
730 int JackEngine::ClientInternalClose(int refnum, bool wait)
732 jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
733 return ClientCloseAux(refnum, wait);
736 int JackEngine::ClientCloseAux(int refnum, bool wait)
738 jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
740 JackClientInterface* client = fClientTable[refnum];
741 fEngineControl->fTransport.ResetTimebase(refnum);
743 jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
744 jack_uuid_copy (&uuid, client->GetClientControl()->fSessionID);
746 // Unregister all ports ==> notifications are sent
747 jack_int_t ports[PORT_NUM_FOR_CLIENT];
748 int i;
750 fGraphManager->GetInputPorts(refnum, ports);
751 for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
752 PortUnRegister(refnum, ports[i]);
755 fGraphManager->GetOutputPorts(refnum, ports);
756 for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
757 PortUnRegister(refnum, ports[i]);
760 // Remove the client from the table
761 ReleaseRefnum(refnum);
763 // Remove all ports
764 fGraphManager->RemoveAllPorts(refnum);
766 // Wait until next cycle to be sure client is not used anymore
767 if (wait) {
768 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
769 jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
773 // Notify running clients
774 NotifyRemoveClient(client->GetClientControl()->fName, refnum);
776 fMetadata.RemoveProperties(NULL, uuid);
777 /* have to do the notification ourselves, since the client argument
778 to fMetadata->RemoveProperties() was NULL
780 PropertyChangeNotify(uuid, NULL, PropertyDeleted);
782 // Cleanup...
783 fSynchroTable[refnum].Destroy();
784 fEngineControl->ResetRollingUsecs();
785 return 0;
788 int JackEngine::ClientActivate(int refnum, bool is_real_time)
790 JackClientInterface* client = fClientTable[refnum];
791 jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
793 if (is_real_time) {
794 fGraphManager->Activate(refnum);
797 // Wait for graph state change to be effective
798 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
799 jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
800 return -1;
801 } else {
802 jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
803 jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
804 fGraphManager->GetInputPorts(refnum, input_ports);
805 fGraphManager->GetOutputPorts(refnum, output_ports);
807 // Notify client
808 NotifyActivate(refnum);
810 // Then issue port registration notification
811 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
812 NotifyPortRegistation(input_ports[i], true);
814 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
815 NotifyPortRegistation(output_ports[i], true);
818 return 0;
822 // May be called without client
823 int JackEngine::ClientDeactivate(int refnum)
825 JackClientInterface* client = fClientTable[refnum];
826 jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
828 jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
829 jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
830 fGraphManager->GetInputPorts(refnum, input_ports);
831 fGraphManager->GetOutputPorts(refnum, output_ports);
833 // First disconnect all ports
834 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
835 PortDisconnect(-1, input_ports[i], ALL_PORTS);
837 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
838 PortDisconnect(-1, output_ports[i], ALL_PORTS);
841 // Then issue port registration notification
842 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
843 NotifyPortRegistation(input_ports[i], false);
845 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
846 NotifyPortRegistation(output_ports[i], false);
849 fGraphManager->Deactivate(refnum);
850 fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
852 // Wait for graph state change to be effective
853 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
854 jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
855 return -1;
856 } else {
857 return 0;
861 void JackEngine::ClientKill(int refnum)
863 jack_log("JackEngine::ClientKill ref = %ld", refnum);
864 if (ClientDeactivate(refnum) < 0) {
865 jack_error("JackEngine::ClientKill ref = %ld cannot be removed from the graph !!", refnum);
867 if (ClientExternalClose(refnum) < 0) {
868 jack_error("JackEngine::ClientKill ref = %ld cannot be closed", refnum);
872 //-----------------
873 // Port management
874 //-----------------
876 int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
878 jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
879 JackClientInterface* client = fClientTable[refnum];
881 // Check if port name already exists
882 if (fGraphManager->GetPort(name) != NO_PORT) {
883 jack_error("port_name \"%s\" already exists", name);
884 return -1;
887 // buffer_size is actually ignored...
888 *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
889 if (*port_index != NO_PORT) {
890 if (client->GetClientControl()->fActive) {
891 NotifyPortRegistation(*port_index, true);
893 return 0;
894 } else {
895 return -1;
899 int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
901 jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
902 JackClientInterface* client = fClientTable[refnum];
903 assert(client);
905 // Disconnect port ==> notification is sent
906 PortDisconnect(-1, port_index, ALL_PORTS);
908 if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
909 if (client->GetClientControl()->fActive) {
910 NotifyPortRegistation(port_index, false);
912 return 0;
913 } else {
914 return -1;
918 // this check is to prevent apps to self connect to other apps
919 // TODO: make this work with multiple clients per app
920 int JackEngine::CheckPortsConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
922 if (fSelfConnectMode == ' ') return 1;
924 JackPort* src_port = fGraphManager->GetPort(src);
925 JackPort* dst_port = fGraphManager->GetPort(dst);
927 jack_log("JackEngine::CheckPortsConnect(ref = %d, src = %d, dst = %d)", refnum, src_port->GetRefNum(), dst_port->GetRefNum());
929 //jack_log("%s -> %s", src_port->GetName(), dst_port->GetName());
930 //jack_log("mode = '%c'", fSelfConnectMode);
932 int src_self = src_port->GetRefNum() == refnum ? 1 : 0;
933 int dst_self = dst_port->GetRefNum() == refnum ? 1 : 0;
935 //jack_log("src_self is %s", src_self ? "true" : "false");
936 //jack_log("dst_self is %s", dst_self ? "true" : "false");
938 // 0 means client is connecting other client ports (control app patchbay functionality)
939 // 1 means client is connecting its own port to port of other client (e.g. self connecting into "system" client)
940 // 2 means client is connecting its own ports (for app internal functionality)
941 int sum = src_self + dst_self;
942 //jack_log("sum = %d", sum);
943 if (sum == 0) return 1;
944 char lmode = tolower(fSelfConnectMode);
945 //jack_log("lmode = '%c'", lmode);
946 if (sum == 2 && lmode == 'e') return 1;
947 bool fail = lmode != fSelfConnectMode; // fail modes are upper case
948 //jack_log("fail = %d", (int)fail);
950 jack_info(
951 "%s port self connect request%s (%s -> %s)",
952 fail ? "rejecting" : "ignoring",
953 sum == 1 ? " to external port" : "",
954 src_port->GetName(),
955 dst_port->GetName());
957 return fail ? -1 : 0;
960 int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
962 jack_log("JackEngine::PortConnect ref = %d src = %s dst = %s", refnum, src, dst);
963 jack_port_id_t port_src, port_dst;
965 return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
966 ? -1
967 : PortConnect(refnum, port_src, port_dst);
970 int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
972 jack_log("JackEngine::PortConnect ref = %d src = %d dst = %d", refnum, src, dst);
973 JackClientInterface* client;
974 int ref;
976 if (fGraphManager->CheckPorts(src, dst) < 0) {
977 return -1;
980 ref = fGraphManager->GetOutputRefNum(src);
981 assert(ref >= 0);
982 client = fClientTable[ref];
983 assert(client);
984 if (!client->GetClientControl()->fActive) {
985 jack_error("Cannot connect ports owned by inactive clients:"
986 " \"%s\" is not active", client->GetClientControl()->fName);
987 return -1;
990 ref = fGraphManager->GetInputRefNum(dst);
991 assert(ref >= 0);
992 client = fClientTable[ref];
993 assert(client);
994 if (!client->GetClientControl()->fActive) {
995 jack_error("Cannot connect ports owned by inactive clients:"
996 " \"%s\" is not active", client->GetClientControl()->fName);
997 return -1;
1000 int res = CheckPortsConnect(refnum, src, dst);
1001 if (res != 1) {
1002 return res;
1005 res = fGraphManager->Connect(src, dst);
1006 if (res == 0) {
1007 NotifyPortConnect(src, dst, true);
1009 return res;
1012 int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
1014 jack_log("JackEngine::PortDisconnect ref = %d src = %s dst = %s", refnum, src, dst);
1015 jack_port_id_t port_src, port_dst;
1017 return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
1018 ? -1
1019 : PortDisconnect(refnum, port_src, port_dst);
1022 int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
1024 jack_log("JackEngine::PortDisconnect ref = %d src = %d dst = %d", refnum, src, dst);
1026 if (dst == ALL_PORTS) {
1028 jack_int_t connections[CONNECTION_NUM_FOR_PORT];
1029 fGraphManager->GetConnections(src, connections);
1031 JackPort* port = fGraphManager->GetPort(src);
1032 int res = 0;
1033 if (port->GetFlags() & JackPortIsOutput) {
1034 for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
1035 if (PortDisconnect(refnum, src, connections[i]) != 0) {
1036 res = -1;
1039 } else {
1040 for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
1041 if (PortDisconnect(refnum, connections[i], src) != 0) {
1042 res = -1;
1047 return res;
1050 if (fGraphManager->CheckPorts(src, dst) < 0) {
1051 return -1;
1054 int res = CheckPortsConnect(refnum, src, dst);
1055 if (res != 1) {
1056 return res;
1059 res = fGraphManager->Disconnect(src, dst);
1060 if (res == 0)
1061 NotifyPortConnect(src, dst, false);
1062 return res;
1065 int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
1067 char old_name[REAL_JACK_PORT_NAME_SIZE+1];
1068 strcpy(old_name, fGraphManager->GetPort(port)->GetName());
1069 fGraphManager->GetPort(port)->SetName(name);
1070 NotifyPortRename(port, old_name);
1071 return 0;
1074 //--------------------
1075 // Session management
1076 //--------------------
1078 void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
1080 if (fSessionPendingReplies != 0) {
1081 JackSessionNotifyResult res(-1);
1082 res.Write(socket);
1083 jack_log("JackEngine::SessionNotify ... busy");
1084 if (result != NULL) *result = NULL;
1085 return;
1088 for (int i = 0; i < CLIENT_NUM; i++) {
1089 JackClientInterface* client = fClientTable[i];
1090 if (client && jack_uuid_empty(client->GetClientControl()->fSessionID)) {
1091 client->GetClientControl()->fSessionID = jack_client_uuid_generate();
1094 fSessionResult = new JackSessionNotifyResult();
1096 for (int i = 0; i < CLIENT_NUM; i++) {
1097 JackClientInterface* client = fClientTable[i];
1098 if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
1100 // check if this is a notification to a specific client.
1101 if (target != NULL && strlen(target) != 0) {
1102 if (strcmp(target, client->GetClientControl()->fName)) {
1103 continue;
1107 char path_buf[JACK_PORT_NAME_SIZE];
1108 if (path[strlen(path) - 1] == DIR_SEPARATOR) {
1109 snprintf(path_buf, sizeof path_buf, "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
1110 } else {
1111 snprintf(path_buf, sizeof path_buf, "%s%c%s%c", path, DIR_SEPARATOR, client->GetClientControl()->fName, DIR_SEPARATOR);
1114 int res = JackTools::MkDir(path_buf);
1115 if (res) jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
1117 int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
1119 if (result == kPendingSessionReply) {
1120 fSessionPendingReplies += 1;
1121 } else if (result == kImmediateSessionReply) {
1122 char uuid_buf[JACK_UUID_STRING_SIZE];
1123 jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
1124 fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1125 client->GetClientControl()->fName,
1126 client->GetClientControl()->fSessionCommand,
1127 client->GetClientControl()->fSessionFlags));
1132 if (result != NULL) *result = fSessionResult;
1134 if (fSessionPendingReplies == 0) {
1135 fSessionResult->Write(socket);
1136 if (result == NULL) delete fSessionResult;
1137 fSessionResult = NULL;
1138 } else {
1139 fSessionTransaction = socket;
1143 int JackEngine::SessionReply(int refnum)
1145 JackClientInterface* client = fClientTable[refnum];
1146 assert(client);
1147 char uuid_buf[JACK_UUID_STRING_SIZE];
1148 jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
1149 fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1150 client->GetClientControl()->fName,
1151 client->GetClientControl()->fSessionCommand,
1152 client->GetClientControl()->fSessionFlags));
1153 fSessionPendingReplies -= 1;
1155 if (fSessionPendingReplies == 0) {
1156 fSessionResult->Write(fSessionTransaction);
1157 if (fSessionTransaction != NULL) {
1158 delete fSessionResult;
1160 fSessionResult = NULL;
1163 return 0;
1166 int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
1168 for (int i = 0; i < CLIENT_NUM; i++) {
1169 JackClientInterface* client = fClientTable[i];
1171 if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
1172 jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_res);
1173 return 0;
1176 // Did not find name.
1177 return -1;
1180 int JackEngine::GetClientNameForUUID(const char *uuid_buf, char *name_res)
1182 jack_uuid_t uuid;
1183 if (jack_uuid_parse(uuid_buf, &uuid) != 0)
1184 return -1;
1186 for (int i = 0; i < CLIENT_NUM; i++) {
1187 JackClientInterface* client = fClientTable[i];
1189 if (!client) {
1190 continue;
1193 if (jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
1194 strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
1195 return 0;
1198 // Did not find uuid.
1199 return -1;
1202 int JackEngine::ReserveClientName(const char *name, const char *uuidstr)
1204 jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuidstr);
1206 if (ClientCheckName(name)) {
1207 jack_log("name already taken");
1208 return -1;
1211 jack_uuid_t uuid;
1212 if (jack_uuid_parse(uuidstr, &uuid) != 0) {
1213 jack_error("JackEngine::ReserveClientName invalid uuid %s", uuidstr);
1214 return -1;
1217 EnsureUUID(uuid);
1218 fReservationMap[uuid] = name;
1219 return 0;
1222 int JackEngine::ClientHasSessionCallback(const char *name)
1224 JackClientInterface* client = NULL;
1225 for (int i = 0; i < CLIENT_NUM; i++) {
1226 client = fClientTable[i];
1227 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
1228 break;
1232 if (client) {
1233 return client->GetClientControl()->fCallback[kSessionCallback];
1234 } else {
1235 return -1;
1239 } // end of namespace