[b37029]: plugins / codec_wav / WavDecoder.cpp Maximize Restore History

Download this file

WavDecoder.cpp    771 lines (661 with data), 25.0 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
/*************************************************************************
WavDecoder.cpp - decoder for wav data
-------------------
begin : Sun Mar 10 2002
copyright : (C) 2002 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 <stdlib.h>
#include <audiofile.h>
#include <QApplication>
#include <QList>
#include <QProgressDialog>
#include <QtGlobal>
#include <klocale.h>
#include <kmimetype.h>
#include "libkwave/byteswap.h"
#include "libkwave/ConfirmCancelProxy.h"
#include "libkwave/MultiWriter.h"
#include "libkwave/Label.h"
#include "libkwave/MessageBox.h"
#include "libkwave/MetaData.h"
#include "libkwave/MetaDataList.h"
#include "libkwave/Sample.h"
#include "libkwave/VirtualAudioFile.h"
#include "libkwave/Writer.h"
#include "RecoveryBuffer.h"
#include "RecoveryMapping.h"
#include "RecoverySource.h"
#include "RepairVirtualAudioFile.h"
#include "RIFFChunk.h"
#include "RIFFParser.h"
#include "WavDecoder.h"
#include "WavFileFormat.h"
#include "WavFormatMap.h"
// some byteswapping helper macros
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
#define CPU_TO_LE32(x) (bswap_32(x))
#define LE32_TO_CPU(x) (bswap_32(x))
#else
#define CPU_TO_LE32(x) (x)
#define LE32_TO_CPU(x) (x)
#endif
#define CHECK(cond) Q_ASSERT(cond); if (!(cond)) { src.close(); return false; }
//***************************************************************************
WavDecoder::WavDecoder()
:Decoder(), m_source(0), m_src_adapter(0), m_known_chunks(),
m_property_map()
{
REGISTER_MIME_TYPES;
REGISTER_COMPRESSION_TYPES;
// native WAVE chunk names
m_known_chunks.append("cue "); /* Markers */
m_known_chunks.append("data"); /* Sound Data */
m_known_chunks.append("fact"); /* Fact (length in samples) */
m_known_chunks.append("fmt "); /* Format */
m_known_chunks.append("inst"); /* Instrument */
m_known_chunks.append("labl"); /* label */
m_known_chunks.append("ltxt"); /* labeled text */
m_known_chunks.append("note"); /* note chunk */
m_known_chunks.append("plst"); /* Play List */
m_known_chunks.append("smpl"); /* Sampler */
// add all sub-chunks of the LIST chunk (properties)
foreach (QByteArray name, m_property_map.chunks())
m_known_chunks.append( name );
// some chunks known from AIFF format
m_known_chunks.append("FVER");
m_known_chunks.append("COMM");
m_known_chunks.append("wave");
m_known_chunks.append("SSND");
// chunks of .lbm image files, IFF format
m_known_chunks.append("BMHD");
m_known_chunks.append("CMAP");
m_known_chunks.append("BODY");
}
//***************************************************************************
WavDecoder::~WavDecoder()
{
if (m_source) close();
if (m_src_adapter) delete m_src_adapter;
}
//***************************************************************************
Decoder *WavDecoder::instance()
{
return new WavDecoder();
}
//***************************************************************************
bool WavDecoder::open(QWidget *widget, QIODevice &src)
{
FileInfo info;
LabelList labels;
metaData().clear();
Q_ASSERT(!m_source);
bool need_repair = false;
if (m_source) qWarning("WavDecoder::open(), already open !");
// try to open the source
if (!src.open(QIODevice::ReadOnly)) {
qWarning("failed to open source !");
return false;
}
QStringList main_chunks;
main_chunks.append("RIFF"); /* RIFF, little-endian */
main_chunks.append("RIFX"); /* RIFF, big-endian */
main_chunks.append("FORM"); /* used in AIFF, big-endian or IFF/.lbm */
main_chunks.append("LIST"); /* additional information */
main_chunks.append("adtl"); /* Associated Data */
RIFFParser parser(src, main_chunks, m_known_chunks);
// prepare a progress dialog
QProgressDialog progress(widget);
progress.setWindowTitle(i18n("Auto Repair"));
progress.setModal(true);
progress.setMinimumDuration(0);
progress.setMaximum(100);
progress.setAutoClose(true);
progress.setValue(0);
progress.setLabelText(i18n("Reading..."));
connect(&parser, SIGNAL(progress(int)),
&progress, SLOT(setValue(int)));
connect(&parser, SIGNAL(action(const QString &)),
&progress, SLOT(setLabelText(const QString &)));
ConfirmCancelProxy confirm_cancel(widget,
&progress, SIGNAL(canceled()),
&parser, SLOT(cancel()));
// parse, including endianness detection
parser.parse();
progress.reset();
if (progress.wasCanceled()) return false;
// qDebug("--- RIFF file structure after first pass ---");
// parser.dumpStructure();
// check if there is a RIFF chunk at all...
RIFFChunk *riff_chunk = parser.findChunk("/RIFF:WAVE");
RIFFChunk *fmt_chunk = parser.findChunk("/RIFF:WAVE/fmt ");
RIFFChunk *data_chunk = parser.findChunk("/RIFF:WAVE/data");
if (!riff_chunk || !fmt_chunk || !data_chunk || !parser.isSane()) {
if (Kwave::MessageBox::warningContinueCancel(widget,
i18n("The file has been structurally damaged or "
"it is no WAV file.\n"
"Should Kwave try to repair it?"),
i18n("Kwave Auto Repair"),
i18n("&Repair")) != KMessageBox::Continue)
{
// user didn't let us try :-(
return false;
}
need_repair = true;
}
// collect all missing chunks
if (!riff_chunk) riff_chunk = parser.findMissingChunk("RIFF:WAVE");
if (progress.wasCanceled()) return false;
if (!fmt_chunk) {
parser.findMissingChunk("fmt ");
fmt_chunk = parser.findChunk("/RIFF:WAVE/fmt ");
if (progress.wasCanceled()) return false;
if (!fmt_chunk) fmt_chunk = parser.findChunk("fmt ");
need_repair = true;
}
if (!data_chunk) {
parser.findMissingChunk("data");
data_chunk = parser.findChunk("/RIFF:WAVE/data");
if (progress.wasCanceled()) return false;
if (!data_chunk) data_chunk = parser.findChunk("data");
need_repair = true;
}
// not everything found -> need heavy repair actions !
if (!fmt_chunk || !data_chunk || need_repair) {
qDebug("doing heavy repair actions...");
parser.dumpStructure();
parser.repair();
parser.dumpStructure();
if (progress.wasCanceled()) return false;
if (!fmt_chunk) fmt_chunk = parser.findChunk("/RIFF:WAVE/fmt ");
if (!fmt_chunk) fmt_chunk = parser.findChunk("/RIFF/fmt ");
if (!fmt_chunk) fmt_chunk = parser.findChunk("fmt ");
if (!data_chunk) data_chunk = parser.findChunk("/RIFF:WAVE/data");
if (!data_chunk) data_chunk = parser.findChunk("/RIFF/data");
if (!data_chunk) data_chunk = parser.findChunk("data");
need_repair = true;
}
u_int32_t fmt_offset = 0;
if (fmt_chunk) fmt_offset = fmt_chunk->dataStart();
// qDebug("fmt chunk starts at 0x%08X", fmt_offset);
// u_int32_t data_offset = 0;
u_int32_t data_size = 0;
if (data_chunk) {
// data_offset = data_chunk->dataStart();
data_size = data_chunk->physLength();
// qDebug("data chunk at 0x%08X (%u byte)", data_offset, data_size);
}
if (!data_size) {
// hide progress bar, finally
progress.hide();
qApp->processEvents();
// show final error message
Kwave::MessageBox::sorry(widget,
i18n("The opened file is no WAV file or it is damaged:\n"
"There is not enough valid sound data.\n\n"
"It makes no sense to continue now."));
return false;
}
// final check for structural integrity:
// we should have exactly one RIFF, fmt and data chunk !
if ((parser.chunkCount("fmt ") != 1) ||
(parser.chunkCount("data") != 1))
{
// hide progress bar, temporarily
progress.hide();
qApp->processEvents();
if (Kwave::MessageBox::warningContinueCancel(widget,
i18n("The WAV file seems to be damaged:\n"
"Some chunks are duplicate or missing.\n\n"
"Kwave will only use the first ones and ignore\n"
"the rest. This might lead to loss of data.\n"
"If you want to get your file repaired completely,\n"
"please write an email to the Kwave mailing list\n"
"and we will help you."),
i18n("Kwave Auto Repair")
) != KMessageBox::Continue)
{
// user decided to abort and repair on his own
// good luck!
return false;
}
need_repair = true;
// show progress bar again
progress.show();
qApp->processEvents();
}
// source successfully opened
m_source = &src;
// read the wave header
wav_fmt_header_t header;
unsigned int rate = 0;
unsigned int bits = 0;
src.seek(fmt_offset);
// get the encoded block of data from the mime source
CHECK(static_cast<unsigned int>(src.size()) >
sizeof(wav_header_t) + 8);
// get the header
src.read(reinterpret_cast<char *>(&header), sizeof(wav_fmt_header_t));
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
header.min.format = bswap_16(header.min.format);
header.min.channels = bswap_16(header.min.channels);
header.min.samplerate = bswap_32(header.min.samplerate);
header.min.bytespersec = bswap_32(header.min.bytespersec);
header.min.blockalign = bswap_16(header.min.blockalign);
header.min.bitwidth = bswap_16(header.min.bitwidth);
#endif
unsigned int tracks = header.min.channels;
rate = header.min.samplerate;
bits = header.min.bitwidth;
WavFormatMap known_formats;
QString format_name = known_formats.findName(header.min.format);
// qDebug("-------------------------");
// qDebug("wav header:");
// qDebug("format = 0x%04X, (%s)", header.min.format,
// format_name.toLocal8Bit().data());
// qDebug("channels = %d", header.min.channels);
// qDebug("rate = %u", header.min.samplerate);
// qDebug("bytes/s = %u", header.min.bytespersec);
// qDebug("block align = %d", header.min.blockalign);
// qDebug("bits/sample = %d", header.min.bitwidth);
// qDebug("-------------------------");
// open the file through libaudiofile :)
if (need_repair) {
QList<RecoverySource *> *repair_list = new QList<RecoverySource *>();
Q_ASSERT(repair_list);
if (!repair_list) return false;
RIFFChunk *root = (riff_chunk) ? riff_chunk : parser.findChunk("");
// parser.dumpStructure();
// qDebug("riff chunk = %p, parser.findChunk('')=%p", riff_chunk,
// parser.findChunk(""));
repair(repair_list, root, fmt_chunk, data_chunk);
m_src_adapter = new RepairVirtualAudioFile(*m_source, repair_list);
} else {
m_src_adapter = new VirtualAudioFile(*m_source);
}
Q_ASSERT(m_src_adapter);
if (!m_src_adapter) return false;
m_src_adapter->open(m_src_adapter, 0);
AFfilehandle fh = m_src_adapter->handle();
if (!fh || (m_src_adapter->lastError() >= 0)) {
QString reason;
switch (m_src_adapter->lastError()) {
case AF_BAD_NOT_IMPLEMENTED:
reason = i18n("Format or function is not implemented") +
"\n("+format_name+")";
break;
case AF_BAD_MALLOC:
reason = i18n("Out of memory");
break;
case AF_BAD_HEADER:
reason = i18n("file header is damaged");
break;
case AF_BAD_CODEC_TYPE:
reason = i18n("Invalid codec type") +
"\n("+format_name+")";
break;
case AF_BAD_OPEN:
reason = i18n("Opening the file failed");
break;
case AF_BAD_READ:
reason = i18n("Read access failed");
break;
case AF_BAD_SAMPFMT:
reason = i18n("Invalid sample format");
break;
default:
reason = i18n("internal libaudiofile error #%1: '%2'",
m_src_adapter->lastError(),
m_src_adapter->lastErrorText()
);
}
QString text= i18n("An error occurred while opening the file:\n'%1'",
reason);
Kwave::MessageBox::error(widget, text);
return false;
}
unsigned int length = afGetFrameCount(fh, AF_DEFAULT_TRACK);
tracks = afGetVirtualChannels(fh, AF_DEFAULT_TRACK);
int sample_format;
afGetVirtualSampleFormat(fh, AF_DEFAULT_TRACK, &sample_format,
reinterpret_cast<int *>(&bits));
int compression = afGetCompression(fh, AF_DEFAULT_TRACK);
if (static_cast<signed int>(bits) < 0) bits = 0;
info.setRate(rate);
info.setBits(bits);
info.setTracks(tracks);
info.setLength(length);
info.set(INF_SAMPLE_FORMAT, sample_format);
info.set(INF_COMPRESSION, compression);
// read in all info from the LIST (INFO) chunk
RIFFChunk *info_chunk = parser.findChunk("/RIFF:WAVE/LIST:INFO");
if (info_chunk) {
// found info chunk !
RIFFChunkList &list = info_chunk->subChunks();
foreach (RIFFChunk *chunk, list) {
if (!chunk) continue;
if (!m_property_map.containsChunk(chunk->name())) continue;
// read the content into a QString
FileProperty prop = m_property_map.property(chunk->name());
unsigned int offset = chunk->dataStart();
unsigned int length = chunk->dataLength();
QByteArray buffer(length+1, 0x00);
src.seek(offset);
src.read(buffer.data(), length);
buffer[length] = 0;
QString value;
value = QString::fromUtf8(buffer);
info.set(prop, value);
}
}
// read in the Labels (cue list)
RIFFChunk *cue_chunk = parser.findChunk("/RIFF:WAVE/cue ");
if (cue_chunk) {
// found a cue list chunk !
u_int32_t count;
src.seek(cue_chunk->dataStart());
src.read(reinterpret_cast<char *>(&count), 4);
count = LE32_TO_CPU(count);
// unsigned int length = cue_chunk->dataLength();
// qDebug("cue list found: %u entries, %u bytes (should be: %u)",
// count, length, count * (6 * 4) + 4);
for (unsigned int i = 0; i < count; i++) {
u_int32_t data, index, position;
src.seek(cue_chunk->dataStart() + 4 + ((6 * 4) * i));
/*
* typedef struct {
* u_int32_t dwIdentifier; <- index
* u_int32_t dwPosition; <- 0
* u_int32_t fccChunk; <- 'data'
* u_int32_t dwChunkStart; <- 0
* u_int32_t dwBlockStart; <- 0
* u_int32_t dwSampleOffset; <- label.pos()
* } cue_list_entry_t;
*/
/* dwIdentifier */
src.read(reinterpret_cast<char *>(&data), 4);
index = LE32_TO_CPU(data);
/* dwPosition (ignored) */
src.read(reinterpret_cast<char *>(&data), 4);
/* fccChunk */
src.read(reinterpret_cast<char *>(&data), 4);
/* we currently support only 'data' */
if (qstrncmp(reinterpret_cast<const char *>(&data), "data", 4)) {
qWarning("cue list entry %d refers to '%s', "\
"which is not supported -> skipped",
index, QByteArray(
reinterpret_cast<const char *>(&data), 4).data());
continue;
}
src.read(reinterpret_cast<char *>(&data), 4);
/* dwChunkStart (must be 0) */
if (data != 0) {
qWarning("cue list entry %d has dwChunkStart != 0 -> skipped",
index);
continue;
}
src.read(reinterpret_cast<char *>(&data), 4);
/* dwBlockStart (must be 0) */
if (data != 0) {
qWarning("cue list entry %d has dwBlockStart != 0 -> skipped",
index);
continue;
}
src.read(reinterpret_cast<char *>(&data), 4); /* dwSampleOffset */
position = LE32_TO_CPU(data);
// as we now have index and position, find out the name
QByteArray name = "";
RIFFChunk *adtl_chunk = parser.findChunk("/RIFF:WAVE/LIST:adtl");
if (adtl_chunk) {
RIFFChunk *labl_chunk = 0;
bool found = false;
QListIterator<RIFFChunk *> it(adtl_chunk->subChunks());
while (it.hasNext()) {
u_int32_t data, labl_index;
labl_chunk = it.next();
/*
* typedef struct {
* u_int32_t dwChunkID; <- 'labl'
* u_int32_t dwChunkSize; (without padding !)
* u_int32_t dwIdentifier; <- index
* char dwText[]; <- label->name()
* } label_list_entry_t;
*/
if (labl_chunk->name() != "labl") continue;
data = 0;
src.seek(labl_chunk->dataStart());
src.read(reinterpret_cast<char *>(&data), 4); /* dwIdentifier */
labl_index = LE32_TO_CPU(data);
if (labl_index == index) {
found = true;
break; /* found it! */
}
}
if (found) {
Q_ASSERT(labl_chunk);
unsigned int length = labl_chunk->length();
if (length > 4) {
length -= 4;
name.resize(length);
src.seek(labl_chunk->dataStart() + 4);
src.read(static_cast<char *>(name.data()), length);
if (name[name.count()-1] != '\0')
name += '\0';
}
}
}
if (!name.length()) {
// qDebug("cue list entry %d has no name", index);
name = "";
}
// put a new label into the list
QString str = QString::fromUtf8(name);
labels.append(Label(position, str));
}
}
labels.sort();
metaData().replace(info);
metaData().replace(labels.toMetaDataList());
// set up libaudiofile to produce Kwave's internal sample format
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
afSetVirtualByteOrder(fh, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN);
#else
afSetVirtualByteOrder(fh, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN);
#endif
afSetVirtualSampleFormat(fh, AF_DEFAULT_TRACK,
AF_SAMPFMT_TWOSCOMP, SAMPLE_STORAGE_BITS);
return true;
}
//***************************************************************************
bool WavDecoder::decode(QWidget */*widget*/, Kwave::MultiWriter &dst)
{
Q_ASSERT(m_src_adapter);
Q_ASSERT(m_source);
if (!m_source) return false;
if (!m_src_adapter) return false;
AFfilehandle fh = m_src_adapter->handle();
Q_ASSERT(fh);
if (!fh) return false;
// info().dump();
const unsigned int tracks = dst.tracks();
// allocate an array of Writers, for speeding up
QVector<Kwave::Writer *>writers;
for (unsigned int t = 0; t < tracks; t++)
writers.append(dst[t]);
Q_ASSERT(writers.count() == static_cast<int>(dst.tracks()));
if (writers.count() != static_cast<int>(dst.tracks())) return false;
Kwave::Writer **writer_fast = writers.data();
unsigned int frame_size = static_cast<unsigned int>(
afGetVirtualFrameSize(fh, AF_DEFAULT_TRACK, 1));
// allocate a buffer for input data
const unsigned int buffer_frames = (8*1024);
int32_t *buffer = static_cast<int32_t *>(
malloc(buffer_frames * frame_size));
Q_ASSERT(buffer);
if (!buffer) return false;
// read in from the audiofile source
Q_ASSERT(tracks == FileInfo(metaData()).tracks());
sample_index_t rest = FileInfo(metaData()).length();
while (rest) {
unsigned int frames = buffer_frames;
if (frames > rest) frames = rest;
unsigned int buffer_used = afReadFrames(fh,
AF_DEFAULT_TRACK, reinterpret_cast<char *>(buffer), frames);
// break if eof reached
if (!buffer_used) break;
rest -= buffer_used;
// split into the tracks
int32_t *p = buffer;
unsigned int count = buffer_used;
while (count--) {
for (unsigned int track = 0; track < tracks; track++) {
int32_t s = *p++;
// adjust precision
if (SAMPLE_STORAGE_BITS != SAMPLE_BITS) {
s /= (1 << (SAMPLE_STORAGE_BITS - SAMPLE_BITS));
}
// the following cast is only necessary if
// sample_t is not equal to a u_int32_t
Q_ASSERT(writer_fast[track]);
*(writer_fast[track]) << static_cast<sample_t>(s);
}
}
// abort if the user pressed cancel
if (dst.isCanceled()) break;
}
// return with a valid Signal, even if the user pressed cancel !
if (buffer) free(buffer);
return true;
}
//***************************************************************************
bool WavDecoder::repairChunk(QList<RecoverySource *> *repair_list,
RIFFChunk *chunk, u_int32_t &offset)
{
Q_ASSERT(chunk);
Q_ASSERT(m_source);
Q_ASSERT(repair_list);
if (!chunk) return false;
if (!m_source) return false;
if (!repair_list) return false;
char buffer[16];
u_int32_t length;
RecoverySource *repair = 0;
// create buffer with header
strncpy(buffer, chunk->name().data(), 4);
length = (chunk->type() == RIFFChunk::Main) ? chunk->physLength() :
chunk->dataLength();
buffer[4] = (length ) & 0xFF;
buffer[5] = (length >> 8) & 0xFF;
buffer[6] = (length >> 16) & 0xFF;
buffer[7] = (length >> 24) & 0xFF;
if (chunk->type() == RIFFChunk::Main) {
strncpy(&(buffer[8]), chunk->format().data(), 4);
repair = new RecoveryBuffer(offset, 12, buffer);
qDebug("[0x%08X-0x%08X] - main header '%s' (%s), len=%u",
offset, offset+11, chunk->name().data(),
chunk->format().data(), length);
offset += 12;
} else {
repair = new RecoveryBuffer(offset, 8, buffer);
qDebug("[0x%08X-0x%08X] - sub header '%s', len=%u",
offset, offset+7, chunk->name().data(), length);
offset += 8;
}
Q_ASSERT(repair);
if (!repair) return false;
repair_list->append(repair);
// map the chunk's data if not main or root
if ((chunk->type() != RIFFChunk::Root) &&
(chunk->type() != RIFFChunk::Main))
{
repair = new RecoveryMapping(offset, chunk->physLength(),
*m_source, chunk->dataStart());
qDebug("[0x%08X-0x%08X] - restoring from offset 0x%08X (%u)",
offset, offset+chunk->physLength()-1, chunk->dataStart(),
chunk->physLength());
Q_ASSERT(repair);
if (!repair) return false;
repair_list->append(repair);
offset += chunk->physLength();
}
// recursively go over all sub-chunks
RIFFChunkList &list = chunk->subChunks();
foreach (RIFFChunk *chunk, list) {
if (!chunk) continue;
if (!repairChunk(repair_list, chunk, offset))
return false;
}
return true;
}
//***************************************************************************
bool WavDecoder::repair(QList<RecoverySource *> *repair_list,
RIFFChunk *riff_chunk, RIFFChunk *fmt_chunk, RIFFChunk *data_chunk)
{
Q_ASSERT(fmt_chunk);
Q_ASSERT(data_chunk);
if (!fmt_chunk || !data_chunk) return false;
// --- first create a chunk tree for the structure ---
// make a new "RIFF" chunk as root
RIFFChunk new_root(0, "RIFF", "WAVE", 0,0,0);
new_root.setType(RIFFChunk::Main);
// create a new "fmt " chunk
RIFFChunk *new_fmt = new RIFFChunk(&new_root, "fmt ",0,0,
fmt_chunk->physStart(), fmt_chunk->physLength());
Q_ASSERT(new_fmt);
if (!new_fmt) return false;
new_root.subChunks().append(new_fmt);
// create a new "data" chunk
RIFFChunk *new_data = new RIFFChunk(&new_root, "data",0,0,
data_chunk->physStart(), data_chunk->physLength());
Q_ASSERT(new_data);
if (!new_data) return false;
new_root.subChunks().append(new_data);
// if we have a RIFF chunk, add it's subchunks, except "fmt " and "data"
// we keep only pointers here, just for getting the right structure,
// sizes and start positions.
// NOTE: The sizes might be re-assigned and get invalid afterwards!!!
if (riff_chunk) {
RIFFChunkList &list = riff_chunk->subChunks();
foreach (RIFFChunk *chunk, list) {
if (!chunk) continue;
if (chunk->name() == "fmt ") continue;
if (chunk->name() == "data") continue;
if (chunk->name() == "RIFF") continue;
if (chunk->type() == RIFFChunk::Empty) continue;
if (chunk->type() == RIFFChunk::Garbage) continue;
new_root.subChunks().append(chunk);
}
}
// fix all node sizes (compress)
new_root.fixSize();
// attention: some of the offsets belong to source file, some belong
// to reconstructed buffers! only the sizes are correct.
// new_root.dumpStructure();
// --- set up the repair list ---
// RIFF chunk length
u_int32_t offset = 0;
bool repaired = repairChunk(repair_list, &new_root, offset);
// clean up...
new_root.subChunks().clear();
delete new_fmt;
delete new_data;
return (repaired);
}
//***************************************************************************
void WavDecoder::close()
{
if (m_src_adapter) delete m_src_adapter;
m_src_adapter = 0;
m_source = 0;
}
//***************************************************************************
//***************************************************************************