[920a14]: src / SignalManager.cpp Maximize Restore History

Download this file

SignalManager.cpp    1507 lines (1291 with data), 43.7 kB

   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
/***************************************************************************
SignalManager.cpp - manager class for multi-channel signals
-------------------
begin : Sun Oct 15 2000
copyright : (C) 2000 by Thomas Eschenbacher
email : Thomas.Eschenbacher@gmx.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "config.h"
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <endian.h>
#include <byteswap.h>
#include <limits.h>
#include <math.h>
#include <sched.h> // for sched_yield()
#include <sys/ioctl.h>
#include <linux/soundcard.h>
#include <qbitmap.h>
#include <qpainter.h>
#include <qtimer.h>
#include <kmsgbox.h>
#include <libkwave/Signal.h>
#include <libkwave/DynamicLoader.h>
#include <libkwave/TimeOperation.h>
#include <libkwave/Global.h>
#include <libkwave/DialogOperation.h>
#include <libkwave/Parser.h>
#include <libkwave/FileFormat.h>
#include "KwaveApp.h"
#include "sampleop.h"
#include "ClipBoard.h"
#include "ProgressDialog.h"
#include "SignalManager.h"
#include "SignalWidget.h"
extern Global globals;
/** use at least 2^8 = 256 bytes for playback buffer !!! */
#define MIN_PLAYBACK_BUFFER 8
/** use at most 2^16 = 65536 bytes for playback buffer !!! */
#define MAX_PLAYBACK_BUFFER 16
#if __BYTE_ORDER==__BIG_ENDIAN
#define IS_BIG_ENDIAN
#endif
#define min(x,y) ((x<y) ? x : y)
#define max(x,y) ((x>y) ? x : y)
#define CASE_COMMAND(x) } else if (matchCommand(command, x)) {
//***************************************************************************
void threadStub(TimeOperation *obj)
{
debug("thread started");
ASSERT(obj);
if (obj) {
ASSERT(obj->getSignal());
if (obj->getSignal()) {
(obj->getSignal())->command(obj);
}
}
debug("thread done");
}
//***************************************************************************
SignalManager::SignalManager(Signal *sig)
:QObject(),
m_spx_playback_pos(this, SLOT(updatePlaybackPos())),
m_spx_playback_done(this, SLOT(forwardPlaybackDone()))
{
initialize();
ASSERT(sig);
if (!sig) return;
signal.append(sig);
signal.last()->select(true);
m_channels = 1;
this->rate = sig->getRate();
}
//***************************************************************************
SignalManager::SignalManager(unsigned int numsamples,
int rate, unsigned int channels)
:QObject(),
m_spx_playback_pos(this, SLOT(updatePlaybackPos())),
m_spx_playback_done(this, SLOT(forwardPlaybackDone()))
{
initialize();
this->rate = rate;
this->name = duplicateString(i18n("noname"));
for (unsigned int i = 0; i < channels; i++) {
Signal *new_signal = new Signal(numsamples, rate);
ASSERT(new_signal);
appendChannel(new_signal);
}
}
//***************************************************************************
SignalManager::SignalManager(const char *name, int type)
:QObject(),
m_spx_playback_pos(this, SLOT(updatePlaybackPos())),
m_spx_playback_done(this, SLOT(forwardPlaybackDone()))
{
initialize();
ASSERT(name);
this->name = duplicateString(name);
switch (type) {
case WAV:
loadWav();
break;
case ASCII:
loadAscii();
break;
default:
ASSERT("unknown file type");
}
}
//***************************************************************************
void SignalManager::initialize()
{
name = 0;
lmarker = 0;
rmarker = 0;
m_channels = 0;
rate = 0;
for (unsigned int i = 0; i < sizeof(msg) / sizeof(msg[0]); i++)
msg[i] = 0;
m_spx_playback_pos.setLimit(32); // limit for the queue
signal.setAutoDelete(false);
signal.clear();
}
//***************************************************************************
void SignalManager::getMaxMin(unsigned int channel, int &max, int &min,
unsigned int begin, unsigned int len)
{
ASSERT(channel >= 0);
ASSERT(channel < signal.count());
if (channel >= signal.count()) return;
ASSERT(signal.at(channel));
if (!signal.at(channel)) return;
unsigned int sig_len;
sig_len = signal.at(channel)->getLength();
ASSERT(sig_len);
if (begin + len > sig_len) len = sig_len - begin;
signal.at(channel)->getMaxMin(max, min, begin, len);
}
//***************************************************************************
unsigned int SignalManager::getLength()
{
if (!signal.count()) return 0;
return signal.at(0) ? signal.at(0)->getLength() : 0;
}
//***************************************************************************
const QArray<unsigned int> SignalManager::selectedChannels()
{
unsigned int channel;
unsigned int count = 0;
QArray<unsigned int> list(signal.count());
for (channel=0; channel < signal.count(); channel++) {
Signal *sig = signal.at(channel);
if (!sig) continue;
if (!sig->isSelected()) continue;
list[count]=channel;
count++;
}
list.resize(count);
return list;
}
//***************************************************************************
int SignalManager::singleSample(unsigned int channel, unsigned int offset)
{
ASSERT(channel >= 0);
ASSERT(channel < signal.count());
if ((channel < 0) || (channel >= signal.count())) return 0;
return signal.at(channel) ?
signal.at(channel)->getSingleSample(offset) : 0;
}
//***************************************************************************
int SignalManager::averageSample(unsigned int offset,
const QArray<unsigned int> *channels)
{
unsigned int count = 0;
unsigned int channel;
double value = 0.0;
if (channels) {
for (count=0; count < channels->size(); count++) {
channel = (*channels)[count];
Signal *sig = signal.at(channel);
if (!sig) continue;
value += sig->getSingleSample(offset);
}
} else {
for (channel=0; channel < signal.count(); channel++) {
Signal *sig = signal.at(channel);
if (!sig) continue;
if (!sig->isSelected()) continue;
value += sig->getSingleSample(offset);
count++;
}
}
return (count) ? (int)(value/(double)count) : 0;
}
//****************************************************************************
QBitmap *SignalManager::overview(unsigned int width, unsigned int height,
unsigned int offset, unsigned int length)
{
QBitmap *overview = new QBitmap(width, height);
ASSERT(overview);
if (!overview) return 0;
unsigned int channel;
unsigned int left;
unsigned int right;
unsigned int x;
unsigned int channels = m_channels;
float samples_per_pixel = (float)(length-1) / (float)(width-1);
int min;
int max;
float scale_y = (float)height / (float)(1 << 24);
QPainter p;
overview->fill(color0);
p.begin(overview);
p.setPen(color1);
left = offset;
for (x=0; x < width; x++) {
right = offset + (unsigned int)((x+1) * samples_per_pixel);
// find minimum and maximum over all channels
min = (1<<24);
max = -(1<<24);
for (channel = 0; channel < channels; channel++) {
int min2 = (1<<24);
int max2 = -(1<<24);
getMaxMin(channel, max2, min2, left, right-left+1);
if (min2 < min) min = min2;
if (max2 > max) max = max2;
}
// transform min/max into pixel coordinates
min = (height >> 1) + (int)(min * scale_y);
max = (height >> 1) + (int)(max * scale_y);
// draw the line between min and max
p.drawLine(x, min, x, max);
left = right+1;
}
p.end ();
return overview;
}
//***************************************************************************
int SignalManager::getBitsPerSample()
{
int max_bps = 0;
for (unsigned int i = 0; i < m_channels; i++) {
int bps = (signal.at(i)) ? signal.at(i)->getBits() : 0;
if (bps > max_bps) max_bps = bps;
}
return max_bps;
}
//***************************************************************************
void SignalManager::deleteChannel(unsigned int channel)
{
signal.setAutoDelete(true);
signal.remove(channel);
signal.setAutoDelete(false);
m_channels--; //decrease number of channels...
emit sigChannelDeleted(channel);
emit signalChanged( -1, -1);
}
//***************************************************************************
void SignalManager::addChannel()
{
if (!getLength()) return ;
appendChannel(new Signal(getLength(), rate));
}
//***************************************************************************
void SignalManager::appendChannel(Signal *newsig)
{
ASSERT(newsig);
if (!newsig) return;
signal.append(newsig);
m_channels++;
emit sigChannelAdded(signal.count()-1);
emit signalChanged( -1, -1);
}
//***************************************************************************
void SignalManager::toggleChannel(const unsigned int channel)
{
ASSERT(channel < signal.count());
if (channel >= signal.count()) return;
ASSERT(signal.at(channel));
if (!signal.at(channel)) return;
signal.at(channel)->select(!signal.at(channel)->isSelected());
debug("SignalManager::toggleChannel(%d): selected=%d",
channel, signal.at(channel)->isSelected());
}
//***************************************************************************
bool SignalManager::executeCommand(const char *command)
{
ASSERT(command);
if (!command) return false;
debug("SignalManager::executeCommand(%s)", command); // ###
if (false) {
CASE_COMMAND("playback")
playback_param_t &params = KwaveApp::getPlaybackParams();
Parser parser(command);
params.rate = parser.toInt();
params.channels = parser.toInt();
params.bits_per_sample = parser.toInt();
if (params.device) delete[] params.device;
params.device = duplicateString(parser.getNextParam());
params.bufbase = parser.toInt();
CASE_COMMAND("copy")
if (globals.clipboard) delete globals.clipboard;
globals.clipboard = new ClipBoard();
ASSERT(globals.clipboard);
if (globals.clipboard) {
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) globals.clipboard->appendChannel(
signal.at(i)->copyRange());
}
}
CASE_COMMAND("cut")
if (globals.clipboard) delete globals.clipboard;
globals.clipboard = new ClipBoard();
ASSERT(globals.clipboard);
if (globals.clipboard) {
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) globals.clipboard->appendChannel(
signal.at(i)->cutRange());
}
}
rmarker = lmarker;
emit signalChanged(getLMarker(), -1);
CASE_COMMAND("crop")
if (globals.clipboard) delete globals.clipboard;
globals.clipboard = new ClipBoard();
ASSERT(globals.clipboard);
if (globals.clipboard) {
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) (signal.at(i)->cropRange());
}
}
emit signalChanged( -1, -1);
CASE_COMMAND("delete")
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) signal.at(i)->deleteRange();
}
rmarker = lmarker;
emit signalChanged(getLMarker(), -1);
CASE_COMMAND("paste")
if (globals.clipboard) {
SignalManager *toinsert = globals.clipboard->getSignal();
if (toinsert) {
unsigned int clipchan = toinsert->channels();
unsigned int sourcechan = 0;
/* ### check if the signal has to be re-sampled ### */
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) {
signal.at(i)->insertPaste(toinsert->getSignal(
sourcechan)
);
}
sourcechan++;
sourcechan %= clipchan;
}
if (toinsert->getLength()) {
rmarker = lmarker + toinsert->getLength() - 1;
} else {
rmarker = lmarker;
}
}
emit signalChanged(getLMarker(), -1);
}
CASE_COMMAND("mixpaste")
if (globals.clipboard) {
SignalManager *toinsert = globals.clipboard->getSignal();
if (toinsert) {
unsigned int clipchan = toinsert->channels();
unsigned int sourcechan = 0;
/* ### check if the signal has to be re-sampled ### */
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) {
signal.at(i)->mixPaste(
toinsert->getSignal(sourcechan)
);
}
sourcechan++;
sourcechan %= clipchan;
}
}
emit signalChanged(getLMarker(), -1);
}
CASE_COMMAND("addchannel")
addChannel();
CASE_COMMAND("deletechannel")
Parser parser(command);
unsigned int i = atoi(parser.getFirstParam());
deleteChannel(i);
CASE_COMMAND("selectchannels")
for (unsigned int i = 0; i < m_channels; i++)
if (signal.at(i)) signal.at(i)->select(true);
CASE_COMMAND("invertchannels")
for (unsigned int i = 0; i < m_channels; i++)
toggleChannel(i);
} else {
bool result = promoteCommand(command);
emit signalChanged( -1, -1);
return result;
}
return true;
}
//***************************************************************************
bool SignalManager::promoteCommand (const char *command)
{
debug("SignalManager::promoteCommand(%s)", command); // ###
// loop over all channels
unsigned int i;
for (i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (!signal.at(i)) continue;
// skip channel if not selected
if (!signal.at(i)->isSelected()) continue;
int begin, len;
if (lmarker != rmarker) {
begin = lmarker;
len = rmarker - lmarker + 1;
} else {
begin = 0;
len = signal.at(i)->getLength();
}
char buf[64];
snprintf(buf, sizeof(buf), "%d", i + 1);
char *caption = catString(i18n(command), i18n(" on channel "), buf);
// =====================================================
// === under construction ==============================
// create a nice little Object that should contain everything important
TimeOperation *operation =
new TimeOperation(signal.at(i), command, begin, len);
ASSERT(operation);
if (!operation) {
warning("out of memory: could not allocate TimeOperation");
continue;
}
debug("lmarker=%d, rmarker=%d, begin=%d, len=%d",
lmarker,rmarker,begin,len);
//create a new progress dialog, that watches an memory address
//that is updated by the modules
ProgressDialog *dialog = createProgressDialog(operation, caption);
ASSERT(dialog);
// if (dialog) {
// // connect the signal for "command done"
// connect(dialog, SIGNAL(commandDone()),
// this, SLOT(commandDone()));
//
#ifdef USE_THREADS
pthread_t thread;
// emit modifyingSignal(signal.at(i), begin, length);
// extern int pthread_create __P ((pthread_t *__thread,
// __const pthread_attr_t *__attr,
// void *(*__start_routine) (void *),
// void *__arg));
//create the new thread
if (pthread_create (&thread,
0,
(void *(*)(void *))(threadStub),
(void *)operation) != 0) {
warning("thread creation failed");
if (dialog) delete dialog;
return false;
}
#else /* USE_THREADS */
threadStub(operation);
#endif /* USE_THREADS */
if (dialog) delete dialog;
// === under construction ==============================
// =====================================================
// }
// else warning("out of memory: could not allocate ProgressDialog");
}
// could not promote command to modules or an error occured
if (i < m_channels) return false;
return true;
}
//***************************************************************************
void SignalManager::commandDone()
{
debug("SignalManager::commandDone()"); // ###
emit signalChanged( -1, -1);
}
//***************************************************************************
SignalManager::~SignalManager()
{
stopplay();
while (m_channels) deleteChannel(m_channels-1);
if (name) delete[] name;
}
//***************************************************************************
void SignalManager::setRange(unsigned int l, unsigned int r)
{
for (unsigned int i = 0; i < m_channels; i++) {
ASSERT(signal.at(i));
if (signal.at(i)) signal.at(i)->setMarkers(l, r);
}
ASSERT(signal.at(0));
if (signal.at(0)) {
lmarker = signal.at(0)->getLMarker();
rmarker = signal.at(0)->getRMarker();
}
}
//***************************************************************************
ProgressDialog *SignalManager::createProgressDialog(TimeOperation *operation,
const char *caption)
{
ProgressDialog *dialog = new ProgressDialog (operation, caption);
ASSERT(dialog);
if (dialog) {
dialog->show();
return dialog;
}
return 0;
}
//**********************************************************
//below are all methods of Class SignalManager that deal with I/O
//such as loading and saving.
//***************************************************************************
int SignalManager::loadAscii()
{
float value;
int cnt = 0;
float max = 0;
float amp;
int *sample = 0;
FILE *sigin = fopen(name, "r");
if (!sigin) {
KMsgBox::message(0, i18n("Info"), i18n("File does not exist !"), 2);
return -ENOENT;
}
// scan in the first line for the sample rate
// ### to be done ###
rate = 44100; //will be asked in requester
// scan for number of channels
m_channels = 1;
// loop over all samples in file to get maximum value
while (!feof(sigin)) {
if (fscanf (sigin, "%e\n", &value) == 1) {
if ( value > max) max = value;
if ( -value > max) max = -value;
cnt++;
}
}
debug("SignalManager::loadAscii(): reading ascii file with %d samples",
cnt); // ###
// get the maximum and the scale
amp = (float)((1 << 23)-1) / max;
Signal *new_signal = new Signal(cnt, rate);
ASSERT(new_signal);
if (new_signal) {
signal.append(new_signal);
new_signal->setBits(24);
sample = new_signal->getSample();
}
if (sample) {
fseek (sigin, 0, SEEK_SET); //seek to beginning
cnt = 0;
while (!feof(sigin)) {
if (fscanf(sigin, "%e\n", &value) == 1) {
sample[cnt++] = (int)(value * amp);
}
}
}
fclose (sigin);
return 0;
}
//***************************************************************************
int SignalManager::loadWav()
{
int result = 0;
__uint32_t length = 0;
wavheader header;
FILE *sigfile = fopen(name, "r");
if (!sigfile) {
KMsgBox::message(0, i18n("Info"), i18n("File does not exist !"), 2);
return -ENOENT;
}
int num = fread(&header, 1, sizeof(wavheader), sigfile);
if (num == sizeof(struct wavheader))
{
if ( (strncmp("RIFF", (char*)&(header.riffid), 4) == 0) &&
(strncmp("WAVE", (char*)&(header.wavid), 4) == 0) &&
(strncmp("fmt ", (char*)&(header.fmtid), 4) == 0) )
{
#if defined(IS_BIG_ENDIAN)
header.mode = bswap_16(header.mode);
header.rate = bswap_32(header.rate);
header.channels = bswap_16(header.channels);
header.bitspersample = bswap_16(header.bitspersample);
length = bswap_32(length);
#endif
debug("filelength = 0x%08X", header.filelength);
debug("fmtlength = %d", header.fmtlength);
debug("mode = %d", header.mode);
debug("channels = %d", header.channels);
debug("rate = %d", header.rate);
debug("AvgBytesPerSec = %d", header.AvgBytesPerSec);
debug("BlockAlign = %d", header.BlockAlign);
debug("bitspersample = %d", header.bitspersample);
if (header.mode == 1) {
rate = header.rate;
int res = findWavChunk(sigfile);
if (res == 0) {
KMsgBox::message(0, i18n("Info"),
i18n("File has no data chunk!"),
2);
result = -ENODATA;
} else {
//seek after DATA
fseek(sigfile, res, SEEK_SET);
//load length of data chunk
fread(&length, 1, sizeof(__uint32_t), sigfile);
#if defined(IS_BIG_ENDIAN)
length = bswap_32(length);
#endif
length = (length/(header.bitspersample/8))/header.channels;
switch (header.bitspersample) {
case 8:
case 16:
case 24:
result = loadWavChunk(sigfile, length,
header.channels,
header.bitspersample);
break;
default:
KMsgBox::message(0, i18n("Info"),
i18n("Sorry only 8/16/24 Bits per Sample"\
" are supported !"), 2);
result = -EMEDIUMTYPE;
break;
}
m_channels = header.channels;
}
} else {
KMsgBox::message(0, i18n("Info"),
i18n("File must be uncompressed (Mode 1) !"), 2);
result = -EMEDIUMTYPE;
}
} else {
KMsgBox::message(0, i18n("Info"),
i18n("File is no RIFF Wave File !"), 2);
result = -EMEDIUMTYPE;
}
} else {
KMsgBox::message(0, i18n("Info"),
i18n("File does not contain enough data !"), 2);
result = -ENODATA;
}
fclose(sigfile);
return result;
}
//**********************************************************
// the following routines are for loading and saving in dataformats
// specified by names little/big endian problems are dealt with at compile time
// The corresponding header should have already been written to the file before
// invocation of this methods
//***************************************************************************
void SignalManager::exportAscii(const char *name)
{
ASSERT(name);
if (!name) return ;
unsigned int length = getLength();
ASSERT(length);
if (!length) return;
ASSERT(m_channels);
if (!m_channels) return;
FILE *sigout = fopen(name, "w");
ASSERT(sigout);
if (!sigout) return;
//prepare and show the progress dialog
char progress_title[256];
char str_channels[128];
if (m_channels == 1)
strncpy(str_channels, i18n("Mono"), sizeof(str_channels));
else if (m_channels == 2)
strncpy(str_channels, i18n("Stereo"), sizeof(str_channels));
else
snprintf(str_channels, sizeof(str_channels), "%d-channel", m_channels);
snprintf(progress_title, sizeof(progress_title),
i18n("Exporting %s ASCII file :"),
str_channels);
char *title = duplicateString(i18n(progress_title));
ProgressDialog *dialog = new ProgressDialog (100, title);
delete[] title;
if (dialog) dialog->show();
// loop for writing data
int *sample;
int percent_count = 0;
const double scale_y = (1 << 23)-1;
for (unsigned int pos = 0; pos < length ; pos++) {
// loop over all channels
for (unsigned int channel=0; channel < m_channels; channel++) {
sample = signal.at(channel)->getSample();
if (!sample) continue;
if (channel != 0) fprintf(sigout, ",");
fprintf(sigout, "%0.8e", (double)sample[pos]/scale_y);
}
fprintf(sigout,"\n");
// update the progress bar
percent_count--;
if (dialog && (percent_count <= 0)) {
percent_count = length / 200;
float percent = (float)pos;
percent /= (float)length;
percent *= 100.0;
dialog->setProgress (percent);
}
}
if (dialog) delete dialog;
fclose(sigout);
}
//***************************************************************************
int SignalManager::writeWavChunk(FILE *sigout, unsigned int begin,
unsigned int length, int bits)
{
unsigned int bufsize = 16 * 1024 * sizeof(int);
unsigned char *savebuffer = 0;
sample_t **sample = 0; // array of pointers to samples
int bytes = bits / 8;
int bytes_per_sample = bytes * m_channels;
bufsize -= bufsize % bytes_per_sample;
// try to allocate memory for the save buffer
// if failed, try again with the half buffer size as long
// as <1kB is not reached (then we are really out of memory)
while (savebuffer == 0) {
if (bufsize < 1024) {
debug("SignalManager::writeWavSignal:not enough memory for buffer");
return -ENOMEM;
}
savebuffer = new unsigned char[bufsize];
if (!savebuffer) {
bufsize >>= 1;
bufsize -= bufsize % bytes_per_sample;
}
}
//prepare and show the progress dialog
char progress_title[256];
char str_channels[128];
if (m_channels == 1)
strncpy(str_channels, i18n("Mono"), sizeof(str_channels));
else if (m_channels == 2)
strncpy(str_channels, i18n("Stereo"), sizeof(str_channels));
else
snprintf(str_channels, sizeof(str_channels), "%d-channel", m_channels);
snprintf(progress_title, sizeof(progress_title), "Saving %d-Bit-%s File :",
bits, str_channels);
char *title = duplicateString(i18n(progress_title));
ProgressDialog *dialog = new ProgressDialog (100, title);
delete[] title;
if (dialog) dialog->show();
// prepare the store loop
int percent_count = length / 200;
unsigned int shift = 24-bits;
sample = new (int*)[m_channels];
for (unsigned int channel = 0; channel < m_channels; channel++) {
sample[channel] = signal.at(channel)->getSample();
ASSERT(sample[channel]);
if (!sample[channel]) {
KMsgBox(0, i18n("Warning"),
i18n("empty channel detected, channel count reduced by one"),
2);
m_channels--;
}
}
// loop for writing data
for (unsigned int pos = begin; pos < length; ) {
unsigned char *buf = savebuffer;
unsigned int nsamples = 0;
while (pos < length && (nsamples < bufsize / bytes_per_sample)) {
for (unsigned int channel = 0; channel < m_channels; channel++) {
int *smp = sample[channel] + pos;
int act = (*smp) >> shift;
if (bytes == 1) {
// 8 bits -> unsigned
*(buf++) = (char)((act - 128) & 0xFF);
} else {
// >= 16 bits -> signed
for (register int byte = bytes; byte; byte--) {
*(buf++) = (char)(act & 0xFF);
act >>= 8;
}
}
}
nsamples++;
pos++;
}
int written_bytes = fwrite(savebuffer,
bytes_per_sample, nsamples, sigout);
percent_count -= written_bytes;
if (dialog && (percent_count <= 0)) {
percent_count = length / 200;
float percent = (float)pos;
percent /= (float)length;
percent *= 100.0;
dialog->setProgress (percent);
}
}
if (sample) delete[] sample;
if (dialog) delete dialog;
if (savebuffer) delete[] savebuffer;
return 0;
}
//***************************************************************************
void SignalManager::save(const char *filename, int bits, bool selection)
{
debug("SignalManager::save(): %d Bit to %s ,%d", bits, filename, selection);
int begin = 0;
int length = this->getLength();
struct wavheader header;
ASSERT(filename);
if (!filename) return;
if (selection && (lmarker != rmarker)) {
begin = lmarker;
length = rmarker - lmarker + 1;
}
FILE *sigout = fopen (filename, "w");
if (name) delete[] name;
name = duplicateString(filename);
ASSERT(name);
if (!name) return;
if (!m_channels) KMsgBox(0, i18n("info"),
i18n("Signal is empty, nothing to save !"), 2);
if (sigout) {
fseek (sigout, 0, SEEK_SET);
strncpy ((char*)&(header.riffid), "RIFF", 4);
strncpy ((char*)&(header.wavid), "WAVE", 4);
strncpy ((char*)&(header.fmtid), "fmt ", 4);
header.fmtlength = 16;
header.filelength = (length * bits / 8 * m_channels + sizeof(struct wavheader));
header.mode = 1;
header.channels = m_channels;
header.rate = rate;
header.AvgBytesPerSec = rate * bits / 8 * m_channels;
header.BlockAlign = bits * m_channels / 8;
header.bitspersample = bits;
int datalen = length * header.channels * header.bitspersample / 8;
#if defined(IS_BIG_ENDIAN)
header.mode = bswap_16(header.mode);
header.rate = bswap_32(header.rate);
header.channels = bswap_16(header.channels);
header.bitspersample = bswap_16(header.bitspersample);
header.AvgBytesPerSec = bswap_32(header.AvgBytesPerSec);
header.fmtlength = bswap_32(header.fmtlength);
header.filelength = bswap_32(header.filelength);
datalen = bswap_32(datalen);
#endif
fwrite ((char *) &header, 1, sizeof (struct wavheader), sigout);
fwrite ("data", 1, 4, sigout);
fwrite ((char *)&datalen, 1, 4, sigout);
switch (bits) {
case 8:
case 16:
case 24:
writeWavChunk(sigout, begin, length, bits);
break;
default:
KMsgBox::message(0, i18n("Info"),
i18n("Sorry only 8/16/24 Bits per Sample are supported !"),
2);
break;
}
fclose(sigout);
}
}
//***************************************************************************
int SignalManager::loadWavChunk(FILE *sigfile, unsigned int length,
unsigned int channels, int bits)
{
unsigned int bufsize = 16 * 1024 * sizeof(int);
unsigned char *loadbuffer = 0;
sample_t **sample = 0; // array of pointers to samples
int bytes = bits / 8;
unsigned int sign = 1 << (24-1);
unsigned int negative = ~(sign - 1);
unsigned int shift = 24-bits;
unsigned int bytes_per_sample = bytes * channels;
unsigned int max_samples = bufsize / bytes_per_sample;
long int start_offset = ftell(sigfile);
ASSERT(bytes);
ASSERT(channels);
// try to allocate memory for the load buffer
// if failed, try again with the half buffer size as long
// as <1kB is not reached (then we are really out of memory)
while (loadbuffer == 0) {
if (bufsize < 1024) {
debug("SignalManager::loadWavChunk:not enough memory for buffer");
return -ENOMEM;
}
loadbuffer = new unsigned char[bufsize];
if (!loadbuffer) bufsize >>= 1;
}
// check if the file is large enough for "length" samples
fseek(sigfile, 0, SEEK_END);
size_t file_rest = ftell(sigfile) - start_offset;
fseek(sigfile, start_offset, SEEK_SET);
if (length > file_rest/bytes_per_sample) {
debug("SignalManager::loadWavChunk: "\
"length=%d, rest of file=%d",length,file_rest);
KMsgBox::message(0, i18n("Warning"),
i18n("Error in input: file is smaller than stated "\
"in the header. \n"\
"File has been truncated."),2);
length = file_rest/bytes_per_sample;
}
sample = new (sample_t*)[channels];
for (unsigned int channel = 0; channel < channels; channel++) {
Signal *new_signal = new Signal(length, rate);
ASSERT(new_signal);
if (!new_signal || !new_signal->getSample()) {
KMsgBox::message(0, i18n("Info"), i18n("Out of Memory!"), 2);
return -ENOMEM;
}
signal.append(new_signal);
signal.at(channel)->setBits(bits);
signal.at(channel)->select(true);
sample[channel] = signal.at(channel)->getSample();
}
//prepare and show the progress dialog
char progress_title[256];
char str_channels[32];
if (channels == 1)
strncpy(str_channels, i18n("Mono"), sizeof(str_channels));
else if (channels == 2)
strncpy(str_channels, i18n("Stereo"), sizeof(str_channels));
else
snprintf(str_channels, sizeof(str_channels),
i18n("%d voices"), channels);
snprintf(progress_title, sizeof(progress_title),
i18n("Loading %d-Bit (%s) File :"), bits, str_channels);
char *title = duplicateString(progress_title);
ProgressDialog *dialog = new ProgressDialog (100, title);
ASSERT(dialog);
delete[] title;
if (dialog) dialog->show();
//prepare the load loop
int percent_count = length / 1000;
// debug("sign=%08X, negative=%08X, shift=%d",sign,negative,shift);
for (unsigned int pos = 0; pos < length; ) {
// limit reading to end of wav chunk length
if ((pos + max_samples) > length) max_samples=length-pos;
int read_samples = fread((char *)loadbuffer, bytes_per_sample,
max_samples, sigfile);
percent_count -= read_samples;
// debug("read %d samples", read_samples);
if (read_samples <= 0) {
warning("SignalManager::loadWavChunk:EOF reached?"\
" (at sample %ld, expected length=%d",
ftell(sigfile) / bytes_per_sample - start_offset, length);
break;
}
unsigned char *buffer = loadbuffer;
while (read_samples--) {
for (register unsigned int channel = 0;
channel < channels;
channel++)
{
register int *smp = sample[channel] + pos;
if (bytes == 1) {
// 8-bit files are always unsigned !
*smp = (*(buffer++) - 128) << shift;
} else {
// >= 16 bits is signed
for (register int byte = 0; byte < bytes; byte++)
*smp |= *(buffer++) << ((byte << 3) + shift);
// sign correcture for negative values
if ((unsigned int)*smp & sign)
*smp |= negative;
}
}
pos++;
}
if (dialog && (percent_count <= 0)) {
percent_count = length / 1000;
float percent = (float)pos;
percent /= (float)length;
percent *= 100.0;
dialog->setProgress (percent);
}
}
if (dialog) delete dialog;
if (loadbuffer) delete[] loadbuffer;
if (sample) delete[] sample;
return 0;
}
//***************************************************************************
int SignalManager::findWavChunk(FILE *sigin)
{
ASSERT(sigin);
if (!sigin) return 0;
char buffer[4096];
int point = 0, max = 0;
int filecount = ftell(sigin);
int res = (filecount >= 0) ? 0 : -1;
while ((point == max) && (res == 0)) {
max = fread (buffer, 1, 4096, sigin);
// max=sigin->readBlock (buffer,4096);
point = 0;
while (point < max)
if (strncmp (&buffer[point++], "data", 4) == 0) break;
if (point == max) {
filecount += point - 4; //rewind 4 Bytes;
res = fseek (sigin, filecount, SEEK_SET);
} else return filecount + point + 3;
}
return 0;
}
/***************************************************************************/
//below all methods of Class SignalManager that deal with sound playback
//***************************************************************************
//following are the playback routines
struct Play {
SignalManager *manage;
playback_param_t params;
unsigned int start;
bool loop;
};
//***************************************************************************
void playThread(struct Play *par)
{
ASSERT(par);
if (!par) return;
ASSERT(par->manage);
if (!par->manage) {
delete par;
return;
}
int device; // handle of the playback device
unsigned char *buffer = 0;
unsigned int bufsize;
// prepeare for playback by opening the sound device
// and initializing with the proper settings
if ((device = open(par->params.device, O_WRONLY)) != -1 ) {
bufsize = par->manage->setSoundParams(device,
par->params.bits_per_sample,
par->params.channels,
par->params.rate, par->params.bufbase);
if (bufsize) {
buffer = new unsigned char[bufsize];
ASSERT(buffer);
if (buffer) {
par->manage->playback(device, par->params,
buffer, bufsize, par->start, par->loop);
delete[] buffer;
}
}
close (device);
} else {
warning("SignalManager::playback(): unable to open device");
}
par->manage->msg[stopprocess] = true;
par->manage->msg[processid] = 0;
if (par) delete par;
return;
}
//***************************************************************************
void SignalManager::startplay(unsigned int start, bool loop)
{
msg[processid] = 1;
msg[stopprocess] = false;
Play *par = new Play;
pthread_t thread;
par->manage = this;
par->start = start;
par->loop = loop;
par->params = KwaveApp::getPlaybackParams();
par->params.rate = this->getRate();
m_playback_error = 0;
pthread_create(&thread, 0, (void * (*) (void *))playThread, par);
}
//***************************************************************************
void SignalManager::stopplay()
{
msg[stopprocess] = true; //set flag for stopping
QTimer timeout;
timeout.start(5000, true);
while (msg[processid] != 0) {
sched_yield();
// wait for termination
if (!timeout.isActive()) {
warning("SignalManager::stopplay(): TIMEOUT");
break;
}
}
debug("SignalManager::stopplay(): threads stopped");
}
//***************************************************************************
int SignalManager::setSoundParams(int audio, int bitspersample,
unsigned int channels, int rate,
int bufbase)
{
// const char *trouble = i18n("playback problem");
debug("SignalManager::setSoundParams(fd=%d,bps=%d,channels=%d,"\
"rate=%d, bufbase=%d)", audio, bitspersample, channels,
rate, bufbase);
// ### under construction ###
// from standard oss interface (linux/soundcard.h)
///* Audio data formats (Note! U8=8 and S16_LE=16 for compatibility) */
//#define SNDCTL_DSP_GETFMTS _SIOR ('P',11, int) /* Returns a mask */
//#define SNDCTL_DSP_SETFMT _SIOWR('P',5, int) /* Selects ONE fmt*/
//# define AFMT_QUERY 0x00000000 /* Return current fmt */
//# define AFMT_MU_LAW 0x00000001
//# define AFMT_A_LAW 0x00000002
//# define AFMT_IMA_ADPCM 0x00000004
//# define AFMT_U8 0x00000008
//# define AFMT_S16_LE 0x00000010 /* Little endian signed 16*/
//# define AFMT_S16_BE 0x00000020 /* Big endian signed 16 */
//# define AFMT_S8 0x00000040
//# define AFMT_U16_LE 0x00000080 /* Little endian U16 */
//# define AFMT_U16_BE 0x00000100 /* Big endian U16 */
//# define AFMT_MPEG 0x00000200 /* MPEG (2) audio */
// from ALSA interface (asound.h)
//#define SND_PCM_SFMT_S8 0
//#define SND_PCM_SFMT_U8 1
//#define SND_PCM_SFMT_S16 SND_PCM_SFMT_S16_LE
//#define SND_PCM_SFMT_U16 SND_PCM_SFMT_U16_LE
//#define SND_PCM_SFMT_S24 SND_PCM_SFMT_S24_LE
//#define SND_PCM_SFMT_U24 SND_PCM_SFMT_U24_LE
//#define SND_PCM_SFMT_S32 SND_PCM_SFMT_S32_LE
//#define SND_PCM_SFMT_U32 SND_PCM_SFMT_U32_LE
//#define SND_PCM_SFMT_FLOAT SND_PCM_SFMT_FLOAT_LE
//#define SND_PCM_SFMT_FLOAT64 SND_PCM_SFMT_FLOAT64_LE
//#define SND_PCM_SFMT_IEC958_SUBFRAME SND_PCM_SFMT_IEC958_SUBFRAME_LE
int format = (bitspersample == 8) ? AFMT_U8 : AFMT_S16_LE;
// number of bits per sample
if (ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &format) == -1) {
m_playback_error = i18n("number of bits per samples not supported");
return 0;
}
// mono/stereo selection
int stereo = (channels >= 2) ? 1 : 0;
if (ioctl(audio, SNDCTL_DSP_STEREO, &stereo) == -1) {
m_playback_error = i18n("stereo not supported");
return 0;
}
// playback rate
if (ioctl(audio, SNDCTL_DSP_SPEED, &rate) == -1) {
m_playback_error = i18n("playback rate not supported");
return 0;
}
// buffer size
ASSERT(bufbase >= MIN_PLAYBACK_BUFFER);
ASSERT(bufbase <= MAX_PLAYBACK_BUFFER);
if (bufbase < MIN_PLAYBACK_BUFFER) bufbase = MIN_PLAYBACK_BUFFER;
if (bufbase > MAX_PLAYBACK_BUFFER) bufbase = MAX_PLAYBACK_BUFFER;
if (ioctl(audio, SNDCTL_DSP_SETFRAGMENT, &bufbase) == -1) {
m_playback_error = i18n("unusable buffer size");
return 0;
}
// return the buffer size in bytes
int size;
ioctl(audio, SNDCTL_DSP_GETBLKSIZE, &size);
return size;
}
//***************************************************************************
void SignalManager::playback(int device, playback_param_t &param,
unsigned char *buffer, unsigned int bufsize,
unsigned int start, bool loop)
{
ASSERT(buffer);
ASSERT(bufsize);
ASSERT(param.channels);
if (!buffer || !bufsize || !param.channels) return;
unsigned int i;
unsigned int active_channels = 0;
unsigned int in_channels = m_channels;
unsigned int out_channels = param.channels;
unsigned int active_channel[in_channels]; // list of active channels
// get the number of channels with enabled playback
for (i=0; i < in_channels; i++) {
if (!signal.at(i)) continue;
// ### TODO: use state of play widget instead of "enabled" ###
if (!signal.at(i)->isSelected()) continue;
active_channel[active_channels++] = i;
}
// abort if no channels -> nothing to do
if (!active_channels) {
debug("SignalManager::playback(): no active channel, nothing to do");
msg[stopprocess] = true;
}
// set up the matrix for channel mixing
int matrix[active_channels][out_channels];
unsigned int x, y;
for (y=0; y < out_channels; y++) {
unsigned int m1, m2;
m1 = y * active_channels;
m2 = (y+1) * active_channels;
for (x=0; x < active_channels; x++) {
unsigned int n1, n2;
n1 = x * out_channels;
n2 = (x+1) * out_channels;
// get the common area of [n1..n2] and [m1..m2]
unsigned int left = max(n1, m1);
unsigned int right = min(n2, m2);
matrix[x][y] = (right > left) ? (right-left) : 0;
}
}
// loop until process is stopped
// or run once if not in loop mode
unsigned int pointer = start;
unsigned int last = rmarker;
int samples[active_channels];
if (lmarker == rmarker) last = getLength()-1;
m_spx_playback_pos.enqueue(pointer);
do {
while ((pointer <= last) && !msg[stopprocess]) {
// fill the buffer with audio data
unsigned int cnt;
for (cnt = 0; (cnt < bufsize) && (pointer <= last); pointer++) {
unsigned int channel;
for (y=0; y < out_channels; y++) {
double s = 0;
for (x=0; x < active_channels; x++) {
s += signal.at(
active_channel[x])->getSingleSample(
pointer) * matrix[x][y];
}
samples[y] = (int)(s / active_channels);
}
for (channel=0; channel < out_channels; channel++) {
int sample = samples[channel];
switch (param.bits_per_sample) {
case 8:
sample += 1 << 23;
buffer[cnt++] = sample >> 16;
break;
case 16:
sample += 1 << 23;
buffer[cnt++] = sample >> 8;
buffer[cnt++] = (sample >> 16) + 128;
break;
case 24:
// play in 32 bit format
buffer[cnt++] = 0x00;
buffer[cnt++] = sample & 0x0FF;
buffer[cnt++] = sample >> 8;
buffer[cnt++] = (sample >> 16) + 128;
break;
default:
// invalid bits per sample
msg[stopprocess] = true;
pointer = last;
cnt = 0;
break;
}
}
}
// write buffer to the playback device
write(device, buffer, cnt);
m_spx_playback_pos.enqueue(pointer);
}
// maybe we loop. in this case the playback starts
// again from the left marker
if (loop && !msg[stopprocess]) pointer = lmarker;
} while (loop && !msg[stopprocess]);
// playback is done
m_spx_playback_done.AsyncHandler();
}
//***************************************************************************
void SignalManager::updatePlaybackPos()
{
unsigned int count = m_spx_playback_pos.count();
unsigned int pos = 0;
// dequeue all pointers and keep the latest one
if (!count) return;
while (count--) {
unsigned int *ppos = m_spx_playback_pos.dequeue();
ASSERT(ppos);
if (!ppos) continue;
pos = *ppos;
delete ppos;
}
emit sigPlaybackPos(pos);
}
//***************************************************************************
void SignalManager::forwardPlaybackDone()
{
emit sigPlaybackDone();
}
//***************************************************************************
//***************************************************************************