summaryrefslogtreecommitdiff
path: root/common/JackGraphManager.cpp
blob: 713c67475c9ee1aade1fe599cd09ed9d069fce22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
/*
Copyright (C) 2001 Paul Davis
Copyright (C) 2004-2008 Grame

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

*/

#include "JackGraphManager.h"
#include "JackConstants.h"
#include "JackError.h"
#include <assert.h>
#include <stdlib.h>
#include <algorithm>
#ifdef HAVE_TRE_REGEX_H
#include <tre/regex.h>
#else
#include <regex.h>
#endif

namespace Jack
{

static void AssertBufferSize(jack_nframes_t buffer_size)
{
    if (buffer_size > BUFFER_SIZE_MAX) {
        jack_log("JackGraphManager::AssertBufferSize frames = %ld", buffer_size);
        assert(buffer_size <= BUFFER_SIZE_MAX);
    }
}

void JackGraphManager::AssertPort(jack_port_id_t port_index)
{
    if (port_index >= fPortMax) {
        jack_log("JackGraphManager::AssertPort port_index = %ld", port_index);
        assert(port_index < fPortMax);
    }
}

JackGraphManager* JackGraphManager::Allocate(int port_max)
{
    // Using "Placement" new
    void* shared_ptr = JackShmMem::operator new(sizeof(JackGraphManager) + port_max * sizeof(JackPort));
    return new(shared_ptr) JackGraphManager(port_max);
}

void JackGraphManager::Destroy(JackGraphManager* manager)
{
    // "Placement" new was used
    manager->~JackGraphManager();
    JackShmMem::operator delete(manager);
}

JackGraphManager::JackGraphManager(int port_max)
{
    assert(port_max <= PORT_NUM_MAX);

    for (int i = 0; i < port_max; i++) {
        fPortArray[i].Release();
    }

    fPortMax = port_max;
}

JackPort* JackGraphManager::GetPort(jack_port_id_t port_index)
{
    AssertPort(port_index);
    return &fPortArray[port_index];
}

jack_default_audio_sample_t* JackGraphManager::GetBuffer(jack_port_id_t port_index)
{
    return fPortArray[port_index].GetBuffer();
}

// Server
void JackGraphManager::InitRefNum(int refnum)
{
    JackConnectionManager* manager = WriteNextStateStart();
    manager->InitRefNum(refnum);
    WriteNextStateStop();
}

// RT
void JackGraphManager::RunCurrentGraph()
{
    JackConnectionManager* manager = ReadCurrentState();
    manager->ResetGraph(fClientTiming);
}

// RT
bool JackGraphManager::RunNextGraph()
{
    bool res;
    JackConnectionManager* manager = TrySwitchState(&res);
    manager->ResetGraph(fClientTiming);
    return res;
}

// RT
bool JackGraphManager::IsFinishedGraph()
{
    JackConnectionManager* manager = ReadCurrentState();
    return (manager->GetActivation(FREEWHEEL_DRIVER_REFNUM) == 0);
}

// RT
int JackGraphManager::ResumeRefNum(JackClientControl* control, JackSynchro* table)
{
    JackConnectionManager* manager = ReadCurrentState();
    return manager->ResumeRefNum(control, table, fClientTiming);
}

// RT
int JackGraphManager::SuspendRefNum(JackClientControl* control, JackSynchro* table, long usec)
{
    JackConnectionManager* manager = ReadCurrentState();
    return manager->SuspendRefNum(control, table, fClientTiming, usec);
}

void JackGraphManager::TopologicalSort(std::vector<jack_int_t>& sorted)
{
    UInt16 cur_index;
    UInt16 next_index;

    do {
        cur_index = GetCurrentIndex();
        sorted.clear();
        ReadCurrentState()->TopologicalSort(sorted);
        next_index = GetCurrentIndex();
    } while (cur_index != next_index); // Until a coherent state has been read
}

// Server
void JackGraphManager::DirectConnect(int ref1, int ref2)
{
    JackConnectionManager* manager = WriteNextStateStart();
    manager->DirectConnect(ref1, ref2);
    jack_log("JackGraphManager::ConnectRefNum cur_index = %ld ref1 = %ld ref2 = %ld", CurIndex(fCounter), ref1, ref2);
    WriteNextStateStop();
}

// Server
void JackGraphManager::DirectDisconnect(int ref1, int ref2)
{
    JackConnectionManager* manager = WriteNextStateStart();
    manager->DirectDisconnect(ref1, ref2);
    jack_log("JackGraphManager::DisconnectRefNum cur_index = %ld ref1 = %ld ref2 = %ld", CurIndex(fCounter), ref1, ref2);
    WriteNextStateStop();
}

// Server
bool JackGraphManager::IsDirectConnection(int ref1, int ref2)
{
    JackConnectionManager* manager = ReadCurrentState();
    return manager->IsDirectConnection(ref1, ref2);
}

// RT
void* JackGraphManager::GetBuffer(jack_port_id_t port_index, jack_nframes_t buffer_size)
{
    AssertPort(port_index);
    AssertBufferSize(buffer_size);

    JackConnectionManager* manager = ReadCurrentState();
    JackPort* port = GetPort(port_index);

    // This happens when a port has just been unregistered and is still used by the RT code
    if (!port->IsUsed()) {
        jack_log("JackGraphManager::GetBuffer : port = %ld is released state", port_index);
        return GetBuffer(0); // port_index 0 is not used
    }

    jack_int_t len = manager->Connections(port_index);

    // Output port
    if (port->fFlags & JackPortIsOutput) {
        return (port->fTied != NO_PORT) ? GetBuffer(port->fTied, buffer_size) : GetBuffer(port_index);
    }

    // No connections : return a zero-filled buffer
    if (len == 0) {
        port->ClearBuffer(buffer_size);
        return port->GetBuffer();

    // One connection
    } else if (len == 1) {
        jack_port_id_t src_index = manager->GetPort(port_index, 0);

        // Ports in same client : copy the buffer
        if (GetPort(src_index)->GetRefNum() == port->GetRefNum()) {
            void* buffers[1];
            buffers[0] = GetBuffer(src_index, buffer_size);
            port->MixBuffers(buffers, 1, buffer_size);
            return port->GetBuffer();
        // Otherwise, use zero-copy mode, just pass the buffer of the connected (output) port.
        } else {
            return GetBuffer(src_index, buffer_size);
        }

    // Multiple connections : mix all buffers
    } else {

        const jack_int_t* connections = manager->GetConnections(port_index);
        void* buffers[CONNECTION_NUM_FOR_PORT];
        jack_port_id_t src_index;
        int i;

        for (i = 0; (i < CONNECTION_NUM_FOR_PORT) && ((src_index = connections[i]) != EMPTY); i++) {
            AssertPort(src_index);
            buffers[i] = GetBuffer(src_index, buffer_size);
        }

        port->MixBuffers(buffers, i, buffer_size);
        return port->GetBuffer();
    }
}

// Server
int JackGraphManager::RequestMonitor(jack_port_id_t port_index, bool onoff) // Client
{
    AssertPort(port_index);
    JackPort* port = GetPort(port_index);

    /**
    jackd.h
        * If @ref JackPortCanMonitor is set for this @a port, turn input
        * monitoring on or off. Otherwise, do nothing.

     if (!(fFlags & JackPortCanMonitor))
    	return -1;
    */

    port->RequestMonitor(onoff);

    const jack_int_t* connections = ReadCurrentState()->GetConnections(port_index);
    if ((port->fFlags & JackPortIsOutput) == 0) { // ?? Taken from jack, why not (port->fFlags  & JackPortIsInput) ?
        jack_port_id_t src_index;
        for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && ((src_index = connections[i]) != EMPTY); i++) {
            // XXX much worse things will happen if there is a feedback loop !!!
            RequestMonitor(src_index, onoff);
        }
    }

    return 0;
}

// Client
jack_nframes_t JackGraphManager::ComputeTotalLatencyAux(jack_port_id_t port_index, jack_port_id_t src_port_index, JackConnectionManager* manager, int hop_count)
{
    const jack_int_t* connections = ReadCurrentState()->GetConnections(port_index);
    jack_nframes_t max_latency = 0;
    jack_port_id_t dst_index;

    if (hop_count > 8)
        return GetPort(port_index)->GetLatency();

    for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && ((dst_index = connections[i]) != EMPTY); i++) {
        if (src_port_index != dst_index) {
            AssertPort(dst_index);
            JackPort* dst_port = GetPort(dst_index);
            jack_nframes_t this_latency = (dst_port->fFlags & JackPortIsTerminal)
                                          ? dst_port->GetLatency()
                                          : ComputeTotalLatencyAux(dst_index, port_index, manager, hop_count + 1);
            max_latency = ((max_latency > this_latency) ? max_latency : this_latency);
        }
    }

    return max_latency + GetPort(port_index)->GetLatency();
}

// Client
int JackGraphManager::ComputeTotalLatency(jack_port_id_t port_index)
{
    UInt16 cur_index;
    UInt16 next_index;
    JackPort* port = GetPort(port_index);
    AssertPort(port_index);

    do {
        cur_index = GetCurrentIndex();
        port->fTotalLatency = ComputeTotalLatencyAux(port_index, port_index, ReadCurrentState(), 0);
        next_index = GetCurrentIndex();
    } while (cur_index != next_index); // Until a coherent state has been read

    jack_log("JackGraphManager::GetTotalLatency port_index = %ld total latency = %ld", port_index, port->fTotalLatency);
    return 0;
}

// Client
int JackGraphManager::ComputeTotalLatencies()
{
    jack_port_id_t port_index;
    for (port_index = FIRST_AVAILABLE_PORT; port_index < fPortMax; port_index++) {
        JackPort* port = GetPort(port_index);
        if (port->IsUsed()) {
            ComputeTotalLatency(port_index);
        }
    }
    return 0;
}

void JackGraphManager::RecalculateLatencyAux(jack_port_id_t port_index, jack_latency_callback_mode_t mode)
{
    const jack_int_t* connections = ReadCurrentState()->GetConnections(port_index);
    JackPort* port = GetPort(port_index);
    jack_latency_range_t latency = { UINT32_MAX, 0 };
    jack_port_id_t dst_index;

    for (int i = 0; (i < CONNECTION_NUM_FOR_PORT) && ((dst_index = connections[i]) != EMPTY); i++) {
        AssertPort(dst_index);
        JackPort* dst_port = GetPort(dst_index);
        jack_latency_range_t other_latency;

        dst_port->GetLatencyRange(mode, &other_latency);

        if (other_latency.max > latency.max) {
			latency.max = other_latency.max;
        }
		if (other_latency.min < latency.min) {
			latency.min = other_latency.min;
        }
    }

    if (latency.min == UINT32_MAX) {
		latency.min = 0;
    }

	port->SetLatencyRange(mode, &latency);
}

void JackGraphManager::RecalculateLatency(jack_port_id_t port_index, jack_latency_callback_mode_t mode)
{
    UInt16 cur_index;
    UInt16 next_index;

    do {
        cur_index = GetCurrentIndex();
        RecalculateLatencyAux(port_index, mode);
        next_index = GetCurrentIndex();
    } while (cur_index != next_index); // Until a coherent state has been read

    //jack_log("JackGraphManager::RecalculateLatency port_index = %ld", port_index);
}

// Server
void JackGraphManager::SetBufferSize(jack_nframes_t buffer_size)
{
    jack_log("JackGraphManager::SetBufferSize size = %ld", buffer_size);

    jack_port_id_t port_index;
    for (port_index = FIRST_AVAILABLE_PORT; port_index < fPortMax; port_index++) {
        JackPort* port = GetPort(port_index);
        if (port->IsUsed()) {
            port->ClearBuffer(buffer_size);
        }
    }
}

// Server
jack_port_id_t JackGraphManager::AllocatePortAux(int refnum, const char* port_name, const char* port_type, JackPortFlags flags)
{
    jack_port_id_t port_index;

    // Available ports start at FIRST_AVAILABLE_PORT (= 1), otherwise a port_index of 0 is "seen" as a NULL port by the external API...
    for (port_index = FIRST_AVAILABLE_PORT; port_index < fPortMax; port_index++) {
        JackPort* port = GetPort(port_index);
        if (!port->IsUsed()) {
            jack_log("JackGraphManager::AllocatePortAux port_index = %ld name = %s type = %s", port_index, port_name, port_type);
            if (!port->Allocate(refnum, port_name, port_type, flags)) {
                return NO_PORT;
            }
            break;
        }
    }

    return (port_index < fPortMax) ? port_index : NO_PORT;
}

// Server
jack_port_id_t JackGraphManager::AllocatePort(int refnum, const char* port_name, const char* port_type, JackPortFlags flags, jack_nframes_t buffer_size)
{
    JackConnectionManager* manager = WriteNextStateStart();
    jack_port_id_t port_index = AllocatePortAux(refnum, port_name, port_type, flags);

    if (port_index != NO_PORT) {
        JackPort* port = GetPort(port_index);
        assert(port);
        port->ClearBuffer(buffer_size);

        int res;
        if (flags & JackPortIsOutput) {
            res = manager->AddOutputPort(refnum, port_index);
        } else {
            res = manager->AddInputPort(refnum, port_index);
        }
        // Insertion failure
        if (res < 0) {
            port->Release();
            port_index = NO_PORT;
        }
    }

    WriteNextStateStop();
    return port_index;
}

// Server
int JackGraphManager::ReleasePort(int refnum, jack_port_id_t port_index)
{
    JackConnectionManager* manager = WriteNextStateStart();
    JackPort* port = GetPort(port_index);
    int res;

    if (port->fFlags & JackPortIsOutput) {
        DisconnectAllOutput(port_index);
        res = manager->RemoveOutputPort(refnum, port_index);
    } else {
        DisconnectAllInput(port_index);
        res = manager->RemoveInputPort(refnum, port_index);
    }

    port->Release();
    WriteNextStateStop();
    return res;
}

void JackGraphManager::GetInputPorts(int refnum, jack_int_t* res)
{
    JackConnectionManager* manager = WriteNextStateStart();
    const jack_int_t* input = manager->GetInputPorts(refnum);
    memcpy(res, input, sizeof(jack_int_t) * PORT_NUM_FOR_CLIENT);
    WriteNextStateStop();
}

void JackGraphManager::GetOutputPorts(int refnum, jack_int_t* res)
{
    JackConnectionManager* manager = WriteNextStateStart();
    const jack_int_t* output = manager->GetOutputPorts(refnum);
    memcpy(res, output, sizeof(jack_int_t) * PORT_NUM_FOR_CLIENT);
    WriteNextStateStop();
}

// Server
void JackGraphManager::RemoveAllPorts(int refnum)
{
    jack_log("JackGraphManager::RemoveAllPorts ref = %ld", refnum);
    JackConnectionManager* manager = WriteNextStateStart();
    jack_port_id_t port_index;

    // Warning : ReleasePort shift port to left, thus we always remove the first port until the "input" table is empty
    const jack_int_t* input = manager->GetInputPorts(refnum);
    while ((port_index = input[0]) != EMPTY) {
        int res = ReleasePort(refnum, port_index);
        if (res < 0) {
            jack_error("JackGraphManager::RemoveAllPorts failure ref = %ld port_index = %ld", refnum, port_index);
            assert(true);
            break;
        }
    }

    // Warning : ReleasePort shift port to left, thus we always remove the first port until the "output" table is empty
    const jack_int_t* output = manager->GetOutputPorts(refnum);
    while ((port_index = output[0]) != EMPTY) {
        int res = ReleasePort(refnum, port_index);
        if (res < 0) {
            jack_error("JackGraphManager::RemoveAllPorts failure ref = %ld port_index = %ld", refnum, port_index);
            assert(true);
            break;
        }
    }

    WriteNextStateStop();
}

// Server
void JackGraphManager::DisconnectAllPorts(int refnum)
{
    int i;
    jack_log("JackGraphManager::DisconnectAllPorts ref = %ld", refnum);
    JackConnectionManager* manager = WriteNextStateStart();

    const jack_int_t* input = manager->GetInputPorts(refnum);
    for (i = 0; i < PORT_NUM_FOR_CLIENT && input[i] != EMPTY ; i++) {
        DisconnectAllInput(input[i]);
    }

    const jack_int_t* output = manager->GetOutputPorts(refnum);
    for (i = 0; i < PORT_NUM_FOR_CLIENT && output[i] != EMPTY; i++) {
        DisconnectAllOutput(output[i]);
    }

    WriteNextStateStop();
}

// Server
void JackGraphManager::DisconnectAllInput(jack_port_id_t port_index)
{
    jack_log("JackGraphManager::DisconnectAllInput port_index = %ld", port_index);
    JackConnectionManager* manager = WriteNextStateStart();

    for (unsigned int i = 0; i < fPortMax; i++) {
        if (manager->IsConnected(i, port_index)) {
            jack_log("JackGraphManager::Disconnect i = %ld  port_index = %ld", i, port_index);
            Disconnect(i, port_index);
        }
    }
    WriteNextStateStop();
}

// Server
void JackGraphManager::DisconnectAllOutput(jack_port_id_t port_index)
{
    jack_log("JackGraphManager::DisconnectAllOutput port_index = %ld ", port_index);
    JackConnectionManager* manager = WriteNextStateStart();

    const jack_int_t* connections = manager->GetConnections(port_index);
    while (connections[0] != EMPTY) {
        Disconnect(port_index, connections[0]); // Warning : Disconnect shift port to left
    }
    WriteNextStateStop();
}

// Server
int JackGraphManager::DisconnectAll(jack_port_id_t port_index)
{
    AssertPort(port_index);

    JackPort* port = GetPort(port_index);
    if (port->fFlags & JackPortIsOutput) {
        DisconnectAllOutput(port_index);
    } else {
        DisconnectAllInput(port_index);
    }
    return 0;
}

// Server
void JackGraphManager::GetConnections(jack_port_id_t port_index, jack_int_t* res)
{
    JackConnectionManager* manager = WriteNextStateStart();
    const jack_int_t* connections = manager->GetConnections(port_index);
    memcpy(res, connections, sizeof(jack_int_t) * CONNECTION_NUM_FOR_PORT);
    WriteNextStateStop();
}

// Server
void JackGraphManager::Activate(int refnum)
{
    DirectConnect(FREEWHEEL_DRIVER_REFNUM, refnum);
    DirectConnect(refnum, FREEWHEEL_DRIVER_REFNUM);
}

/*
	Disconnection from the FW must be done in last otherwise an intermediate "unconnected"
	(thus unactivated) state may happen where the client is still checked for its end.
*/

// Server
void JackGraphManager::Deactivate(int refnum)
{
    // Disconnect only when needed
    if (IsDirectConnection(refnum, FREEWHEEL_DRIVER_REFNUM)) {
        DirectDisconnect(refnum, FREEWHEEL_DRIVER_REFNUM);
    } else {
        jack_log("JackServer::Deactivate client = %ld was not activated", refnum);
    }

    // Disconnect only when needed
    if (IsDirectConnection(FREEWHEEL_DRIVER_REFNUM, refnum)) {
        DirectDisconnect(FREEWHEEL_DRIVER_REFNUM, refnum);
    } else {
        jack_log("JackServer::Deactivate client = %ld was not activated", refnum);
    }
}

// Server
int JackGraphManager::GetInputRefNum(jack_port_id_t port_index)
{
    AssertPort(port_index);
    JackConnectionManager* manager = WriteNextStateStart();
    int res = manager->GetInputRefNum(port_index);
    WriteNextStateStop();
    return res;
}

// Server
int JackGraphManager::GetOutputRefNum(jack_port_id_t port_index)
{
    AssertPort(port_index);
    JackConnectionManager* manager = WriteNextStateStart();
    int res = manager->GetOutputRefNum(port_index);
    WriteNextStateStop();
    return res;
}

int JackGraphManager::Connect(jack_port_id_t port_src, jack_port_id_t port_dst)
{
    JackConnectionManager* manager = WriteNextStateStart();
    jack_log("JackGraphManager::Connect port_src = %ld port_dst = %ld", port_src, port_dst);
    JackPort* src = GetPort(port_src);
    JackPort* dst = GetPort(port_dst);
    int res = 0;

    if (!src->fInUse || !dst->fInUse) {
        if (!src->fInUse)
            jack_error("JackGraphManager::Connect port_src = %ld not used name = %s", port_src, GetPort(port_src)->fName);
        if (!dst->fInUse)
            jack_error("JackGraphManager::Connect port_dst = %ld not used name = %s", port_dst, GetPort(port_dst)->fName);
        res = -1;
        goto end;
    }
    if (src->fTypeId != dst->fTypeId) {
        jack_error("JackGraphManager::Connect different port types port_src = %ld port_dst = %ld", port_src, port_dst);
        res = -1;
        goto end;
    }
    if (manager->IsConnected(port_src, port_dst)) {
        jack_error("JackGraphManager::Connect already connected port_src = %ld port_dst = %ld", port_src, port_dst);
        res = EEXIST;
        goto end;
    }

    res = manager->Connect(port_src, port_dst);
    if (res < 0) {
        jack_error("JackGraphManager::Connect failed port_src = %ld port_dst = %ld", port_src, port_dst);
        goto end;
    }
    res = manager->Connect(port_dst, port_src);
    if (res < 0) {
        jack_error("JackGraphManager::Connect failed port_dst = %ld port_src = %ld", port_dst, port_src);
        goto end;
    }

    if (manager->IsLoopPath(port_src, port_dst)) {
        jack_log("JackGraphManager::Connect: LOOP detected");
        manager->IncFeedbackConnection(port_src, port_dst);
    } else {
        manager->IncDirectConnection(port_src, port_dst);
    }

end:
    WriteNextStateStop();
    return res;
}

// Server
int JackGraphManager::Disconnect(jack_port_id_t port_src, jack_port_id_t port_dst)
{
    JackConnectionManager* manager = WriteNextStateStart();
    jack_log("JackGraphManager::Disconnect port_src = %ld port_dst = %ld", port_src, port_dst);
    bool in_use_src = GetPort(port_src)->fInUse;
    bool in_use_dst = GetPort(port_dst)->fInUse;
    int res = 0;

    if (!in_use_src || !in_use_dst) {
        if (!in_use_src)
            jack_error("JackGraphManager::Disconnect: port_src = %ld not used name = %s", port_src, GetPort(port_src)->fName);
        if (!in_use_dst)
            jack_error("JackGraphManager::Disconnect: port_src = %ld not used name = %s", port_dst, GetPort(port_dst)->fName);
        res = -1;
        goto end;
    }
    if (!manager->IsConnected(port_src, port_dst)) {
        jack_error("JackGraphManager::Disconnect not connected port_src = %ld port_dst = %ld", port_src, port_dst);
        res = -1;
        goto end;
    }

    res = manager->Disconnect(port_src, port_dst);
    if (res < 0) {
        jack_error("JackGraphManager::Disconnect failed port_src = %ld port_dst = %ld", port_src, port_dst);
        goto end;
    }
    res = manager->Disconnect(port_dst, port_src);
    if (res < 0) {
        jack_error("JackGraphManager::Disconnect failed port_dst = %ld port_src = %ld", port_dst, port_src);
        goto end;
    }

    if (manager->IsFeedbackConnection(port_src, port_dst)) {
        jack_log("JackGraphManager::Disconnect: FEEDBACK removed");
        manager->DecFeedbackConnection(port_src, port_dst);
    } else {
        manager->DecDirectConnection(port_src, port_dst);
    }

end:
    WriteNextStateStop();
    return res;
}

// Client
int JackGraphManager::IsConnected(jack_port_id_t port_src, jack_port_id_t port_dst)
{
    JackConnectionManager* manager = ReadCurrentState();
    return manager->IsConnected(port_src, port_dst);
}

// Server
int JackGraphManager::CheckPorts(jack_port_id_t port_src, jack_port_id_t port_dst)
{
    JackPort* src = GetPort(port_src);
    JackPort* dst = GetPort(port_dst);

    if ((dst->fFlags & JackPortIsInput) == 0) {
        jack_error("Destination port in attempted (dis)connection of %s and %s is not an input port", src->fName, dst->fName);
        return -1;
    }

    if ((src->fFlags & JackPortIsOutput) == 0) {
        jack_error("Source port in attempted (dis)connection of %s and %s is not an output port", src->fName, dst->fName);
        return -1;
    }

    return 0;
}

int JackGraphManager::GetTwoPorts(const char* src_name, const char* dst_name, jack_port_id_t* port_src, jack_port_id_t* port_dst)
{
    jack_log("JackGraphManager::CheckConnect src_name = %s dst_name = %s", src_name, dst_name);

    if ((*port_src = GetPort(src_name)) == NO_PORT) {
        jack_error("Unknown source port in attempted (dis)connection src_name [%s] dst_name [%s]", src_name, dst_name);
        return -1;
    }

    if ((*port_dst = GetPort(dst_name)) == NO_PORT) {
        jack_error("Unknown destination port in attempted (dis)connection src_name [%s] dst_name [%s]", src_name, dst_name);
        return -1;
    }

    return 0;
}

// Client : port array
jack_port_id_t JackGraphManager::GetPort(const char* name)
{
    for (unsigned int i = 0; i < fPortMax; i++) {
        JackPort* port = GetPort(i);
        if (port->IsUsed() && port->NameEquals(name)) {
            return i;
        }
    }
    return NO_PORT;
}

/*!
\brief Get the connection port name array.
*/

// Client
void JackGraphManager::GetConnectionsAux(JackConnectionManager* manager, const char** res, jack_port_id_t port_index)
{
    const jack_int_t* connections = manager->GetConnections(port_index);
    jack_int_t index;
    int i;

    // Cleanup connection array
    memset(res, 0, sizeof(char*) * CONNECTION_NUM_FOR_PORT);

    for (i = 0; (i < CONNECTION_NUM_FOR_PORT) && ((index = connections[i]) != EMPTY); i++) {
        JackPort* port = GetPort(index);
        res[i] = port->fName;
    }

    res[i] = NULL;
}

/*
	Use the state returned by ReadCurrentState and check that the state was not changed during the read operation.
	The operation is lock-free since there is no intermediate state in the write operation that could cause the
	read to loop forever.
*/

// Client
const char** JackGraphManager::GetConnections(jack_port_id_t port_index)
{
    const char** res = (const char**)malloc(sizeof(char*) * CONNECTION_NUM_FOR_PORT);
    UInt16 cur_index, next_index;

    if (!res)
        return NULL;

    do {
        cur_index = GetCurrentIndex();
        GetConnectionsAux(ReadCurrentState(), res, port_index);
        next_index = GetCurrentIndex();
    } while (cur_index != next_index); // Until a coherent state has been read

    if (res[0]) {	// At least one connection
        return res;
    } else {		// Empty array, should return NULL
        free(res);
        return NULL;
    }
}

// Client
void JackGraphManager::GetPortsAux(const char** matching_ports, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags)
{
    // Cleanup port array
    memset(matching_ports, 0, sizeof(char*) * fPortMax);

    int match_cnt = 0;
    regex_t port_regex, type_regex;

    if (port_name_pattern && port_name_pattern[0]) {
        if (regcomp(&port_regex, port_name_pattern, REG_EXTENDED | REG_NOSUB)!=0) {
             jack_log("JackGraphManager::GetPortsAux could not compile regex for port_name_pattern '%s'", port_name_pattern);
             return;
        }
    }
    if (type_name_pattern && type_name_pattern[0]) {
        if (regcomp(&type_regex, type_name_pattern, REG_EXTENDED | REG_NOSUB)!=0) {
             jack_log("JackGraphManager::GetPortsAux could not compile regex for type_name_pattern '%s'", type_name_pattern);
             return;
        }
    }

    for (unsigned int i = 0; i < fPortMax; i++) {
        bool matching = true;
        JackPort* port = GetPort(i);

        if (port->IsUsed()) {

            if (flags) {
                if ((port->fFlags & flags) != flags) {
                    matching = false;
                }
            }

            if (matching && port_name_pattern && port_name_pattern[0]) {
                if (regexec(&port_regex, port->GetName(), 0, NULL, 0)) {
                    matching = false;
                }
            }
            if (matching && type_name_pattern && type_name_pattern[0]) {
                if (regexec(&type_regex, port->GetType(), 0, NULL, 0)) {
                    matching = false;
                }
            }

            if (matching) {
                matching_ports[match_cnt++] = port->fName;
            }
        }
    }

    matching_ports[match_cnt] = 0;

    if (port_name_pattern && port_name_pattern[0]) {
        regfree(&port_regex);
    }
    if (type_name_pattern && type_name_pattern[0]) {
        regfree(&type_regex);
    }
}

// Client
/*
	Check that the state was not changed during the read operation.
	The operation is lock-free since there is no intermediate state in the write operation that could cause the
	read to loop forever.
*/
const char** JackGraphManager::GetPorts(const char* port_name_pattern, const char* type_name_pattern, unsigned long flags)
{
    const char** res = (const char**)malloc(sizeof(char*) * fPortMax);
    UInt16 cur_index, next_index;

    if (!res)
        return NULL;

    do {
        cur_index = GetCurrentIndex();
        GetPortsAux(res, port_name_pattern, type_name_pattern, flags);
        next_index = GetCurrentIndex();
    } while (cur_index != next_index);  // Until a coherent state has been read

    if (res[0]) {    // At least one port
        return res;
    } else {
        free(res);   // Empty array, should return NULL
        return NULL;
    }
}

// Server
void JackGraphManager::Save(JackConnectionManager* dst)
{
    JackConnectionManager* manager = WriteNextStateStart();
    memcpy(dst, manager, sizeof(JackConnectionManager));
    WriteNextStateStop();
}

// Server
void JackGraphManager::Restore(JackConnectionManager* src)
{
    JackConnectionManager* manager = WriteNextStateStart();
    memcpy(manager, src, sizeof(JackConnectionManager));
    WriteNextStateStop();
}

} // end of namespace