Merge pull request #23 from jackaudio/device_reservation_fixes
[jack2.git] / common / JackEngine.cpp
blob43b50b3eb3300e263337908df1f94f116ba92b9b
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>
25 #include "JackSystemDeps.h"
26 #include "JackLockedEngine.h"
27 #include "JackExternalClient.h"
28 #include "JackInternalClient.h"
29 #include "JackEngineControl.h"
30 #include "JackClientControl.h"
31 #include "JackServerGlobals.h"
32 #include "JackGlobals.h"
33 #include "JackChannel.h"
34 #include "JackError.h"
36 namespace Jack
39 JackEngine::JackEngine(JackGraphManager* manager,
40 JackSynchro* table,
41 JackEngineControl* control)
42 : JackLockAble(control->fServerName),
43 fSignal(control->fServerName)
45 fGraphManager = manager;
46 fSynchroTable = table;
47 fEngineControl = control;
48 for (int i = 0; i < CLIENT_NUM; i++) {
49 fClientTable[i] = NULL;
51 fLastSwitchUsecs = 0;
52 fMaxUUID = 0;
53 fSessionPendingReplies = 0;
54 fSessionTransaction = NULL;
55 fSessionResult = NULL;
58 JackEngine::~JackEngine()
61 int JackEngine::Open()
63 jack_log("JackEngine::Open");
65 // Open audio thread => request thread communication channel
66 if (fChannel.Open(fEngineControl->fServerName) < 0) {
67 jack_error("Cannot connect to server");
68 return -1;
69 } else {
70 return 0;
74 int JackEngine::Close()
76 jack_log("JackEngine::Close");
77 fChannel.Close();
79 // Close remaining clients (RT is stopped)
80 for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
81 if (JackLoadableInternalClient* loadable_client = dynamic_cast<JackLoadableInternalClient*>(fClientTable[i])) {
82 jack_log("JackEngine::Close loadable client = %s", loadable_client->GetClientControl()->fName);
83 loadable_client->Close();
84 fClientTable[i] = NULL;
85 delete loadable_client;
86 } else if (JackExternalClient* external_client = dynamic_cast<JackExternalClient*>(fClientTable[i])) {
87 jack_log("JackEngine::Close external client = %s", external_client->GetClientControl()->fName);
88 external_client->Close();
89 fClientTable[i] = NULL;
90 delete external_client;
94 return 0;
97 void JackEngine::ShutDown()
99 jack_log("JackEngine::ShutDown");
101 // Shutdown remaining clients (RT is stopped)
102 for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
103 if (JackLoadableInternalClient* loadable_client = dynamic_cast<JackLoadableInternalClient*>(fClientTable[i])) {
104 jack_log("JackEngine::ShutDown loadable client = %s", loadable_client->GetClientControl()->fName);
105 loadable_client->ShutDown();
111 void JackEngine::NotifyQuit()
113 fChannel.NotifyQuit();
116 //-----------------------------
117 // Client ressource management
118 //-----------------------------
120 int JackEngine::AllocateRefnum()
122 for (int i = 0; i < CLIENT_NUM; i++) {
123 if (!fClientTable[i]) {
124 jack_log("JackEngine::AllocateRefNum ref = %ld", i);
125 return i;
128 return -1;
131 void JackEngine::ReleaseRefnum(int ref)
133 fClientTable[ref] = NULL;
135 if (fEngineControl->fTemporary) {
136 int i;
137 for (i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
138 if (fClientTable[i]) {
139 break;
142 if (i == CLIENT_NUM) {
143 // last client and temporay case: quit the server
144 jack_log("JackEngine::ReleaseRefnum server quit");
145 fEngineControl->fTemporary = false;
146 throw JackTemporaryException();
151 //------------------
152 // Graph management
153 //------------------
155 void JackEngine::ProcessNext(jack_time_t cur_cycle_begin)
157 fLastSwitchUsecs = cur_cycle_begin;
158 if (fGraphManager->RunNextGraph()) { // True if the graph actually switched to a new state
159 fChannel.Notify(ALL_CLIENTS, kGraphOrderCallback, 0);
161 fSignal.Signal(); // Signal for threads waiting for next cycle
164 void JackEngine::ProcessCurrent(jack_time_t cur_cycle_begin)
166 if (cur_cycle_begin < fLastSwitchUsecs + 2 * fEngineControl->fPeriodUsecs) { // Signal XRun only for the first failing cycle
167 CheckXRun(cur_cycle_begin);
169 fGraphManager->RunCurrentGraph();
172 bool JackEngine::Process(jack_time_t cur_cycle_begin, jack_time_t prev_cycle_end)
174 bool res = true;
176 // Cycle begin
177 fEngineControl->CycleBegin(fClientTable, fGraphManager, cur_cycle_begin, prev_cycle_end);
179 // Graph
180 if (fGraphManager->IsFinishedGraph()) {
181 ProcessNext(cur_cycle_begin);
182 res = true;
183 } else {
184 jack_log("Process: graph not finished!");
185 if (cur_cycle_begin > fLastSwitchUsecs + fEngineControl->fTimeOutUsecs) {
186 jack_log("Process: switch to next state delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
187 ProcessNext(cur_cycle_begin);
188 res = true;
189 } else {
190 jack_log("Process: waiting to switch delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
191 ProcessCurrent(cur_cycle_begin);
192 res = false;
196 // Cycle end
197 fEngineControl->CycleEnd(fClientTable);
198 return res;
202 Client that finish *after* the callback date are considered late even if their output buffers may have been
203 correctly mixed in the time window: callbackUsecs <==> Read <==> Write.
206 static const char* State2String(jack_client_state_t state)
208 switch (state) {
209 case NotTriggered:
210 return "NotTriggered";
211 case Triggered:
212 return "Triggered";
213 case Running:
214 return "Running";
215 case Finished:
216 return "Finished";
217 default:
218 return "";
222 void JackEngine::CheckXRun(jack_time_t callback_usecs) // REVOIR les conditions de fin
224 for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
225 JackClientInterface* client = fClientTable[i];
226 if (client && client->GetClientControl()->fActive) {
227 JackClientTiming* timing = fGraphManager->GetClientTiming(i);
228 jack_client_state_t status = timing->fStatus;
229 jack_time_t finished_date = timing->fFinishedAt;
231 if (status != NotTriggered && status != Finished) {
232 jack_error("JackEngine::XRun: client = %s was not finished, state = %s", client->GetClientControl()->fName, State2String(status));
233 fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
236 if (status == Finished && (long)(finished_date - callback_usecs) > 0) {
237 jack_error("JackEngine::XRun: client %s finished after current callback", client->GetClientControl()->fName);
238 fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
244 int JackEngine::ComputeTotalLatencies()
246 std::vector<jack_int_t> sorted;
247 std::vector<jack_int_t>::iterator it;
248 std::vector<jack_int_t>::reverse_iterator rit;
250 fGraphManager->TopologicalSort(sorted);
252 /* iterate over all clients in graph order, and emit
253 * capture latency callback.
256 for (it = sorted.begin(); it != sorted.end(); it++) {
257 NotifyClient(*it, kLatencyCallback, true, "", 0, 0);
260 /* now issue playback latency callbacks in reverse graph order.
262 for (rit = sorted.rbegin(); rit != sorted.rend(); rit++) {
263 NotifyClient(*rit, kLatencyCallback, true, "", 1, 0);
266 return 0;
269 //---------------
270 // Notifications
271 //---------------
273 int JackEngine::ClientNotify(JackClientInterface* client, int refnum, const char* name, int notify, int sync, const char* message, int value1, int value2)
275 if (!client) {
276 return 0;
279 if (!client->GetClientControl()->fCallback[notify]) {
280 jack_log("JackEngine::ClientNotify: no callback for notification = %ld", notify);
281 return 0;
284 int ret;
286 // External client
287 if (dynamic_cast<JackExternalClient*>(client)) {
288 ret = client->ClientNotify(refnum, name, notify, sync, message, value1, value2);
289 // Important for internal client : unlock before calling the notification callbacks
290 } else {
291 bool res = Unlock();
292 ret = client->ClientNotify(refnum, name, notify, sync, message, value1, value2);
293 if (res) {
294 Lock();
298 if (ret < 0) {
299 jack_error("NotifyClient fails name = %s notification = %ld val1 = %ld val2 = %ld", name, notify, value1, value2);
301 return ret;
304 void JackEngine::NotifyClient(int refnum, int event, int sync, const char* message, int value1, int value2)
306 JackClientInterface* client = fClientTable[refnum];
307 if (client) {
308 ClientNotify(client, refnum, client->GetClientControl()->fName, event, sync, message, value1, value2);
312 void JackEngine::NotifyClients(int event, int sync, const char* message, int value1, int value2)
314 for (int i = 0; i < CLIENT_NUM; i++) {
315 NotifyClient(i, event, sync, message, value1, value2);
319 int JackEngine::NotifyAddClient(JackClientInterface* new_client, const char* new_name, int refnum)
321 jack_log("JackEngine::NotifyAddClient: name = %s", new_name);
323 // Notify existing clients of the new client and new client of existing clients.
324 for (int i = 0; i < CLIENT_NUM; i++) {
325 JackClientInterface* old_client = fClientTable[i];
326 if (old_client && old_client != new_client) {
327 char* old_name = old_client->GetClientControl()->fName;
328 if (ClientNotify(old_client, refnum, new_name, kAddClient, false, "", 0, 0) < 0) {
329 jack_error("NotifyAddClient old_client fails name = %s", old_name);
330 // Not considered as a failure...
332 if (ClientNotify(new_client, i, old_name, kAddClient, true, "", 0, 0) < 0) {
333 jack_error("NotifyAddClient new_client fails name = %s", new_name);
334 return -1;
339 return 0;
342 void JackEngine::NotifyRemoveClient(const char* name, int refnum)
344 // Notify existing clients (including the one beeing suppressed) of the removed client
345 for (int i = 0; i < CLIENT_NUM; i++) {
346 ClientNotify(fClientTable[i], refnum, name, kRemoveClient, false, "", 0, 0);
350 // Coming from the driver
351 void JackEngine::NotifyXRun(jack_time_t callback_usecs, float delayed_usecs)
353 // Use the audio thread => request thread communication channel
354 fEngineControl->NotifyXRun(callback_usecs, delayed_usecs);
355 fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0);
358 void JackEngine::NotifyXRun(int refnum)
360 if (refnum == ALL_CLIENTS) {
361 NotifyClients(kXRunCallback, false, "", 0, 0);
362 } else {
363 NotifyClient(refnum, kXRunCallback, false, "", 0, 0);
367 void JackEngine::NotifyGraphReorder()
369 ComputeTotalLatencies();
370 NotifyClients(kGraphOrderCallback, false, "", 0, 0);
373 void JackEngine::NotifyBufferSize(jack_nframes_t buffer_size)
375 NotifyClients(kBufferSizeCallback, true, "", buffer_size, 0);
378 void JackEngine::NotifySampleRate(jack_nframes_t sample_rate)
380 NotifyClients(kSampleRateCallback, true, "", sample_rate, 0);
383 void JackEngine::NotifyFailure(int code, const char* reason)
385 NotifyClients(kShutDownCallback, false, reason, code, 0);
388 void JackEngine::NotifyFreewheel(bool onoff)
390 if (onoff) {
391 // Save RT state
392 fEngineControl->fSavedRealTime = fEngineControl->fRealTime;
393 fEngineControl->fRealTime = false;
394 } else {
395 // Restore RT state
396 fEngineControl->fRealTime = fEngineControl->fSavedRealTime;
397 fEngineControl->fSavedRealTime = false;
399 NotifyClients((onoff ? kStartFreewheelCallback : kStopFreewheelCallback), true, "", 0, 0);
402 void JackEngine::NotifyPortRegistation(jack_port_id_t port_index, bool onoff)
404 NotifyClients((onoff ? kPortRegistrationOnCallback : kPortRegistrationOffCallback), false, "", port_index, 0);
407 void JackEngine::NotifyPortRename(jack_port_id_t port, const char* old_name)
409 NotifyClients(kPortRenameCallback, false, old_name, port, 0);
412 void JackEngine::NotifyPortConnect(jack_port_id_t src, jack_port_id_t dst, bool onoff)
414 NotifyClients((onoff ? kPortConnectCallback : kPortDisconnectCallback), false, "", src, dst);
417 void JackEngine::NotifyActivate(int refnum)
419 NotifyClient(refnum, kActivateClient, true, "", 0, 0);
422 //----------------------------
423 // Loadable client management
424 //----------------------------
426 int JackEngine::GetInternalClientName(int refnum, char* name_res)
428 JackClientInterface* client = fClientTable[refnum];
429 strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
430 return 0;
433 int JackEngine::InternalClientHandle(const char* client_name, int* status, int* int_ref)
435 // Clear status
436 *status = 0;
438 for (int i = 0; i < CLIENT_NUM; i++) {
439 JackClientInterface* client = fClientTable[i];
440 if (client && dynamic_cast<JackLoadableInternalClient*>(client) && (strcmp(client->GetClientControl()->fName, client_name) == 0)) {
441 jack_log("InternalClientHandle found client name = %s ref = %ld", client_name, i);
442 *int_ref = i;
443 return 0;
447 *status |= (JackNoSuchClient | JackFailure);
448 return -1;
451 int JackEngine::InternalClientUnload(int refnum, int* status)
453 JackClientInterface* client = fClientTable[refnum];
454 if (client) {
455 int res = client->Close();
456 delete client;
457 *status = 0;
458 return res;
459 } else {
460 *status = (JackNoSuchClient | JackFailure);
461 return -1;
465 //-------------------
466 // Client management
467 //-------------------
469 int JackEngine::ClientCheck(const char* name, int uuid, char* name_res, int protocol, int options, int* status)
471 // Clear status
472 *status = 0;
473 strcpy(name_res, name);
475 jack_log("Check protocol client = %ld server = %ld", protocol, JACK_PROTOCOL_VERSION);
477 if (protocol != JACK_PROTOCOL_VERSION) {
478 *status |= (JackFailure | JackVersionError);
479 jack_error("JACK protocol mismatch (%d vs %d)", protocol, JACK_PROTOCOL_VERSION);
480 return -1;
483 std::map<int,std::string>::iterator res = fReservationMap.find(uuid);
485 if (res != fReservationMap.end()) {
486 strncpy(name_res, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
487 } else if (ClientCheckName(name)) {
489 *status |= JackNameNotUnique;
491 if (options & JackUseExactName) {
492 jack_error("cannot create new client; %s already exists", name);
493 *status |= JackFailure;
494 return -1;
497 if (GenerateUniqueName(name_res)) {
498 *status |= JackFailure;
499 return -1;
503 return 0;
506 bool JackEngine::GenerateUniqueName(char* name)
508 int tens, ones;
509 int length = strlen(name);
511 if (length > JACK_CLIENT_NAME_SIZE - 4) {
512 jack_error("%s exists and is too long to make unique", name);
513 return true; /* failure */
516 /* generate a unique name by appending "-01".."-99" */
517 name[length++] = '-';
518 tens = length++;
519 ones = length++;
520 name[tens] = '0';
521 name[ones] = '1';
522 name[length] = '\0';
524 while (ClientCheckName(name)) {
525 if (name[ones] == '9') {
526 if (name[tens] == '9') {
527 jack_error("client %s has 99 extra instances already", name);
528 return true; /* give up */
530 name[tens]++;
531 name[ones] = '0';
532 } else {
533 name[ones]++;
536 return false;
539 bool JackEngine::ClientCheckName(const char* name)
541 for (int i = 0; i < CLIENT_NUM; i++) {
542 JackClientInterface* client = fClientTable[i];
543 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
544 return true;
548 for (std::map<int,std::string>::iterator i = fReservationMap.begin(); i != fReservationMap.end(); i++) {
549 if (i->second == name) {
550 return true;
554 return false;
557 int JackEngine::GetNewUUID()
559 return fMaxUUID++;
562 void JackEngine::EnsureUUID(int uuid)
564 if (uuid > fMaxUUID) {
565 fMaxUUID = uuid + 1;
568 for (int i = 0; i < CLIENT_NUM; i++) {
569 JackClientInterface* client = fClientTable[i];
570 if (client && (client->GetClientControl()->fSessionID == uuid)) {
571 client->GetClientControl()->fSessionID = GetNewUUID();
576 int JackEngine::GetClientPID(const char* name)
578 for (int i = 0; i < CLIENT_NUM; i++) {
579 JackClientInterface* client = fClientTable[i];
580 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
581 return client->GetClientControl()->fPID;
585 return 0;
588 int JackEngine::GetClientRefNum(const char* name)
590 for (int i = 0; i < CLIENT_NUM; i++) {
591 JackClientInterface* client = fClientTable[i];
592 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
593 return client->GetClientControl()->fRefNum;
597 return -1;
600 // Used for external clients
601 int JackEngine::ClientExternalOpen(const char* name, int pid, int uuid, int* ref, int* shared_engine, int* shared_client, int* shared_graph_manager)
603 char real_name[JACK_CLIENT_NAME_SIZE + 1];
605 if (uuid < 0) {
606 uuid = GetNewUUID();
607 strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
608 } else {
609 std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
610 if (res != fReservationMap.end()) {
611 strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
612 fReservationMap.erase(uuid);
613 } else {
614 strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
616 EnsureUUID(uuid);
619 jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s ", uuid, real_name);
621 int refnum = AllocateRefnum();
622 if (refnum < 0) {
623 jack_error("No more refnum available");
624 return -1;
627 JackExternalClient* client = new JackExternalClient();
629 if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
630 jack_error("Cannot allocate synchro");
631 goto error;
634 if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
635 jack_error("Cannot open client");
636 goto error;
639 if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
640 // Failure if RT thread is not running (problem with the driver...)
641 jack_error("Driver is not running");
642 goto error;
645 fClientTable[refnum] = client;
647 if (NotifyAddClient(client, real_name, refnum) < 0) {
648 jack_error("Cannot notify add client");
649 goto error;
652 fGraphManager->InitRefNum(refnum);
653 fEngineControl->ResetRollingUsecs();
654 *shared_engine = fEngineControl->GetShmIndex();
655 *shared_graph_manager = fGraphManager->GetShmIndex();
656 *ref = refnum;
657 return 0;
659 error:
660 // Cleanup...
661 fSynchroTable[refnum].Destroy();
662 fClientTable[refnum] = 0;
663 client->Close();
664 delete client;
665 return -1;
668 // Used for server driver clients
669 int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
671 jack_log("JackEngine::ClientInternalOpen: name = %s", name);
673 int refnum = AllocateRefnum();
674 if (refnum < 0) {
675 jack_error("No more refnum available");
676 goto error;
679 if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
680 jack_error("Cannot allocate synchro");
681 goto error;
684 if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
685 // Failure if RT thread is not running (problem with the driver...)
686 jack_error("Driver is not running");
687 goto error;
690 fClientTable[refnum] = client;
692 if (NotifyAddClient(client, name, refnum) < 0) {
693 jack_error("Cannot notify add client");
694 goto error;
697 fGraphManager->InitRefNum(refnum);
698 fEngineControl->ResetRollingUsecs();
699 *shared_engine = fEngineControl;
700 *shared_manager = fGraphManager;
701 *ref = refnum;
702 return 0;
704 error:
705 // Cleanup...
706 fSynchroTable[refnum].Destroy();
707 fClientTable[refnum] = 0;
708 return -1;
711 // Used for external clients
712 int JackEngine::ClientExternalClose(int refnum)
714 jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
715 JackClientInterface* client = fClientTable[refnum];
716 int res = ClientCloseAux(refnum, true);
717 client->Close();
718 delete client;
719 return res;
722 // Used for server internal clients or drivers when the RT thread is stopped
723 int JackEngine::ClientInternalClose(int refnum, bool wait)
725 jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
726 return ClientCloseAux(refnum, wait);
729 int JackEngine::ClientCloseAux(int refnum, bool wait)
731 jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
733 JackClientInterface* client = fClientTable[refnum];
734 fEngineControl->fTransport.ResetTimebase(refnum);
736 // Unregister all ports ==> notifications are sent
737 jack_int_t ports[PORT_NUM_FOR_CLIENT];
738 int i;
740 fGraphManager->GetInputPorts(refnum, ports);
741 for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
742 PortUnRegister(refnum, ports[i]);
745 fGraphManager->GetOutputPorts(refnum, ports);
746 for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
747 PortUnRegister(refnum, ports[i]);
750 // Remove the client from the table
751 ReleaseRefnum(refnum);
753 // Remove all ports
754 fGraphManager->RemoveAllPorts(refnum);
756 // Wait until next cycle to be sure client is not used anymore
757 if (wait) {
758 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
759 jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
763 // Notify running clients
764 NotifyRemoveClient(client->GetClientControl()->fName, client->GetClientControl()->fRefNum);
766 // Cleanup...
767 fSynchroTable[refnum].Destroy();
768 fEngineControl->ResetRollingUsecs();
769 return 0;
772 int JackEngine::ClientActivate(int refnum, bool is_real_time)
774 JackClientInterface* client = fClientTable[refnum];
775 jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
777 if (is_real_time) {
778 fGraphManager->Activate(refnum);
781 // Wait for graph state change to be effective
782 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
783 jack_error("JackEngine::ClientActivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
784 return -1;
785 } else {
786 jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
787 jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
788 fGraphManager->GetInputPorts(refnum, input_ports);
789 fGraphManager->GetOutputPorts(refnum, output_ports);
791 // Notify client
792 NotifyActivate(refnum);
794 // Then issue port registration notification
795 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
796 NotifyPortRegistation(input_ports[i], true);
798 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
799 NotifyPortRegistation(output_ports[i], true);
802 return 0;
806 // May be called without client
807 int JackEngine::ClientDeactivate(int refnum)
809 JackClientInterface* client = fClientTable[refnum];
810 jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
812 jack_int_t input_ports[PORT_NUM_FOR_CLIENT];
813 jack_int_t output_ports[PORT_NUM_FOR_CLIENT];
814 fGraphManager->GetInputPorts(refnum, input_ports);
815 fGraphManager->GetOutputPorts(refnum, output_ports);
817 // First disconnect all ports
818 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
819 PortDisconnect(refnum, input_ports[i], ALL_PORTS);
821 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
822 PortDisconnect(refnum, output_ports[i], ALL_PORTS);
825 // Then issue port registration notification
826 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (input_ports[i] != EMPTY); i++) {
827 NotifyPortRegistation(input_ports[i], false);
829 for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
830 NotifyPortRegistation(output_ports[i], false);
833 fGraphManager->Deactivate(refnum);
834 fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
836 // Wait for graph state change to be effective
837 if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 10)) {
838 jack_error("JackEngine::ClientDeactivate wait error ref = %ld name = %s", refnum, client->GetClientControl()->fName);
839 return -1;
840 } else {
841 return 0;
845 //-----------------
846 // Port management
847 //-----------------
849 int JackEngine::PortRegister(int refnum, const char* name, const char *type, unsigned int flags, unsigned int buffer_size, jack_port_id_t* port_index)
851 jack_log("JackEngine::PortRegister ref = %ld name = %s type = %s flags = %d buffer_size = %d", refnum, name, type, flags, buffer_size);
852 JackClientInterface* client = fClientTable[refnum];
854 // Check if port name already exists
855 if (fGraphManager->GetPort(name) != NO_PORT) {
856 jack_error("port_name \"%s\" already exists", name);
857 return -1;
860 // buffer_size is actually ignored...
861 *port_index = fGraphManager->AllocatePort(refnum, name, type, (JackPortFlags)flags, fEngineControl->fBufferSize);
862 if (*port_index != NO_PORT) {
863 if (client->GetClientControl()->fActive) {
864 NotifyPortRegistation(*port_index, true);
866 return 0;
867 } else {
868 return -1;
872 int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
874 jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
875 JackClientInterface* client = fClientTable[refnum];
877 // Disconnect port ==> notification is sent
878 PortDisconnect(refnum, port_index, ALL_PORTS);
880 if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
881 if (client->GetClientControl()->fActive) {
882 NotifyPortRegistation(port_index, false);
884 return 0;
885 } else {
886 return -1;
890 int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
892 jack_log("JackEngine::PortConnect src = %s dst = %s", src, dst);
893 jack_port_id_t port_src, port_dst;
895 return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
896 ? -1
897 : PortConnect(refnum, port_src, port_dst);
900 int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
902 jack_log("JackEngine::PortConnect src = %d dst = %d", src, dst);
903 JackClientInterface* client;
904 int ref;
906 if (fGraphManager->CheckPorts(src, dst) < 0) {
907 return -1;
910 ref = fGraphManager->GetOutputRefNum(src);
911 assert(ref >= 0);
912 client = fClientTable[ref];
913 assert(client);
914 if (!client->GetClientControl()->fActive) {
915 jack_error("Cannot connect ports owned by inactive clients:"
916 " \"%s\" is not active", client->GetClientControl()->fName);
917 return -1;
920 ref = fGraphManager->GetInputRefNum(dst);
921 assert(ref >= 0);
922 client = fClientTable[ref];
923 assert(client);
924 if (!client->GetClientControl()->fActive) {
925 jack_error("Cannot connect ports owned by inactive clients:"
926 " \"%s\" is not active", client->GetClientControl()->fName);
927 return -1;
930 int res = fGraphManager->Connect(src, dst);
931 if (res == 0) {
932 NotifyPortConnect(src, dst, true);
934 return res;
937 int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
939 jack_log("JackEngine::PortDisconnect src = %s dst = %s", src, dst);
940 jack_port_id_t port_src, port_dst;
942 return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
943 ? -1
944 : PortDisconnect(refnum, port_src, port_dst);
947 int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
949 jack_log("JackEngine::PortDisconnect src = %d dst = %d", src, dst);
951 if (dst == ALL_PORTS) {
953 jack_int_t connections[CONNECTION_NUM_FOR_PORT];
954 fGraphManager->GetConnections(src, connections);
956 JackPort* port = fGraphManager->GetPort(src);
957 int ret = 0;
958 if (port->GetFlags() & JackPortIsOutput) {
959 for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
960 if (PortDisconnect(refnum, src, connections[i]) != 0) {
961 ret = -1;
964 } else {
965 for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
966 if (PortDisconnect(refnum, connections[i], src) != 0) {
967 ret = -1;
972 return ret;
973 } else if (fGraphManager->CheckPorts(src, dst) < 0) {
974 return -1;
975 } else if (fGraphManager->Disconnect(src, dst) == 0) {
976 // Notifications
977 NotifyPortConnect(src, dst, false);
978 return 0;
979 } else {
980 return -1;
984 int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
986 char old_name[REAL_JACK_PORT_NAME_SIZE];
987 strcpy(old_name, fGraphManager->GetPort(port)->GetName());
988 fGraphManager->GetPort(port)->SetName(name);
989 NotifyPortRename(port, old_name);
990 return 0;
993 //--------------------
994 // Session management
995 //--------------------
997 void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
999 if (fSessionPendingReplies != 0) {
1000 JackSessionNotifyResult res(-1);
1001 res.Write(socket);
1002 jack_log("JackEngine::SessionNotify ... busy");
1003 if (result != NULL) {
1004 *result = NULL;
1006 return;
1009 for (int i = 0; i < CLIENT_NUM; i++) {
1010 JackClientInterface* client = fClientTable[i];
1011 if (client && (client->GetClientControl()->fSessionID < 0)) {
1012 client->GetClientControl()->fSessionID = GetNewUUID();
1015 fSessionResult = new JackSessionNotifyResult();
1017 for (int i = 0; i < CLIENT_NUM; i++) {
1018 JackClientInterface* client = fClientTable[i];
1019 if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
1021 // check if this is a notification to a specific client.
1022 if (target != NULL && strlen(target) != 0) {
1023 if (strcmp(target, client->GetClientControl()->fName)) {
1024 continue;
1028 char path_buf[JACK_PORT_NAME_SIZE];
1029 snprintf(path_buf, sizeof(path_buf), "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
1031 int res = JackTools::MkDir(path_buf);
1032 if (res) {
1033 jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
1036 int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
1038 if (result == kPendingSessionReply) {
1039 fSessionPendingReplies += 1;
1040 } else if (result == kImmediateSessionReply) {
1041 char uuid_buf[JACK_UUID_SIZE];
1042 snprintf(uuid_buf, sizeof(uuid_buf), "%d", client->GetClientControl()->fSessionID);
1043 fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1044 client->GetClientControl()->fName,
1045 client->GetClientControl()->fSessionCommand,
1046 client->GetClientControl()->fSessionFlags));
1051 if (result != NULL) {
1052 *result = fSessionResult;
1055 if (fSessionPendingReplies == 0) {
1056 fSessionResult->Write(socket);
1057 if (result == NULL) {
1058 delete fSessionResult;
1060 fSessionResult = NULL;
1061 } else {
1062 fSessionTransaction = socket;
1066 int JackEngine::SessionReply(int refnum)
1068 JackClientInterface* client = fClientTable[refnum];
1069 char uuid_buf[JACK_UUID_SIZE];
1070 snprintf(uuid_buf, sizeof(uuid_buf), "%d", client->GetClientControl()->fSessionID);
1071 fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1072 client->GetClientControl()->fName,
1073 client->GetClientControl()->fSessionCommand,
1074 client->GetClientControl()->fSessionFlags));
1075 fSessionPendingReplies -= 1;
1077 if (fSessionPendingReplies == 0) {
1078 fSessionResult->Write(fSessionTransaction);
1079 if (fSessionTransaction != NULL) {
1080 delete fSessionResult;
1082 fSessionResult = NULL;
1085 return 0;
1088 int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
1090 for (int i = 0; i < CLIENT_NUM; i++) {
1091 JackClientInterface* client = fClientTable[i];
1093 if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
1094 snprintf(uuid_res, JACK_UUID_SIZE, "%d", client->GetClientControl()->fSessionID);
1095 return 0;
1098 // Did not find name.
1099 return -1;
1102 int JackEngine::GetClientNameForUUID(const char *uuid, char *name_res)
1104 for (int i = 0; i < CLIENT_NUM; i++) {
1105 JackClientInterface* client = fClientTable[i];
1107 if (!client) {
1108 continue;
1111 char uuid_buf[JACK_UUID_SIZE];
1112 snprintf(uuid_buf, JACK_UUID_SIZE, "%d", client->GetClientControl()->fSessionID);
1114 if (strcmp(uuid,uuid_buf) == 0) {
1115 strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
1116 return 0;
1119 // Did not find uuid.
1120 return -1;
1123 int JackEngine::ReserveClientName(const char *name, const char *uuid)
1125 jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuid);
1127 if (ClientCheckName(name)) {
1128 jack_log("name already taken");
1129 return -1;
1132 EnsureUUID(atoi(uuid));
1133 fReservationMap[atoi(uuid)] = name;
1134 return 0;
1137 int JackEngine::ClientHasSessionCallback(const char *name)
1139 JackClientInterface* client = NULL;
1140 for (int i = 0; i < CLIENT_NUM; i++) {
1141 client = fClientTable[i];
1142 if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
1143 break;
1147 if (client) {
1148 return client->GetClientControl()->fCallback[kSessionCallback];
1149 } else {
1150 return -1;
1154 } // end of namespace