summaryrefslogtreecommitdiffstats
path: root/src/gui/seqmanager/SequenceManager.cpp
blob: 1176e3a750c7fb40a27e0f3be41f36437983c9d7 (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
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
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */

/*
    Rosegarden
    A MIDI and audio sequencer and musical notation editor.
 
    This program is Copyright 2000-2008
        Guillaume Laurent   <glaurent@telegraph-road.org>,
        Chris Cannam        <cannam@all-day-breakfast.com>,
        Richard Bown        <richard.bown@ferventsoftware.com>
 
    The moral rights of Guillaume Laurent, Chris Cannam, and Richard
    Bown to claim authorship of this work have been asserted.
 
    Other copyrights also apply to some parts of this work.  Please
    see the AUTHORS file and individual file headers for details.
 
    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.  See the file
    COPYING included with this distribution for more information.
*/


#include "SequenceManager.h"

#include "sound/Midi.h"
#include "misc/Debug.h"
#include "document/ConfigGroups.h"
#include "base/Composition.h"
#include "base/Device.h"
#include "base/Exception.h"
#include "base/Instrument.h"
#include "base/MidiProgram.h"
#include "base/RealTime.h"
#include "base/Segment.h"
#include "base/Studio.h"
#include "base/Track.h"
#include "base/TriggerSegment.h"
#include "CompositionMmapper.h"
#include "document/RosegardenGUIDoc.h"
#include "document/MultiViewCommandHistory.h"
#include "gui/application/RosegardenApplication.h"
#include "gui/application/RosegardenGUIApp.h"
#include "gui/application/RosegardenGUIView.h"
#include "gui/dialogs/AudioManagerDialog.h"
#include "gui/dialogs/CountdownDialog.h"
#include "gui/dialogs/TransportDialog.h"
#include "gui/kdeext/KStartupLogo.h"
#include "gui/studio/StudioControl.h"
#include "gui/widgets/CurrentProgressDialog.h"
#include "MetronomeMmapper.h"
#include "SegmentMmapperFactory.h"
#include "SequencerMapper.h"
#include "ControlBlockMmapper.h"
#include "sound/AudioFile.h"
#include "sound/MappedComposition.h"
#include "sound/MappedEvent.h"
#include "sound/MappedInstrument.h"
#include "sound/SoundDriver.h"
#include "TempoSegmentMmapper.h"
#include "TimeSigSegmentMmapper.h"
#include <klocale.h>
#include <kstddirs.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kmessagebox.h>
#include <tqapplication.h>
#include <tqcstring.h>
#include <tqcursor.h>
#include <tqdatastream.h>
#include <tqevent.h>
#include <tqobject.h>
#include <tqpushbutton.h>
#include <tqstring.h>
#include <tqstringlist.h>
#include <tqtimer.h>
#include <algorithm>


namespace Rosegarden
{

SequenceManager::SequenceManager(RosegardenGUIDoc *doc,
                                 TransportDialog *transport):
            m_doc(doc),
            m_compositionMmapper(new CompositionMmapper(m_doc)),
            m_controlBlockMmapper(new ControlBlockMmapper(m_doc)),
            m_metronomeMmapper(SegmentMmapperFactory::makeMetronome(m_doc)),
            m_tempoSegmentMmapper(SegmentMmapperFactory::makeTempo(m_doc)),
            m_timeSigSegmentMmapper(SegmentMmapperFactory::makeTimeSig(m_doc)),
            m_transporttqStatus(STOPPED),
            m_soundDrivertqStatus(NO_DRIVER),
            m_transport(transport),
            m_lastRewoundAt(clock()),
            m_countdownDialog(0),
            m_countdownTimer(new TQTimer(m_doc)),
            m_shownOverrunWarning(false),
            m_recordTime(new TQTime()),
            m_compositionRefreshStatusId(m_doc->getComposition().getNewRefreshStatusId()),
            m_updateRequested(true),
            m_compositionMmapperResetTimer(new TQTimer(m_doc)),
            m_sequencerMapper(0),
            m_reportTimer(new TQTimer(m_doc)),
            m_canReport(true),
            m_lastLowLatencySwitchSent(false),
            m_lastTransportStartPosition(0),
            m_sampleRate(0)
{
    // Replaced this with a call to cleanup() from composition mmapper ctor:
    // if done here, this removes the mmapped versions of any segments stored
    // in the autoload (that have only just been mapped by the ctor!)
    //    m_compositionMmapper->cleanup();

    m_countdownDialog = new CountdownDialog(dynamic_cast<TQWidget*>
                                            (m_doc->tqparent())->tqparentWidget());
    // Connect these for use later
    //
    connect(m_countdownTimer, TQT_SIGNAL(timeout()),
            this, TQT_SLOT(slotCountdownTimerTimeout()));

    connect(m_reportTimer, TQT_SIGNAL(timeout()),
            this, TQT_SLOT(slotAllowReport()));

    connect(m_compositionMmapperResetTimer, TQT_SIGNAL(timeout()),
            this, TQT_SLOT(slotScheduledCompositionMmapperReset()));


    connect(doc->getCommandHistory(), TQT_SIGNAL(commandExecuted()),
            this, TQT_SLOT(update()));

    m_doc->getComposition().addObserver(this);

    // The owner of this sequence manager will need to call
    // checkSoundDrivertqStatus on it to set up its status appropriately
    // immediately after construction; we used to do it from here but
    // we're not well placed to handle reporting to the user if it
    // throws an exception (and we don't want to leave the object half
    // constructed).

    // Try to map the sequencer file
    //
    mapSequencer();
}

SequenceManager::~SequenceManager()
{
    m_doc->getComposition().removeObserver(this);

    SETQMAN_DEBUG << "SequenceManager::~SequenceManager()\n";
    delete m_compositionMmapper;
    delete m_controlBlockMmapper;
    delete m_metronomeMmapper;
    delete m_tempoSegmentMmapper;
    delete m_timeSigSegmentMmapper;
    delete m_sequencerMapper;
}

void SequenceManager::setDocument(RosegardenGUIDoc* doc)
{
    SETQMAN_DEBUG << "SequenceManager::setDocument(" << doc << ")\n";

    DataBlockRepository::clear();

    m_doc->getComposition().removeObserver(this);
    disconnect(m_doc->getCommandHistory(), TQT_SIGNAL(commandExecuted()));

    m_segments.clear();
    m_triggerSegments.clear();

    m_doc = doc;
    Composition &comp = m_doc->getComposition();

    // Must recreate and reconnect the countdown timer and dialog
    // (bug 729039)
    //
    delete m_countdownDialog;
    delete m_countdownTimer;
    delete m_compositionMmapperResetTimer;

    m_countdownDialog = new CountdownDialog(dynamic_cast<TQWidget*>
                                            (m_doc->tqparent())->tqparentWidget());

    // Bug 933041: no longer connect the CountdownDialog from
    // SequenceManager; instead let the RosegardenGUIApp connect it to
    // its own slotStop to ensure the right housekeeping is done

    m_countdownTimer = new TQTimer(m_doc);

    // Connect this for use later
    //
    connect(m_countdownTimer, TQT_SIGNAL(timeout()),
            this, TQT_SLOT(slotCountdownTimerTimeout()));

    m_compositionRefreshStatusId = comp.getNewRefreshStatusId();
    comp.addObserver(this);

    connect(m_doc->getCommandHistory(), TQT_SIGNAL(commandExecuted()),
            this, TQT_SLOT(update()));

    for (Composition::iterator i = comp.begin(); i != comp.end(); ++i) {

        SETQMAN_DEBUG << "Adding segment with rid " << (*i)->getRuntimeId() << endl;

        m_segments.insert(SegmentRefreshMap::value_type
                          (*i, (*i)->getNewRefreshStatusId()));
    }

    for (Composition::triggersegmentcontaineriterator i =
                comp.getTriggerSegments().begin();
            i != comp.getTriggerSegments().end(); ++i) {
        m_triggerSegments.insert(SegmentRefreshMap::value_type
                                 ((*i)->getSegment(),
                                  (*i)->getSegment()->getNewRefreshStatusId()));
    }


    m_compositionMmapperResetTimer = new TQTimer(m_doc);
    connect(m_compositionMmapperResetTimer, TQT_SIGNAL(timeout()),
            this, TQT_SLOT(slotScheduledCompositionMmapperReset()));

    resetCompositionMmapper();

    // Try to map the sequencer file
    //
    mapSequencer();
}

void
SequenceManager::setTransporttqStatus(const TransporttqStatus &status)
{
    m_transporttqStatus = status;
}

void
SequenceManager::mapSequencer()
{
    if (m_sequencerMapper)
        return ;

    try {
        m_sequencerMapper = new SequencerMapper(
                                KGlobal::dirs()->resourceDirs("tmp").last() + "/rosegarden_sequencer_timing_block");
    } catch (Exception) {
        m_sequencerMapper = 0;
    }
}

bool
SequenceManager::play()
{
    mapSequencer();

    Composition &comp = m_doc->getComposition();

    // If already playing or recording then stop
    //
    if (m_transporttqStatus == PLAYING ||
            m_transporttqStatus == RECORDING ) {
        stopping();
        return true;
    }

    // This check may throw an exception
    checkSoundDrivertqStatus(false);

    // Align Instrument lists and send initial program changes
    //
    preparePlayback();

    m_lastTransportStartPosition = comp.getPosition();

    // Update play metronome status
    //
    m_controlBlockMmapper->updateMetronomeData
    (m_metronomeMmapper->getMetronomeInstrument());
    m_controlBlockMmapper->updateMetronomeForPlayback();

    // make sure we toggle the play button
    //
    m_transport->PlayButton()->setOn(true);

    //!!! disable the record button, because recording while playing is horribly
    // broken, and disabling it is less complicated than fixing it
    // see #1223025 - DMM
    //    SETQMAN_DEBUG << "SequenceManager::play() - disabling record button, as we are playing\n";
    //    m_transport->RecordButton()->setEnabled(false);

    if (comp.getCurrentTempo() == 0) {
        comp.setCompositionDefaultTempo(comp.getTempoForQpm(120.0));

        SETQMAN_DEBUG << "SequenceManager::play() - setting Tempo to Default value of 120.000\n";
    } else {
        SETQMAN_DEBUG << "SequenceManager::play() - starting to play\n";
    }

    // Send initial tempo
    //
    double qnD = 60.0 / comp.getTempoQpm(comp.getCurrentTempo());
    RealTime qnTime =
        RealTime(long(qnD),
                 long((qnD - double(long(qnD))) * 1000000000.0));
    StudioControl::sendQuarterNoteLength(qnTime);

    // set the tempo in the transport
    m_transport->setTempo(comp.getCurrentTempo());

    // The arguments for the Sequencer
    RealTime startPos = comp.getElapsedRealTime(comp.getPosition());

    // If we're looping then jump to loop start
    if (comp.isLooping())
        startPos = comp.getElapsedRealTime(comp.getLoopStart());

    KConfig* config = kapp->config();
    config->setGroup(SequencerOptionsConfigGroup);

    bool lowLat = config->readBoolEntry("audiolowlatencymonitoring", true);

    if (lowLat != m_lastLowLatencySwitchSent) {

        TQByteArray data;
        TQDataStream streamOut(data, IO_WriteOnly);
        streamOut << lowLat;

        rgapp->sequencerSend("setLowLatencyMode(bool)", data);
        m_lastLowLatencySwitchSent = lowLat;
    }

    TQByteArray data;
    TQCString replyType;
    TQByteArray replyData;
    TQDataStream streamOut(data, IO_WriteOnly);

    // playback start position
    streamOut << (long)startPos.sec;
    streamOut << (long)startPos.nsec;

    // Apart from perhaps the small file size, I think with hindsight
    // that these options are more easily set to reasonable defaults
    // here than left to the user.  Mostly.

    //!!! need some cleverness somewhere to ensure the read-ahead
    //is larger than the JACK period size

    if (lowLat) {
        streamOut << 0L; // read-ahead sec
        streamOut << 160000000L; // read-ahead nsec
        streamOut << 0L; // audio mix sec
        streamOut << 60000000L; // audio mix nsec: ignored in lowlat mode
        streamOut << 2L; // audio read sec
        streamOut << 500000000L; // audio read nsec
        streamOut << 4L; // audio write sec
        streamOut << 0L; // audio write nsec
        streamOut << 256L; // cacheable small file size in K
    } else {
        streamOut << 0L; // read-ahead sec
        streamOut << 500000000L; // read-ahead nsec
        streamOut << 0L; // audio mix sec
        streamOut << 400000000L; // audio mix nsec
        streamOut << 2L; // audio read sec
        streamOut << 500000000L; // audio read nsec
        streamOut << 4L; // audio write sec
        streamOut << 0L; // audio write nsec
        streamOut << 256L; // cacheable small file size in K
    }

    // Send Play to the Sequencer
    if (!rgapp->sequencerCall("play(long int, long int, long int, long int, long int, long int, long int, long int, long int, long int, long int)",
                              replyType, replyData, data)) {
        m_transporttqStatus = STOPPED;
        return false;
    }

    // ensure the return type is ok
    TQDataStream streamIn(replyData, IO_ReadOnly);
    int result;
    streamIn >> result;

    if (result) {
        // completed successfully
        m_transporttqStatus = STARTING_TO_PLAY;
    } else {
        m_transporttqStatus = STOPPED;
        std::cerr << "ERROR: SequenceManager::play(): Failed to start playback!" << std::endl;
    }

    return false;
}

void
SequenceManager::stopping()
{
    if (m_countdownTimer)
        m_countdownTimer->stop();
    if (m_countdownDialog)
        m_countdownDialog->hide();

    // Do this here rather than in stop() to avoid any potential
    // race condition (we use setPointerPosition() during stop()).
    //
    if (m_transporttqStatus == STOPPED) {
        /*!!!
                if (m_doc->getComposition().isLooping())
                    m_doc->slotSetPointerPosition(m_doc->getComposition().getLoopStart());
                else
                    m_doc->slotSetPointerPosition(m_doc->getComposition().getStartMarker());
        */
        m_doc->slotSetPointerPosition(m_lastTransportStartPosition);

        return ;
    }

    // Disarm recording and drop back to STOPPED
    //
    if (m_transporttqStatus == RECORDING_ARMED) {
        m_transporttqStatus = STOPPED;
        m_transport->RecordButton()->setOn(false);
        m_transport->MetronomeButton()->
        setOn(m_doc->getComposition().usePlayMetronome());
        return ;
    }

    SETQMAN_DEBUG << "SequenceManager::stopping() - preparing to stop\n";

    //    SETQMAN_DEBUG << kdBacktrace() << endl;

    stop();

    m_shownOverrunWarning = false;
}

void
SequenceManager::stop()
{
    // Toggle off the buttons - first record
    //
    if (m_transporttqStatus == RECORDING) {
        m_transport->RecordButton()->setOn(false);
        m_transport->MetronomeButton()->
        setOn(m_doc->getComposition().usePlayMetronome());

        // Remove the countdown dialog and stop the timer
        //
        m_countdownDialog->hide();
        m_countdownTimer->stop();
    }

    // Now playback
    m_transport->PlayButton()->setOn(false);

    // re-enable the record button if it was previously disabled when
    // going into play mode - DMM
    //    SETQMAN_DEBUG << "SequenceManager::stop() - re-enabling record button\n";
    //    m_transport->RecordButton()->setEnabled(true);


    // "call" the sequencer with a stop so we get a synchronous
    // response - then we can fiddle about with the audio file
    // without worrying about the sequencer causing problems
    // with access to the same audio files.
    //

    // wait cursor
    //
    TQApplication::setOverrideCursor(TQCursor(TQt::waitCursor));

    TQCString replyType;
    TQByteArray replyData;

    bool failed = false;
    if (!rgapp->sequencerCall("stop()", replyType, replyData)) {
        failed = true;
    }

    // restore
    TQApplication::restoreOverrideCursor();

    TransporttqStatus status = m_transporttqStatus;

    // set new transport status first, so that if we're stopping
    // recording we don't risk the record segment being restored by a
    // timer while the document is busy trying to do away with it
    m_transporttqStatus = STOPPED;

    // if we're recording MIDI or Audio then tidy up the recording Segment
    if (status == RECORDING) {
        m_doc->stopRecordingMidi();
        m_doc->stopRecordingAudio();

        SETQMAN_DEBUG << "SequenceManager::stop() - stopped recording\n";
    }

    // always untoggle the play button at this stage
    //
    m_transport->PlayButton()->setOn(false);
    SETQMAN_DEBUG << "SequenceManager::stop() - stopped playing\n";

    // We don't reset controllers at this point - what happens with static
    // controllers the next time we play otherwise?  [rwb]
    //resetControllers();

    if (failed) {
        throw(Exception("Failed to contact Rosegarden sequencer with stop command.   Please save your composition and restart Rosegarden to continue."));
    }
}

void
SequenceManager::rewind()
{
    Composition &composition = m_doc->getComposition();

    timeT position = composition.getPosition();
    std::pair<timeT, timeT> barRange =
        composition.getBarRangeForTime(position - 1);

    if (m_transporttqStatus == PLAYING) {

        // if we're playing and we had a rewind request less than 200ms
        // ago and we're some way into the bar but less than half way
        // through it, rewind two barlines instead of one

        clock_t now = clock();
        int elapsed = (now - m_lastRewoundAt) * 1000 / CLOCKS_PER_SEC;

        SETQMAN_DEBUG << "That was " << m_lastRewoundAt << ", this is " << now << ", elapsed is " << elapsed << endl;

        if (elapsed >= 0 && elapsed <= 200) {
            if (position > barRange.first &&
                    position < barRange.second &&
                    position <= (barRange.first + (barRange.second -
                                                   barRange.first) / 2)) {
                barRange = composition.getBarRangeForTime(barRange.first - 1);
            }
        }

        m_lastRewoundAt = now;
    }

    if (barRange.first < composition.getStartMarker()) {
        m_doc->slotSetPointerPosition(composition.getStartMarker());
    } else {
        m_doc->slotSetPointerPosition(barRange.first);
    }
}

void
SequenceManager::fastforward()
{
    Composition &composition = m_doc->getComposition();

    timeT position = composition.getPosition() + 1;
    timeT newPosition = composition.getBarRangeForTime(position).second;

    // Don't skip past end marker
    //
    if (newPosition > composition.getEndMarker())
        newPosition = composition.getEndMarker();

    m_doc->slotSetPointerPosition(newPosition);

}

void
SequenceManager::notifySequencertqStatus(TransporttqStatus status)
{
    // for the moment we don't do anything fancy
    m_transporttqStatus = status;

}

void
SequenceManager::sendSequencerJump(const RealTime &time)
{
    TQByteArray data;
    TQDataStream streamOut(data, IO_WriteOnly);
    streamOut << (long)time.sec;
    streamOut << (long)time.nsec;

    rgapp->sequencerSend("jumpTo(long int, long int)", data);
}

void
SequenceManager::record(bool toggled)
{
    mapSequencer();

    SETQMAN_DEBUG << "SequenceManager::record(" << toggled << ")" << endl;

    Composition &comp = m_doc->getComposition();
    Studio &studio = m_doc->getStudio();
    KConfig* config = kapp->config();
    config->setGroup(GeneralOptionsConfigGroup);

    bool punchIn = false; // are we punching in?

    // If we have any audio tracks armed, then we need to check for
    // a valid audio record path and a working audio subsystem before
    // we go any further

    const Composition::recordtrackcontainer &recordTracks =
        comp.getRecordTracks();

    for (Composition::recordtrackcontainer::const_iterator i =
                recordTracks.begin();
            i != recordTracks.end(); ++i) {

        Track *track = comp.getTrackById(*i);
        InstrumentId instrId = track->getInstrument();
        Instrument *instr = studio.getInstrumentById(instrId);

        if (instr && instr->getType() == Instrument::Audio) {
            if (!m_doc || !(m_soundDrivertqStatus & AUDIO_OK)) {
                m_transport->RecordButton()->setOn(false);
                throw(Exception("Audio subsystem is not available - can't record audio"));
            }
            // throws BadAudioPathException if path is not valid:
            m_doc->getAudioFileManager().testAudioPath();
            break;
        }
    }

    if (toggled) { // preparing record or punch-in record

        if (m_transporttqStatus == RECORDING_ARMED) {
            SETQMAN_DEBUG << "SequenceManager::record - unarming record\n";
            m_transporttqStatus = STOPPED;

            // Toggle the buttons
            m_transport->MetronomeButton()->setOn(comp.usePlayMetronome());
            m_transport->RecordButton()->setOn(false);

            return ;
        }

        if (m_transporttqStatus == STOPPED) {
            SETQMAN_DEBUG << "SequenceManager::record - armed record\n";
            m_transporttqStatus = RECORDING_ARMED;

            // Toggle the buttons
            m_transport->MetronomeButton()->setOn(comp.useRecordMetronome());
            m_transport->RecordButton()->setOn(true);

            return ;
        }

        if (m_transporttqStatus == RECORDING) {
            SETQMAN_DEBUG << "SequenceManager::record - stop recording and keep playing\n";

            TQByteArray data;
            TQCString replyType;
            TQByteArray replyData;

            // Send Record to the Sequencer to signal it to drop out of record mode
            if (!rgapp->sequencerCall("punchOut()", replyType, replyData, data)) {
                SETQMAN_DEBUG << "SequenceManager::record - the \"not very plausible\" code executed\n";
                // #1797873 - set new transport status first, so that
                // if we're stopping recording we don't risk the
                // record segment being restored by a timer while the
                // document is busy trying to do away with it
                m_transporttqStatus = STOPPED;

                m_doc->stopRecordingMidi();
                m_doc->stopRecordingAudio();
                return ;
            }

            // #1797873 - as above
            m_transporttqStatus = PLAYING;

            m_doc->stopRecordingMidi();
            m_doc->stopRecordingAudio();

            return ;
        }

        if (m_transporttqStatus == PLAYING) {
            SETQMAN_DEBUG << "SequenceManager::record - punch in recording\n";
            punchIn = true;
            goto punchin;
        }

    } else {

        m_lastTransportStartPosition = comp.getPosition();

punchin:

        // Get the record tracks and check we have a record instrument

        bool haveInstrument = false;
        bool haveAudioInstrument = false;
        bool haveMIDIInstrument = false;
        //TrackId recordMIDITrack = 0;

        for (Composition::recordtrackcontainer::const_iterator i =
                    comp.getRecordTracks().begin();
                i != comp.getRecordTracks().end(); ++i) {

            InstrumentId iid =
                comp.getTrackById(*i)->getInstrument();

            Instrument *inst = studio.getInstrumentById(iid);
            if (inst) {
                haveInstrument = true;
                if (inst->getType() == Instrument::Audio) {
                    haveAudioInstrument = true;
                    break;
                } else { // soft synths count as MIDI for our purposes here
                    haveMIDIInstrument = true;
                    //recordMIDITrack = *i;
                }
            }
        }

        if (!haveInstrument) {
            m_transport->RecordButton()->setDown(false);
            throw(Exception("No Record instrument selected"));
        }

        // may throw an exception
        checkSoundDrivertqStatus(false);

        // toggle the Metronome button if it's in use
        m_transport->MetronomeButton()->setOn(comp.useRecordMetronome());

        // Update record metronome status
        //
        m_controlBlockMmapper->updateMetronomeData
        (m_metronomeMmapper->getMetronomeInstrument());
        m_controlBlockMmapper->updateMetronomeForRecord();

        // If we are looping then jump to start of loop and start recording,
        // if we're not take off the number of count-in bars and start
        // recording.
        //
        if (comp.isLooping())
            m_doc->slotSetPointerPosition(comp.getLoopStart());
        else {
            if (m_transporttqStatus != RECORDING_ARMED && punchIn == false) {
                int startBar = comp.getBarNumber(comp.getPosition());
                startBar -= config->readUnsignedNumEntry("countinbars", 0);
                m_doc->slotSetPointerPosition(comp.getBarRange(startBar).first);
            }
        }

        m_doc->setRecordStartTime(m_doc->getComposition().getPosition());

        if (haveAudioInstrument) {
            // Ask the document to update its record latencies so as to
            // do latency compensation when we stop
            m_doc->updateAudioRecordLatency();
        }

        if (haveMIDIInstrument) {
            // Create the record MIDI segment now, so that the
            // composition view has a real segment to display.  It
            // won't actually be added to the composition until the
            // first recorded event arrives.  We don't have to do this
            // from here for audio, because for audio the sequencer
            // calls back on createRecordAudioFiles so as to find out
            // what files it needs to write to.
            /*m_doc->addRecordMIDISegment(recordMIDITrack);*/
            for (Composition::recordtrackcontainer::const_iterator i =
                        comp.getRecordTracks().begin(); i != comp.getRecordTracks().end(); ++i) {
                InstrumentId iid = comp.getTrackById(*i)->getInstrument();
                Instrument *inst = studio.getInstrumentById(iid);
                if (inst && (inst->getType() != Instrument::Audio)) {
                    SETQMAN_DEBUG << "SequenceManager:  mdoc->addRecordMIDISegment(" << *i << ")" << endl;
                    m_doc->addRecordMIDISegment(*i);
                }
            }
        }

        // set the buttons
        m_transport->RecordButton()->setOn(true);
        m_transport->PlayButton()->setOn(true);

        if (comp.getCurrentTempo() == 0) {
            SETQMAN_DEBUG << "SequenceManager::play() - setting Tempo to Default value of 120.000\n";
            comp.setCompositionDefaultTempo(comp.getTempoForQpm(120.0));
        } else {
            SETQMAN_DEBUG << "SequenceManager::record() - starting to record\n";
        }

        // set the tempo in the transport
        //
        m_transport->setTempo(comp.getCurrentTempo());

        // The arguments for the Sequencer - record is similar to playback,
        // we must being playing to record.
        //
        RealTime startPos =
            comp.getElapsedRealTime(comp.getPosition());

        bool lowLat = config->readBoolEntry("audiolowlatencymonitoring", true);

        if (lowLat != m_lastLowLatencySwitchSent) {

            TQByteArray data;
            TQDataStream streamOut(data, IO_WriteOnly);
            streamOut << lowLat;

            rgapp->sequencerSend("setLowLatencyMode(bool)", data);
            m_lastLowLatencySwitchSent = lowLat;
        }

        TQByteArray data;
        TQCString replyType;
        TQByteArray replyData;
        TQDataStream streamOut(data, IO_WriteOnly);

        // playback start position
        streamOut << (long)startPos.sec;
        streamOut << (long)startPos.nsec;

        // Apart from perhaps the small file size, I think with hindsight
        // that these options are more easily set to reasonable defaults
        // here than left to the user.  Mostly.

        //!!! Duplicates code in play()

        //!!! need some cleverness somewhere to ensure the read-ahead
        //is larger than the JACK period size

        if (lowLat) {
            streamOut << 0L; // read-ahead sec
            streamOut << 160000000L; // read-ahead nsec
            streamOut << 0L; // audio mix sec
            streamOut << 60000000L; // audio mix nsec: ignored in lowlat mode
            streamOut << 2L; // audio read sec
            streamOut << 500000000L; // audio read nsec
            streamOut << 4L; // audio write sec
            streamOut << 0L; // audio write nsec
            streamOut << 256L; // cacheable small file size in K
        } else {
            streamOut << 0L; // read-ahead sec
            streamOut << 500000000L; // read-ahead nsec
            streamOut << 0L; // audio mix sec
            streamOut << 400000000L; // audio mix nsec
            streamOut << 2L; // audio read sec
            streamOut << 500000000L; // audio read nsec
            streamOut << 4L; // audio write sec
            streamOut << 0L; // audio write nsec
            streamOut << 256L; // cacheable small file size in K
        }

        // record type
        streamOut << (long)STARTING_TO_RECORD;

        // Send Play to the Sequencer
        if (!rgapp->sequencerCall("record(long int, long int, long int, long int, long int, long int, long int, long int, long int, long int, long int, long int)",
                                  replyType, replyData, data)) {
            // failed
            m_transporttqStatus = STOPPED;
            return ;
        }

        // ensure the return type is ok
        TQDataStream streamIn(replyData, IO_ReadOnly);
        int result;
        streamIn >> result;

        if (result) {

            // completed successfully
            m_transporttqStatus = STARTING_TO_RECORD;

            // Create the countdown timer dialog to show recording time
            // remaining.  (Note (dmm) this has changed, and it now reports
            // the time remaining during both MIDI and audio recording.)
            //
            timeT p = comp.getPosition();
            timeT d = comp.getEndMarker();
            // end marker less current position == available duration
            d -= p;

            // set seconds to total possible time, initially
            RealTime rtd = comp.getElapsedRealTime(d);
            int seconds = rtd.sec;

            // re-initialise
            m_countdownDialog->setTotalTime(seconds);

            // Create the timer
            //
            m_recordTime->start();

            // Start an elapse timer for updating the dialog -
            // it will fire every second.
            //
            m_countdownTimer->start(1000);

            // Pop-up the dialog (don't use exec())
            //
            // bug #1505805, abolish recording countdown dialog
            //m_countdownDialog->show();

        } else {
            // Stop immediately - turn off buttons in tqparent
            //
            m_transporttqStatus = STOPPED;

            if (haveAudioInstrument) {
                throw(Exception("Couldn't start recording audio.\nPlease set a valid file path in the Document Properties\n(Composition menu -> Edit Document Properties -> Audio)."));
            }
        }
    }
}

void
SequenceManager::processAsynchronousMidi(const MappedComposition &mC,
                                         AudioManagerDialog *audioManagerDialog)
{
    static bool boolShowingWarning = false;
    static bool boolShowingALSAWarning = false;
    static long warningShownAt = 0;

    if (m_doc == 0 || mC.size() == 0)
        return ;

    MappedComposition::const_iterator i;

    // Thru filtering is done at the sequencer for the actual sound
    // output, but here we need both filtered (for OUT display) and
    // unfiltered (for insertable note callbacks) compositions, so
    // we've received the unfiltered copy and will filter here
    MappedComposition tempMC =
        applyFiltering(mC,
                       MappedEvent::MappedEventType(
                           m_doc->getStudio().getMIDIThruFilter()));

    // send to the MIDI labels (which can only hold one event at a time)
    i = mC.begin();
    if (i != mC.end()) {
        m_transport->setMidiInLabel(*i);
    }

    i = tempMC.begin();
    while (i != tempMC.end()) {
        if ((*i)->getRecordedDevice() != Device::CONTROL_DEVICE) {
            m_transport->setMidiOutLabel(*i);
            break;
        }
        ++i;
    }

    for (i = mC.begin(); i != mC.end(); ++i ) {
        if ((*i)->getType() >= MappedEvent::Audio) {
            if ((*i)->getType() == MappedEvent::AudioStopped) {
                /*
                  SETQMAN_DEBUG << "AUDIO FILE ID = "
                  << int((*i)->getData1())
                  << " - FILE STOPPED - " 
                  << "INSTRUMENT = "
                  << (*i)->getInstrument()
                  << endl;
                */

                if (audioManagerDialog && (*i)->getInstrument() ==
                        m_doc->getStudio().getAudioPreviewInstrument()) {
                    audioManagerDialog->
                    closePlayingDialog(
                        AudioFileId((*i)->getData1()));
                }
            }

            if ((*i)->getType() == MappedEvent::AudioLevel)
                sendAudioLevel(*i);

            if ((*i)->getType() ==
                    MappedEvent::AudioGeneratePreview) {
                SETQMAN_DEBUG << "Received AudioGeneratePreview: data1 is " << int((*i)->getData1()) << ", data2 " << int((*i)->getData2()) << ", instrument is " << (*i)->getInstrument() << endl;

                m_doc->finalizeAudioFile((int)(*i)->getData1() +
                                         (int)(*i)->getData2() * 256);
            }

            if ((*i)->getType() ==
                MappedEvent::SystemUpdateInstruments) {
                // resync Devices and Instruments
                //
                m_doc->syncDevices();

                /*KConfig* config = kapp->config();
                  		config->setGroup(SequencerOptionsConfigGroup);
                TQString recordDeviceStr = config->readEntry("midirecorddevice");
                sendMIDIRecordingDevice(recordDeviceStr);*/
                restoreRecordSubscriptions();
            }

            if (m_transporttqStatus == PLAYING ||
                m_transporttqStatus == RECORDING) {
                if ((*i)->getType() == MappedEvent::SystemFailure) {

                    SETQMAN_DEBUG << "Failure of some sort..." << endl;

                    bool handling = true;

                    /* These are the ones that we always report or handle. */

                    if ((*i)->getData1() == MappedEvent::FailureJackDied) {

                        // Something horrible has happened to JACK or we got
                        // bumped out of the graph.  Either way stop playback.
                        //
                        stopping();

                    } else if ((*i)->getData1() == MappedEvent::FailureJackRestartFailed) {

                        KMessageBox::error(
                            dynamic_cast<TQWidget*>(m_doc->tqparent())->tqparentWidget(),
                            i18n("The JACK Audio subsystem has failed or it has stopped Rosegarden from processing audio.\nPlease restart Rosegarden to continue working with audio.\nQuitting other running applications may improve Rosegarden's performance."));

                    } else if ((*i)->getData1() == MappedEvent::FailureJackRestart) {

                        KMessageBox::error(
                            dynamic_cast<TQWidget*>(m_doc->tqparent())->tqparentWidget(),
                            i18n("The JACK Audio subsystem has stopped Rosegarden from processing audio, probably because of a processing overload.\nAn attempt to restart the audio service has been made, but some problems may remain.\nQuitting other running applications may improve Rosegarden's performance."));

                    } else if ((*i)->getData1() == MappedEvent::FailureCPUOverload) {

#define REPORT_CPU_OVERLOAD 1
#ifdef REPORT_CPU_OVERLOAD

                        stopping();

                        KMessageBox::error(
                            dynamic_cast<TQWidget*>(m_doc->tqparent())->tqparentWidget(),
                            i18n("Run out of processor power for real-time audio processing.  Cannot continue."));

#endif

                    } else {

                        handling = false;
                    }

                    if (handling)
                        continue;

                    if (!m_canReport) {
                        SETQMAN_DEBUG << "Not reporting it to user just yet"
                        << endl;
                        continue;
                    }

                    if ((*i)->getData1() == MappedEvent::FailureALSACallFailed) {

                        struct timeval tv;
                        (void)gettimeofday(&tv, 0);

                        if (tv.tv_sec - warningShownAt >= 5 &&
                                !boolShowingALSAWarning) {

                            TQString message = i18n("A serious error has occurred in the ALSA MIDI subsystem.  It may not be possible to continue sequencing.  Please check console output for more information.");
                            boolShowingALSAWarning = true;

                            KMessageBox::information(0, message);
                            boolShowingALSAWarning = false;

                            (void)gettimeofday(&tv, 0);
                            warningShownAt = tv.tv_sec;
                        }

                    } else if ((*i)->getData1() == MappedEvent::FailureXRuns) {

                        //#define REPORT_XRUNS 1
#ifdef REPORT_XRUNS

                        struct timeval tv;
                        (void)gettimeofday(&tv, 0);

                        if (tv.tv_sec - warningShownAt >= 5 &&
                                !boolShowingWarning) {

                            TQString message = i18n("JACK Audio subsystem is losing sample frames.");
                            boolShowingWarning = true;

                            KMessageBox::information(0, message);
                            boolShowingWarning = false;

                            (void)gettimeofday(&tv, 0);
                            warningShownAt = tv.tv_sec;
                        }
#endif

                    } else if (!m_shownOverrunWarning) {

                        TQString message;

                        switch ((*i)->getData1()) {

                        case MappedEvent::FailureDiscUnderrun:
                            message = i18n("Failed to read audio data from disc in time to service the audio subsystem.");
                            break;

                        case MappedEvent::FailureDiscOverrun:
                            message = i18n("Failed to write audio data to disc fast enough to service the audio subsystem.");
                            break;

                        case MappedEvent::FailureBussMixUnderrun:
                            message = i18n("The audio mixing subsystem is failing to keep up.");
                            break;

                        case MappedEvent::FailureMixUnderrun:
                            message = i18n("The audio subsystem is failing to keep up.");
                            break;

                        default:
                            message = i18n("Unknown sequencer failure mode!");
                            break;
                        }

                        m_shownOverrunWarning = true;

#ifdef REPORT_XRUNS

                        KMessageBox::information(0, message);
#else

                        if ((*i)->getData1() == MappedEvent::FailureDiscOverrun) {
                            // the error you can't hear
                            KMessageBox::information(0, message);
                        } else {
                            std::cerr << message << std::endl;
                        }
#endif

                    }

                    // Turn off the report flag and set off a one-shot
                    // timer for 5 seconds.
                    //
                    if (!m_reportTimer->isActive()) {
                        m_canReport = false;
                        m_reportTimer->start(5000, true);
                    }
                }
            } else {
                KStartupLogo::hideIfStillThere();

                if ((*i)->getType() == MappedEvent::SystemFailure) {

                    if ((*i)->getData1() == MappedEvent::FailureJackRestartFailed) {

                        KMessageBox::error(
                            dynamic_cast<TQWidget*>(m_doc->tqparent()),
                            i18n("The JACK Audio subsystem has failed or it has stopped Rosegarden from processing audio.\nPlease restart Rosegarden to continue working with audio.\nQuitting other running applications may improve Rosegarden's performance."));

                    } else if ((*i)->getData1() == MappedEvent::FailureJackRestart) {

                        KMessageBox::error(
                            dynamic_cast<TQWidget*>(m_doc->tqparent()),
                            i18n("The JACK Audio subsystem has stopped Rosegarden from processing audio, probably because of a processing overload.\nAn attempt to restart the audio service has been made, but some problems may remain.\nQuitting other running applications may improve Rosegarden's performance."));

                    } else if ((*i)->getData1() == MappedEvent::WarningImpreciseTimer &&
                               shouldWarnForImpreciseTimer()) {

                        std::cerr << "Rosegarden: WARNING: No accurate sequencer timer available" << std::endl;

                        KStartupLogo::hideIfStillThere();
                        CurrentProgressDialog::freeze();

                        RosegardenGUIApp::self()->awaitDialogClearance();

                        KMessageBox::information(
                            dynamic_cast<TQWidget*>(m_doc->tqparent()),
                            i18n("<h3>System timer resolution is too low</h3><p>Rosegarden was unable to find a high-resolution timing source for MIDI performance.</p><p>This may mean you are using a Linux system with the kernel timer resolution set too low.  Please contact your Linux distributor for more information.</p><p>Some Linux distributors already provide low latency kernels, see <a href=\"http://rosegarden.wiki.sourceforge.net/Low+latency+kernels\">http://rosegarden.wiki.sourceforge.net/Low+latency+kernels</a> for instructions.</p>"), 
			    NULL, NULL, 
			    KMessageBox::Notify + KMessageBox::AllowLink);
                        
                        CurrentProgressDialog::thaw();

                    } else if ((*i)->getData1() == MappedEvent::WarningImpreciseTimerTryRTC &&
                               shouldWarnForImpreciseTimer()) {

                        std::cerr << "Rosegarden: WARNING: No accurate sequencer timer available" << std::endl;

                        KStartupLogo::hideIfStillThere();
                        CurrentProgressDialog::freeze();

                        RosegardenGUIApp::self()->awaitDialogClearance();

                        KMessageBox::information(
                            dynamic_cast<TQWidget*>(m_doc->tqparent()),
                            i18n("<h3>System timer resolution is too low</h3><p>Rosegarden was unable to find a high-resolution timing source for MIDI performance.</p><p>You may be able to solve this problem by loading the RTC timer kernel module.  To do this, try running <b>sudo modprobe snd-rtctimer</b> in a terminal window and then restarting Rosegarden.</p><p>Alternatively, check whether your Linux distributor provides a multimedia-optimized kernel.  See <a href=\"http://rosegarden.wiki.sourceforge.net/Low+latency+kernels\">http://rosegarden.wiki.sourceforge.net/Low+latency+kernels</a> for notes about this.</p>"), 
			    NULL, NULL, 
			    KMessageBox::Notify + KMessageBox::AllowLink);
                        
                        CurrentProgressDialog::thaw();
                    }
                }
            }
        }
    }

    // if we aren't playing or recording, consider invoking any
    // step-by-step clients (using unfiltered composition).  send
    // out any incoming external controller events

    for (i = mC.begin(); i != mC.end(); ++i ) {
        if (m_transporttqStatus == STOPPED ||
            m_transporttqStatus == RECORDING_ARMED) {
            if ((*i)->getType() == MappedEvent::MidiNote) {
                if ((*i)->getVelocity() == 0) {
                    emit insertableNoteOffReceived((*i)->getPitch(), (*i)->getVelocity());
                } else {
                    emit insertableNoteOnReceived((*i)->getPitch(), (*i)->getVelocity());
                }
            }
        }
        if ((*i)->getRecordedDevice() == Device::CONTROL_DEVICE) {
            SETQMAN_DEBUG << "controllerDeviceEventReceived" << endl;
            emit controllerDeviceEventReceived(*i);
        }
    }
}

void
SequenceManager::rewindToBeginning()
{
    SETQMAN_DEBUG << "SequenceManager::rewindToBeginning()\n";
    m_doc->slotSetPointerPosition(m_doc->getComposition().getStartMarker());
}

void
SequenceManager::fastForwardToEnd()
{
    SETQMAN_DEBUG << "SequenceManager::fastForwardToEnd()\n";

    Composition &comp = m_doc->getComposition();
    m_doc->slotSetPointerPosition(comp.getDuration());
}

void
SequenceManager::setLoop(const timeT &lhs, const timeT &rhs)
{
    // do not set a loop if JACK transport sync is enabled, because this is
    // completely broken, and aptqparently broken due to a limitation of JACK
    // transport itself.  #1240039 - DMM
    //    KConfig* config = kapp->config();
    //    config->setGroup(SequencerOptionsConfigGroup);
    //    if (config->readBoolEntry("jacktransport", false))
    //    {
    //	//!!! message box should go here to inform user of why the loop was
    //	// not set, but I can't add it at the moment due to to the pre-release
    //	// freeze - DMM
    //	return;
    //    }

    // Let the sequencer know about the loop markers
    //
    TQByteArray data;
    TQDataStream streamOut(data, IO_WriteOnly);

    RealTime loopStart =
        m_doc->getComposition().getElapsedRealTime(lhs);
    RealTime loopEnd =
        m_doc->getComposition().getElapsedRealTime(rhs);

    streamOut << (long)loopStart.sec;
    streamOut << (long)loopStart.nsec;
    streamOut << (long)loopEnd.sec;
    streamOut << (long)loopEnd.nsec;

    rgapp->sequencerSend("setLoop(long int, long int, long int, long int)", data);
}

void
SequenceManager::checkSoundDrivertqStatus(bool warnUser)
{
    TQByteArray data;
    TQCString replyType;
    TQByteArray replyData;
    TQDataStream streamOut(data, IO_WriteOnly);

    streamOut << TQString(VERSION);

    if (! rgapp->sequencerCall("getSoundDrivertqStatus(TQString)",
                               replyType, replyData, data)) {

        m_soundDrivertqStatus = NO_DRIVER;

    } else {

        TQDataStream streamIn(replyData, IO_ReadOnly);
        unsigned int result;
        streamIn >> result;
        m_soundDrivertqStatus = result;
    }

    SETQMAN_DEBUG << "Sound driver status is: " << m_soundDrivertqStatus << endl;

    if (!warnUser) return;

#ifdef HAVE_LIBJACK
    if ((m_soundDrivertqStatus & (AUDIO_OK | MIDI_OK | VERSION_OK)) ==
        (AUDIO_OK | MIDI_OK | VERSION_OK)) return;
#else
    if ((m_soundDrivertqStatus & (MIDI_OK | VERSION_OK)) ==
        (MIDI_OK | VERSION_OK)) return;
#endif

    KStartupLogo::hideIfStillThere();
    CurrentProgressDialog::freeze();

    TQString text = "";

    if (m_soundDrivertqStatus == NO_DRIVER) {
        text = i18n("<p>Both MIDI and Audio subsystems have failed to initialize.</p><p>You may continue without the sequencer, but we suggest closing Rosegarden, running \"alsaconf\" as root, and starting Rosegarden again.  If you wish to run with no sequencer by design, then use \"rosegarden --nosequencer\" to avoid seeing this error in the future.</p>");
    } else if (!(m_soundDrivertqStatus & MIDI_OK)) {
        text = i18n("<p>The MIDI subsystem has failed to initialize.</p><p>You may continue without the sequencer, but we suggest closing Rosegarden, running \"modprobe snd-seq-midi\" as root, and starting Rosegarden again.  If you wish to run with no sequencer by design, then use \"rosegarden --nosequencer\" to avoid seeing this error in the future.</p>");
    } else if (!(m_soundDrivertqStatus & VERSION_OK)) {
        text = i18n("<p>The Rosegarden sequencer module version does not match the GUI module version.</p><p>You have probably mixed up files from two different versions of Rosegarden.  Please check your installation.</p>");
    }

    if (text != "") {
        RosegardenGUIApp::self()->awaitDialogClearance();
        KMessageBox::error(RosegardenGUIApp::self(),
                           i18n("<h3>Sequencer startup failed</h3>%1").tqarg(text));
        CurrentProgressDialog::thaw();
        return;
    }

#ifdef HAVE_LIBJACK
    if (!(m_soundDrivertqStatus & AUDIO_OK)) {
        RosegardenGUIApp::self()->awaitDialogClearance();
        KMessageBox::information(RosegardenGUIApp::self(), i18n("<h3>Failed to connect to JACK audio server.</h3><p>Rosegarden could not connect to the JACK audio server.  This probably means the JACK server is not running.</p><p>If you want to be able to play or record audio files or use plugins, you should exit Rosegarden and start the JACK server before running Rosegarden again.</p>"),
                                 i18n("Failed to connect to JACK"),
                                 "startup-jack-failed");
    }
#endif
    CurrentProgressDialog::thaw();
}

void
SequenceManager::preparePlayback(bool forceProgramChanges)
{
    Studio &studio = m_doc->getStudio();
    InstrumentList list = studio.getAllInstruments();
    MappedComposition mC;
    MappedEvent *mE;

    std::set<InstrumentId> activeInstruments;

    Composition &composition = m_doc->getComposition();

    for (Composition::trackcontainer::const_iterator i =
             composition.getTracks().begin();
         i != composition.getTracks().end(); ++i) {

        Track *track = i->second;
        if (track) activeInstruments.insert(track->getInstrument());
    }

    // Send the MappedInstruments (minimal Instrument information
    // required for Performance) to the Sequencer
    //
    InstrumentList::iterator it = list.begin();
    for (; it != list.end(); it++) {

        StudioControl::sendMappedInstrument(MappedInstrument(*it));

        // Send program changes for MIDI Instruments
        //
        if ((*it)->getType() == Instrument::Midi) {

            if (activeInstruments.find((*it)->getId()) ==
                activeInstruments.end()) {
//                std::cerr << "SequenceManager::preparePlayback: instrument "
//                          << (*it)->getId() << " is not in use" << std::endl;
                continue;
            }            

            // send bank select always before program change
            //
            if ((*it)->sendsBankSelect()) {
                mE = new MappedEvent((*it)->getId(),
                                     MappedEvent::MidiController,
                                     MIDI_CONTROLLER_BANK_MSB,
                                     (*it)->getMSB());
                mC.insert(mE);

                mE = new MappedEvent((*it)->getId(),
                                     MappedEvent::MidiController,
                                     MIDI_CONTROLLER_BANK_LSB,
                                     (*it)->getLSB());
                mC.insert(mE);
            }

            // send program change
            //
            if ((*it)->sendsProgramChange() || forceProgramChanges) {
                RG_DEBUG << "SequenceManager::preparePlayback() : sending prg change for "
                << (*it)->getPresentationName().c_str() << endl;

                mE = new MappedEvent((*it)->getId(),
                                     MappedEvent::MidiProgramChange,
                                     (*it)->getProgramChange());
                mC.insert(mE);
            }

        } else if ((*it)->getType() == Instrument::Audio ||
                   (*it)->getType() == Instrument::SoftSynth) {
        } else {
            RG_DEBUG << "SequenceManager::preparePlayback - "
            << "unrecognised instrument type" << endl;
        }


    }

    // Send the MappedComposition if it's got anything in it
    showVisuals(mC);
    StudioControl::sendMappedComposition(mC);
}

void
SequenceManager::sendAudioLevel(MappedEvent *mE)
{
    RosegardenGUIView *v;
    TQList<RosegardenGUIView>& viewList = m_doc->getViewList();

    for (v = viewList.first(); v != 0; v = viewList.next()) {
        v->showVisuals(mE);
    }

}

void
SequenceManager::resetControllers()
{
    SETQMAN_DEBUG << "SequenceManager::resetControllers - resetting\n";

    // Should do all Midi Instrument - not just guess like this is doing
    // currently.

    InstrumentList list = m_doc->getStudio().getPresentationInstruments();
    InstrumentList::iterator it;

    MappedComposition mC;

    for (it = list.begin(); it != list.end(); it++) {
        if ((*it)->getType() == Instrument::Midi) {
            MappedEvent *mE = new MappedEvent((*it)->getId(),
                                              MappedEvent::MidiController,
                                              MIDI_CONTROLLER_RESET,
                                              0);
            mC.insert(mE);
        }
    }

    StudioControl::sendMappedComposition(mC);
    //showVisuals(mC);
}

void
SequenceManager::resetMidiNetwork()
{
    SETQMAN_DEBUG << "SequenceManager::resetMidiNetwork - resetting\n";
    MappedComposition mC;

    // Should do all Midi Instrument - not just guess like this is doing
    // currently.

    for (unsigned int i = 0; i < 16; i++) {
        MappedEvent *mE =
            new MappedEvent(MidiInstrumentBase + i,
                            MappedEvent::MidiController,
                            MIDI_SYSTEM_RESET,
                            0);

        mC.insert(mE);
    }
    showVisuals(mC);
    StudioControl::sendMappedComposition(mC);
}

void
SequenceManager::sendMIDIRecordingDevice(const TQString recordDeviceStr)
{

    if (recordDeviceStr) {
        int recordDevice = recordDeviceStr.toInt();

        if (recordDevice >= 0) {
            MappedEvent mE(MidiInstrumentBase,  // InstrumentId
                           MappedEvent::SystemRecordDevice,
                           MidiByte(recordDevice),
                           MidiByte(true));

            StudioControl::sendMappedEvent(mE);
            SETQMAN_DEBUG << "set MIDI record device to "
            << recordDevice << endl;
        }
    }
}

void
SequenceManager::restoreRecordSubscriptions()
{
    KConfig* config = kapp->config();
    config->setGroup(SequencerOptionsConfigGroup);
    //TQString recordDeviceStr = config->readEntry("midirecorddevice");
    TQStringList devList = config->readListEntry("midirecorddevice");

    for ( TQStringList::ConstIterator it = devList.begin();
            it != devList.end(); ++it) {
        sendMIDIRecordingDevice(*it);
    }

}

void
SequenceManager::reinitialiseSequencerStudio()
{
    KConfig* config = kapp->config();
    config->setGroup(SequencerOptionsConfigGroup);
    //TQString recordDeviceStr = config->readEntry("midirecorddevice");

    //sendMIDIRecordingDevice(recordDeviceStr);
    restoreRecordSubscriptions();

    // Toggle JACK audio ports appropriately
    //
    bool submasterOuts = config->readBoolEntry("audiosubmasterouts", false);
    bool faderOuts = config->readBoolEntry("audiofaderouts", false);
    unsigned int audioFileFormat = config->readUnsignedNumEntry("audiorecordfileformat", 1);

    MidiByte ports = 0;
    if (faderOuts) {
        ports |= MappedEvent::FaderOuts;
    }
    if (submasterOuts) {
        ports |= MappedEvent::SubmasterOuts;
    }
    MappedEvent mEports
    (MidiInstrumentBase,
     MappedEvent::SystemAudioPorts,
     ports);

    StudioControl::sendMappedEvent(mEports);

    MappedEvent mEff
    (MidiInstrumentBase,
     MappedEvent::SystemAudioFileFormat,
     audioFileFormat);
    StudioControl::sendMappedEvent(mEff);


    // Set the studio from the current document
    //
    m_doc->initialiseStudio();
}

void
SequenceManager::panic()
{
    SETQMAN_DEBUG << "panic button\n";

    stopping();

    MappedEvent mE(MidiInstrumentBase, MappedEvent::Panic, 0, 0);
    emit setProgress(40);
    StudioControl::sendMappedEvent(mE);
    emit setProgress(100);

    //    Studio &studio = m_doc->getStudio();
    //
    //    InstrumentList list = studio.getPresentationInstruments();
    //    InstrumentList::iterator it;
    //
    //    int maxDevices = 0, device = 0;
    //    for (it = list.begin(); it != list.end(); it++)
    //        if ((*it)->getType() == Instrument::Midi)
    //            maxDevices++;
    //
    //    emit setProgress(40);
    //
    //    for (it = list.begin(); it != list.end(); it++)
    //    {
    //        if ((*it)->getType() == Instrument::Midi)
    //        {
    //            for (unsigned int i = 0; i < 128; i++)
    //            {
    //                MappedEvent
    //                    mE((*it)->getId(),
    //                                MappedEvent::MidiNote,
    //                                i,
    //                                0);
    //
    //                StudioControl::sendMappedEvent(mE);
    //            }
    //
    //            device++;
    //        }
    //
    //        emit setProgress(int(90.0 * (double(device) / double(maxDevices))));
    //    }
    //
    //    resetControllers();
}

void
SequenceManager::showVisuals(const MappedComposition &mC)
{
    MappedComposition::const_iterator it = mC.begin();
    if (it != mC.end())
        m_transport->setMidiOutLabel(*it);
}

MappedComposition
SequenceManager::applyFiltering(const MappedComposition &mC,
                                MappedEvent::MappedEventType filter)
{
    MappedComposition retMc;
    MappedComposition::const_iterator it = mC.begin();

    for (; it != mC.end(); it++) {
        if (!((*it)->getType() & filter))
            retMc.insert(new MappedEvent(*it));
    }

    return retMc;
}

void SequenceManager::resetCompositionMmapper()
{
    SETQMAN_DEBUG << "SequenceManager::resetCompositionMmapper()\n";
    delete m_compositionMmapper;
    m_compositionMmapper = new CompositionMmapper(m_doc);

    resetMetronomeMmapper();
    resetTempoSegmentMmapper();
    resetTimeSigSegmentMmapper();
    resetControlBlockMmapper();
}

void SequenceManager::resetMetronomeMmapper()
{
    SETQMAN_DEBUG << "SequenceManager::resetMetronomeMmapper()\n";

    delete m_metronomeMmapper;
    m_metronomeMmapper = SegmentMmapperFactory::makeMetronome(m_doc);
}

void SequenceManager::resetTempoSegmentMmapper()
{
    SETQMAN_DEBUG << "SequenceManager::resetTempoSegmentMmapper()\n";

    delete m_tempoSegmentMmapper;
    m_tempoSegmentMmapper = SegmentMmapperFactory::makeTempo(m_doc);
}

void SequenceManager::resetTimeSigSegmentMmapper()
{
    SETQMAN_DEBUG << "SequenceManager::resetTimeSigSegmentMmapper()\n";

    delete m_timeSigSegmentMmapper;
    m_timeSigSegmentMmapper = SegmentMmapperFactory::makeTimeSig(m_doc);
}

void SequenceManager::resetControlBlockMmapper()
{
    SETQMAN_DEBUG << "SequenceManager::resetControlBlockMmapper()\n";

    m_controlBlockMmapper->setDocument(m_doc);
}

bool SequenceManager::event(TQEvent *e)
{
    if (e->type() == TQEvent::User) {
        SETQMAN_DEBUG << "SequenceManager::event() with user event\n";
        if (m_updateRequested) {
            SETQMAN_DEBUG << "SequenceManager::event(): update requested\n";
            checkRefreshtqStatus();
            m_updateRequested = false;
        }
        return true;
    } else {
        return TQObject::event(e);
    }
}

void SequenceManager::update()
{
    SETQMAN_DEBUG << "SequenceManager::update()\n";
    // schedule a refresh-status check for the next event loop
    TQEvent *e = new TQEvent(TQEvent::User);
    m_updateRequested = true;
    TQApplication::postEvent(this, e);
}

void SequenceManager::checkRefreshtqStatus()
{
    SETQMAN_DEBUG << "SequenceManager::checkRefreshtqStatus()\n";

    // Look at trigger segments first: if one of those has changed, we'll
    // need to be aware of it when scanning segments subsequently

    TriggerSegmentRec::SegmentRuntimeIdSet ridset;
    Composition &comp = m_doc->getComposition();
    SegmentRefreshMap newTriggerMap;

    for (Composition::triggersegmentcontaineriterator i =
                comp.getTriggerSegments().begin();
            i != comp.getTriggerSegments().end(); ++i) {

        Segment *s = (*i)->getSegment();

        if (m_triggerSegments.find(s) == m_triggerSegments.end()) {
            newTriggerMap[s] = s->getNewRefreshStatusId();
        } else {
            newTriggerMap[s] = m_triggerSegments[s];
        }

        if (s->getRefreshtqStatus(newTriggerMap[s]).needsRefresh()) {
            TriggerSegmentRec::SegmentRuntimeIdSet &thisSet = (*i)->getReferences();
            ridset.insert(thisSet.begin(), thisSet.end());
            s->getRefreshtqStatus(newTriggerMap[s]).setNeedsRefresh(false);
        }
    }

    m_triggerSegments = newTriggerMap;

    SETQMAN_DEBUG << "SequenceManager::checkRefreshtqStatus: segments modified by changes to trigger segments are:" << endl;
    int x = 0;
    for (TriggerSegmentRec::SegmentRuntimeIdSet::iterator i = ridset.begin();
            i != ridset.end(); ++i) {
        SETQMAN_DEBUG << x << ": " << *i << endl;
        ++x;
    }

    std::vector<Segment*>::iterator i;

    // Check removed segments first
    for (i = m_removedSegments.begin(); i != m_removedSegments.end(); ++i) {
        processRemovedSegment(*i);
    }
    m_removedSegments.clear();

    SETQMAN_DEBUG << "SequenceManager::checkRefreshtqStatus: we have "
    << m_segments.size() << " segments" << endl;

    // then the ones which are still there
    for (SegmentRefreshMap::iterator i = m_segments.begin();
            i != m_segments.end(); ++i) {
        if (i->first->getRefreshtqStatus(i->second).needsRefresh() ||
                ridset.find(i->first->getRuntimeId()) != ridset.end()) {
            segmentModified(i->first);
            i->first->getRefreshtqStatus(i->second).setNeedsRefresh(false);
        }
    }

    // then added ones
    for (i = m_addedSegments.begin(); i != m_addedSegments.end(); ++i) {
        processAddedSegment(*i);
    }
    m_addedSegments.clear();
}

void SequenceManager::segmentModified(Segment* s)
{
    SETQMAN_DEBUG << "SequenceManager::segmentModified(" << s << ")\n";

    bool sizeChanged = m_compositionMmapper->segmentModified(s);

    SETQMAN_DEBUG << "SequenceManager::segmentModified() : size changed = "
    << sizeChanged << endl;

    if ((m_transporttqStatus == PLAYING) && sizeChanged) {
        TQByteArray data;
        TQDataStream streamOut(data, IO_WriteOnly);

        streamOut << (TQString)m_compositionMmapper->getSegmentFileName(s);
        streamOut << (size_t)m_compositionMmapper->getSegmentFileSize(s);

        SETQMAN_DEBUG << "SequenceManager::segmentModified() : DCOP-call sequencer remapSegment"
        << m_compositionMmapper->getSegmentFileName(s) << endl;

        rgapp->sequencerSend("remapSegment(TQString, size_t)", data);
    }
}

void SequenceManager::segmentAdded(const Composition*, Segment* s)
{
    SETQMAN_DEBUG << "SequenceManager::segmentAdded(" << s << ")\n";
    m_addedSegments.push_back(s);
}

void SequenceManager::segmentRemoved(const Composition*, Segment* s)
{
    SETQMAN_DEBUG << "SequenceManager::segmentRemoved(" << s << ")\n";
    m_removedSegments.push_back(s);
    std::vector<Segment*>::iterator i = find(m_addedSegments.begin(), m_addedSegments.end(), s);
    if (i != m_addedSegments.end())
        m_addedSegments.erase(i);
}

void SequenceManager::segmentRepeatChanged(const Composition*, Segment* s, bool repeat)
{
    SETQMAN_DEBUG << "SequenceManager::segmentRepeatChanged(" << s << ", " << repeat << ")\n";
    segmentModified(s);
}

void SequenceManager::segmentRepeatEndChanged(const Composition*, Segment* s, timeT newEndTime)
{
    SETQMAN_DEBUG << "SequenceManager::segmentRepeatEndChanged(" << s << ", " << newEndTime << ")\n";
    segmentModified(s);
}

void SequenceManager::segmentEventsTimingChanged(const Composition*, Segment * s, timeT t, RealTime)
{
    SETQMAN_DEBUG << "SequenceManager::segmentEventsTimingChanged(" << s << ", " << t << ")\n";
    segmentModified(s);
    if (s && s->getType() == Segment::Audio && m_transporttqStatus == PLAYING) {
        TQByteArray data;
        rgapp->sequencerSend("remapTracks()", data);
    }
}

void SequenceManager::segmentTransposeChanged(const Composition*, Segment *s, int transpose)
{
    SETQMAN_DEBUG << "SequenceManager::segmentTransposeChanged(" << s << ", " << transpose << ")\n";
    segmentModified(s);
}

void SequenceManager::segmentTrackChanged(const Composition*, Segment *s, TrackId id)
{
    SETQMAN_DEBUG << "SequenceManager::segmentTrackChanged(" << s << ", " << id << ")\n";
    segmentModified(s);
    if (s && s->getType() == Segment::Audio && m_transporttqStatus == PLAYING) {
        TQByteArray data;
        rgapp->sequencerSend("remapTracks()", data);
    }
}

void SequenceManager::segmentEndMarkerChanged(const Composition*, Segment *s, bool)
{
    SETQMAN_DEBUG << "SequenceManager::segmentEndMarkerChanged(" << s << ")\n";
    segmentModified(s);
}

void SequenceManager::processAddedSegment(Segment* s)
{
    SETQMAN_DEBUG << "SequenceManager::processAddedSegment(" << s << ")\n";

    m_compositionMmapper->segmentAdded(s);

    if (m_transporttqStatus == PLAYING) {

        TQByteArray data;
        TQDataStream streamOut(data, IO_WriteOnly);

        streamOut << m_compositionMmapper->getSegmentFileName(s);

        if (!rgapp->sequencerSend("addSegment(TQString)", data)) {
            m_transporttqStatus = STOPPED;
        }
    }

    // Add to segments map
    int id = s->getNewRefreshStatusId();
    m_segments.insert(SegmentRefreshMap::value_type(s, id));

}

void SequenceManager::processRemovedSegment(Segment* s)
{
    SETQMAN_DEBUG << "SequenceManager::processRemovedSegment(" << s << ")\n";

    TQString filename = m_compositionMmapper->getSegmentFileName(s);
    m_compositionMmapper->segmentDeleted(s);

    if (m_transporttqStatus == PLAYING) {

        TQByteArray data;
        TQDataStream streamOut(data, IO_WriteOnly);

        streamOut << filename;

        if (!rgapp->sequencerSend("deleteSegment(TQString)", data)) {
            // failed
            m_transporttqStatus = STOPPED;
        }
    }

    // Remove from segments map
    m_segments.erase(s);
}

void SequenceManager::endMarkerTimeChanged(const Composition *, bool /*shorten*/)
{
    SETQMAN_DEBUG << "SequenceManager::endMarkerTimeChanged()\n";
    m_compositionMmapperResetTimer->start(500, true); // schedule a composition mmapper reset in 0.5s
}

void SequenceManager::timeSignatureChanged(const Composition *)
{
    resetMetronomeMmapper();
}

void SequenceManager::trackChanged(const Composition *, Track* t)
{
    SETQMAN_DEBUG << "SequenceManager::trackChanged(" << t << ", " << (t ? t->getPosition() : -1) << ")\n";
    m_controlBlockMmapper->updateTrackData(t);

    if (m_transporttqStatus == PLAYING) {
        TQByteArray data;
        rgapp->sequencerSend("remapTracks()", data);
    }
}

void SequenceManager::trackDeleted(const Composition *, TrackId t)
{
    m_controlBlockMmapper->setTrackDeleted(t);
}

void SequenceManager::metronomeChanged(InstrumentId id,
                                       bool regenerateTicks)
{
    // This method is called when the user has changed the
    // metronome instrument, pitch etc

    SETQMAN_DEBUG << "SequenceManager::metronomeChanged (simple)"
    << ", instrument = "
    << id
    << endl;

    if (regenerateTicks)
        resetMetronomeMmapper();

    m_controlBlockMmapper->updateMetronomeData(id);
    if (m_transporttqStatus == PLAYING) {
        m_controlBlockMmapper->updateMetronomeForPlayback();
    } else {
        m_controlBlockMmapper->updateMetronomeForRecord();
    }

    m_metronomeMmapper->refresh();
    m_timeSigSegmentMmapper->refresh();
    m_tempoSegmentMmapper->refresh();
}

void SequenceManager::metronomeChanged(const Composition *)
{
    // This method is called when the muting status in the composition
    // has changed -- the metronome itself has not actually changed

    SETQMAN_DEBUG << "SequenceManager::metronomeChanged "
    << ", instrument = "
    << m_metronomeMmapper->getMetronomeInstrument()
    << endl;

    m_controlBlockMmapper->updateMetronomeData
    (m_metronomeMmapper->getMetronomeInstrument());

    if (m_transporttqStatus == PLAYING) {
        m_controlBlockMmapper->updateMetronomeForPlayback();
    } else {
        m_controlBlockMmapper->updateMetronomeForRecord();
    }
}

void SequenceManager::filtersChanged(MidiFilter thruFilter,
                                     MidiFilter recordFilter)
{
    m_controlBlockMmapper->updateMidiFilters(thruFilter, recordFilter);
}

void SequenceManager::soloChanged(const Composition *, bool solo, TrackId selectedTrack)
{
    if (m_controlBlockMmapper->updateSoloData(solo, selectedTrack)) {
        if (m_transporttqStatus == PLAYING) {
            TQByteArray data;
            rgapp->sequencerSend("remapTracks()", data);
        }
    }
}

void SequenceManager::tempoChanged(const Composition *c)
{
    SETQMAN_DEBUG << "SequenceManager::tempoChanged()\n";

    // Refresh all segments
    //
    for (SegmentRefreshMap::iterator i = m_segments.begin();
            i != m_segments.end(); ++i) {
        segmentModified(i->first);
    }

    // and metronome, time sig and tempo
    //
    m_metronomeMmapper->refresh();
    m_timeSigSegmentMmapper->refresh();
    m_tempoSegmentMmapper->refresh();

    if (c->isLooping())
        setLoop(c->getLoopStart(), c->getLoopEnd());
    else if (m_transporttqStatus == PLAYING) {
        // If the tempo changes during playback, reset the pointer
        // position because the sequencer keeps track of position in
        // real time and we want to maintain the same position in
        // musical time.  Turn off play tracking while this happens,
        // so that we don't jump about in the main window while the
        // user's trying to drag the tempo in it.  (That doesn't help
        // for matrix or notation though, sadly)
        bool tracking = RosegardenGUIApp::self()->isTrackEditorPlayTracking();
        if (tracking)
            RosegardenGUIApp::self()->slotToggleTracking();
        m_doc->slotSetPointerPosition(c->getPosition());
        if (tracking)
            RosegardenGUIApp::self()->slotToggleTracking();
    }
}

void
SequenceManager::sendTransportControlStatuses()
{
    KConfig* config = kapp->config();
    config->setGroup(SequencerOptionsConfigGroup);

    // Get the config values
    //
    bool jackTransport = config->readBoolEntry("jacktransport", false);
    bool jackMaster = config->readBoolEntry("jackmaster", false);

    int mmcMode = config->readNumEntry("mmcmode", 0);
    int mtcMode = config->readNumEntry("mtcmode", 0);

    int midiClock = config->readNumEntry("midiclock", 0);
    bool midiSyncAuto = config->readBoolEntry("midisyncautoconnect", false);

    // Send JACK transport
    //
    int jackValue = 0;
    if (jackTransport && jackMaster)
        jackValue = 2;
    else {
        if (jackTransport)
            jackValue = 1;
        else
            jackValue = 0;
    }

    MappedEvent mEjackValue(MidiInstrumentBase,  // InstrumentId
                            MappedEvent::SystemJackTransport,
                            MidiByte(jackValue));
    StudioControl::sendMappedEvent(mEjackValue);


    // Send MMC transport
    //
    MappedEvent mEmmcValue(MidiInstrumentBase,  // InstrumentId
                           MappedEvent::SystemMMCTransport,
                           MidiByte(mmcMode));

    StudioControl::sendMappedEvent(mEmmcValue);


    // Send MTC transport
    //
    MappedEvent mEmtcValue(MidiInstrumentBase,  // InstrumentId
                           MappedEvent::SystemMTCTransport,
                           MidiByte(mtcMode));

    StudioControl::sendMappedEvent(mEmtcValue);


    // Send MIDI Clock
    //
    MappedEvent mEmidiClock(MidiInstrumentBase,  // InstrumentId
                            MappedEvent::SystemMIDIClock,
                            MidiByte(midiClock));

    StudioControl::sendMappedEvent(mEmidiClock);


    // Send MIDI Sync Auto-Connect
    //
    MappedEvent mEmidiSyncAuto(MidiInstrumentBase,  // InstrumentId
                               MappedEvent::SystemMIDISyncAuto,
                               MidiByte(midiSyncAuto ? 1 : 0));

    StudioControl::sendMappedEvent(mEmidiSyncAuto);

}

void
SequenceManager::slotCountdownTimerTimeout()
{
    // Set the elapsed time in seconds
    //
    m_countdownDialog->setElapsedTime(m_recordTime->elapsed() / 1000);
}

void
SequenceManager::slotFoundMountPoint(const TQString&,
                                     unsigned long kBSize,
                                     unsigned long /*kBUsed*/,
                                     unsigned long kBAvail)
{
    m_gotDiskSpaceResult = true;
    m_diskSpaceKBAvail = kBAvail;
}

void
SequenceManager::enableMIDIThruRouting(bool state)
{
    m_controlBlockMmapper->enableMIDIThruRouting(state);
}

int
SequenceManager::getSampleRate() 
{
    if (m_sampleRate != 0) return m_sampleRate;

    TQCString replyType;
    TQByteArray replyData;
    if (rgapp->sequencerCall("getSampleRate()", replyType, replyData)) {
        TQDataStream streamIn(replyData, IO_ReadOnly);
        unsigned int result;
        streamIn >> m_sampleRate;
    }

    return m_sampleRate;
}

bool
SequenceManager::shouldWarnForImpreciseTimer()
{
    kapp->config()->setGroup(SequencerOptionsConfigGroup);
    TQString timer = kapp->config()->readEntry("timer");
    if (timer == "(auto)" || timer == "") return true;
    else return false; // if the user has chosen the timer, leave them alone
}

}
#include "SequenceManager.moc"