File: audioio_jack_manager.cpp

package info (click to toggle)
ecasound 2.9.3-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 6,292 kB
  • sloc: cpp: 39,475; sh: 4,335; lisp: 1,918; ansic: 1,883; makefile: 888; python: 617; ruby: 202
file content (2016 lines) | stat: -rw-r--r-- 58,352 bytes parent folder | download | duplicates (5)
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
// ------------------------------------------------------------------------
// audioio_jack_manager.cpp: Manager for JACK client objects
// Copyright (C) 2001-2004,2008,2009,2011 Kai Vehmanen
//
// Attributes:
//     eca-style-version: 3
//
// References:
//     http://jackit.sourceforge.net/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 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 General Public License for more details.
// 
// You should have received a copy of the GNU 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
// ------------------------------------------------------------------------

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <algorithm> /* std::count() */
#include <iostream>
#include <string>
#include <utility>

#include <sys/time.h> /* gettimeofday() */
#include <errno.h> /* ETIMEDOUT */
#include <jack/jack.h>

#include <kvu_dbc.h>
#include <kvu_numtostr.h>
#include <kvu_procedure_timer.h>
#include <kvu_threads.h>

#include "audioio.h"
#include "eca-engine.h"
#include "eca-chainsetup.h"
#include "eca-logger.h"

#include <cstring>

/**
 * Enable and disable features
 */

/* Debug control flow */ 
// #define DEBUG_CFLOW

/* Profile callback execution */
// #define PROFILE_CALLBACK_EXECUTION

/**
 * Local macro definitions
 */

#ifdef DEBUG_CFLOW
#define DEBUG_CFLOW_STATEMENT(x) (x)
#else
#define DEBUG_CFLOW_STATEMENT(x) ((void)0)
#endif

#ifdef PROFILE_CALLBACK_EXECUTION
#define PROFILE_CE_STATEMENT(x) (x)
static PROCEDURE_TIMER profile_callback_timer;
#else
#define PROFILE_CE_STATEMENT(x) ((void)0)
#endif

/**
 * Prototypes for static functions
 */

static int eca_jack_process_callback(jack_nframes_t nframes, void *arg);

#if ECA_JACK_TRANSPORT_API >= 3
static int eca_jack_sync_callback(jack_transport_state_t state, jack_position_t *pos, void *arg);
static void eca_jack_sync_start_seek_to(jack_transport_state_t state, jack_position_t *pos, void *arg);
static void eca_jack_sync_start_live_seek_to(jack_transport_state_t state, jack_position_t *pos, void *arg);
static void eca_jack_process_timebase_slave(jack_nframes_t nframes, void *arg);
#endif

static void eca_jack_process_engine_iteration(jack_nframes_t nframes, void *arg);
static void eca_jack_process_mute(jack_nframes_t nframes, void* arg);
#ifdef PROFILE_CALLBACK_EXECUTION
static void eca_jack_process_profile_pre(void);
static void eca_jack_process_profile_post(void);
#endif
static int eca_jack_bsize_cb(jack_nframes_t nframes, void *arg);
static int eca_jack_srate_cb(jack_nframes_t nframes, void *arg);
static void eca_jack_shutdown_cb(void *arg);

static std::string eca_get_jack_port_item(const char **ports, int item);

#include "audioio_jack_manager.h"

using std::cerr;
using std::endl;
using std::list;
using std::string;
using std::vector;

/**
 * Implementations of static functions
 */

/**
 * How many ecasound JACK manager instances 
 * can run at the same time (affects connection
 * setup time in some situations).
 */
const int AUDIO_IO_JACK_MANAGER::instance_limit = 8;

/**
 * Context help:
 *  J = originates from JACK callback
 *  E = ----- " ------- engine thread (exec())
 *  C = ----- " ------- control/client thread
 */

#if ECA_JACK_TRANSPORT_API >= 3
/**
 * JACK sync callback function. Called when someone has 
 * issued a state change request.
 *
 * context: J-level-0
 */
static int eca_jack_sync_callback(jack_transport_state_t state, jack_position_t *pos, void *arg)
{
  // DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_SYNC: entering...");

  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);
  int result = 1; /* ready for rolling */

  if (current->exit_request_rep == 1 || current->shutdown_request_rep == 1) { 
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: after exit/shutdown!!!" << endl); 
    return 0;
  }

  /* try to get the driver lock; if it fails or connection 
   * is not fully establish, skip this processing cycle */
  int ret = pthread_mutex_trylock(&current->engine_mod_lock_rep);
  if (ret == 0) {
    SAMPLE_SPECS::sample_pos_t enginepos = current->engine_repp->current_position_in_samples();

    /* 1. engine locked for editing, do not touch! */
    // 2012/May: no longer needed
    
    /* 2. transport stopped */
    if (state == JackTransportStopped) {
      DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: JACK stopped" << endl);
      
      /* 2.1 engine at correct place; report success */
      if (enginepos == pos->frame) {
	result = 1;
      }
      /* 2.2 only start seek if engine is not already at correct place */
      else if (current->jackslave_seekahead_target_rep == -1) {
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: stopped - starting seek to "
			      << pos->frame << "." << endl);
	eca_jack_sync_start_seek_to(state, pos, arg);
      }
      result = 0;
    }
    
    /* 3. transport  starting (or looping, all these states are fine to us, as 
       is the case where state info is not available at all) */
    else if (state == JackTransportStarting) {
      DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: JACK starting" << endl);
      /* 3.1 engine at correct position */
      if (enginepos == pos->frame) {
	/* 3.1.1 engine ready for process callback; return positive */
	if (current->engine_repp->is_prepared() &&
	    current->engine_repp->is_running()) {
	  DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: JACK running; correct position, engine running\n");
	  result = 1;
	  current->jackslave_seekahead_target_rep = -1;
	}
	/* 3.1.2 engine not ready for process callback; request start */
	else {
	  current->start_request_rep++;
	  current->engine_repp->command(ECA_ENGINE::ep_start, 0.0f);
	  result = 0;
	}
      }
      /* 3.2 engine at the wrong position but no seek target set; restart seek */
      else if (current->jackslave_seekahead_target_rep == -1) {
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: starting - new seek to "
			      << pos->frame << "." << endl);
	eca_jack_sync_start_seek_to(state, pos, arg);
	result = 0;
      }
      /* 3.3 engine at the wrong position; seek still ongoing */
      else {
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: still seeking, pos=" 
			      << pos->frame 
			      << ", enginepos=" << enginepos << "." << endl);
	if (pos->frame != static_cast<unsigned long>(current->jackslave_seekahead_target_rep)) {
	  eca_jack_sync_start_seek_to(state, pos, arg);
	}
	result = 0;
      }
    }
    
    /* 4. slow-start timeout elapsed; transport forced to rolling */
    else {
      DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: JACK running, forced, trying to catch up" << endl);
      
      eca_jack_sync_start_live_seek_to(state, pos, arg);
    }

    pthread_mutex_unlock(&current->engine_mod_lock_rep);
  }
  else {
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: couldn't get lock" << endl);
    result = 0;
  }

  return result;
}
#endif

#if ECA_JACK_TRANSPORT_API >= 3
/**
 * Helper function to start seeking to a new position.
 *
 * context: J-level-1
 */
static void eca_jack_sync_start_seek_to(jack_transport_state_t state, jack_position_t *pos, void *arg)
{
  // DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_sync_start_seek_to(): entering...");

  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);
  SAMPLE_SPECS::sample_pos_t enginepos = current->engine_repp->current_position_in_samples();

  /* prepare for the next start by seeking to the correct position */
  if (enginepos != pos->frame) {
    current->jackslave_seekahead_target_rep = pos->frame;
    current->engine_repp->command(ECA_ENGINE::ep_setpos_samples, 
				  current->jackslave_seekahead_target_rep);
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_SYNC: seeking to " << pos->frame << endl);
  }

  current->engine_repp->command(ECA_ENGINE::ep_prepare, 0.0f);
}
#endif

#if ECA_JACK_TRANSPORT_API >= 3
/**
 * Helper function to start forced (live-)seeking to a new 
 * position. We have to be prepared to chase the timebase 
 * master.
 *
 * context: J-level-1/2
 */
static void eca_jack_sync_start_live_seek_to(jack_transport_state_t state, jack_position_t *pos, void *arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);
  SAMPLE_SPECS::sample_pos_t enginepos = current->engine_repp->current_position_in_samples();

  if (current->is_running() != true) {
    /* transport rolling: engine not started; start it now */
    if (current->engine_repp->status() != ECA_ENGINE::engine_status_finished &&
	((pos->frame <=
	  current->engine_repp->connected_chainsetup()->length_in_samples()) ||
	 (current->engine_repp->is_finite_length() != true))) {

      /* conditions when we should start the engine 
       *  a. engine status not finished, AND...
       *   a.1. transport position not beyond csetup length, OR...
       *   a.2. csetup has infinite length
       */

      if (current->engine_repp->is_prepared() == true && 
	  (enginepos == pos->frame)) {
	current->engine_repp->start_operation();
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_FORCESYNC: Starting engine (direct)\n");
      }
      else {
	current->start_request_rep++;
	current->engine_repp->command(ECA_ENGINE::ep_start, 0.0f);
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_FORCESYNC: Starting engine (cmdpipe)\n");
	enginepos = -1;
      }
    }
  }
  else {
    DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_FORCESYNC:  engine curpos '" << 
			  current->engine_repp->current_position_in_samples() << 
			  "' doesn't match JACK curpos '" << 
			  pos->frame << "'!" << endl);

    if ((pos->frame >= current->engine_repp->connected_chainsetup()->length_in_samples() &&
	 (current->engine_repp->is_finite_length() == true))) {
      DEBUG_CFLOW_STATEMENT(cerr << endl <<
			    "eca_jack_FORCESYNC: over max length" << endl);
      current->stop_request_rep++;
      current->engine_repp->command(ECA_ENGINE::ep_stop, 0.0f);
    }
    else if (current->jackslave_seekahead_target_rep == -1 ||
	     current->jackslave_seekahead_target_rep < 
	     static_cast<long int>(pos->frame + current->buffersize()) ||
	     current->jackslave_seekahead_target_rep - current->jackslave_seekahead_rep * current->buffersize() >
	     static_cast<long int>(pos->frame + current->buffersize())) {

      /* note: we use seek-ahead to give time for the disk
	 i/o subsystem to catch up for the next round, seek-ahead 
	 must be re-initialized if...
	 a) seek-ahead target not set,
	 b) we have missed the current seek-ahead target, or
	 c) transport position has been rewinded (current seek-ahead target
	 too far in the fututre)
      */

      if (current->jackslave_seekahead_target_rep != -1) {
	/* previous seek has failed; try again with a longer look-ahead */
	current->jackslave_seekahead_rep = 
	  (current->jackslave_seekahead_rep < (65536 / current->buffersize()) ?
	   current->jackslave_seekahead_rep * 2 : (65536 / current->buffersize()));
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_FORCESYNC: seek-ahead request failed; increasing seek-ahead to "
			      << current->jackslave_seekahead_rep << endl);

      }

      current->jackslave_seekahead_target_rep = pos->frame + 
	current->jackslave_seekahead_rep * current->buffersize();

      current->engine_repp->command(ECA_ENGINE::ep_setpos_live_samples, 
				    current->jackslave_seekahead_target_rep);
      DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_FORCESYNC: seek-ahead request sent; seeking to "
			    << current->jackslave_seekahead_target_rep << endl);
    }
    else {
      /* engine is already seeking to a new pos */
      DEBUG_CFLOW_STATEMENT(cerr << endl 
			    << "eca_jack_FORCESYNC:  seek to new pos underway; " 
			    << pos->frame
			    << " is transport-curpos." <<  endl);
    }
  }
}
#endif

/**
 * Processes all registered JACK input and output ports.
 * This is the main callback function registered to 
 * the JACK framework.
 *
 * context: J-level-0
 */
static int eca_jack_process_callback(jack_nframes_t nframes, void *arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);

  PROFILE_CE_STATEMENT(eca_jack_process_profile_pre());

  if (current->exit_request_rep == 1 || current->shutdown_request_rep == 1) { 
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: after shutdown/exit!!!" << endl); 
    if (current->exit_request_rep)
      eca_jack_process_mute(nframes, current);
    return 0;
  }

  if (current->engine_repp == 0) {
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: after engine destructor!!!" << endl); 
    return 0;
  }

  /* try to get the driver lock; if it fails or connection 
   * is not fully establish, skip this processing cycle */
  int ret = pthread_mutex_trylock(&current->engine_mod_lock_rep);
  if (ret == 0) {
    // DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: got lock" << endl);
    
    /* 1. transport control processing in "notransport" and "transport" mode */
    if (current->mode_rep == AUDIO_IO_JACK_MANAGER::Transport_none ||
	current->mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send) {
      /* execute one engine iteration */
      if (current->is_running() == true) {
	eca_jack_process_engine_iteration(nframes, current);
      }
      else {
	DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: not running, mute" << endl);
	eca_jack_process_mute(nframes, current);
      }
    }
#if ECA_JACK_TRANSPORT_API >= 3
    else {
      /* 2. transport control processing in "slave" mode */
      if (current->mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive ||
	  current->mode_rep == AUDIO_IO_JACK_MANAGER::Transport_receive) {
	eca_jack_process_timebase_slave(nframes, arg);
      }
      else { /* never reached */ }
    }
#endif

    pthread_mutex_unlock(&current->engine_mod_lock_rep);
    // DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: released lock" << endl);
  }
  else {
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: couldn't get lock; muting" << endl);
    eca_jack_process_mute(nframes, current);
  }
  
  PROFILE_CE_STATEMENT(eca_jack_process_profile_post());

  return 0;
}

/**
 * Helper routine. Only called by eca_jack_process*() functions.
 *
 * context: J-level-1/
 */
static void eca_jack_process_engine_iteration(jack_nframes_t nframes, void* arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);

  /* this is guaranteed by libjack */
  DBC_CHECK(current->buffersize_rep == static_cast<long int>(nframes));

  /* FIXME: remove me! */
  if (current->buffersize_rep != static_cast<long int>(nframes)) {
    std::cerr << "JACK_MANAGER: invalid nframes! buffersize=" << current->buffersize_rep << ", nframes=" << nframes << std::endl;
  }

  if (current->engine_repp->status() != ECA_ENGINE::engine_status_finished) {

    /* 1. copy audio data from port input buffers to ecasound buffers */
    for(size_t n = 0; n < current->inports_rep.size(); n++) {
      if (current->inports_rep[n]->cb_buffer != 0) {
	jack_default_audio_sample_t* in_cb_buffer = 
	  static_cast<jack_default_audio_sample_t*>
	  (jack_port_get_buffer(current->inports_rep[n]->jackport, nframes));
	
	memcpy(current->inports_rep[n]->cb_buffer, 
	       in_cb_buffer, 
	       current->buffersize_rep * sizeof(jack_default_audio_sample_t));
      }
    }
    
    // DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_PROCESS: engine_iter_in");
  
    /* 2. execute one engine iteration */
    current->engine_repp->engine_iteration(); 
    
    // DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_PROCESS: engine_iter_out");
    
    /* 3. copy data from ecasound buffers to port output buffers */
    for(size_t n = 0; n < current->outports_rep.size(); n++) {
      if (current->outports_rep[n]->cb_buffer != 0) {
	jack_default_audio_sample_t* out_cb_buffer = 
	  static_cast<jack_default_audio_sample_t*>
	  (jack_port_get_buffer(current->outports_rep[n]->jackport, nframes));
	
	memcpy(out_cb_buffer, 
	       current->outports_rep[n]->cb_buffer, 
	       current->buffersize_rep * sizeof(jack_default_audio_sample_t));
      }
    }
  }
  else {
    /* 4. chainsetup finished, mute */
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: chainsetup finished, muting\n");
    eca_jack_process_mute(nframes, current);
  }
  
  /* 5. update engine status based on the last iteration */
  current->engine_repp->update_engine_state();
}

/**
 * Helper routine. Only called by eca_jack_process*() functions.
 *
 * context: J-level-1/2
 */
static void eca_jack_process_mute(jack_nframes_t nframes, void* arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);

  for(size_t n = 0; n < current->outports_rep.size(); n++) {
    if (current->outports_rep[n]->cb_buffer != 0) {
      jack_default_audio_sample_t* out_cb_buffer = 
	static_cast<jack_default_audio_sample_t*>
	(jack_port_get_buffer(current->outports_rep[n]->jackport, nframes));

      memset(out_cb_buffer, 
	     0, 
	     current->buffersize_rep * sizeof(jack_default_audio_sample_t));
    }
  }
}

#if ECA_JACK_TRANSPORT_API >= 3
/**
 * Helper routine. Only called by eca_jack_process_callback() function.
 *
 * context: J-level-1
 */
static void eca_jack_process_timebase_slave(jack_nframes_t nframes, void *arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);
  jack_transport_state_t jackstate;
  jack_position_t jackpos;
  bool need_mute = true;

  jackstate = jack_transport_query(current->client_repp, &jackpos);
 
  /* 1. engine locked for editing, do not touch! */
  // 2012/May: no longer needed

  /* 2. transport stopped or starting */
  if (jackstate == JackTransportStopped) {
    // DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_process_timebase_slave(): JACK state stopped" << endl);
    ++current->j_stopped_rounds_rep;
    
    /* 2.1 transport stopped and no pending start requests */
    if (current->is_running() == true && current->j_stopped_rounds_rep > 3) {
      DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_PROCESS: running, request stop" << endl);
      current->stop_request_rep++;
      current->engine_repp->command(ECA_ENGINE::ep_stop, 0.0f);
    }
  }
  /* 3. transport stopped or starting */
  else if (jackstate == JackTransportStarting) {
    DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_process_timebase_slave(): JACK state starting" << endl);
    ++current->j_stopped_rounds_rep;
  }

  /* 4. transport rolling (or looping, both states are fine to us, as 
        is the case where state info is not available at all) */
  else {
    current->j_stopped_rounds_rep = 0;

    /* 4.1 engine not running for some odd reason; try a live-seek */
    if (current->is_running() != true) {
      DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_process_timebase_slave(): not running!" << endl);
      eca_jack_sync_start_live_seek_to(jackstate, &jackpos, arg);
    }
    /* 4.2 engine running normally */
    else {
      SAMPLE_SPECS::sample_pos_t enginepos = current->engine_repp->current_position_in_samples();

      /* 4.2.1 engine at correct position, run the engine cycle */
      if (enginepos == jackpos.frame) {
	if (current->jackslave_seekahead_target_rep != -1) {
	  // report only on the first time
	  DEBUG_CFLOW_STATEMENT(cerr << "eca_jack_process_timebase_slave(): JACK running; correct position\n");
	}
	/* execute engine iteration */
	eca_jack_process_engine_iteration(nframes, current);
	current->jackslave_seekahead_target_rep = -1;
	need_mute = false;
      }
      /* 4.2.2 engine at wrong position for some odd reason; try a live-seek */
      else {
	DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_process_timebase_slave():  engine curpos '" << 
			      current->engine_repp->current_position_in_samples() << 
			      "' doesn't match JACK curpos '" << 
			      jackpos.frame << "'!" << endl);
	eca_jack_sync_start_live_seek_to(jackstate, &jackpos, arg);
      }
    }
  }
  
  if (need_mute == true) {
    eca_jack_process_mute(nframes, current);
  }
}
#endif

#ifdef PROFILE_CALLBACK_EXECUTION
static void eca_jack_process_profile_pre(void)
{
  profile_callback_timer.start();
  DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_PROCESS: entry ----> ");
}

static void eca_jack_process_profile_post(void)
{
  profile_callback_timer.stop();
  DEBUG_CFLOW_STATEMENT(cerr << endl << "eca_jack_PROCESS: process out" << endl);
  
  if (profile_callback_timer.last_duration_seconds() > 0.005f) {
    cerr << "(audioio-jack-manager) event " << profile_callback_timer.event_count();
    cerr << ", process() took " << profile_callback_timer.last_duration_seconds() * 1000;

    cerr << " msecs." << endl;
  }
  else {
    if (profile_callback_timer.event_count() < 5) {
      cerr << "(audioio-jack-manager) event " << profile_callback_timer.event_count();
      cerr << ", process() took " << profile_callback_timer.last_duration_seconds() * 1000;
      cerr << " msecs." << endl;
      
    }
  }
}
#endif /* PROFILE_CALLBACK_EXECUTION */

/**
 * Changes current sampling rate. Callback function registered
 * to the JACK framework.
 *
 * @param nframes new engine sample rate
 * @param arg pointer to a client supplied structure
 *
 * @return zero on success, non-zero on error
 */
static int eca_jack_srate_cb(jack_nframes_t nframes, void *arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);

  ECA_LOG_MSG(ECA_LOGGER::user_objects, 
	      "[callback] " + current->jackname_rep + 
	      ": setting srate to " + kvu_numtostr(nframes));

  if (static_cast<long int>(nframes) != current->srate_rep) {
    current->shutdown_request_rep = true;
    ECA_LOG_MSG(ECA_LOGGER::info, 
		"Unable to adapt to the new samplerate received from JACK, shutting down.");
  }

  return 0;
}

/**
 * Callback function that is called when the engine 
 * buffersize changes.
 *
 * context: J-level-0
 *
 * @param nframes new engine buffer size
 * @param arg pointer to a client supplied structure
 *
 * @return zero on success, non-zero on error
 */ 
static int eca_jack_bsize_cb(jack_nframes_t nframes, void *arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);

  ECA_LOG_MSG(ECA_LOGGER::user_objects, 
	      "[callback] " + current->jackname_rep + 
	      ": setting buffersize to " + kvu_numtostr(nframes));

  if (static_cast<long int>(nframes) != current->buffersize()) {
    // FIXME: leads into a segfault...?
    current->shutdown_request_rep = true;
    ECA_LOG_MSG(ECA_LOGGER::info, 
		"Unable to adapt to the new buffersize received from JACK, shutting down.");
  }

  return 0;
}

/**
 * Shuts down the callback context. Callback function registered
 * to the JACK framework.
 *
 * context: J-level-0
 */
static void eca_jack_shutdown_cb(void *arg)
{
  AUDIO_IO_JACK_MANAGER* current = static_cast<AUDIO_IO_JACK_MANAGER*>(arg);
  ECA_LOG_MSG(ECA_LOGGER::user_objects, 
	      "" + current->jackname_rep + 
	      ": [callback] jackd shutdown, stopping processing");
  current->shutdown_request_rep = true;
}

/**
 * Implementations of non-static functions
 *
 * context: E-level-0
 */
AUDIO_IO_JACK_MANAGER::AUDIO_IO_JACK_MANAGER(void)
{
  ECA_LOG_MSG(ECA_LOGGER::system_objects, "constructor");

  open_rep = false;
  activated_rep = false;

  open_clients_rep = 0;
  last_node_id_rep = 1;
  jackslave_seekahead_rep = 2;
  jackslave_seekahead_target_rep = -1;

  engine_repp = 0;
  jackname_rep = "ecasound";

  pthread_cond_init(&exit_cond_rep, NULL);
  pthread_mutex_init(&exit_mutex_rep, NULL);
  pthread_mutex_init(&engine_mod_lock_rep, NULL);

  mode_rep = AUDIO_IO_JACK_MANAGER::Transport_invalid;

  shutdown_request_rep = false;
  cb_allocated_frames_rep = 0;
  buffersize_rep = 0;
}

/**
 * Class destructor.
 *
 * context: E-level-0
 */
AUDIO_IO_JACK_MANAGER::~AUDIO_IO_JACK_MANAGER(void)
{
  ECA_LOG_MSG(ECA_LOGGER::system_objects, "destructor");

  /* 1. close JACK connection */
  if (is_open() == true) close_server_connection();

  /* 2. clear input ports */
  vector<eca_jack_port_data_t*>::iterator q = inports_rep.begin();
  while(q != inports_rep.end()) {
    if ((*q)->cb_buffer != 0) {
      delete[] (*q)->cb_buffer;
      (*q)->cb_buffer = 0;
    }
    delete *q;
    ++q;
  }

  /* 3. clear output ports */
  q = inports_rep.begin();
  while(q != inports_rep.end()) {
    if ((*q)->cb_buffer != 0) {
      delete[] (*q)->cb_buffer;
      (*q)->cb_buffer = 0;
    }
    delete *q;
    ++q;
  }

  /* 4. clear objects */
  list<eca_jack_node_t*>::iterator p = node_list_rep.begin();
  while(p != node_list_rep.end()) {
    delete *p;
    ++p;
  }
}

/**
 * context: C-level-1
 */
bool AUDIO_IO_JACK_MANAGER::is_managed_type(const AUDIO_IO* aobj) const
{
  // ---
  DBC_REQUIRE(aobj != 0);
  // ---

  if (aobj->name() == "JACK interface") {
    DBC_CHECK(dynamic_cast<const AUDIO_IO_JACK*>(aobj) != 0);
    return(true);
  }

  return false;
}

/**
 * context: C-level-1
 */
void AUDIO_IO_JACK_MANAGER::register_object(AUDIO_IO* aobj)
{
  // ---
  DBC_REQUIRE(aobj != 0);
  DBC_REQUIRE(is_managed_type(aobj) == true);
  // ---

  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		"register object " + aobj->label());  

  AUDIO_IO_JACK* jobj = static_cast<AUDIO_IO_JACK*>(aobj);

  eca_jack_node_t* tmp = new eca_jack_node_t;
  tmp->aobj = jobj;
  tmp->origptr = aobj;
  tmp->client_id = last_node_id_rep;
  node_list_rep.push_back(tmp);

  jobj->set_manager(this, tmp->client_id);

  ++last_node_id_rep;

  // ---
  DBC_ENSURE(is_managed_type(aobj) == true);
  // ---
}

/**
 * context: C-level-0
 */
int AUDIO_IO_JACK_MANAGER::get_object_id(const AUDIO_IO* aobj) const
{
  // ---
  DBC_REQUIRE(is_managed_type(aobj) == true);
  // ---

  list<eca_jack_node_t*>::const_iterator p = node_list_rep.begin();
  while(p != node_list_rep.end()) {
    if ((*p)->origptr == aobj) {
      ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		  "found object id for aobj " +
		  aobj->name() + ": " + kvu_numtostr((*p)->client_id));
      return (*p)->client_id;
    }
    ++p;
  }
  return -1;
}

/**
 * context: C-level-0
 */
list<int> AUDIO_IO_JACK_MANAGER::get_object_list(void) const
{
  list<int> object_list;
  list<eca_jack_node_t*>::const_iterator p = node_list_rep.begin();
  while(p != node_list_rep.end()) {
    object_list.push_back((*p)->client_id);
    ++p;
  }
  return object_list;
}

/**
 * Unregisters object previously registered with register_object()
 * from the manager.
 *
 * @param id unique identifier for managed objects; @see
 *        get_object_id
 *
 * context: C-level-0
 */
void AUDIO_IO_JACK_MANAGER::unregister_object(int id)
{
  // ---
  DBC_DECLARE(unsigned int old_total_nodes = node_list_rep.size());
  // ---

  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		"unregister object ");

  list<eca_jack_node_t*>::iterator p = node_list_rep.begin();
  while(p != node_list_rep.end()) {
    if ((*p)->client_id == id) {
      ECA_LOG_MSG(ECA_LOGGER::system_objects,
		  "removing object " + (*p)->aobj->label());
      (*p)->aobj->set_manager(0, -1);

      delete *p;
      node_list_rep.erase(p);

      break;
    }
    ++p;
  }

  // ---
  DBC_ENSURE(node_list_rep.size() == old_total_nodes - 1);
  DBC_DECLARE(list<int> ol = get_object_list());
  DBC_ENSURE(std::count(ol.begin(), ol.end(), id) == 0);
  // ---
}

void AUDIO_IO_JACK_MANAGER::set_transport_mode(enum Operation_mode mode, bool print_trace)
{
  mode_rep = mode;
  
  if (print_trace == false)
    return;

  switch(mode) 
    {
    case Transport_none:
      ECA_LOG_MSG(ECA_LOGGER::info, 
		  "JACK transport: send/receive disabled (mode: notransport)");
      break;
    case Transport_receive:
      ECA_LOG_MSG(ECA_LOGGER::info,
		  "JACK transport: slave, reacting to transport events (mode: recv)");
      break;
    case Transport_send:
      ECA_LOG_MSG(ECA_LOGGER::info, 
		  "JACK transport: master, sending transport events (mode: send)");
      break;
    case Transport_send_receive:
      ECA_LOG_MSG(ECA_LOGGER::info, 
		  "JACK transport: both sending and reacting to transport events (mode: sendrecv)"); 
      break;
    case Transport_invalid:
      break;
    default:
      ;
    }
}

/**
 * context: E-level-0
 */
void AUDIO_IO_JACK_MANAGER::set_parameter(int param, std::string value)
{
  switch(param) 
    {
    case 1: 
      {
	jackname_rep = value;
	ECA_LOG_MSG(ECA_LOGGER::user_objects, 
		    "client name set to '" +
		    value + "'.");
	break;
      }

    case 2: 
      {
#if ECA_JACK_TRANSPORT_API >= 3
	if (value == "notransport" || 
	    value == "streaming") {
	  set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_none, true);
	}
	else if (value == "send" ||
		 value == "master") {
	  set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_send, true);
	}
	else if (value == "sendrecv" ||
		 value == "slave") {
	  set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_send_receive, true);
	}
	else if (value == "recv") {
	  set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_receive, true);
	}
#else
	set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_none, false);
	if (value != "notransport")
	  ECA_LOG_MSG(ECA_LOGGER::info, 
		      "WARNING: JACK transport support disabled at build time, using 'notransport'.");
#endif /* ECA_JACK_TRANSPORT_API */
	break;
      }
    }
}

/**
 * context: E-level-0
 */
std::string AUDIO_IO_JACK_MANAGER::get_parameter(int param) const
{
  switch(param) 
    {
    case 1:
      {
	return jackname_rep;
      }

    case 2: 
      { 
	switch(mode_rep) {
	case AUDIO_IO_JACK_MANAGER::Transport_none: return "notransport";
	case AUDIO_IO_JACK_MANAGER::Transport_receive: return "recv";
	case AUDIO_IO_JACK_MANAGER::Transport_send: return "send";
	case AUDIO_IO_JACK_MANAGER::Transport_send_receive: return "sendrecv";
	default: return "notransport";
	}
	break;
      }
    }
  return "";
}

/**
 * If transport is stopped, request JACK to seek to 
 * Ecasond's current position. Otherwise let Ecasound seek
 * to JACK's position.
 */
void AUDIO_IO_JACK_MANAGER::initial_seek(void)
{
#if ECA_JACK_TRANSPORT_API >= 3
  jack_transport_state_t jackstate;
  jack_position_t jackpos;

  jackstate = jack_transport_query(client_repp, &jackpos);

  if (jackstate == JackTransportStopped &&
      (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send ||
       mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive)) {
    ECA_LOG_MSG(ECA_LOGGER::info,
		"JACK transport: sending out initial locate to " +
		kvu_numtostr(engine_repp->current_position_in_seconds_exact(), 3) +
		"sec");
    jack_transport_locate(client_repp, engine_repp->current_position_in_samples());
  }
#endif
}

#if ECA_JACK_TRANSPORT_API >= 3
static std::string priv_jack_transport_state_str(jack_transport_state_t state)
{
  switch(state)
    {
    case JackTransportStopped: return "STOPPED";
    case JackTransportRolling: return "ROLLING";
    case JackTransportLooping: return "LOOPING";
    case JackTransportStarting: return "STARTING";
    default:
      ;
    }
  return std::string();
}

static std::string priv_jack_transport_pos_str(jack_position_t *state)
{
  if (state->frame_rate == 0)
    return std::string();

  return kvu_numtostr(static_cast<float>(state->frame) / state->frame_rate, 3) + "sec";
}
#endif

void AUDIO_IO_JACK_MANAGER::helper_print_transport_state(const std::string& when) const
{
#if ECA_JACK_TRANSPORT_API >= 3
  jack_position_t jpos;
  jack_transport_state_t jstate;

  jstate = jack_transport_query(client_repp, &jpos);

  ECA_LOG_MSG(ECA_LOGGER::info,
	      "JACK transport: at ecasound " +
	      when +
	      " JACK state is " + 
	      priv_jack_transport_state_str(jstate) +
	      " (position " +
	      priv_jack_transport_pos_str(&jpos) +
	      ")");
#endif
}

void AUDIO_IO_JACK_MANAGER::exec_helper_setup_transport(void)
{
  if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_invalid) {
    /* set default transport mode */
#if ECA_JACK_TRANSPORT_API >= 3
    set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_send_receive, true);
#else
    set_transport_mode(AUDIO_IO_JACK_MANAGER::Transport_none, false);
#endif
  }

  if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive ||
      mode_rep == AUDIO_IO_JACK_MANAGER::Transport_receive)
    helper_print_transport_state("start");
}

void AUDIO_IO_JACK_MANAGER::exec_helper_clean_transport(void)
{
  if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive ||
      mode_rep == AUDIO_IO_JACK_MANAGER::Transport_receive)
    helper_print_transport_state("stop");
}

/**
 * context: E-level-0
 */
int AUDIO_IO_JACK_MANAGER::exec(ECA_ENGINE* engine, ECA_CHAINSETUP* csetup)
{
  int result = 0;

  ECA_LOG_MSG(ECA_LOGGER::system_objects, "driver exec");

  engine_repp = engine;
  engine->init_engine_state();

  exec_helper_setup_transport();

  exit_request_rep = false;
  stop_request_rep = 0;
  j_stopped_rounds_rep = 0;
  start_request_rep = 0;

  activate_server_connection();
  if (is_connection_active() != true) {
    signal_exit();
  }

  initial_seek();

  while(true) {

    DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: wait for commands" << endl);

    engine_repp->wait_for_commands();

    DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: wakes up; commands available" << endl);

    /* we must take the lock to ensure that 
     * process callback does not run at the same time 
     *
     * note: the RT-optimized command queue (VALUE_QUEUE_RT_C) is not
     * safe when accessed from more than 2 threads, but here it is ok
     * as we limit concurrent threads to two with engine_mod_lock_rep
     **/

    SAMPLE_SPECS::sample_pos_t enginepos = engine_repp->current_position_in_samples();
    pthread_mutex_lock(&engine_mod_lock_rep);
    engine_repp->check_command_queue();
    if (exit_request_rep != true &&
	enginepos != engine_repp->current_position_in_samples()) {
      /* seek requested */
#if ECA_JACK_TRANSPORT_API >= 3
      if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send ||
	  mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive) {
	if (engine_repp->current_position_in_samples() != 
	    jackslave_seekahead_target_rep) {
	  DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: seek requested to pos=" 
				<< engine_repp->current_position_in_samples() << "." << endl);
	  jack_transport_locate(client_repp, engine_repp->current_position_in_samples());
	}
      }
#endif
    }
    pthread_mutex_unlock(&engine_mod_lock_rep);

    DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: check_commands finished" << endl);

    /* case 1: external exit request */
    if (exit_request_rep == true) {
      ECA_LOG_MSG(ECA_LOGGER::system_objects, "exit request in exec");
      break;
    }

    /* case 2-i: engine finished and in batch mode -> exit */
    if (engine_repp->status() == ECA_ENGINE::engine_status_finished &&
	engine_repp->batch_mode() == true) {
      ECA_LOG_MSG(ECA_LOGGER::system_objects, "batch finished in exec, exit");
      break;
    }
    
    /* case 2-ii: engine error occured -> exit */
    else if (engine_repp->status() == ECA_ENGINE::engine_status_error) {
      ECA_LOG_MSG(ECA_LOGGER::system_objects, "engine error, exit");
      break;
    }

    /* case 3: problems with jack callbacks -> exit */
    if (shutdown_request_rep == true) {
      ECA_LOG_MSG(ECA_LOGGER::system_objects, "problems with JACK callbacks");
      result = -1;
      break;
    }
  }

  DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: out of exec" << endl);

  if (is_connection_active() == true) {
    deactivate_server_connection();
  }

  exec_helper_clean_transport();
  DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: deactivated" << endl);

  pthread_mutex_lock(&engine_mod_lock_rep);
  exit_request_rep = 0;
  engine_repp = 0;
  pthread_mutex_unlock(&engine_mod_lock_rep);

  /* signal exit() that we are done */
  signal_exit();

  DEBUG_CFLOW_STATEMENT(cerr << "jack_exec: exit" << endl);

  return result;
}

/**
 * Activate connection to the JACK server.
 *
 * context: E-level-0/3
 *          Can be called at the same time with
 *          JACK callbacks, so proper locking 
 *          must be ensured (engine_mod_lock_rep taken
 *          upon entry).
 *
 * @pre is_running() != true
 * @post is_running() == true
 *
 */
void AUDIO_IO_JACK_MANAGER::start(void)
{
  // --
  DBC_REQUIRE(is_running() != true);
  // --

  ECA_LOG_MSG(ECA_LOGGER::system_objects, "driver start");

  if (engine_repp->is_prepared() != true) engine_repp->prepare_operation();
  engine_repp->start_operation();

#if ECA_JACK_TRANSPORT_API >= 3
  if (start_request_rep > 0) {
    start_request_rep = 0;
  }
  else {
    if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send ||
	mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive) {
      jack_transport_start(client_repp);
    }
  }
  j_stopped_rounds_rep = 0;
#endif

  // --
  DBC_ENSURE(is_running() == true);
  // --
}

/**
 * Signals that driver should stop operation.
 * Once stopped, driver must not call
 * any ECA_ENGINE functions.
 *
 * context: E-level-0/3
 *          Caller must ensure that JACK process callback
 *          does not run at the same time (engine_mod_lock_rep 
 *          taken upon entry).
 */
void AUDIO_IO_JACK_MANAGER::stop(bool drain)
{
  ECA_LOG_MSG(ECA_LOGGER::system_objects, "driver stop");

#if ECA_JACK_TRANSPORT_API >= 3
  if (stop_request_rep > 0) {
    stop_request_rep = 0;
  }
  else {
    if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send ||
	mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive) {
      jack_transport_stop(client_repp);
    }
  }
#endif

  if (engine_repp->is_prepared() == true) engine_repp->stop_operation(drain);
}

/**
 * Activates connection to server.
 *
 * context: E-level-1
 *
 * @pre is_connection_active() != true
 */
void AUDIO_IO_JACK_MANAGER::activate_server_connection(void)
{
  // --
  DBC_REQUIRE(is_connection_active() != true);
  // --

  if (engine_repp->is_prepared() != true) engine_repp->prepare_operation();

  ECA_LOG_MSG(ECA_LOGGER::system_objects, "jack_activate()");
  if (jack_activate (client_repp)) {
    ECA_LOG_MSG(ECA_LOGGER::info, "Error! Cannot active client!");
    activated_rep = false;
  }
  else {
    connect_all_nodes();
  
    /* update port-specific latency values */
    engine_repp->update_cache_latency_values();

    activated_rep = true;
  }
}

/**
 * Disconnects all connected ports and then
 * deactives the client.
 *
 * context: E-level-1
 *          Caller must ensure that JACK process callback
 *          does not rung at the same time.
 *
 * @pre is_connection_active() == true
 * @post is_connection_active() != true
 */
void AUDIO_IO_JACK_MANAGER::deactivate_server_connection(void)
{
  // --
  DBC_REQUIRE(is_connection_active() == true);
  // --

  if (shutdown_request_rep != true) {
    /* no need to disconnect as deactivate does that for us */
    // disconnect_all_nodes();

    ECA_LOG_MSG(ECA_LOGGER::system_objects, "jack_deactivate() ");
    if (jack_deactivate (client_repp)) {
      ECA_LOG_MSG(ECA_LOGGER::info, "Error! Cannot deactive client!");
    }
  }
 
  if (engine_repp->is_prepared() == true) engine_repp->stop_operation();

  activated_rep = false;

  signal_stop();

  // --
  DBC_ENSURE(is_connection_active() != true);
  // --
}

/**
 * Signals that driver should stop operation 
 * and return from its exec() method.
 *
 * context: E-level-0/3
 *          Can be called at the same time with
 *          JACK callbacks, so proper locking 
 *          must be ensured (caller must hold
 *          lock against the callbacks).
 */
void AUDIO_IO_JACK_MANAGER::exit(void)
{
  ECA_LOG_MSG(ECA_LOGGER::system_objects, "driver exit");
  exit_request_rep = true;
  if (engine_repp->is_prepared() == true) engine_repp->stop_operation();
}

/**
 * Returns a pointer to a 'eca_jack_node_t' structure 
 * matching client 'client_id'.
 *
 * @pre list<int> l = get_object_list(); std::count(l.begin(), l.end(), client_id) == 1
 * @return non-zero pointer
 */
AUDIO_IO_JACK_MANAGER::eca_jack_node_t* AUDIO_IO_JACK_MANAGER::get_node(int client_id)
{
  // --
  DBC_DECLARE(list<int> ol = get_object_list());
  DBC_REQUIRE(std::count(ol.begin(), ol.end(), client_id) == 1);
  // --

  eca_jack_node_t* node = 0;
  list<eca_jack_node_t*>::iterator p = node_list_rep.begin();
  while(p != node_list_rep.end()) {
    if ((*p)->client_id == client_id) { 
      node = *p;
      break;
    }
    ++p;
  }

  // --
  DBC_ENSURE(node != 0);
  // --

  return node;
}

/**
 * Sets up automatic port connection for client_id's port
 * 'portnum'. When jack client is activated, this port
 * is automatically connected to port 'portname'. The 
 * direction of the connection is based on audio objects I/O mode 
 * (@see AUDIO_IO::io_mode()).
 *
 * @pre list<int> l = get_object_list(); std::count(l.begin(), l.end(), client_id) == 1
 * @pre is_open() == true
 @ @pre portnum > 0
 */
void AUDIO_IO_JACK_MANAGER::auto_connect_jack_port(int client_id, int portnum, const string& portname)
{
  // ---
  DBC_DECLARE(list<int> ol = get_object_list());
  DBC_REQUIRE(std::count(ol.begin(), ol.end(), client_id) == 1);
  DBC_REQUIRE(is_open() == true);
  DBC_REQUIRE(portnum > 0);
  // ---

  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		"auto-connect jack ports for client " + kvu_numtostr(client_id));

  eca_jack_node_t* node = get_node(client_id);

  list<eca_jack_port_data*>::const_iterator p = node->ports.begin();
  int n = 1;
  while(p != node->ports.end()) {
    if (n == portnum) {
      (*p)->autoconnect_string = portname;
      break;
    }
    ++n;
    ++p;
  }
}

static std::string eca_get_jack_port_item(const char **ports, int item)
{
  int n = 0;
  while(ports != 0 && ports[n] != 0) {
    if (n + 1 == item) return string(ports[n]);
    n++;
  }
  return string("");
}

/**
 * Sets up automatic port connections to matching ports of
 * client 'dst'.
 *
 * @pre list<int> l = get_object_list(); std::count(l.begin(), l.end(), client_id) == 1
 * @pre is_open() == true
 @ @pre portnum > 0
 */
void AUDIO_IO_JACK_MANAGER::auto_connect_jack_port_client(int client_id, const string& dst, int channels)
{
  // ---
  DBC_DECLARE(list<int> ol = get_object_list());
  DBC_REQUIRE(std::count(ol.begin(), ol.end(), client_id) == 1);
  DBC_REQUIRE(is_open() == true);
  DBC_REQUIRE(channels > 0);
  // ---

  const char** ports;

  ECA_LOG_MSG(ECA_LOGGER::user_objects,
	      "Making autoconnection to ports matching: " + dst);
  
  eca_jack_node_t* node = get_node(client_id);
  list<eca_jack_port_data*>::const_iterator p = node->ports.begin();
  int n = 1;
  while(p != node->ports.end()) {
    if (n <= channels) {
      ports = 0;
      if (node->aobj->io_mode() == AUDIO_IO::io_read) {
	ports = jack_get_ports (client_repp, dst.c_str(), NULL, JackPortIsOutput);
      }
      else {
	ports = jack_get_ports (client_repp, dst.c_str(), NULL, JackPortIsInput);
      }
      (*p)->autoconnect_string = eca_get_jack_port_item(ports, n);
      ECA_LOG_MSG(ECA_LOGGER::user_objects,
		  "Making autoconnection to terminal port: " + 
		  (*p)->autoconnect_string +
		  ", channel " + kvu_numtostr(n));
      if (ports != NULL) free(ports);
    }
    else {
      break;
    }
    ++n;
    ++p;
  }
}

/**
 * Returns the total latency for ports of client 
 * 'client_id'. If client ports have different latency
 * values, the worst-case latency is reported.
 */
long int AUDIO_IO_JACK_MANAGER::client_latency(int client_id)
{
  eca_jack_node_t* node = get_node(client_id);
  long int latency = -1;

  list<eca_jack_port_data*>::const_iterator p = node->ports.begin();
  while(p != node->ports.end()) {
    if (latency == -1) {
      latency = (*p)->total_latency;
    }
    else {
      if (static_cast<long int>((*p)->total_latency) > latency) {
	ECA_LOG_MSG(ECA_LOGGER::info,
		    "warning! port latencies don't match for client " + kvu_numtostr(client_id));
	latency = (*p)->total_latency;
      }
    }
    ++p;
  }
 
  return latency;
}

/**
 * Registers new JACK port for client 'client_id'. The direction of
 * the port is based on audio objects I/O mode (@see
 * AUDIO_IO::io_mode()). If 'portname' is a non-empty string, 
 * the port will be automatically connected to the 'portname' 
 * port once JACK client is activated.
 *
 * The final port names are of the form 'clientname:portprefix_N', 
 * where N is 1...max_port.
 *
 * @pre list<int> l = get_object_list(); std::count(l.begin(), l.end(), client_id) == 1
 * @pre is_open() == true
 */
void AUDIO_IO_JACK_MANAGER::register_jack_ports(int client_id, int ports, const string& portprefix)
{
  // ---
  DBC_DECLARE(list<int> ol = get_object_list());
  DBC_REQUIRE(std::count(ol.begin(), ol.end(), client_id) == 1);
  DBC_REQUIRE(is_open() == true);
  DBC_DECLARE(unsigned int old_port_count_vectors = inports_rep.size() + outports_rep.size());
  // ---

  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
	      "register jack ports for client " + kvu_numtostr(client_id));

  eca_jack_node_t* node = get_node(client_id);

  for(int n = 0; n < ports; n++) {
    eca_jack_port_data_t* portdata = new eca_jack_port_data_t;

    portdata->jackport = 0;
    portdata->autoconnect_string = "";
    portdata->total_latency = 0;
    portdata->cb_buffer = new jack_default_audio_sample_t [cb_allocated_frames_rep];

    std::map<string, int>::iterator it = port_numbers_rep.find(portprefix);
    if (it == port_numbers_rep.end()) {
      it = port_numbers_rep.insert(std::make_pair(portprefix, 0)).first;
    }
    string tport = portprefix + "_" + kvu_numtostr(++it->second);

    if (node->aobj->io_mode() == AUDIO_IO::io_read) {
      portdata->jackport = jack_port_register(client_repp, 
					      tport.c_str(), 
					      JACK_DEFAULT_AUDIO_TYPE, 
					      JackPortIsInput, 
					      0);
      inports_rep.push_back(portdata);
    }
    else {
      portdata->jackport = jack_port_register(client_repp, 
					      tport.c_str(), 
					      JACK_DEFAULT_AUDIO_TYPE, 
					      JackPortIsOutput, 
					      0);
      outports_rep.push_back(portdata);
    }

    node->ports.push_back(portdata);
  }

  // ---
  DBC_ENSURE(inports_rep.size() + outports_rep.size() == 
	     old_port_count_vectors + ports);
  // ---
}

/**
 * Unregisters all JACK ports for client 'client_id'.
 *
 * @pre list<int> l = get_object_list(); std::count(l.begin(), l.end(), client_id) == 1
 * @pre is_open() == true
 * @post node->in_ports == 0 &&node->out_ports == 0
 */
void AUDIO_IO_JACK_MANAGER::unregister_jack_ports(int client_id)
{
  // ---
  DBC_DECLARE(list<int> ol = get_object_list());
  DBC_REQUIRE(std::count(ol.begin(), ol.end(), client_id) == 1);
  DBC_REQUIRE(is_open() == true);
  DBC_DECLARE(unsigned int old_node_port_count = get_node(client_id)->ports.size());
  DBC_DECLARE(unsigned int old_port_count_vectors = inports_rep.size() + outports_rep.size());
  // ---

  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		"unregister all jack ports for client " + kvu_numtostr(client_id));

  eca_jack_node_t* node = get_node(client_id);

  list<eca_jack_port_data_t*>::iterator p = node->ports.begin();
  while(p != node->ports.end()) {
    /* 1. unregister port from JACK */
    if (open_rep == true && (*p)->jackport != 0) {
      jack_port_unregister(client_repp, (*p)->jackport);
    }

    /* 2. delete the port from inports and outports vectors */
    vector<eca_jack_port_data_t*>::iterator q = inports_rep.begin();
    while(q != inports_rep.end()) {
      if (*p == *q) {
	inports_rep.erase(q);
	break;
      }
      ++q;
    }
    
    q = outports_rep.begin();
    while(q != outports_rep.end()) {
      if (*p == *q) {
	outports_rep.erase(q);
	break;
      }
      ++q;
    }
    
    /* 3. delete sub-structures */
      
    delete[] (*p)->cb_buffer;
    (*p)->cb_buffer = 0;

    /* 4. delete the actual port_data object */
    delete *p;

    ++p;
  }

  /* 5. clear the whole node port list */
  node->ports.clear();

  // ---
  DBC_ENSURE(node->ports.size() == 0);
  DBC_ENSURE(inports_rep.size() + outports_rep.size() == 
	     old_port_count_vectors - old_node_port_count);
  // ---
}

void AUDIO_IO_JACK_MANAGER::open(int client_id)
{
  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		"open for client " + kvu_numtostr(client_id));

  DBC_CHECK(shutdown_request_rep != true);

  /* only for the first client */
  if (is_open() != true) {
    open_server_connection();
  }

  ++open_clients_rep;
}

void AUDIO_IO_JACK_MANAGER::close(int client_id)
{
  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		"close for client " + kvu_numtostr(client_id));

  DBC_CHECK(open_clients_rep > 0);

  /* only for the last client */
  if (open_clients_rep == 1) {
    if (is_open() == true) 
      close_server_connection();
  }
  else 
    ECA_LOG_MSG(ECA_LOGGER::user_objects, 
		"Not yet closing JACK server connection as there are "
		+ kvu_numtostr(open_clients_rep - 1) + " clients still active.");

  --open_clients_rep;
}

/**
 * Returns current buffersize in sample frames. 
 * Always returns 0 if manager is not connected.
 */
long int AUDIO_IO_JACK_MANAGER::buffersize(void) const
{
  if (is_open() != true) return 0;

  return buffersize_rep;
}

bool AUDIO_IO_JACK_MANAGER::is_running(void) const
{ 
  if (engine_repp != 0) {
    return engine_repp->is_running();
  }
  return false;
}

/**
 * Returns the current JACK engine sample rate.
 * Always returns 0 if manager is not connected.
 */
SAMPLE_SPECS::sample_rate_t AUDIO_IO_JACK_MANAGER::samples_per_second(void) const
{
  if (is_open() != true) return 0;

  return srate_rep;
}

/**
 * context: J-E-C-level-3
 */
long int AUDIO_IO_JACK_MANAGER::read_samples(int client_id, void* target_buffer, long int samples)
{
  // DEBUG_CFLOW_STATEMENT(cerr << endl << "read_samples:" << client_id);

  jack_default_audio_sample_t* ptr = 
    static_cast<jack_default_audio_sample_t*>(target_buffer);
  eca_jack_node_t* node = get_node(client_id);

  list<eca_jack_port_data*>::const_iterator p = node->ports.begin();
  while(p != node->ports.end()) {
    if ((*p)->cb_buffer != 0) {
      memcpy(ptr, (*p)->cb_buffer, buffersize_rep * sizeof(jack_default_audio_sample_t));
      ptr += buffersize_rep;
    }
    ++p;
  }

  return buffersize_rep;
}

/**
 * context: J-E-C-level-3
 */
void AUDIO_IO_JACK_MANAGER::write_samples(int client_id, void* target_buffer, long int samples)
{
  // DEBUG_CFLOW_STATEMENT(cerr << endl << "write_samples:" << client_id);
  size_t sample_size = sizeof(jack_default_audio_sample_t);
  long int writesamples = (samples <= buffersize_rep) ? samples : buffersize_rep;
  jack_default_audio_sample_t* ptr =
    static_cast<jack_default_audio_sample_t*>(target_buffer);

  eca_jack_node_t* node = get_node(client_id);
  list<eca_jack_port_data*>::const_iterator p = node->ports.begin();
  while(p != node->ports.end()) {
    if ((*p)->cb_buffer != 0) {
      /* note: cb_buffer points to jack_default_audio_sample_t* */
      memcpy((*p)->cb_buffer, ptr, writesamples * sample_size);
      ptr += writesamples;
      memset((*p)->cb_buffer + writesamples,
	     0,
	     (buffersize_rep - writesamples) * sample_size);
    }
    ++p;
  }
}

/**
 * Opens connection to the JACK server. Sets
 * is_open() to 'true' if connection is 
 * successfully opened.
 *
 * @pre is_open() != true
 *
 * context: C-level-1
 */
void AUDIO_IO_JACK_MANAGER::open_server_connection(void)
{
  // --
  DBC_REQUIRE(is_open() != true);
  // --

  string client_name (jackname_rep);
  int n;

  for(n = 0; n < AUDIO_IO_JACK_MANAGER::instance_limit; n++) {
    client_repp = jack_client_open (client_name.c_str(), JackNullOption, NULL);
    if (client_repp != 0) break;
    client_name = jackname_rep + "_" + kvu_numtostr(n + 2);
  }

  if (n != AUDIO_IO_JACK_MANAGER::instance_limit) {
    srate_rep = static_cast<long int>(jack_get_sample_rate(client_repp));
    /* FIXME: add better control of allocated memory */
    cb_allocated_frames_rep = buffersize_rep = static_cast<long int>(jack_get_buffer_size(client_repp));
    shutdown_request_rep = false;
    jackslave_seekahead_rep = 4096 / buffersize_rep + 1;

    /* set callbacks */
    jack_set_process_callback(client_repp, eca_jack_process_callback, static_cast<void*>(this));
    jack_set_sample_rate_callback(client_repp, eca_jack_srate_cb, static_cast<void*>(this));
    jack_set_buffer_size_callback(client_repp, eca_jack_bsize_cb, static_cast<void*>(this));
    jack_on_shutdown(client_repp, eca_jack_shutdown_cb, static_cast<void*>(this));
    
#if ECA_JACK_TRANSPORT_API >= 3
    if (mode_rep == AUDIO_IO_JACK_MANAGER::Transport_receive ||
	mode_rep == AUDIO_IO_JACK_MANAGER::Transport_send_receive) {
      jack_set_sync_callback(client_repp, eca_jack_sync_callback, static_cast<void*>(this));
    }
#endif

    open_rep = true;

#ifdef PROFILE_CALLBACK_EXECUTION
    profile_callback_timer.set_lower_bound_seconds(0.001f);
    profile_callback_timer.set_upper_bound_seconds(0.005f);
#endif

    ECA_LOG_MSG(ECA_LOGGER::user_objects, 
		"Successfully opened JACK server connection.");
  }
  else {
    ECA_LOG_MSG(ECA_LOGGER::info, "Error! Cannot connect to JACK server!");
    open_rep = false;
  }
}

/**
 * Closes connection to the JACK server.
 *
 * @pre is_open() == true
 * @post is_open() != true
 *
 * context: C-level-1
 */
void AUDIO_IO_JACK_MANAGER::close_server_connection(void)
{
  // --
  DBC_REQUIRE(is_open() == true);
  // --

  // FIXME: add proper unregistration
  // iterate over cids: unregister_jack_ports()

  jack_client_close (client_repp);
  shutdown_request_rep = false;
  open_rep = false;

  port_numbers_rep.clear();

  ECA_LOG_MSG(ECA_LOGGER::user_objects, 
		"Successfully closed JACK server connection.");

#ifdef PROFILE_CALLBACK_EXECUTION
  cerr << profile_callback_timer.to_string() << endl;
#endif 

  // --
  DBC_ENSURE(is_open() != true);
  DBC_REQUIRE(shutdown_request_rep != true);
  // --
}

/**
 * Fetches total port latency information.
 *
 * context: E-level-5
 */
void AUDIO_IO_JACK_MANAGER::get_total_port_latency(jack_client_t* client, eca_jack_port_data_t* port, int iomode)
{
  jack_nframes_t latency = 0;
#if ECA_JACK_FEATSET >= 1
  jack_latency_range_t range;
  jack_port_get_latency_range(port->jackport,
			      iomode == AUDIO_IO::io_read ? JackCaptureLatency : JackPlaybackLatency,
			      &range);
  if (range.min != range.max)
    ECA_LOG_MSG(ECA_LOGGER::user_objects, 
		"jack_port_get_latency_range mix=" +
		kvu_numtostr(range.min) + ", max=" +
		kvu_numtostr(range.max));
  latency = range.min;
#else
  latency = jack_port_get_total_latency(client, port->jackport);
#endif

  port->total_latency = latency;

  ECA_LOG_MSG(ECA_LOGGER::user_objects, 
	      "Total latency for port '" +
	      string(jack_port_name(port->jackport)) +
	      "' is " + kvu_numtostr(port->total_latency) + ".");
}

/**
 * Connects ports of node 'node'. 
 *
 * @param node pointers to a node object
 * @param connect whether to connect (true) or disconnect (false)
 *
 * context: E-level-4
 */
void AUDIO_IO_JACK_MANAGER::set_node_connection(eca_jack_node_t* node, bool connect)
{
  list<eca_jack_port_data*>::iterator p = node->ports.begin();
  while(p != node->ports.end()) {
    if ((*p)->cb_buffer != 0) {
      string ecaport = (*p)->autoconnect_string;
      if (ecaport.size() > 0) {
	string jackport (jack_port_name((*p)->jackport));
	const string* fromport = &ecaport;
	const string* toport = &jackport;
	if (node->aobj->io_mode() != AUDIO_IO::io_read) {
	  /* output object -> switch direction */
	  fromport = &jackport;
	  toport = &ecaport;
	}
	
	if (connect == true) {
	  ECA_LOG_MSG(ECA_LOGGER::system_objects, 
		      "Connecting JACK port " +
		      *fromport + " to " + *toport);
	  if (jack_connect (client_repp,
			    fromport->c_str(), 
			    toport->c_str())) {
	    ECA_LOG_MSG(ECA_LOGGER::info, 
			"Error! Cannot make connection " + 
			*fromport + " -> " + *toport + ".");
	  }
	  else {
	    AUDIO_IO_JACK_MANAGER::get_total_port_latency(client_repp, *p, node->aobj->io_mode());
	  }
	}
	else {
	  ECA_LOG_MSG(ECA_LOGGER::system_objects, "jack_port_disconnect()");
	  /* don't call jack_disconnect() if engine has shut down */
	  if (jack_disconnect(client_repp, 
			      fromport->c_str(),
			      toport->c_str())) {
	    ECA_LOG_MSG(ECA_LOGGER::info, 
			"Error! Cannot disconnect " + 
			*fromport + " -> " + *toport + ".");
	  }
	}
      }
    }
    
    ++p;
  }
}

/**
 * Connects ports of all registered nodes.
 *
 * @see set_node_connection()
 *
 * context: E-level-3
 */
void AUDIO_IO_JACK_MANAGER::connect_all_nodes(void)
{ 
  if (shutdown_request_rep != true) {
    list<eca_jack_node_t*>::iterator p = node_list_rep.begin();
    while(p != node_list_rep.end()) {
      set_node_connection(*p, true);
      ++p;
    }
  }
  else {
    if (is_open() == true) close_server_connection();
  }
}

/**
 * Disconnects all ports of registered nodes.
 *
 * @see set_node_connection()
 *
 * context: E-level-3
 */
void AUDIO_IO_JACK_MANAGER::disconnect_all_nodes(void)
{
  list<eca_jack_node_t*>::iterator p = node_list_rep.begin();
  while(p != node_list_rep.end()) {
    set_node_connection(*p, false);
    ++p;
  }
}

/**
 * Signals that exec() has exited.
 *
 * @see wait_for_exit();
 *
 * context: E-level-1
 */
void AUDIO_IO_JACK_MANAGER::signal_exit(void)
{
  pthread_mutex_lock(&exit_mutex_rep);
  pthread_cond_signal(&exit_cond_rep);
  pthread_mutex_unlock(&exit_mutex_rep);
}

/**
 * Waits until exec() has exited.
 *
 * context: not in use
 */
void AUDIO_IO_JACK_MANAGER::wait_for_exit(void)
{
  int ret = kvu_pthread_timed_wait(&exit_mutex_rep, &exit_cond_rep, 5);
  ECA_LOG_MSG(ECA_LOGGER::info, 
		kvu_pthread_timed_wait_result(ret, "(audioio_jack_manager) wait_for_exit"));
}

/**
 * Signals that client has stopped.
 *
 * @see wait_for_stop()
 *
 * context: E-level-2
 */
void AUDIO_IO_JACK_MANAGER::signal_stop(void)
{
  pthread_mutex_lock(&exit_mutex_rep);
  pthread_cond_signal(&exit_cond_rep);
  pthread_mutex_unlock(&exit_mutex_rep);
}

/**
 * Waits until client has stopped (no more callbacks).
 *
 * context: not in use
 */
void AUDIO_IO_JACK_MANAGER::wait_for_stop(void)
{
  int ret = kvu_pthread_timed_wait(&stop_mutex_rep, &stop_cond_rep, 5);
  ECA_LOG_MSG(ECA_LOGGER::info, 
		kvu_pthread_timed_wait_result(ret, "(audioio_jack_manager) wait_for_stop"));
}