Jack2  1.9.13
JackEngine.cpp
1 /*
2 Copyright (C) 2004-2008 Grame
3 
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.
8 
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.
13 
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.
17 
18 */
19 
20 #include <iostream>
21 #include <fstream>
22 #include <set>
23 #include <assert.h>
24 #include <ctype.h>
25 
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"
36 
37 extern const char* JACK_METADATA_HARDWARE;
38 extern const char* JACK_METADATA_PRETTY_NAME;
39 
40 namespace Jack
41 {
42 
43 JackEngine::JackEngine(JackGraphManager* manager,
44  JackSynchro* table,
45  JackEngineControl* control,
46  char self_connect_mode)
47  : JackLockAble(control->fServerName),
48  fSignal(control->fServerName),
49  fMetadata(true)
50 {
51  fGraphManager = manager;
52  fSynchroTable = table;
53  fEngineControl = control;
54  fSelfConnectMode = self_connect_mode;
55  for (int i = 0; i < CLIENT_NUM; i++) {
56  fClientTable[i] = NULL;
57  }
58  fLastSwitchUsecs = 0;
59  fSessionPendingReplies = 0;
60  fSessionTransaction = NULL;
61  fSessionResult = NULL;
62 }
63 
64 JackEngine::~JackEngine()
65 {}
66 
67 int JackEngine::Open()
68 {
69  jack_log("JackEngine::Open");
70 
71  // Open audio thread => request thread communication channel
72  if (fChannel.Open(fEngineControl->fServerName) < 0) {
73  jack_error("Cannot connect to server");
74  return -1;
75  } else {
76  return 0;
77  }
78 }
79 
80 int JackEngine::Close()
81 {
82  jack_log("JackEngine::Close");
83  fChannel.Close();
84 
85  // Close remaining clients (RT is stopped)
86  for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
87  if (JackLoadableInternalClient* loadable_client = dynamic_cast<JackLoadableInternalClient*>(fClientTable[i])) {
88  jack_log("JackEngine::Close loadable client = %s", loadable_client->GetClientControl()->fName);
89  loadable_client->Close();
90  fClientTable[i] = NULL;
91  delete loadable_client;
92  } else if (JackExternalClient* external_client = dynamic_cast<JackExternalClient*>(fClientTable[i])) {
93  jack_log("JackEngine::Close external client = %s", external_client->GetClientControl()->fName);
94  external_client->Close();
95  fClientTable[i] = NULL;
96  delete external_client;
97  }
98  }
99 
100  return 0;
101 }
102 
103 void JackEngine::NotifyQuit()
104 {
105  fChannel.NotifyQuit();
106 }
107 
108 
109 //-----------------------------
110 // Client resource management
111 //-----------------------------
112 
113 int JackEngine::AllocateRefnum()
114 {
115  for (int i = 0; i < CLIENT_NUM; i++) {
116  if (!fClientTable[i]) {
117  jack_log("JackEngine::AllocateRefNum ref = %ld", i);
118  return i;
119  }
120  }
121  return -1;
122 }
123 
124 void JackEngine::ReleaseRefnum(int refnum)
125 {
126  fClientTable[refnum] = NULL;
127 
128  if (fEngineControl->fTemporary) {
129  int i;
130  for (i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
131  if (fClientTable[i]) {
132  break;
133  }
134  }
135  if (i == CLIENT_NUM) {
136  // Last client and temporary case: quit the server
137  jack_log("JackEngine::ReleaseRefnum server quit");
138  fEngineControl->fTemporary = false;
139  throw JackTemporaryException();
140  }
141  }
142 }
143 
144 //------------------
145 // Graph management
146 //------------------
147 
148 void JackEngine::ProcessNext(jack_time_t cur_cycle_begin)
149 {
150  fLastSwitchUsecs = cur_cycle_begin;
151  if (fGraphManager->RunNextGraph()) { // True if the graph actually switched to a new state
152  fChannel.Notify(ALL_CLIENTS, kGraphOrderCallback, 0);
153  }
154  fSignal.Signal(); // Signal for threads waiting for next cycle
155 }
156 
157 void JackEngine::ProcessCurrent(jack_time_t cur_cycle_begin)
158 {
159  if (cur_cycle_begin < fLastSwitchUsecs + 2 * fEngineControl->fPeriodUsecs) { // Signal XRun only for the first failing cycle
160  CheckXRun(cur_cycle_begin);
161  }
162  fGraphManager->RunCurrentGraph();
163 }
164 
165 bool JackEngine::Process(jack_time_t cur_cycle_begin, jack_time_t prev_cycle_end)
166 {
167  bool res = true;
168 
169  // Cycle begin
170  fEngineControl->CycleBegin(fClientTable, fGraphManager, cur_cycle_begin, prev_cycle_end);
171 
172  // Graph
173  if (fGraphManager->IsFinishedGraph()) {
174  ProcessNext(cur_cycle_begin);
175  res = true;
176  } else {
177  jack_log("Process: graph not finished!");
178  if (cur_cycle_begin > fLastSwitchUsecs + fEngineControl->fTimeOutUsecs) {
179  jack_log("Process: switch to next state delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
180  ProcessNext(cur_cycle_begin);
181  res = true;
182  } else {
183  jack_log("Process: waiting to switch delta = %ld", long(cur_cycle_begin - fLastSwitchUsecs));
184  ProcessCurrent(cur_cycle_begin);
185  res = false;
186  }
187  }
188 
189  // Cycle end
190  fEngineControl->CycleEnd(fClientTable);
191  return res;
192 }
193 
194 /*
195 Client that finish *after* the callback date are considered late even if their output buffers may have been
196 correctly mixed in the time window: callbackUsecs <==> Read <==> Write.
197 */
198 
199 static const char* State2String(jack_client_state_t state)
200 {
201  switch (state) {
202  case NotTriggered:
203  return "NotTriggered";
204  case Triggered:
205  return "Triggered";
206  case Running:
207  return "Running";
208  case Finished:
209  return "Finished";
210  default:
211  return "";
212  }
213 }
214 
215 void JackEngine::CheckXRun(jack_time_t callback_usecs) // REVOIR les conditions de fin
216 {
217  for (int i = fEngineControl->fDriverNum; i < CLIENT_NUM; i++) {
218  JackClientInterface* client = fClientTable[i];
219  if (client && client->GetClientControl()->fActive) {
220  JackClientTiming* timing = fGraphManager->GetClientTiming(i);
221  jack_client_state_t status = timing->fStatus;
222  jack_time_t finished_date = timing->fFinishedAt;
223 
224  if (status != NotTriggered && status != Finished) {
225  jack_error("JackEngine::XRun: client = %s was not finished, state = %s", client->GetClientControl()->fName, State2String(status));
226  fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
227  }
228 
229  if (status == Finished && (long)(finished_date - callback_usecs) > 0) {
230  jack_error("JackEngine::XRun: client %s finished after current callback", client->GetClientControl()->fName);
231  fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0); // Notify all clients
232  }
233  }
234  }
235 }
236 
237 int JackEngine::ComputeTotalLatencies()
238 {
239  std::vector<jack_int_t> sorted;
240  std::vector<jack_int_t>::iterator it;
241  std::vector<jack_int_t>::reverse_iterator rit;
242 
243  fGraphManager->TopologicalSort(sorted);
244 
245  /* iterate over all clients in graph order, and emit
246  * capture latency callback.
247  */
248 
249  for (it = sorted.begin(); it != sorted.end(); it++) {
250  NotifyClient(*it, kLatencyCallback, true, "", 0, 0);
251  }
252 
253  /* now issue playback latency callbacks in reverse graph order.
254  */
255  for (rit = sorted.rbegin(); rit != sorted.rend(); rit++) {
256  NotifyClient(*rit, kLatencyCallback, true, "", 1, 0);
257  }
258 
259  return 0;
260 }
261 
262 //--------------
263 // Metadata API
264 //--------------
265 
266 int JackEngine::PropertyChangeNotify(jack_uuid_t subject, const char* key, jack_property_change_t change)
267 {
268  jack_log("JackEngine::PropertyChangeNotify: subject = %x key = %s change = %x", subject, key, change);
269 
270  for (int i = 0; i < CLIENT_NUM; i++) {
271  JackClientInterface* client = fClientTable[i];
272  if (client) {
273  char buf[JACK_UUID_STRING_SIZE];
274  jack_uuid_unparse(subject, buf);
275  client->ClientNotify(i, buf, kPropertyChangeCallback, false, key, change, 0);
276  }
277  }
278 
279  return 0;
280 }
281 
282 //---------------
283 // Notifications
284 //---------------
285 
286 int JackEngine::ClientNotify(JackClientInterface* client, int refnum, const char* name, int notify, int sync, const char* message, int value1, int value2)
287 {
288  // Check if notification is needed
289  if (!client->GetClientControl()->fCallback[notify]) {
290  jack_log("JackEngine::ClientNotify: no callback for notification = %ld", notify);
291  return 0;
292  }
293 
294  int res1;
295 
296  // External client
297  if (dynamic_cast<JackExternalClient*>(client)) {
298  res1 = client->ClientNotify(refnum, name, notify, sync, message, value1, value2);
299  // Important for internal client : unlock before calling the notification callbacks
300  } else {
301  bool res2 = Unlock();
302  res1 = client->ClientNotify(refnum, name, notify, sync, message, value1, value2);
303  if (res2) {
304  Lock();
305  }
306  }
307 
308  if (res1 < 0) {
309  jack_error("ClientNotify fails name = %s notification = %ld val1 = %ld val2 = %ld", name, notify, value1, value2);
310  }
311  return res1;
312 }
313 
314 void JackEngine::NotifyClient(int refnum, int event, int sync, const char* message, int value1, int value2)
315 {
316  JackClientInterface* client = fClientTable[refnum];
317  if (client) {
318  ClientNotify(client, refnum, client->GetClientControl()->fName, event, sync, message, value1, value2);
319  }
320 }
321 
322 void JackEngine::NotifyClients(int event, int sync, const char* message, int value1, int value2)
323 {
324  for (int i = 0; i < CLIENT_NUM; i++) {
325  NotifyClient(i, event, sync, message, value1, value2);
326  }
327 }
328 
329 int JackEngine::NotifyAddClient(JackClientInterface* new_client, const char* new_name, int refnum)
330 {
331  jack_log("JackEngine::NotifyAddClient: name = %s", new_name);
332 
333  // Notify existing clients of the new client and new client of existing clients.
334  for (int i = 0; i < CLIENT_NUM; i++) {
335  JackClientInterface* old_client = fClientTable[i];
336  if (old_client && old_client != new_client) {
337  char* old_name = old_client->GetClientControl()->fName;
338  if (ClientNotify(old_client, refnum, new_name, kAddClient, false, "", 0, 0) < 0) {
339  jack_error("NotifyAddClient old_client fails name = %s", old_name);
340  // Not considered as a failure...
341  }
342  if (ClientNotify(new_client, i, old_name, kAddClient, true, "", 0, 0) < 0) {
343  jack_error("NotifyAddClient new_client fails name = %s", new_name);
344  return -1;
345  }
346  }
347  }
348 
349  return 0;
350 }
351 
352 void JackEngine::NotifyRemoveClient(const char* name, int refnum)
353 {
354  // Notify existing clients (including the one being suppressed) of the removed client
355  for (int i = 0; i < CLIENT_NUM; i++) {
356  JackClientInterface* client = fClientTable[i];
357  if (client) {
358  ClientNotify(client, refnum, name, kRemoveClient, false, "", 0, 0);
359  }
360  }
361 }
362 
363 // Coming from the driver
364 void JackEngine::NotifyDriverXRun()
365 {
366  // Use the audio thread => request thread communication channel
367  fChannel.Notify(ALL_CLIENTS, kXRunCallback, 0);
368 }
369 
370 void JackEngine::NotifyClientXRun(int refnum)
371 {
372  if (refnum == ALL_CLIENTS) {
373  NotifyClients(kXRunCallback, false, "", 0, 0);
374  } else {
375  NotifyClient(refnum, kXRunCallback, false, "", 0, 0);
376  }
377 }
378 
379 void JackEngine::NotifyGraphReorder()
380 {
381  ComputeTotalLatencies();
382  NotifyClients(kGraphOrderCallback, false, "", 0, 0);
383 }
384 
385 void JackEngine::NotifyBufferSize(jack_nframes_t buffer_size)
386 {
387  NotifyClients(kBufferSizeCallback, true, "", buffer_size, 0);
388 }
389 
390 void JackEngine::NotifySampleRate(jack_nframes_t sample_rate)
391 {
392  NotifyClients(kSampleRateCallback, true, "", sample_rate, 0);
393 }
394 
395 void JackEngine::NotifyFailure(int code, const char* reason)
396 {
397  NotifyClients(kShutDownCallback, false, reason, code, 0);
398 }
399 
400 void JackEngine::NotifyFreewheel(bool onoff)
401 {
402  if (onoff) {
403  // Save RT state
404  fEngineControl->fSavedRealTime = fEngineControl->fRealTime;
405  fEngineControl->fRealTime = false;
406  } else {
407  // Restore RT state
408  fEngineControl->fRealTime = fEngineControl->fSavedRealTime;
409  fEngineControl->fSavedRealTime = false;
410  }
411  NotifyClients((onoff ? kStartFreewheelCallback : kStopFreewheelCallback), true, "", 0, 0);
412 }
413 
414 void JackEngine::NotifyPortRegistation(jack_port_id_t port_index, bool onoff)
415 {
416  NotifyClients((onoff ? kPortRegistrationOnCallback : kPortRegistrationOffCallback), false, "", port_index, 0);
417 }
418 
419 void JackEngine::NotifyPortRename(jack_port_id_t port, const char* old_name)
420 {
421  NotifyClients(kPortRenameCallback, false, old_name, port, 0);
422 }
423 
424 void JackEngine::NotifyPortConnect(jack_port_id_t src, jack_port_id_t dst, bool onoff)
425 {
426  NotifyClients((onoff ? kPortConnectCallback : kPortDisconnectCallback), false, "", src, dst);
427 }
428 
429 void JackEngine::NotifyActivate(int refnum)
430 {
431  NotifyClient(refnum, kActivateClient, true, "", 0, 0);
432 }
433 
434 //----------------------------
435 // Loadable client management
436 //----------------------------
437 
438 int JackEngine::GetInternalClientName(int refnum, char* name_res)
439 {
440  JackClientInterface* client = fClientTable[refnum];
441  assert(client);
442  strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
443  return 0;
444 }
445 
446 int JackEngine::InternalClientHandle(const char* client_name, int* status, int* int_ref)
447 {
448  // Clear status
449  *status = 0;
450 
451  for (int i = 0; i < CLIENT_NUM; i++) {
452  JackClientInterface* client = fClientTable[i];
453  if (client && dynamic_cast<JackLoadableInternalClient*>(client) && (strcmp(client->GetClientControl()->fName, client_name) == 0)) {
454  jack_log("InternalClientHandle found client name = %s ref = %ld", client_name, i);
455  *int_ref = i;
456  return 0;
457  }
458  }
459 
460  *status |= (JackNoSuchClient | JackFailure);
461  return -1;
462 }
463 
464 int JackEngine::InternalClientUnload(int refnum, int* status)
465 {
466  JackClientInterface* client = fClientTable[refnum];
467  if (client) {
468  int res = client->Close();
469  delete client;
470  *status = 0;
471  return res;
472  } else {
473  *status = (JackNoSuchClient | JackFailure);
474  return -1;
475  }
476 }
477 
478 //-------------------
479 // Client management
480 //-------------------
481 
482 int JackEngine::ClientCheck(const char* name, jack_uuid_t uuid, char* name_res, int protocol, int options, int* status)
483 {
484  // Clear status
485  *status = 0;
486  strcpy(name_res, name);
487 
488  jack_log("Check protocol client = %ld server = %ld", protocol, JACK_PROTOCOL_VERSION);
489 
490  if (protocol != JACK_PROTOCOL_VERSION) {
491  *status |= (JackFailure | JackVersionError);
492  jack_error("JACK protocol mismatch (%d vs %d)", protocol, JACK_PROTOCOL_VERSION);
493  return -1;
494  }
495 
496  std::map<int,std::string>::iterator res = fReservationMap.find(uuid);
497 
498  if (res != fReservationMap.end()) {
499  strncpy(name_res, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
500  } else if (ClientCheckName(name)) {
501 
502  *status |= JackNameNotUnique;
503 
504  if (options & JackUseExactName) {
505  jack_error("cannot create new client; %s already exists", name);
506  *status |= JackFailure;
507  return -1;
508  }
509 
510  if (GenerateUniqueName(name_res)) {
511  *status |= JackFailure;
512  return -1;
513  }
514  }
515 
516  return 0;
517 }
518 
519 bool JackEngine::GenerateUniqueName(char* name)
520 {
521  int tens, ones;
522  int length = strlen(name);
523 
524  if (length > JACK_CLIENT_NAME_SIZE - 4) {
525  jack_error("%s exists and is too long to make unique", name);
526  return true; /* failure */
527  }
528 
529  /* generate a unique name by appending "-01".."-99" */
530  name[length++] = '-';
531  tens = length++;
532  ones = length++;
533  name[tens] = '0';
534  name[ones] = '1';
535  name[length] = '\0';
536 
537  while (ClientCheckName(name)) {
538  if (name[ones] == '9') {
539  if (name[tens] == '9') {
540  jack_error("client %s has 99 extra instances already", name);
541  return true; /* give up */
542  }
543  name[tens]++;
544  name[ones] = '0';
545  } else {
546  name[ones]++;
547  }
548  }
549  return false;
550 }
551 
552 bool JackEngine::ClientCheckName(const char* name)
553 {
554  for (int i = 0; i < CLIENT_NUM; i++) {
555  JackClientInterface* client = fClientTable[i];
556  if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
557  return true;
558  }
559  }
560 
561  for (std::map<int,std::string>::iterator i = fReservationMap.begin(); i != fReservationMap.end(); i++) {
562  if (i->second == name) {
563  return true;
564  }
565  }
566 
567  return false;
568 }
569 
570 void JackEngine::EnsureUUID(jack_uuid_t uuid)
571 {
572  if (jack_uuid_empty(uuid))
573  return;
574 
575  for (int i = 0; i < CLIENT_NUM; i++) {
576  JackClientInterface* client = fClientTable[i];
577  if (client && jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
578  // FIXME? this code does nothing, but jack1 has it like this too..
579  jack_uuid_clear (&uuid);
580  // client->GetClientControl()->fSessionID = jack_client_uuid_generate();
581  }
582  }
583 }
584 
585 int JackEngine::GetClientPID(const char* name)
586 {
587  for (int i = 0; i < CLIENT_NUM; i++) {
588  JackClientInterface* client = fClientTable[i];
589  if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
590  return client->GetClientControl()->fPID;
591  }
592  }
593 
594  return 0;
595 }
596 
597 int JackEngine::GetClientRefNum(const char* name)
598 {
599  for (int i = 0; i < CLIENT_NUM; i++) {
600  JackClientInterface* client = fClientTable[i];
601  if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
602  return client->GetClientControl()->fRefNum;
603  }
604  }
605 
606  return -1;
607 }
608 
609 // Used for external clients
610 int JackEngine::ClientExternalOpen(const char* name, int pid, jack_uuid_t uuid, int* ref, int* shared_engine, int* shared_client, int* shared_graph_manager)
611 {
612  char real_name[JACK_CLIENT_NAME_SIZE + 1];
613 
614  if (jack_uuid_empty(uuid)) {
615  uuid = jack_client_uuid_generate();
616  strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
617  } else {
618  std::map<int, std::string>::iterator res = fReservationMap.find(uuid);
619  if (res != fReservationMap.end()) {
620  strncpy(real_name, res->second.c_str(), JACK_CLIENT_NAME_SIZE);
621  fReservationMap.erase(uuid);
622  } else {
623  strncpy(real_name, name, JACK_CLIENT_NAME_SIZE);
624  }
625  EnsureUUID(uuid);
626  }
627 
628  jack_log("JackEngine::ClientExternalOpen: uuid = %d, name = %s", uuid, real_name);
629 
630  int refnum = AllocateRefnum();
631  if (refnum < 0) {
632  jack_error("No more refnum available");
633  return -1;
634  }
635 
636  JackExternalClient* client = new JackExternalClient();
637 
638  if (!fSynchroTable[refnum].Allocate(real_name, fEngineControl->fServerName, 0)) {
639  jack_error("Cannot allocate synchro");
640  goto error;
641  }
642 
643  if (client->Open(real_name, pid, refnum, uuid, shared_client) < 0) {
644  jack_error("Cannot open client");
645  goto error;
646  }
647 
648  if (!fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
649  // Failure if RT thread is not running (problem with the driver...)
650  jack_error("Driver is not running");
651  goto error;
652  }
653 
654  fClientTable[refnum] = client;
655 
656  if (NotifyAddClient(client, real_name, refnum) < 0) {
657  jack_error("Cannot notify add client");
658  goto error;
659  }
660 
661  fGraphManager->InitRefNum(refnum);
662  fEngineControl->ResetRollingUsecs();
663  *shared_engine = fEngineControl->GetShmIndex();
664  *shared_graph_manager = fGraphManager->GetShmIndex();
665  *ref = refnum;
666  return 0;
667 
668 error:
669  // Cleanup...
670  fSynchroTable[refnum].Destroy();
671  fClientTable[refnum] = 0;
672  client->Close();
673  delete client;
674  return -1;
675 }
676 
677 // Used for server driver clients
678 int JackEngine::ClientInternalOpen(const char* name, int* ref, JackEngineControl** shared_engine, JackGraphManager** shared_manager, JackClientInterface* client, bool wait)
679 {
680  jack_log("JackEngine::ClientInternalOpen: name = %s", name);
681 
682  int refnum = AllocateRefnum();
683  if (refnum < 0) {
684  jack_error("No more refnum available");
685  goto error;
686  }
687 
688  if (!fSynchroTable[refnum].Allocate(name, fEngineControl->fServerName, 0)) {
689  jack_error("Cannot allocate synchro");
690  goto error;
691  }
692 
693  if (wait && !fSignal.LockedTimedWait(DRIVER_OPEN_TIMEOUT * 1000000)) {
694  // Failure if RT thread is not running (problem with the driver...)
695  jack_error("Driver is not running");
696  goto error;
697  }
698 
699  fClientTable[refnum] = client;
700 
701  if (NotifyAddClient(client, name, refnum) < 0) {
702  jack_error("Cannot notify add client");
703  goto error;
704  }
705 
706  fGraphManager->InitRefNum(refnum);
707  fEngineControl->ResetRollingUsecs();
708  *shared_engine = fEngineControl;
709  *shared_manager = fGraphManager;
710  *ref = refnum;
711  return 0;
712 
713 error:
714  // Cleanup...
715  fSynchroTable[refnum].Destroy();
716  fClientTable[refnum] = 0;
717  return -1;
718 }
719 
720 // Used for external clients
721 int JackEngine::ClientExternalClose(int refnum)
722 {
723  jack_log("JackEngine::ClientExternalClose ref = %ld", refnum);
724  JackClientInterface* client = fClientTable[refnum];
725  assert(client);
726  int res = ClientCloseAux(refnum, true);
727  client->Close();
728  delete client;
729  return res;
730 }
731 
732 // Used for server internal clients or drivers when the RT thread is stopped
733 int JackEngine::ClientInternalClose(int refnum, bool wait)
734 {
735  jack_log("JackEngine::ClientInternalClose ref = %ld", refnum);
736  return ClientCloseAux(refnum, wait);
737 }
738 
739 int JackEngine::ClientCloseAux(int refnum, bool wait)
740 {
741  jack_log("JackEngine::ClientCloseAux ref = %ld", refnum);
742 
743  JackClientInterface* client = fClientTable[refnum];
744  fEngineControl->fTransport.ResetTimebase(refnum);
745 
746  jack_uuid_t uuid = JACK_UUID_EMPTY_INITIALIZER;
747  jack_uuid_copy (&uuid, client->GetClientControl()->fSessionID);
748 
749  // Unregister all ports ==> notifications are sent
750  jack_int_t ports[PORT_NUM_FOR_CLIENT];
751  int i;
752 
753  fGraphManager->GetInputPorts(refnum, ports);
754  for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
755  PortUnRegister(refnum, ports[i]);
756  }
757 
758  fGraphManager->GetOutputPorts(refnum, ports);
759  for (i = 0; (i < PORT_NUM_FOR_CLIENT) && (ports[i] != EMPTY); i++) {
760  PortUnRegister(refnum, ports[i]);
761  }
762 
763  // Remove the client from the table
764  ReleaseRefnum(refnum);
765 
766  // Remove all ports
767  fGraphManager->RemoveAllPorts(refnum);
768 
769  // Wait until next cycle to be sure client is not used anymore
770  if (wait) {
771  if (!fSignal.LockedTimedWait(fEngineControl->fTimeOutUsecs * 2)) { // Must wait at least until a switch occurs in Process, even in case of graph end failure
772  jack_error("JackEngine::ClientCloseAux wait error ref = %ld", refnum);
773  }
774  }
775 
776  if (fMetadata.RemoveProperties(NULL, uuid) > 0) {
777  /* have to do the notification ourselves, since the client argument
778  to fMetadata->RemoveProperties() was NULL
779  */
780  PropertyChangeNotify(uuid, NULL, PropertyDeleted);
781  }
782 
783  // Notify running clients
784  NotifyRemoveClient(client->GetClientControl()->fName, refnum);
785 
786  // Cleanup...
787  fSynchroTable[refnum].Destroy();
788  fEngineControl->ResetRollingUsecs();
789  return 0;
790 }
791 
792 int JackEngine::ClientActivate(int refnum, bool is_real_time)
793 {
794  JackClientInterface* client = fClientTable[refnum];
795  jack_log("JackEngine::ClientActivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
796 
797  if (is_real_time) {
798  fGraphManager->Activate(refnum);
799  }
800 
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);
810 
811  // Notify client
812  NotifyActivate(refnum);
813 
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);
817  }
818  for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
819  NotifyPortRegistation(output_ports[i], true);
820  }
821 
822  return 0;
823  }
824 }
825 
826 // May be called without client
827 int JackEngine::ClientDeactivate(int refnum)
828 {
829  JackClientInterface* client = fClientTable[refnum];
830  jack_log("JackEngine::ClientDeactivate ref = %ld name = %s", refnum, client->GetClientControl()->fName);
831 
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);
836 
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);
840  }
841  for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
842  PortDisconnect(-1, output_ports[i], ALL_PORTS);
843  }
844 
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);
848  }
849  for (int i = 0; (i < PORT_NUM_FOR_CLIENT) && (output_ports[i] != EMPTY); i++) {
850  NotifyPortRegistation(output_ports[i], false);
851  }
852 
853  fGraphManager->Deactivate(refnum);
854  fLastSwitchUsecs = 0; // Force switch to occur next cycle, even when called with "dead" clients
855 
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;
862  }
863 }
864 
865 void JackEngine::ClientKill(int refnum)
866 {
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);
870  }
871  if (ClientExternalClose(refnum) < 0) {
872  jack_error("JackEngine::ClientKill ref = %ld cannot be closed", refnum);
873  }
874 }
875 
876 //-----------------
877 // Port management
878 //-----------------
879 
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)
881 {
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];
884 
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;
889  }
890 
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);
896  }
897  return 0;
898  } else {
899  return -1;
900  }
901 }
902 
903 int JackEngine::PortUnRegister(int refnum, jack_port_id_t port_index)
904 {
905  jack_log("JackEngine::PortUnRegister ref = %ld port_index = %ld", refnum, port_index);
906  JackClientInterface* client = fClientTable[refnum];
907  assert(client);
908 
909  // Disconnect port ==> notification is sent
910  PortDisconnect(-1, port_index, ALL_PORTS);
911 
912  if (fGraphManager->ReleasePort(refnum, port_index) == 0) {
913  const jack_uuid_t uuid = jack_port_uuid_generate(port_index);
914  if (!jack_uuid_empty(uuid))
915  {
916  if (fMetadata.RemoveProperties(NULL, uuid) > 0) {
917  /* have to do the notification ourselves, since the client argument
918  to fMetadata->RemoveProperties() was NULL
919  */
920  PropertyChangeNotify(uuid, NULL, PropertyDeleted);
921  }
922  }
923 
924  if (client->GetClientControl()->fActive) {
925  NotifyPortRegistation(port_index, false);
926  }
927  return 0;
928  } else {
929  return -1;
930  }
931 }
932 
933 // this check is to prevent apps to self connect to other apps
934 // TODO: make this work with multiple clients per app
935 int JackEngine::CheckPortsConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
936 {
937  if (fSelfConnectMode == ' ') return 1;
938 
939  JackPort* src_port = fGraphManager->GetPort(src);
940  JackPort* dst_port = fGraphManager->GetPort(dst);
941 
942  jack_log("JackEngine::CheckPortsConnect(ref = %d, src = %d, dst = %d)", refnum, src_port->GetRefNum(), dst_port->GetRefNum());
943 
944  //jack_log("%s -> %s", src_port->GetName(), dst_port->GetName());
945  //jack_log("mode = '%c'", fSelfConnectMode);
946 
947  int src_self = src_port->GetRefNum() == refnum ? 1 : 0;
948  int dst_self = dst_port->GetRefNum() == refnum ? 1 : 0;
949 
950  //jack_log("src_self is %s", src_self ? "true" : "false");
951  //jack_log("dst_self is %s", dst_self ? "true" : "false");
952 
953  // 0 means client is connecting other client ports (control app patchbay functionality)
954  // 1 means client is connecting its own port to port of other client (e.g. self connecting into "system" client)
955  // 2 means client is connecting its own ports (for app internal functionality)
956  int sum = src_self + dst_self;
957  //jack_log("sum = %d", sum);
958  if (sum == 0) return 1;
959  char lmode = tolower(fSelfConnectMode);
960  //jack_log("lmode = '%c'", lmode);
961  if (sum == 2 && lmode == 'e') return 1;
962  bool fail = lmode != fSelfConnectMode; // fail modes are upper case
963  //jack_log("fail = %d", (int)fail);
964 
965  jack_info(
966  "%s port self connect request%s (%s -> %s)",
967  fail ? "rejecting" : "ignoring",
968  sum == 1 ? " to external port" : "",
969  src_port->GetName(),
970  dst_port->GetName());
971 
972  return fail ? -1 : 0;
973 }
974 
975 int JackEngine::PortConnect(int refnum, const char* src, const char* dst)
976 {
977  jack_log("JackEngine::PortConnect ref = %d src = %s dst = %s", refnum, src, dst);
978  jack_port_id_t port_src, port_dst;
979 
980  return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
981  ? -1
982  : PortConnect(refnum, port_src, port_dst);
983 }
984 
985 int JackEngine::PortConnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
986 {
987  jack_log("JackEngine::PortConnect ref = %d src = %d dst = %d", refnum, src, dst);
988  JackClientInterface* client;
989  int ref;
990 
991  if (fGraphManager->CheckPorts(src, dst) < 0) {
992  return -1;
993  }
994 
995  ref = fGraphManager->GetOutputRefNum(src);
996  assert(ref >= 0);
997  client = fClientTable[ref];
998  assert(client);
999  if (!client->GetClientControl()->fActive) {
1000  jack_error("Cannot connect ports owned by inactive clients:"
1001  " \"%s\" is not active", client->GetClientControl()->fName);
1002  return -1;
1003  }
1004 
1005  ref = fGraphManager->GetInputRefNum(dst);
1006  assert(ref >= 0);
1007  client = fClientTable[ref];
1008  assert(client);
1009  if (!client->GetClientControl()->fActive) {
1010  jack_error("Cannot connect ports owned by inactive clients:"
1011  " \"%s\" is not active", client->GetClientControl()->fName);
1012  return -1;
1013  }
1014 
1015  int res = CheckPortsConnect(refnum, src, dst);
1016  if (res != 1) {
1017  return res;
1018  }
1019 
1020  res = fGraphManager->Connect(src, dst);
1021  if (res == 0) {
1022  NotifyPortConnect(src, dst, true);
1023  }
1024  return res;
1025 }
1026 
1027 int JackEngine::PortDisconnect(int refnum, const char* src, const char* dst)
1028 {
1029  jack_log("JackEngine::PortDisconnect ref = %d src = %s dst = %s", refnum, src, dst);
1030  jack_port_id_t port_src, port_dst;
1031 
1032  return (fGraphManager->GetTwoPorts(src, dst, &port_src, &port_dst) < 0)
1033  ? -1
1034  : PortDisconnect(refnum, port_src, port_dst);
1035 }
1036 
1037 int JackEngine::PortDisconnect(int refnum, jack_port_id_t src, jack_port_id_t dst)
1038 {
1039  jack_log("JackEngine::PortDisconnect ref = %d src = %d dst = %d", refnum, src, dst);
1040 
1041  if (dst == ALL_PORTS) {
1042 
1043  jack_int_t connections[CONNECTION_NUM_FOR_PORT];
1044  fGraphManager->GetConnections(src, connections);
1045 
1046  JackPort* port = fGraphManager->GetPort(src);
1047  int res = 0;
1048  if (port->GetFlags() & JackPortIsOutput) {
1049  for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
1050  if (PortDisconnect(refnum, src, connections[i]) != 0) {
1051  res = -1;
1052  }
1053  }
1054  } else {
1055  for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && (connections[i] != EMPTY); i++) {
1056  if (PortDisconnect(refnum, connections[i], src) != 0) {
1057  res = -1;
1058  }
1059  }
1060  }
1061 
1062  return res;
1063  }
1064 
1065  if (fGraphManager->CheckPorts(src, dst) < 0) {
1066  return -1;
1067  }
1068 
1069  int res = CheckPortsConnect(refnum, src, dst);
1070  if (res != 1) {
1071  return res;
1072  }
1073 
1074  res = fGraphManager->Disconnect(src, dst);
1075  if (res == 0)
1076  NotifyPortConnect(src, dst, false);
1077  return res;
1078 }
1079 
1080 int JackEngine::PortRename(int refnum, jack_port_id_t port, const char* name)
1081 {
1082  char old_name[REAL_JACK_PORT_NAME_SIZE+1];
1083  strcpy(old_name, fGraphManager->GetPort(port)->GetName());
1084  fGraphManager->GetPort(port)->SetName(name);
1085  NotifyPortRename(port, old_name);
1086  return 0;
1087 }
1088 
1089 int JackEngine::PortSetDeviceMetadata(jack_port_id_t port, const char* pretty_name)
1090 {
1091  static const char* type = "text/plain";
1092  jack_uuid_t uuid = jack_port_uuid_generate(port);
1093 
1094  int res = fMetadata.SetProperty(NULL, uuid, JACK_METADATA_HARDWARE, pretty_name, type);
1095  if (res == -1) {
1096  return -1;
1097  }
1098 
1099  char *v, *t;
1100  res = fMetadata.GetProperty(uuid, JACK_METADATA_PRETTY_NAME, &v, &t);
1101  if (res == -1) {
1102  res = fMetadata.SetProperty(NULL, uuid, JACK_METADATA_PRETTY_NAME, pretty_name, type);
1103  }
1104 
1105  return res;
1106 }
1107 
1108 //--------------------
1109 // Session management
1110 //--------------------
1111 
1112 void JackEngine::SessionNotify(int refnum, const char *target, jack_session_event_type_t type, const char *path, detail::JackChannelTransactionInterface *socket, JackSessionNotifyResult** result)
1113 {
1114  if (fSessionPendingReplies != 0) {
1115  JackSessionNotifyResult res(-1);
1116  res.Write(socket);
1117  jack_log("JackEngine::SessionNotify ... busy");
1118  if (result != NULL) *result = NULL;
1119  return;
1120  }
1121 
1122  for (int i = 0; i < CLIENT_NUM; i++) {
1123  JackClientInterface* client = fClientTable[i];
1124  if (client && jack_uuid_empty(client->GetClientControl()->fSessionID)) {
1125  client->GetClientControl()->fSessionID = jack_client_uuid_generate();
1126  }
1127  }
1128  fSessionResult = new JackSessionNotifyResult();
1129 
1130  for (int i = 0; i < CLIENT_NUM; i++) {
1131  JackClientInterface* client = fClientTable[i];
1132  if (client && client->GetClientControl()->fCallback[kSessionCallback]) {
1133 
1134  // check if this is a notification to a specific client.
1135  if (target != NULL && strlen(target) != 0) {
1136  if (strcmp(target, client->GetClientControl()->fName)) {
1137  continue;
1138  }
1139  }
1140 
1141  char path_buf[JACK_PORT_NAME_SIZE];
1142  if (path[strlen(path) - 1] == DIR_SEPARATOR) {
1143  snprintf(path_buf, sizeof path_buf, "%s%s%c", path, client->GetClientControl()->fName, DIR_SEPARATOR);
1144  } else {
1145  snprintf(path_buf, sizeof path_buf, "%s%c%s%c", path, DIR_SEPARATOR, client->GetClientControl()->fName, DIR_SEPARATOR);
1146  }
1147 
1148  int res = JackTools::MkDir(path_buf);
1149  if (res) jack_error("JackEngine::SessionNotify: can not create session directory '%s'", path_buf);
1150 
1151  int result = client->ClientNotify(i, client->GetClientControl()->fName, kSessionCallback, true, path_buf, (int)type, 0);
1152 
1153  if (result == kPendingSessionReply) {
1154  fSessionPendingReplies += 1;
1155  } else if (result == kImmediateSessionReply) {
1156  char uuid_buf[JACK_UUID_STRING_SIZE];
1157  jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
1158  fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1159  client->GetClientControl()->fName,
1160  client->GetClientControl()->fSessionCommand,
1161  client->GetClientControl()->fSessionFlags));
1162  }
1163  }
1164  }
1165 
1166  if (result != NULL) *result = fSessionResult;
1167 
1168  if (fSessionPendingReplies == 0) {
1169  fSessionResult->Write(socket);
1170  if (result == NULL) delete fSessionResult;
1171  fSessionResult = NULL;
1172  } else {
1173  fSessionTransaction = socket;
1174  }
1175 }
1176 
1177 int JackEngine::SessionReply(int refnum)
1178 {
1179  JackClientInterface* client = fClientTable[refnum];
1180  assert(client);
1181  char uuid_buf[JACK_UUID_STRING_SIZE];
1182  jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_buf);
1183  fSessionResult->fCommandList.push_back(JackSessionCommand(uuid_buf,
1184  client->GetClientControl()->fName,
1185  client->GetClientControl()->fSessionCommand,
1186  client->GetClientControl()->fSessionFlags));
1187  fSessionPendingReplies -= 1;
1188 
1189  if (fSessionPendingReplies == 0) {
1190  fSessionResult->Write(fSessionTransaction);
1191  if (fSessionTransaction != NULL) {
1192  delete fSessionResult;
1193  }
1194  fSessionResult = NULL;
1195  }
1196 
1197  return 0;
1198 }
1199 
1200 int JackEngine::GetUUIDForClientName(const char *client_name, char *uuid_res)
1201 {
1202  for (int i = 0; i < CLIENT_NUM; i++) {
1203  JackClientInterface* client = fClientTable[i];
1204 
1205  if (client && (strcmp(client_name, client->GetClientControl()->fName) == 0)) {
1206  jack_uuid_unparse(client->GetClientControl()->fSessionID, uuid_res);
1207  return 0;
1208  }
1209  }
1210  // Did not find name.
1211  return -1;
1212 }
1213 
1214 int JackEngine::GetClientNameForUUID(const char *uuid_buf, char *name_res)
1215 {
1216  jack_uuid_t uuid;
1217  if (jack_uuid_parse(uuid_buf, &uuid) != 0)
1218  return -1;
1219 
1220  for (int i = 0; i < CLIENT_NUM; i++) {
1221  JackClientInterface* client = fClientTable[i];
1222 
1223  if (!client) {
1224  continue;
1225  }
1226 
1227  if (jack_uuid_compare(client->GetClientControl()->fSessionID, uuid) == 0) {
1228  strncpy(name_res, client->GetClientControl()->fName, JACK_CLIENT_NAME_SIZE);
1229  return 0;
1230  }
1231  }
1232  // Did not find uuid.
1233  return -1;
1234 }
1235 
1236 int JackEngine::ReserveClientName(const char *name, const char *uuidstr)
1237 {
1238  jack_log("JackEngine::ReserveClientName ( name = %s, uuid = %s )", name, uuidstr);
1239 
1240  if (ClientCheckName(name)) {
1241  jack_log("name already taken");
1242  return -1;
1243  }
1244 
1245  jack_uuid_t uuid;
1246  if (jack_uuid_parse(uuidstr, &uuid) != 0) {
1247  jack_error("JackEngine::ReserveClientName invalid uuid %s", uuidstr);
1248  return -1;
1249  }
1250 
1251  EnsureUUID(uuid);
1252  fReservationMap[uuid] = name;
1253  return 0;
1254 }
1255 
1256 int JackEngine::ClientHasSessionCallback(const char *name)
1257 {
1258  JackClientInterface* client = NULL;
1259  for (int i = 0; i < CLIENT_NUM; i++) {
1260  client = fClientTable[i];
1261  if (client && (strcmp(client->GetClientControl()->fName, name) == 0)) {
1262  break;
1263  }
1264  }
1265 
1266  if (client) {
1267  return client->GetClientControl()->fCallback[kSessionCallback];
1268  } else {
1269  return -1;
1270  }
1271 }
1272 
1273 } // end of namespace
1274 
LIB_EXPORT const char * JACK_METADATA_PRETTY_NAME
SERVER_EXPORT void jack_error(const char *fmt,...)
Definition: JackError.cpp:92
SERVER_EXPORT void jack_info(const char *fmt,...)
Definition: JackError.cpp:100
LIB_EXPORT const char * JACK_METADATA_HARDWARE
SERVER_EXPORT void jack_log(const char *fmt,...)
Definition: JackError.cpp:108