[b479a6]: kwave / SignalManager.cpp Maximize Restore History

Download this file

SignalManager.cpp    1044 lines (937 with data), 30.8 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
/***************************************************************************
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 <errno.h>
#include <endian.h>
#include <byteswap.h>
#include <limits.h>
#include <math.h>
#include <qbitmap.h>
#include <qfile.h>
#include <qlist.h>
#include <qpainter.h>
#include <qstring.h>
#include <qtimer.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kprogress.h>
#include "libkwave/FileFormat.h"
#include "libkwave/Parser.h"
#include "libkwave/Sample.h"
#include "libkwave/SampleReader.h"
#include "libkwave/SampleWriter.h"
#include "libkwave/Signal.h"
#include "libgui/FileProgress.h"
#include "KwaveApp.h"
#include "sampleop.h"
#include "ClipBoard.h"
#include "SignalManager.h"
#include "SignalWidget.h"
#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 (QString(command) == x) {
//***************************************************************************
SignalManager::SignalManager(QWidget *parent)
:QObject(),
m_parent_widget(parent),
m_name(""),
m_closed(true),
m_empty(true),
m_signal(),
m_selection(0,0),
m_rate(0),
m_playback_controller()
{
// connect to the track's signals
Signal *sig = &m_signal;
connect(sig, SIGNAL(sigTrackInserted(unsigned int, Track &)),
this, SLOT(slotTrackInserted(unsigned int, Track &)));
connect(sig, SIGNAL(sigSamplesDeleted(unsigned int, unsigned int,
unsigned int)),
this, SLOT(slotSamplesDeleted(unsigned int, unsigned int,
unsigned int)));
connect(sig, SIGNAL(sigSamplesInserted(unsigned int, unsigned int,
unsigned int)),
this, SLOT(slotSamplesInserted(unsigned int, unsigned int,
unsigned int)));
connect(sig, SIGNAL(sigSamplesModified(unsigned int, unsigned int,
unsigned int)),
this, SLOT(slotSamplesModified(unsigned int, unsigned int,
unsigned int)));
}
//***************************************************************************
void SignalManager::loadFile(const QString &filename, int type)
{
ASSERT(filename.length());
m_name = filename;
debug("SignalManager::loadFile(%s, %d)", filename.data(), type); // ###
switch (type) {
case WAV:
loadWav();
break;
case ASCII:
loadAscii();
break;
default:
ASSERT("unknown file type");
}
}
//***************************************************************************
void SignalManager::close()
{
m_empty = true;
m_name = "";
m_signal.close();
m_closed = true;
m_rate = 0;
m_selection.select(0,0);
emitStatusInfo();
}
//***************************************************************************
const QArray<unsigned int> SignalManager::selectedTracks()
{
unsigned int track;
unsigned int count = 0;
QArray<unsigned int> list(tracks());
for (track=0; track < list.count(); track++) {
// ### TODO ### selection of tracks
// if (!m_track_selected(track)) continue;
list[count++] = track;
}
list.resize(count);
return list;
}
//***************************************************************************
int SignalManager::singleSample(unsigned int /*channel*/, unsigned int /*offset*/)
{
// ASSERT(channel < signal.count());
// if (channel >= signal.count()) return 0;
//
// return signal.at(channel) ?
// signal.at(channel)->getSingleSample(offset) : 0;
return 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;
return 0;
}
//****************************************************************************
QBitmap *SignalManager::overview(unsigned int /*width*/, unsigned int /*height*/,
unsigned int /*offset*/, unsigned int /*length*/)
{
return 0;
// 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;
}
//***************************************************************************
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 QString &/*command*/)
{
// debug("SignalManager::executeCommand(%s)", command.data()); // ###
//
// 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 = parser.nextParam();
// 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;
// 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());
// }
// }
// 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;
// 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;
// }
// }
// }
// 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;
// }
// }
// }
// CASE_COMMAND("addchannel")
// addChannel();
// CASE_COMMAND("deletechannel")
// Parser parser(command);
// unsigned int i = parser.toInt();
// 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);
// return result;
// }
return true;
}
//***************************************************************************
void SignalManager::slotTrackInserted(unsigned int /*index*/,
Track &/*track*/)
{
emitStatusInfo();
}
//***************************************************************************
void SignalManager::slotSamplesInserted(unsigned int /*track*/,
unsigned int /*offset*/, unsigned int /*length*/)
{
emitStatusInfo();
}
//***************************************************************************
void SignalManager::slotSamplesDeleted(unsigned int /*track*/,
unsigned int /*offset*/, unsigned int /*length*/)
{
emitStatusInfo();
}
//***************************************************************************
void SignalManager::slotSamplesModified(unsigned int /*track*/,
unsigned int /*offset*/, unsigned int /*length*/)
{
}
//***************************************************************************
SignalManager::~SignalManager()
{
close();
}
//***************************************************************************
void SignalManager::selectRange(unsigned int offset, unsigned int length)
{
// first do some range checking
unsigned int len = this->length();
if (offset >= len) offset = len ? (len-1) : 0;
if ((offset+length) > len) length = len - offset;
m_selection.select(offset, length);
}
//***************************************************************************
int SignalManager::loadAscii()
{
// float value;
// int cnt = 0;
// float max = 0;
// float amp;
// int *sample = 0;
//
// FILE *sigin = fopen(m_name.data(), "r");
// if (!sigin) {
// KMessageBox::error(0, i18n("File does not exist !"), i18n("Info"), 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;
}
//***************************************************************************
void SignalManager::emitStatusInfo()
{
emit sigStatusInfo(length(), tracks(), rate(), bits());
}
//***************************************************************************
int SignalManager::loadWav()
{
wav_fmt_header_t fmt_header;
int result = 0;
__uint32_t num;
__uint32_t length;
ASSERT(m_closed);
ASSERT(m_empty);
QFile sigfile(m_name);
if (!sigfile.open(IO_ReadOnly)) {
KMessageBox::error(m_parent_widget,
i18n("File does not exist !"));
return -ENOENT;
}
// --- check if the file starts with "RIFF" ---
num = sigfile.size();
length = findChunk(sigfile, "RIFF", 0);
if ((length == 0) || (sigfile.at() != 8)) {
KMessageBox::error(m_parent_widget,
i18n("File is no RIFF File !"));
// maybe recoverable...
} else if (length+8 != num) {
KMessageBox::error(m_parent_widget,
i18n("File has incorrect length! (maybe truncated?)"));
// maybe recoverable...
} else {
// check if the chunk data contains "WAVE"
char file_type[16];
num = sigfile.readBlock((char*)(&file_type), 4);
if ((num != 4) || strncmp("WAVE", file_type, 4)) {
KMessageBox::error(m_parent_widget,
i18n("File is no WAVE File !"));
// maybe recoverable...
}
}
// ------- read the "fmt " chunk -------
ASSERT(sizeof(fmt_header) == 16);
num = findChunk(sigfile, "fmt ");
if (num != sizeof(fmt_header)) {
debug("SignalManager::loadWav(): length of fmt chunk = %d", num);
KMessageBox::error(m_parent_widget,
i18n("File does not contain format information!"));
return -EMEDIUMTYPE;
}
num = sigfile.readBlock((char*)(&fmt_header), sizeof(fmt_header));
#ifdef IS_BIG_ENDIAN
fmt_header.length = bswap_32(fmt_header.length);
fmt_header.mode = bswap_16(fmt_header.mode);
fmt_header.channels = bswap_16(fmt_header.channels);
fmt_header.rate = bswap_32(fmt_header.rate);
fmt_header.AvgBytesPerSec = bswap_32(fmt_header.AvgBytesPerSec);
fmt_header.BlockAlign = bswap_32(fmt_header.BlockAlign);
fmt_header.bitspersample = bswap_16(fmt_header.bitspersample);
#endif
if (fmt_header.mode != 1) {
KMessageBox::error(m_parent_widget,
i18n("File must be uncompressed (Mode 1) !"),
i18n("Sorry"), 2);
return -EMEDIUMTYPE;
}
m_rate = fmt_header.rate;
m_signal.setBits(fmt_header.bitspersample);
// ------- search for the data chunk -------
length = findChunk(sigfile, "data");
if (!length) {
KMessageBox::error(m_parent_widget,
i18n("File does not contain data!"));
return -EMEDIUMTYPE;
}
length = (length/(fmt_header.bitspersample/8))/fmt_header.channels;
switch (fmt_header.bitspersample) {
case 8:
case 16:
case 24:
ASSERT(m_empty);
// currently the signal should be closed and empty
// now make it opened but empty
m_closed = false;
emitStatusInfo();
result = loadWavChunk(sigfile, length,
fmt_header.channels,
fmt_header.bitspersample);
break;
default:
KMessageBox::error(m_parent_widget,
i18n("Sorry only 8/16/24 Bits per Sample"\
" are supported !"), i18n("Sorry"), 2);
result = -EMEDIUMTYPE;
}
if (result == 0) {
debug("SignalManager::loadWav(): successfully opened");
}
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);
//
// QString title = 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(QFile &sigout, unsigned int offset,
unsigned int length, unsigned int bits)
{
unsigned int bufsize = 16 * 1024 * sizeof(int);
unsigned char *savebuffer = 0;
int bytes = bits / 8;
unsigned int tracks = this->tracks();
int bytes_per_sample = bytes * tracks;
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) {
warning("SignalManager::writeWavChunk:no 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
unsigned int file_rest = tracks * length * bytes_per_sample;
FileProgress *dialog = new FileProgress(m_parent_widget,
m_name, file_rest, length, m_rate, bits, tracks);
ASSERT(dialog);
// prepare the store loop
int percent_count = length / 200;
unsigned int shift = 24-bits;
QList<SampleReader> samples;
samples.setAutoDelete(true);
for (unsigned int track = 0; track < tracks; track++) {
SampleReader *s = m_signal.openSampleReader(track,
offset, offset+length-1);
ASSERT(s);
if (!s) {
KMessageBox::sorry(m_parent_widget, i18n("Out of Memory!"));
return -ENOMEM;
}
samples.append(s);
}
// loop for writing data
for (unsigned int pos = offset; pos < offset+length; ) {
unsigned char *buf = savebuffer;
unsigned int nsamples = 0;
while (pos < offset+length &&
(nsamples < (bufsize/bytes_per_sample)))
{
for (unsigned int track = 0; track < tracks; track++) {
SampleReader *stream = samples.at(track);
sample_t sample;
(*stream) >> sample;
// the following cast is only necessary if
// sample_t is not equal to a 32bit int
__uint32_t act = static_cast<__uint32_t>(sample);
act >>= 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 = sigout.writeBlock(
reinterpret_cast<char *>(savebuffer),
bytes_per_sample * nsamples);
percent_count -= written_bytes;
if (dialog && (percent_count <= 0)) {
percent_count = length / 200;
dialog->setValue(pos*tracks*bytes_per_sample);
}
}
if (dialog) delete dialog;
if (savebuffer) delete[] savebuffer;
// close all SampleReaders
samples.clear();
return 0;
}
//***************************************************************************
void SignalManager::save(const QString &filename, unsigned int bits,
bool selection)
{
debug("SignalManager::save(): %u Bit to %s ,%d",
bits, filename.data(), selection);
__uint32_t ofs = 0;
__uint32_t len = length();
unsigned int tracks = this->tracks();
wav_header_t header;
ASSERT(filename);
if (!filename) return;
if (selection) {
if (m_selection.length() == 0) return; // zero-length -> nothing to do
ofs = m_selection.offset();
len = m_selection.length();
}
if (!tracks || !len) {
KMessageBox::error(m_parent_widget,
i18n("Signal is empty, nothing to save !"));
return;
}
QFile sigout(filename);
if (!sigout.open(IO_WriteOnly | IO_Truncate)) {
KMessageBox::error(m_parent_widget,
i18n("Opening the file for writing failed!"));
return;
};
__uint32_t datalen = (bits >> 3) * len * tracks;
strncpy((char*)&(header.riffid), "RIFF", 4);
strncpy((char*)&(header.wavid), "WAVE", 4);
strncpy((char*)&(header.fmtid), "fmt ", 4);
header.filelength = datalen + sizeof(wav_header_t);
header.fmtlength = 16;
header.mode = 1;
header.channels = tracks;
header.rate = m_rate;
header.AvgBytesPerSec = m_rate * (bits >> 3) * tracks;
header.BlockAlign = (bits >> 3) * tracks;
header.bitspersample = bits;
#if defined(IS_BIG_ENDIAN)
header.filelength = bswap_32(header.filelength);
header.fmtlength = bswap_32(header.fmtlength);
header.mode = bswap_16(header.mode);
header.channels = bswap_16(header.channels);
header.rate = bswap_32(header.rate);
header.AvgBytesPerSec = bswap_32(header.AvgBytesPerSec);
header.BlockAlign = bswap_16(header.BlockAlign);
header.bitspersample = bswap_16(header.bitspersample);
datalen = bswap_32(datalen);
#endif
sigout.at(0);
sigout.writeBlock((char *) &header, sizeof(wav_header_t));
sigout.writeBlock("data", 4);
sigout.writeBlock((char *)&datalen, 4);
switch (bits) {
case 8:
case 16:
case 24:
writeWavChunk(sigout, ofs, len, bits);
break;
default:
KMessageBox::sorry(m_parent_widget,
i18n("Sorry only 8/16/24 Bits per Sample are supported !"));
break;
}
sigout.close();
}
//***************************************************************************
__uint32_t SignalManager::findChunk(QFile &sigfile, const char *chunk,
__uint32_t offset)
{
char current_name[16];
__uint32_t length = 0;
int len;
ASSERT(sizeof(length) == 4);
ASSERT(sizeof(int) == 4);
sigfile.at(offset);
while (!sigfile.atEnd()) {
debug("findChunk('%s'): position=%u", chunk, sigfile.at());
// get name of the chunk
len = sigfile.readBlock((char*)(&current_name), 4);
if (len < 4) {
debug("findChunk('%s'): not found, reached EOF while reading name",
chunk);
return 0; // reached EOF
}
// get length of the chunk
len = sigfile.readBlock((char*)(&length), sizeof(length));
if (len < 4) {
debug("findChunk('%s'): not found, reached EOF :-(", chunk);
return 0; // reached EOF
}
#ifdef IS_BIG_ENDIAN
length = bswap_32(length);
#endif
if (strncmp(chunk, current_name, 4) == 0) {
// chunk found !
debug("findChunk('%s'): found chunk with len=%d", chunk, length);
return length;
} else {
debug("findChunk('%s'): skipping '%c%c%c%c'",
chunk, current_name[0], current_name[1],
current_name[2], current_name[3]);
}
// not found -> skip
sigfile.at(sigfile.at()+length);
};
debug("findChunk('%s'): not found :-(", chunk);
return 0;
}
//***************************************************************************
int SignalManager::loadWavChunk(QFile &sigfile, unsigned int length,
unsigned int channels, int bits)
{
unsigned int bufsize = 64 * 1024 * sizeof(sample_t);
unsigned char *loadbuffer = 0;
int bytes = bits >> 3;
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 = sigfile.at();
debug("SignalManager::loadWavChunk(): offset = %d", sigfile.at());
debug("SignalManager::loadWavChunk(): length = %d samples", length);
debug("SignalManager::loadWavChunk(): tracks = %d", channels);
debug("SignalManager::loadWavChunk(): resoultion = %d bits/sample", bits);
ASSERT(bytes);
ASSERT(channels);
ASSERT(length);
if (!bytes || !channels || !length) return -EINVAL;
// 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
size_t file_rest = sigfile.size() - sigfile.at();
if (length > file_rest/bytes_per_sample) {
debug("SignalManager::loadWavChunk: "\
"length=%d, rest of file=%d",length,file_rest);
KMessageBox::error(m_parent_widget,
i18n("Warning"),
i18n("Error in input: file is smaller than stated "\
"in the header. \n"\
"File will be truncated."), 2);
length = file_rest/bytes_per_sample;
}
QList<SampleWriter> samples;
samples.setAutoDelete(true);
for (unsigned int track = 0; track < channels; track++) {
Track *new_track = m_signal.appendTrack(length);
ASSERT(new_track);
if (!new_track) {
KMessageBox::sorry(m_parent_widget, i18n("Out of Memory!"));
return -ENOMEM;
}
SampleWriter *s = m_signal.openSampleWriter(track, Overwrite);
ASSERT(s);
if (!s) {
KMessageBox::sorry(m_parent_widget, i18n("Out of Memory!"));
return -ENOMEM;
}
samples.append(s);
}
// now the signal is considered not to be empty
m_empty = false;
//prepare and show the progress dialog
FileProgress *dialog = new FileProgress(m_parent_widget,
m_name, file_rest, length, m_rate, bits, channels);
ASSERT(dialog);
// prepare the loader loop
int percent_count = length / 100;
// debug("sign=%08X, negative=%08X, shift=%d",sign,negative,shift);
for (unsigned int pos = 0; pos < length; ) {
// break the loop if the user has pressed "cancel"
if (dialog && dialog->isCancelled()) break;
// limit reading to end of wav chunk length
if ((pos + max_samples) > length) max_samples=length-pos;
// read the samples into a temporary buffer
int read_samples = sigfile.readBlock(
reinterpret_cast<char *>(loadbuffer),
bytes_per_sample*max_samples
) / bytes_per_sample;
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",
sigfile.at() / bytes_per_sample - start_offset, length);
break;
}
unsigned char *buffer = loadbuffer;
__uint32_t s = 0; // raw 32bit value
while (read_samples--) {
for (register unsigned int channel = 0;
channel < channels;
channel++)
{
SampleWriter *stream = samples.at(channel);
if (bytes == 1) {
// 8-bit files are always unsigned !
s = (*(buffer++) - 128) << shift;
} else {
// >= 16 bits is signed
s = 0;
for (register int byte = 0; byte < bytes; byte++) {
s |= *(buffer++) << ((byte << 3) + shift);
}
// sign correcture for negative values
if ((unsigned int)s & sign)
s |= negative;
}
// the following cast is only necessary if
// sample_t is not equal to a 32bit int
sample_t sample = static_cast<sample_t>(s);
*stream << sample;
}
pos++;
}
if (dialog && (percent_count <= 0)) {
percent_count = length / 100;
dialog->setValue(pos * bytes_per_sample);
}
}
// close all sample input streams
samples.clear();
if (dialog) delete dialog;
if (loadbuffer) delete[] loadbuffer;
return 0;
}
//***************************************************************************
PlaybackController &SignalManager::playbackController()
{
return m_playback_controller;
}
//***************************************************************************
//***************************************************************************