Passed
Push — master ( d597bd...96fa95 )
by Rafael S.
02:10
created

index.js (3 issues)

1
/*
2
 * Copyright (c) 2017-2018 Rafael da Silva Rocha. MIT License.
3
 * https://github.com/rochars/wavefile
4
 *
5
 */
6
7
/** @const @private */
8
const bitDepth_ = require("bitdepth");
9
/** @const @private */
10
const riffChunks_ = require("riff-chunks");
11
/** @const @private */
12
const imaadpcm_ = require("imaadpcm");
13
/** @const @private */
14
const alawmulaw_ = require("alawmulaw");
15
/** @const @private */
16
const byteData_ = require("byte-data");
17
/** @const @private */
18
const encodeBase64_ = require("base64-arraybuffer").encode;
19
/** @const @private */
20
const decodeBase64_ = require("base64-arraybuffer").decode;
21
/** @const @private */
22
const uInt16_ = {"bits": 16};
23
/** @const @private */
24
const uInt32_ = {"bits": 32};
25
/** @const @private */
26
const fourCC_ = {"bits": 32, "char": true};
27
/** @const @private */
28
const chr_ = {"bits": 8, "char": true};
29
30
/**
31
 * Class representing a wav file.
32
 */
33
class WaveFile {
34
35
    /**
36
     * @param {Uint8Array} bytes A wave file buffer.
37
     * @throws {Error} If no "RIFF" chunk is found.
38
     * @throws {Error} If no "fmt " chunk is found.
39
     * @throws {Error} If no "fact" chunk is found and "fact" is needed.
40
     * @throws {Error} If no "data" chunk is found.
41
     */
42
    constructor(bytes) {
43
        /**
44
         * The container identifier.
45
         * Only "RIFF" and "RIFX" are supported.
46
         * @type {string}
47
         * @export
48
         */
49
        this.container = "";
50
        /**
51
         * @type {number}
52
         * @export
53
         */
54
        this.chunkSize = 0;
55
        /**
56
         * The format.
57
         * Always "WAVE".
58
         * @type {string}
59
         * @export
60
         */
61
        this.format = "";
62
        /**
63
         * The data of the "fmt" chunk.
64
         * @type {!Object<string, *>}
65
         * @export
66
         */
67
        this.fmt = {
68
            /** @export @type {string} */
69
            "chunkId": "",
70
            /** @export @type {number} */
71
            "chunkSize": 0,
72
            /** @export @type {number} */
73
            "audioFormat": 0,
74
            /** @export @type {number} */
75
            "numChannels": 0,
76
            /** @export @type {number} */
77
            "sampleRate": 0,
78
            /** @export @type {number} */
79
            "byteRate": 0,
80
            /** @export @type {number} */
81
            "blockAlign": 0,
82
            /** @export @type {number} */
83
            "bitsPerSample": 0,
84
            /** @export @type {number} */
85
            "cbSize": 0,
86
            /** @export @type {number} */
87
            "validBitsPerSample": 0,
88
            /** @export @type {number} */
89
            "dwChannelMask": 0,
90
            /**
91
             * 4 32-bit values representing a 128-bit ID
92
             * @export @type {!Array<number>}
93
             */
94
            "subformat": []
95
        };
96
        /**
97
         * The data of the "fact" chunk.
98
         * @type {!Object<string, *>}
99
         * @export
100
         */
101
        this.fact = {
102
            /** @export @type {string} */
103
            "chunkId": "",
104
            /** @export @type {number} */
105
            "chunkSize": 0,
106
            /** @export @type {number} */
107
            "dwSampleLength": 0
108
        };
109
        /**
110
         * The data of the "cue " chunk.
111
         * @type {!Object<string, *>}
112
         * @export
113
         */
114
        this.cue = {
115
            /** @export @type {string} */
116
            "chunkId": "",
117
            /** @export @type {number} */
118
            "chunkSize": 0,
119
            /** @export @type {number} */
120
            "dwCuePoints": 0,
121
            /** @export @type {!Array<!Object>} */
122
            "points": [],
123
        };
124
        /**
125
         * The data of the "bext" chunk.
126
         * @type {!Object<string, *>}
127
         * @export
128
         */
129
        this.bext = {
130
            /** @export @type {string} */
131
            "chunkId": "",
132
            /** @export @type {number} */
133
            "chunkSize": 0,
134
            /** @export @type {string} */
135
            "description": "", //256
136
            /** @export @type {string} */
137
            "originator": "", //32
138
            /** @export @type {string} */
139
            "originatorReference": "", //32
140
            /** @export @type {string} */
141
            "originationDate": "", //10
142
            /** @export @type {string} */
143
            "originationTime": "", //8
144
            /**
145
             * 2 32-bit values, timeReference high and low
146
             * @export @type {!Array<number>}
147
             */
148
            "timeReference": [],
149
            /** @export @type {number} */
150
            "version": 0, //WORD
151
            /** @export @type {string} */
152
            "UMID": "", // 64 chars
153
            /** @export @type {number} */
154
            "loudnessValue": 0, //WORD
155
            /** @export @type {number} */
156
            "loudnessRange": 0, //WORD
157
            /** @export @type {number} */
158
            "maxTruePeakLevel": 0, //WORD
159
            /** @export @type {number} */
160
            "maxMomentaryLoudness": 0, //WORD
161
            /** @export @type {number} */
162
            "maxShortTermLoudness": 0, //WORD
163
            /** @export @type {string} */
164
            "reserved": "", //180
165
            /** @export @type {string} */
166
            "codingHistory": "" // string, unlimited
167
        };
168
        /**
169
         * The data of the "ds64" chunk.
170
         * Used only with RF64 files.
171
         * @type {!Object<string, *>}
172
         * @export
173
         */
174
        this.ds64 = {
175
            /** @type {string} */
176
            "chunkId": "",
177
            /** @export @type {number} */
178
            "chunkSize": 0,
179
            /** @export @type {number} */
180
            "riffSizeHigh": 0, // DWORD
181
            /** @export @type {number} */
182
            "riffSizeLow": 0, // DWORD
183
            /** @export @type {number} */
184
            "dataSizeHigh": 0, // DWORD
185
            /** @export @type {number} */
186
            "dataSizeLow": 0, // DWORD
187
            /** @export @type {number} */
188
            "originationTime": 0, // DWORD
189
            /** @export @type {number} */
190
            "sampleCountHigh": 0, // DWORD
191
            /** @export @type {number} */
192
            "sampleCountLow": 0, // DWORD
193
            /** @export @type {number} */
194
            //"tableLength": 0, // DWORD
195
            /** @export @type {!Array<number>} */
196
            //"table": []
197
        };
198
        /**
199
         * The data of the "data" chunk.
200
         * @type {!Object<string, *>}
201
         * @export
202
         */
203
        this.data = {
204
            /** @export @type {string} */
205
            "chunkId": "",
206
            /** @export @type {number} */
207
            "chunkSize": 0,
208
            /** @export @type {!Array<number>} */
209
            "samples": []
210
        };
211
        /**
212
         * The data of the "LIST" chunks.
213
         * Each item in this list must have this signature:
214
         *  {
215
         *      "chunkId": "",
216
         *      "chunkSize": 0,
217
         *      "format": "",
218
         *      "subChunks": []
219
         *   }
220
         * @type {!Array<!Object>}
221
         * @export
222
         */
223
        this.LIST = [];
224
        /**
225
         * The data of the "junk" chunk.
226
         * @type {!Object<string, *>}
227
         * @export
228
         */
229
        this.junk = {
230
            /** @export @type {string} */
231
            "chunkId": "",
232
            /** @export @type {number} */
233
            "chunkSize": 0,
234
            /** @export @type {!Array<number>} */
235
            "chunkData": []
236
        };
237
        /**
238
         * If the data in data.samples is interleaved or not.
239
         * @type {boolean}
240
         * @export
241
         */
242
        this.isInterleaved = true;
243
        /**
244
         * @type {string}
245
         * @export
246
         */
247
        this.bitDepth = "0";
248
        /**
249
         * Audio formats.
250
         * Formats not listed here will be set to 65534
251
         * and treated as WAVE_FORMAT_EXTENSIBLE
252
         * @enum {number}
253
         * @private
254
         */
255
        this.audioFormats_ = {
256
            "4": 17,
257
            "8": 1,
258
            "8a": 6,
259
            "8m": 7,
260
            "16": 1,
261
            "24": 1,
262
            "32": 1,
263
            "32f": 3,
264
            "40": 65534,
265
            "48": 65534,
266
            "64": 3
267
        };
268
        /**
269
         * @type {number}
270
         * @private
271
         */
272
        this.head_ = 0;
273
        // Load a file from the buffer if one was passed
274
        // when creating the object
275
        if(bytes) {
276
            this.fromBuffer(bytes);
277
        }
278
    }
279
280
    /**
281
     * Set up a WaveFile object based on the arguments passed.
282
     * @param {number} numChannels The number of channels
283
     *      (Integer numbers: 1 for mono, 2 stereo and so on).
284
     * @param {number} sampleRate The sample rate.
285
     *      Integer numbers like 8000, 44100, 48000, 96000, 192000.
286
     * @param {string} bitDepth The audio bit depth.
287
     *      One of "4", "8", "8a", "8m", "16", "24", "32", "32f", "64"
288
     *      or any value between "8" and "32".
289
     * @param {!Array<number>} samples Array of samples to be written.
290
     *      The samples must be in the correct range according to the
291
     *      bit depth.
292
     * @param {Object} options Optional. Used to force the container
293
     *      as RIFX with {"container": "RIFX"}
294
     * @throws {Error} If any argument does not meet the criteria.
295
     * @export
296
     */
297
    fromScratch(numChannels, sampleRate, bitDepth, samples, options={}) {
298
        if (!options["container"]) {
299
            options["container"] = "RIFF";
300
        }
301
        this.bitDepth = bitDepth;
302
        // interleave the samples if they were passed de-interleaved
303
        this.data.samples = samples;
304
        if (samples.length > 0) {
305
            if (samples[0].constructor === Array) {
306
                this.isInterleaved = false;
307
                this.assureInterleaved_();
308
            }
309
        } 
310
        /** type {number} */
311
        let numBytes = (((parseInt(bitDepth, 10) - 1) | 7) + 1) / 8;
312
        // Normal PCM file header
313
        if (["8","16","24","32","32f","64"].indexOf(bitDepth) > -1) {
314
            this.createPCMHeader_(
315
                bitDepth, numChannels, sampleRate, numBytes, options);
316
        // IMA ADPCM header
317
        } else if (bitDepth == "4") {
318
            this.createADPCMHeader_(
319
                bitDepth, numChannels, sampleRate, numBytes, options);
320
        // A-Law and mu-Law header
321
        } else if (bitDepth == "8a" || bitDepth == "8m") {
322
            this.createALawMulawHeader_(
323
                bitDepth, numChannels, sampleRate, numBytes, options);
324
        // WAVE_FORMAT_EXTENSIBLE
325
        } else {
326
            this.createExtensibleHeader_(
327
                bitDepth, numChannels, sampleRate, numBytes, options);
328
        }
329
        // the data chunk
330
        this.data.chunkId = "data";
331
        this.data.chunkSize = this.data.samples.length * numBytes;
332
        this.validateHeader_();
333
        this.LEorBE_();
334
    }
335
336
    /**
337
     * Init a WaveFile object from a byte buffer.
338
     * @param {!Uint8Array} bytes The buffer.
339
     * @throws {Error} If container is not RIFF or RIFX.
340
     * @throws {Error} If no "fmt " chunk is found.
341
     * @throws {Error} If no "fact" chunk is found and "fact" is needed.
342
     * @throws {Error} If no "data" chunk is found.
343
     * @export
344
     */
345
    fromBuffer(bytes) {
346
        this.clearHeader_();
347
        this.readRIFFChunk_(bytes);
348
        /** @type {!Object} */
349
        let chunk = riffChunks_.read(bytes);
350
        this.readDs64Chunk_(chunk["subChunks"]);
351
        this.readFmtChunk_(chunk["subChunks"]);
352
        this.readFactChunk_(chunk["subChunks"]);
353
        this.readBextChunk_(chunk["subChunks"]);
354
        this.readCueChunk_(chunk["subChunks"]);
355
        this.readDataChunk_(chunk["subChunks"]);
356
        this.readLISTChunk_(chunk["subChunks"]);
357
        this.readJunkChunk_(chunk["subChunks"]);
358
        this.bitDepthFromFmt_();
359
    }
360
361
    /**
362
     * Return a byte buffer representig the WaveFile object as a .wav file.
363
     * The return value of this method can be written straight to disk.
364
     * @return {!Uint8Array} A .wav file.
365
     * @throws {Error} If any property of the object appears invalid.
366
     * @export
367
     */
368
    toBuffer() {
369
        this.validateHeader_();
370
        this.assureInterleaved_();
371
        return this.createWaveFile_();
372
    }
373
374
    /**
375
     * Use a .wav file encoded as a base64 string to load the WaveFile object.
376
     * @param {string} base64String A .wav file as a base64 string.
377
     * @throws {Error} If any property of the object appears invalid.
378
     * @export
379
     */
380
    fromBase64(base64String) {
381
        this.fromBuffer(new Uint8Array(decodeBase64_(base64String)));
382
    }
383
384
    /**
385
     * Return a base64 string representig the WaveFile object as a .wav file.
386
     * @return {string} A .wav file as a base64 string.
387
     * @throws {Error} If any property of the object appears invalid.
388
     * @export
389
     */
390
    toBase64() {
391
        return encodeBase64_(this.toBuffer());
392
    }
393
394
    /**
395
     * Return a DataURI string representig the WaveFile object as a .wav file.
396
     * The return of this method can be used to load the audio in browsers.
397
     * @return {string} A .wav file as a DataURI.
398
     * @throws {Error} If any property of the object appears invalid.
399
     * @export
400
     */
401
    toDataURI() {
402
        return "data:audio/wav;base64," + this.toBase64();
403
    }
404
405
    /**
406
     * Use a .wav file encoded as a DataURI to load the WaveFile object.
407
     * @param {string} dataURI A .wav file as DataURI.
408
     * @throws {Error} If any property of the object appears invalid.
409
     * @export
410
     */
411
    fromDataURI(dataURI) {
412
        this.fromBase64(dataURI.replace("data:audio/wav;base64,", ""));
413
    }
414
415
    /**
416
     * Force a file as RIFF.
417
     * @export
418
     */
419
    toRIFF() {
420
        if (this.container == "RF64") {
421
            this.fromScratch(
422
                this.fmt.numChannels,
423
                this.fmt.sampleRate,
424
                this.bitDepth,
425
                this.data.samples);
426
        } else {
427
            this.container = "RIFF";
428
            this.LEorBE_();
429
        }
430
    }
431
432
    /**
433
     * Force a file as RIFX.
434
     * @export
435
     */
436
    toRIFX() {
437
        if (this.container == "RF64") {
438
            this.fromScratch(
439
                this.fmt.numChannels,
440
                this.fmt.sampleRate,
441
                this.bitDepth,
442
                this.data.samples,
443
                {"container": "RIFX"});
444
        } else {
445
            this.container = "RIFX";
446
            this.LEorBE_();
447
        }
448
    }
449
450
    /**
451
     * Change the bit depth of the samples.
452
     * @param {string} bitDepth The new bit depth of the samples.
453
     *      One of "8" ... "32" (integers), "32f" or "64" (floats)
454
     * @param {boolean} changeResolution A boolean indicating if the
455
     *      resolution of samples should be actually changed or not.
456
     * @throws {Error} If the bit depth is not valid.
457
     * @export
458
     */
459
    toBitDepth(bitDepth, changeResolution=true) {
460
        let toBitDepth = bitDepth;
461
        let thisBitDepth = this.bitDepth;
462
        if (!changeResolution) {
463
            toBitDepth = this.realBitDepth_(bitDepth);
464
            thisBitDepth = this.realBitDepth_(this.bitDepth);
465
        }
466
        this.assureInterleaved_();
467
        this.assureUncompressed_();
468
        bitDepth_.toBitDepth(this.data.samples, thisBitDepth, toBitDepth);
469
        this.fromScratch(
470
            this.fmt.numChannels,
471
            this.fmt.sampleRate,
472
            bitDepth,
473
            this.data.samples,
474
            {"container": this.correctContainer_()});
475
    }
476
477
    /**
478
     * Interleave multi-channel samples.
479
     * @export
480
     */
481
    interleave() {
482
        if (!this.isInterleaved) {
483
            let finalSamples = [];
484
            let numChannels = this.data.samples[0].length;
485
            for (let i = 0; i < numChannels; i++) {
486
                for (let j = 0; j < this.data.samples.length; j++) {
487
                    finalSamples.push(this.data.samples[j][i]);
488
                }
489
            }
490
            this.data.samples = finalSamples;
491
            this.isInterleaved = true;
492
        }
493
    }
494
495
    /**
496
     * De-interleave samples into multiple channels.
497
     * @export
498
     */
499
    deInterleave() {
500
        if (this.isInterleaved) {
501
            let finalSamples = [];
502
            let i;
503
            for (i = 0; i < this.fmt.numChannels; i++) {
504
                finalSamples[i] = [];
505
            }
506
            i = 0;
0 ignored issues
show
Complexity Coding Style introduced by
You seem to be assigning a new value to the loop variable i here. Please check if this was indeed your intention. Even if it was, consider using another kind of loop instead.
Loading history...
507
            let j;
508
            while (i < this.data.samples.length) {
509
                for (j = 0; j < this.fmt.numChannels; j++) {
510
                    finalSamples[j].push(this.data.samples[i+j]);
511
                }
512
                i += j;
513
            }
514
            this.data.samples = finalSamples;
515
            this.isInterleaved = false;
516
        }
517
    }
518
519
    /**
520
     * Encode a 16-bit wave file as 4-bit IMA ADPCM.
521
     * @throws {Error} If sample rate is not 8000.
522
     * @throws {Error} If number of channels is not 1.
523
     * @export
524
     */
525
    toIMAADPCM() {
526
        if (this.fmt.sampleRate != 8000) {
527
            throw new Error(
528
                "Only 8000 Hz files can be compressed as IMA-ADPCM.");
529
        } else if(this.fmt.numChannels != 1) {
0 ignored issues
show
Comparing this.fmt.numChannels to 1 using the != operator is not safe. Consider using !== instead.
Loading history...
530
            throw new Error(
531
                "Only mono files can be compressed as IMA-ADPCM.");
532
        } else {
533
            this.assure16Bit_();
534
            this.fromScratch(
535
                this.fmt.numChannels,
536
                this.fmt.sampleRate,
537
                "4",
538
                imaadpcm_.encode(this.data.samples),
539
                {"container": this.correctContainer_()});
540
        }
541
    }
542
543
    /**
544
     * Decode a 4-bit IMA ADPCM wave file as a 16-bit wave file.
545
     * @param {string} bitDepth The new bit depth of the samples.
546
     *      One of "8" ... "32" (integers), "32f" or "64" (floats).
547
     *      Optional. Default is 16.
548
     * @export
549
     */
550
    fromIMAADPCM(bitDepth="16") {
551
        this.fromScratch(
552
            this.fmt.numChannels,
553
            this.fmt.sampleRate,
554
            "16",
555
            imaadpcm_.decode(this.data.samples, this.fmt.blockAlign),
556
            {"container": this.correctContainer_()});
557
        if (bitDepth != "16") {
558
            this.toBitDepth(bitDepth);
559
        }
560
    }
561
562
    /**
563
     * Encode 16-bit wave file as 8-bit A-Law.
564
     * @export
565
     */
566
    toALaw() {
567
        this.assure16Bit_();
568
        this.assureInterleaved_();
569
        this.fromScratch(
570
            this.fmt.numChannels,
571
            this.fmt.sampleRate,
572
            "8a",
573
            alawmulaw_.alaw.encode(this.data.samples),
574
            {"container": this.correctContainer_()});
575
    }
576
577
    /**
578
     * Decode a 8-bit A-Law wave file into a 16-bit wave file.
579
     * @param {string} bitDepth The new bit depth of the samples.
580
     *      One of "8" ... "32" (integers), "32f" or "64" (floats).
581
     *      Optional. Default is 16.
582
     * @export
583
     */
584
    fromALaw(bitDepth="16") {
585
        this.fromScratch(
586
            this.fmt.numChannels,
587
            this.fmt.sampleRate,
588
            "16",
589
            alawmulaw_.alaw.decode(this.data.samples),
590
            {"container": this.correctContainer_()});
591
        if (bitDepth != "16") {
592
            this.toBitDepth(bitDepth);
593
        }
594
    }
595
596
    /**
597
     * Encode 16-bit wave file as 8-bit mu-Law.
598
     * @export
599
     */
600
    toMuLaw() {
601
        this.assure16Bit_();
602
        this.assureInterleaved_();
603
        this.fromScratch(
604
            this.fmt.numChannels,
605
            this.fmt.sampleRate,
606
            "8m",
607
            alawmulaw_.mulaw.encode(this.data.samples),
608
            {"container": this.correctContainer_()});
609
    }
610
611
    /**
612
     * Decode a 8-bit mu-Law wave file into a 16-bit wave file.
613
     * @param {string} bitDepth The new bit depth of the samples.
614
     *      One of "8" ... "32" (integers), "32f" or "64" (floats).
615
     *      Optional. Default is 16.
616
     * @export
617
     */
618
    fromMuLaw(bitDepth="16") {
619
        this.fromScratch(
620
            this.fmt.numChannels,
621
            this.fmt.sampleRate,
622
            "16",
623
            alawmulaw_.mulaw.decode(this.data.samples),
624
            {"container": this.correctContainer_()});
625
        if (bitDepth != "16") {
626
            this.toBitDepth(bitDepth);
627
        }
628
    }
629
630
    /**
631
     * Write a RIFF tag in the INFO chunk. If the tag do not exist,
632
     * then it is created. It if exists, it is overwritten.
633
     * @param {string} tag The tag name.
634
     * @param {string} value The tag value.
635
     * @throws {Error} If the tag name is not valid.
636
     * @export
637
     */
638
    setTag(tag, value) {
639
        tag = this.fixTagName_(tag);
640
        /** @type {!Object} */
641
        let index = this.getTagIndex_(tag);
642
        if (index.TAG !== null) {
643
            this.LIST[index.LIST]["subChunks"][index.TAG]["chunkSize"] =
644
                value.length + 1;
645
            this.LIST[index.LIST]["subChunks"][index.TAG]["value"] = value;
646
        } else if (index.LIST !== null) {
647
            this.LIST[index.LIST]["subChunks"].push({
648
                "chunkId": tag,
649
                "chunkSize": value.length + 1,
650
                "value": value});
651
        } else {
652
            this.LIST.push({
653
                "chunkId": "LIST",
654
                "chunkSize": 8 + value.length + 1,
655
                "format": "INFO",
656
                "chunkData": [],
657
                "subChunks": []});
658
            this.LIST[this.LIST.length - 1]["subChunks"].push({
659
                "chunkId": tag,
660
                "chunkSize": value.length + 1,
661
                "value": value});
662
        }
663
    }
664
665
    /**
666
     * Return the value of a RIFF tag in the INFO chunk.
667
     * @param {string} tag The tag name.
668
     * @return {string|null} The value if the tag is found, null otherwise.
669
     * @export
670
     */
671
    getTag(tag) {
672
        /** @type {!Object} */
673
        let index = this.getTagIndex_(tag);
674
        if (index.TAG !== null) {
675
            return this.LIST[index.LIST]["subChunks"][index.TAG]["value"];
676
        }
677
        return null;
678
    }
679
680
    /**
681
     * Remove a RIFF tag in the INFO chunk.
682
     * @param {string} tag The tag name.
683
     * @return {boolean} True if a tag was deleted.
684
     * @export
685
     */
686
    deleteTag(tag) {
687
        /** @type {!Object} */
688
        let index = this.getTagIndex_(tag);
689
        if (index.TAG !== null) {
690
            this.LIST[index.LIST]["subChunks"].splice(index.TAG, 1);
691
            return true;
692
        }
693
        return false;
694
    }
695
696
    /**
697
     * Create a cue point in the wave file.
698
     * @param {number} position The cue point position in milliseconds.
699
     * @param {string} labl The LIST adtl labl text of the marker. Optional.
700
     * @export
701
     */
702
    setCuePoint(position, labl="") {
703
        this.cue.chunkId = "cue ";
704
        position = (position * this.fmt.sampleRate) / 1000;
705
        /** @type {!Array<Object>} */
706
        let existingPoints = this.getCuePoints_();
707
        this.clearLISTadtl_();
708
        /** @type {number} */
709
        let len = this.cue.points.length;
710
        this.cue.points = [];
711
        let hasSet = false;
712
        if (len == 0) {
0 ignored issues
show
Comparing len to 0 using the == operator is not safe. Consider using === instead.
Loading history...
713
            this.setCuePoint_(position, 1, labl);
714
        } else {
715
            for (let i=0; i<len; i++) {
716
                if (existingPoints[i]["dwPosition"] > position && !hasSet) {
717
                    this.setCuePoint_(position, i + 1, labl);
718
                    this.setCuePoint_(
719
                        existingPoints[i]["dwPosition"],
720
                        i + 2,
721
                        existingPoints[i]["label"]);
722
                    hasSet = true;
723
                } else {
724
                    this.setCuePoint_(
725
                        existingPoints[i]["dwPosition"], 
726
                        i + 1, 
727
                        existingPoints[i]["label"]);
728
                }
729
            }
730
            if (!hasSet) {
731
                this.setCuePoint_(position, this.cue.points.length + 1, labl);
732
            }
733
        }
734
        this.cue.dwCuePoints = this.cue.points.length;
735
    }
736
737
    /**
738
     * Remove a cue point from a wave file.
739
     * @param {number} index the index of the point. First is 1,
740
     *      second is 2, and so on.
741
     * @export
742
     */
743
    deleteCuePoint(index) {
744
        this.cue.chunkId = "cue ";
745
        /** @type {!Array<Object>} */
746
        let existingPoints = this.getCuePoints_();
747
        this.clearLISTadtl_();
748
        let len = this.cue.points.length;
749
        this.cue.points = [];
750
        for (let i=0; i<len; i++) {
751
            if (i + 1 != index) {
752
                this.setCuePoint_(
753
                    existingPoints[i]["dwPosition"],
754
                    i + 1,
755
                    existingPoints[i]["label"]);
756
            }
757
        }
758
        this.cue.dwCuePoints = this.cue.points.length;
759
        if (this.cue.dwCuePoints) {
760
            this.cue.chunkId = 'cue ';
761
        } else {
762
            this.cue.chunkId = '';
763
            this.clearLISTadtl_();
764
        }
765
    }
766
767
    /**
768
     * Update the label of a cue point.
769
     * @param {number} pointIndex The ID of the cue point.
770
     * @param {string} label The new text for the label.
771
     * @export
772
     */
773
    updateLabel(pointIndex, label) {
774
        /** @type {number|null} */
775
        let adtlIndex = this.getAdtlChunk_();
776
        if (adtlIndex !== null) {
777
            for (let i=0; i<this.LIST[adtlIndex]["subChunks"].length; i++) {
778
                if (this.LIST[adtlIndex]["subChunks"][i]["dwName"] ==
779
                        pointIndex) {
780
                    this.LIST[adtlIndex]["subChunks"][i]["value"] = label;
781
                }
782
            }
783
        }
784
    }
785
786
    /**
787
     * Push a new cue point in this.cue.points.
788
     * @param {number} position The position in milliseconds.
789
     * @param {number} dwName the dwName of the cue point
790
     */
791
    setCuePoint_(position, dwName, label) {
792
        this.cue.points.push({
793
            "dwName": dwName,
794
            "dwPosition": position,
795
            "fccChunk": "data",
796
            "dwChunkStart": 0,
797
            "dwBlockStart": 0,
798
            "dwSampleOffset": position,
799
        });
800
        this.setLabl_(dwName, label);
801
    }
802
803
    /**
804
     * Return an array with the position of all cue points in the file.
805
     * @return {!Array<!Object>}
806
     */
807
    getCuePoints_() {
808
        /** @type {!Array<Object>} */
809
        let points = [];
810
        for (let i=0; i<this.cue.points.length; i++) {
811
            points.push({
812
                'dwPosition': this.cue.points[i]["dwPosition"],
813
                'label': this.getLabelForCuePoint_(
814
                    this.cue.points[i]["dwName"])});
815
        }
816
        return points;
817
    }
818
819
    /**
820
     * Return the label of a cue point.
821
     * @param {number} pointDwName The ID of the cue point.
822
     * @return {string}
823
     * @private
824
     */
825
    getLabelForCuePoint_(pointDwName) {
826
        /** @type {number|null} */
827
        let adtlIndex = this.getAdtlChunk_();
828
        if (adtlIndex !== null) {
829
            for (let i=0; i<this.LIST[adtlIndex]["subChunks"].length; i++) {
830
                if (this.LIST[adtlIndex]["subChunks"][i]["dwName"] ==
831
                        pointDwName) {
832
                    return this.LIST[adtlIndex]["subChunks"][i]["value"];
833
                }
834
            }
835
        }
836
        return "";
837
    }
838
839
    /**
840
     * Clear any LIST chunk labeled as "adtl".
841
     */
842
    clearLISTadtl_() {
843
        for (let i=0; i<this.LIST.length; i++) {
844
            if (this.LIST[i]["format"] == 'adtl') {
845
                this.LIST.splice(i);
846
            }
847
        }
848
    }
849
850
    /**
851
     * Create a new "labl" subchunk in a "LIST" chunk of type "adtl".
852
     * @param {number} dwName The ID of the cue point.
853
     * @param {string} label The label for the cue point.
854
     * @private
855
     */
856
    setLabl_(dwName, label) {
857
        /** @type {number|null} */
858
        let adtlIndex = this.getAdtlChunk_();
859
        if (adtlIndex === null) {
860
            this.LIST.push({
861
                "chunkId": "LIST",
862
                "chunkSize": 4,
863
                "format": "adtl",
864
                "chunkData": [],
865
                "subChunks": []});
866
            adtlIndex = this.LIST.length - 1;
867
        }
868
        this.setLabelText_(adtlIndex === null ? 0 : adtlIndex, dwName, label);
869
    }
870
871
    /**
872
     * Create a new "labl" subchunk in a "LIST" chunk of type "adtl".
873
     * @param {number} adtlIndex The index of the "adtl" LIST in this.LIST.
874
     * @param {number} dwName The ID of the cue point.
875
     * @param {string} label The label for the cue point.
876
     * @private
877
     */
878
    setLabelText_(adtlIndex, dwName, label) {
879
        this.LIST[adtlIndex]["subChunks"].push({
880
            "chunkId": "labl",
881
            "chunkSize": label.length,
882
            "dwName": dwName,
883
            "value": label
884
        });
885
        this.LIST[adtlIndex]["chunkSize"] += label.length + 4 + 4 + 4 + 1;
886
    }
887
888
    /**
889
     * Return the index of the "adtl" LIST in this.LIST.
890
     * @return {number|null}
891
     * @private
892
     */
893
    getAdtlChunk_() {
894
        for (let i=0; i<this.LIST.length; i++) {
895
            if(this.LIST[i]["format"] == 'adtl') {
896
                return i;
897
            }
898
        }
899
        return null;
900
    }
901
902
    /**
903
     * Return the index of a tag in a FILE chunk.
904
     * @param {string} tag The tag name.
905
     * @return {!Object<string, number|null>}
906
     *      Object.LIST is the INFO index in LIST
907
     *      Object.TAG is the tag index in the INFO
908
     * @private
909
     */
910
    getTagIndex_(tag) {
911
        /** @type {!Object} */
912
        let index = {LIST: null, TAG: null};
913
        for (let i=0; i<this.LIST.length; i++) {
914
            if (this.LIST[i]["format"] == "INFO") {
915
                index.LIST = i;
916
                for (let j=0; j<this.LIST[i]["subChunks"].length; j++) {
917
                    if (this.LIST[i]["subChunks"][j]["chunkId"] == tag) {
918
                        index.TAG = j;
919
                        break;
920
                    }
921
                }
922
                break;
923
            }
924
        }
925
        return index;
926
    }
927
928
    /**
929
     * Fix a RIFF tag format if possible, throw an error otherwise.
930
     * @param {string} tag The tag name.
931
     * @return {string} The tag name in proper fourCC format.
932
     * @private
933
     */
934
    fixTagName_(tag) {
935
        if (tag.constructor !== String) {
936
            throw new Error("Invalid tag name.");
937
        } else if(tag.length < 4) {
938
            for (let i=0; i<4-tag.length; i++) {
939
                tag += ' ';
940
            }
941
        }
942
        return tag;
943
    }
944
945
    /**
946
     * Create the header of a ADPCM wave file.
947
     * @param {string} bitDepth The audio bit depth
948
     * @param {number} numChannels The number of channels
949
     * @param {number} sampleRate The sample rate.
950
     * @param {number} numBytes The number of bytes each sample use.
951
     * @param {!Object} options The extra options, like container defintion.
952
     * @private
953
     */
954
    createADPCMHeader_(bitDepth, numChannels, sampleRate, numBytes, options) {
955
        this.createPCMHeader_(
956
            bitDepth, numChannels, sampleRate, numBytes, options);
957
        this.chunkSize = 40 + this.data.samples.length;
958
        this.fmt.chunkSize = 20;
959
        this.fmt.byteRate = 4055;
960
        this.fmt.blockAlign = 256;
961
        this.fmt.bitsPerSample = 4;
962
        this.fmt.cbSize = 2;
963
        this.fmt.validBitsPerSample = 505;
964
        this.fact.chunkId = "fact";
965
        this.fact.chunkSize = 4;
966
        this.fact.dwSampleLength = this.data.samples.length * 2;
967
        this.data.chunkSize = this.data.samples.length;
968
    }
969
970
    /**
971
     * Create the header of WAVE_FORMAT_EXTENSIBLE file.
972
     * @param {string} bitDepth The audio bit depth
973
     * @param {number} numChannels The number of channels
974
     * @param {number} sampleRate The sample rate.
975
     * @param {number} numBytes The number of bytes each sample use.
976
     * @param {!Object} options The extra options, like container defintion.
977
     * @private
978
     */
979
    createExtensibleHeader_(
980
            bitDepth, numChannels, sampleRate, numBytes, options) {
981
        this.createPCMHeader_(
982
            bitDepth, numChannels, sampleRate, numBytes, options);
983
        this.chunkSize = 36 + 24 + this.data.samples.length * numBytes;
984
        this.fmt.chunkSize = 40;
985
        this.fmt.bitsPerSample = ((parseInt(bitDepth, 10) - 1) | 7) + 1;
986
        this.fmt.cbSize = 22;
987
        this.fmt.validBitsPerSample = parseInt(bitDepth, 10);
988
        this.fmt.dwChannelMask = 0;
989
        // subformat 128-bit GUID as 4 32-bit values
990
        // only supports uncompressed integer PCM samples
991
        this.fmt.subformat = [1, 1048576, 2852126848, 1905997824];
992
    }
993
994
    /**
995
     * Create the header of mu-Law and A-Law wave files.
996
     * @param {string} bitDepth The audio bit depth
997
     * @param {number} numChannels The number of channels
998
     * @param {number} sampleRate The sample rate.
999
     * @param {number} numBytes The number of bytes each sample use.
1000
     * @param {!Object} options The extra options, like container defintion.
1001
     * @private
1002
     */
1003
    createALawMulawHeader_(
1004
            bitDepth, numChannels, sampleRate, numBytes, options) {
1005
        this.createPCMHeader_(
1006
            bitDepth, numChannels, sampleRate, numBytes, options);
1007
        this.chunkSize = 40 + this.data.samples.length;
1008
        this.fmt.chunkSize = 20;
1009
        this.fmt.cbSize = 2;
1010
        this.fmt.validBitsPerSample = 8;
1011
        this.fact.chunkId = "fact";
1012
        this.fact.chunkSize = 4;
1013
        this.fact.dwSampleLength = this.data.samples.length;
1014
    }
1015
1016
    /**
1017
     * Create the header of a linear PCM wave file.
1018
     * @param {string} bitDepth The audio bit depth
1019
     * @param {number} numChannels The number of channels
1020
     * @param {number} sampleRate The sample rate.
1021
     * @param {number} numBytes The number of bytes each sample use.
1022
     * @param {!Object} options The extra options, like container defintion.
1023
     * @private
1024
     */
1025
    createPCMHeader_(bitDepth, numChannels, sampleRate, numBytes, options) {
1026
        this.clearHeader_();
1027
        this.container = options["container"];
1028
        this.chunkSize = 36 + this.data.samples.length * numBytes;
1029
        this.format = "WAVE";
1030
        this.fmt.chunkId = "fmt ";
1031
        this.fmt.chunkSize = 16;
1032
        this.fmt.byteRate = (numChannels * numBytes) * sampleRate;
1033
        this.fmt.blockAlign = numChannels * numBytes;
1034
        this.fmt.audioFormat = this.audioFormats_[bitDepth] ?
1035
            this.audioFormats_[bitDepth] : 65534;
1036
        this.fmt.numChannels = numChannels;
1037
        this.fmt.sampleRate = sampleRate;
1038
        this.fmt.bitsPerSample = parseInt(bitDepth, 10);
1039
        this.fmt.cbSize = 0;
1040
        this.fmt.validBitsPerSample = 0;
1041
    }
1042
1043
    /**
1044
     * Return the closest greater number of bits for a number of bits that
1045
     * do not fill a full sequence of bytes.
1046
     * @param {string} bitDepth The bit depth.
1047
     * @return {string}
1048
     */
1049
    realBitDepth_(bitDepth) {
1050
        if (bitDepth != "32f") {
1051
            bitDepth = (((parseInt(bitDepth, 10) - 1) | 7) + 1).toString();
1052
        }
1053
        return bitDepth;
1054
    }
1055
1056
    /**
1057
     * Validate the header of the file.
1058
     * @throws {Error} If any property of the object appears invalid.
1059
     * @private
1060
     */
1061
    validateHeader_() {
1062
        this.validateBitDepth_();
1063
        this.validateNumChannels_();
1064
        this.validateSampleRate_();
1065
    }
1066
1067
    /**
1068
     * Validate the bit depth.
1069
     * @return {boolean} True is the bit depth is valid.
1070
     * @throws {Error} If bit depth is invalid.
1071
     * @private
1072
     */
1073
    validateBitDepth_() {
1074
        if (!this.audioFormats_[this.bitDepth]) {
1075
            if (parseInt(this.bitDepth, 10) > 8 &&
1076
                    parseInt(this.bitDepth, 10) < 54) {
1077
                return true;
1078
            }
1079
            throw new Error("Invalid bit depth.");
1080
        }
1081
        return true;
1082
    }
1083
1084
    /**
1085
     * Validate the number of channels.
1086
     * @return {boolean} True is the number of channels is valid.
1087
     * @throws {Error} If the number of channels is invalid.
1088
     * @private
1089
     */
1090
    validateNumChannels_() {
1091
        /** @type {number} */
1092
        let blockAlign = this.fmt.numChannels * this.fmt.bitsPerSample / 8;
1093
        if (this.fmt.numChannels < 1 || blockAlign > 65535) {
1094
            throw new Error("Invalid number of channels.");
1095
        }
1096
        return true;
1097
    }
1098
1099
    /**
1100
     * Validate the sample rate value.
1101
     * @return {boolean} True is the sample rate is valid.
1102
     * @throws {Error} If the sample rate is invalid.
1103
     * @private
1104
     */
1105
    validateSampleRate_() {
1106
        /** @type {number} */
1107
        let byteRate = this.fmt.numChannels *
1108
            (this.fmt.bitsPerSample / 8) * this.fmt.sampleRate;
1109
        if (this.fmt.sampleRate < 1 || byteRate > 4294967295) {
1110
            throw new Error("Invalid sample rate.");
1111
        }
1112
        return true;
1113
    }
1114
1115
    /**
1116
     * Reset attributes that should emptied when a file is
1117
     * created with the fromScratch() or fromBuffer() methods.
1118
     * @private
1119
     */
1120
    clearHeader_() {
1121
        this.fmt.cbSize = 0;
1122
        this.fmt.validBitsPerSample = 0;
1123
        this.fact.chunkId = "";
1124
        this.ds64.chunkId = "";
1125
    }
1126
1127
    /**
1128
     * Make the file 16-bit if it is not.
1129
     * @private
1130
     */
1131
    assure16Bit_() {
1132
        this.assureUncompressed_();
1133
        if (this.bitDepth != "16") {
1134
            this.toBitDepth("16");
1135
        }
1136
    }
1137
1138
    /**
1139
     * Uncompress the samples in case of a compressed file.
1140
     * @private
1141
     */
1142
    assureUncompressed_() {
1143
        if (this.bitDepth == "8a") {
1144
            this.fromALaw();
1145
        } else if(this.bitDepth == "8m") {
1146
            this.fromMuLaw();
1147
        } else if (this.bitDepth == "4") {
1148
            this.fromIMAADPCM();
1149
        }
1150
    }
1151
1152
    /**
1153
     * Interleave the samples in case they are de-Interleaved.
1154
     * @private
1155
     */
1156
    assureInterleaved_() {
1157
        if (!this.isInterleaved) {
1158
            this.interleave();
1159
        }
1160
    }
1161
1162
    /**
1163
     * Set up to work wih big-endian or little-endian files.
1164
     * The types used are changed to LE or BE. If the
1165
     * the file is big-endian (RIFX), true is returned.
1166
     * @return {boolean} True if the file is RIFX.
1167
     * @private
1168
     */
1169
    LEorBE_() {
1170
        /** @type {boolean} */
1171
        let bigEndian = this.container === "RIFX";
1172
        uInt16_["be"] = bigEndian;
1173
        uInt32_["be"] = bigEndian;
1174
        return bigEndian;
1175
    }
1176
1177
    /**
1178
     * Find a chunk by its fourCC_ in a array of RIFF chunks.
1179
     * @param {!Array<!Object>} chunks The wav file chunks.
1180
     * @param {string} chunkId The chunk fourCC_.
1181
     * @param {boolean} multiple True if there may be multiple chunks
1182
     *      with the same chunkId.
1183
     * @return {Object|Array<!Object>|null}
1184
     * @private
1185
     */
1186
    findChunk_(chunks, chunkId, multiple=false) {
1187
        /** @type {!Array<!Object>} */
1188
        let chunk = [];
1189
        for (let i=0; i<chunks.length; i++) {
1190
            if (chunks[i]["chunkId"] == chunkId) {
1191
                if (multiple) {
1192
                    chunk.push(chunks[i]);
1193
                } else {
1194
                    return chunks[i];
1195
                }
1196
            }
1197
        }
1198
        if (chunkId == "LIST") {
1199
            return chunk.length ? chunk : null;
1200
        }
1201
        return null;
1202
    }
1203
1204
    /**
1205
     * Read the RIFF chunk a wave file.
1206
     * @param {!Uint8Array} bytes A wav buffer.
1207
     * @throws {Error} If no "RIFF" chunk is found.
1208
     * @private
1209
     */
1210
    readRIFFChunk_(bytes) {
1211
        this.head_ = 0;
1212
        this.container = this.readString_(bytes, 4);
1213
        if (["RIFF", "RIFX", "RF64"].indexOf(this.container) === -1) {
1214
            throw Error("Not a supported format.");
1215
        }
1216
        this.LEorBE_();
1217
        this.chunkSize = this.read_(bytes, uInt32_);
1218
        this.format = this.readString_(bytes, 4);
1219
        if (this.format != "WAVE") {
1220
            throw Error("Could not find the 'WAVE' format identifier");
1221
        }
1222
    }
1223
1224
    /**
1225
     * Read the "fmt " chunk of a wave file.
1226
     * @param {!Array<!Object>} chunks The wav file chunks.
1227
     * @throws {Error} If no "fmt " chunk is found.
1228
     * @private
1229
     */
1230
    readFmtChunk_(chunks) {
1231
        /** type {Array<!Object>} */
1232
        let chunk = this.findChunk_(chunks, "fmt ");
1233
        if (chunk) {
1234
            this.head_ = 0;
1235
            let chunkData = chunk["chunkData"];
1236
            this.fmt.chunkId = chunk["chunkId"];
1237
            this.fmt.chunkSize = chunk["chunkSize"];
1238
            this.fmt.audioFormat = this.read_(chunkData, uInt16_);
1239
            this.fmt.numChannels = this.read_(chunkData, uInt16_);
1240
            this.fmt.sampleRate = this.read_(chunkData, uInt32_);
1241
            this.fmt.byteRate = this.read_(chunkData, uInt32_);
1242
            this.fmt.blockAlign = this.read_(chunkData, uInt16_);
1243
            this.fmt.bitsPerSample = this.read_(chunkData, uInt16_);
1244
            this.readFmtExtension_(chunkData);
1245
        } else {
1246
            throw Error("Could not find the 'fmt ' chunk");
1247
        }
1248
    }
1249
1250
    /**
1251
     * Read the "fmt " chunk extension.
1252
     * @param {!Array<number>} chunkData The "fmt " chunk.
1253
     * @private
1254
     */
1255
    readFmtExtension_(chunkData) {
1256
        if (this.fmt.chunkSize > 16) {
1257
            this.fmt.cbSize = this.read_(
1258
                chunkData, uInt16_);
1259
            if (this.fmt.chunkSize > 18) {
1260
                this.fmt.validBitsPerSample = this.read_(chunkData, uInt16_);
1261
                if (this.fmt.chunkSize > 20) {
1262
                    this.fmt.dwChannelMask = this.read_(chunkData, uInt32_);
1263
                    this.fmt.subformat = [
1264
                        this.read_(chunkData, uInt32_),
1265
                        this.read_(chunkData, uInt32_),
1266
                        this.read_(chunkData, uInt32_),
1267
                        this.read_(chunkData, uInt32_)];
1268
                }
1269
            }
1270
        }
1271
    }
1272
1273
    /**
1274
     * Read the "fact" chunk of a wav file.
1275
     * @param {!Array<Object>} chunks The wav file chunks.
1276
     * @throws {Error} If no "fact" chunk is found.
1277
     * @private
1278
     */
1279
    readFactChunk_(chunks) {
1280
        /** type {Array<!Object>} */
1281
        let chunk = this.findChunk_(chunks, "fact");
1282
        if (chunk) {
1283
            this.head_ = 0;
1284
            this.fact.chunkId = chunk["chunkId"];
1285
            this.fact.chunkSize = chunk["chunkSize"];
1286
            this.fact.dwSampleLength = this.read_(chunk["chunkData"], uInt32_);
1287
        }
1288
    }
1289
1290
    /**
1291
     * Read the "cue " chunk of a wave file.
1292
     * @param {!Array<Object>} chunks The RIFF file chunks.
1293
     * @private
1294
     */
1295
    readCueChunk_(chunks) {
1296
        /** type {Array<!Object>} */
1297
        let chunk = this.findChunk_(chunks, "cue ");
1298
        if (chunk) {
1299
            this.head_ = 0;
1300
            let chunkData = chunk["chunkData"];
1301
            this.cue.chunkId = chunk["chunkId"];
1302
            this.cue.chunkSize = chunk["chunkSize"];
1303
            this.cue.dwCuePoints = this.read_(chunkData, uInt32_);
1304
            for (let i=0; i<this.cue.dwCuePoints; i++) {
1305
                this.cue.points.push({
1306
                    "dwName": this.read_(chunkData, uInt32_),
1307
                    "dwPosition": this.read_(chunkData, uInt32_),
1308
                    "fccChunk": this.readString_(chunkData, 4),
1309
                    "dwChunkStart": this.read_(chunkData, uInt32_),
1310
                    "dwBlockStart": this.read_(chunkData, uInt32_),
1311
                    "dwSampleOffset": this.read_(chunkData, uInt32_),
1312
                });
1313
            }
1314
        }
1315
    }
1316
1317
    /**
1318
     * Read the "data" chunk of a wave file.
1319
     * @param {!Array<Object>} chunks The RIFF file chunks.
1320
     * @throws {Error} If no "data" chunk is found.
1321
     * @private
1322
     */
1323
    readDataChunk_(chunks) {
1324
        /** type {Array<!Object>} */
1325
        let chunk = this.findChunk_(chunks, "data");
1326
        if (chunk) {
1327
            this.data.chunkId = "data";
1328
            this.data.chunkSize = chunk["chunkSize"];
1329
            this.samplesFromBytes_(chunk["chunkData"]);
1330
        } else {
1331
            throw Error("Could not find the 'data' chunk");
1332
        }
1333
    }
1334
1335
    /**
1336
     * Read the "bext" chunk of a wav file.
1337
     * @param {!Array<Object>} chunks The wav file chunks.
1338
     * @private
1339
     */
1340
    readBextChunk_(chunks) {
1341
        /** type {Array<!Object>} */
1342
        let chunk = this.findChunk_(chunks, "bext");
1343
        if (chunk) {
1344
            this.head_ = 0;
1345
            let chunkData = chunk["chunkData"];
1346
            this.bext.chunkId = chunk["chunkId"];
1347
            this.bext.chunkSize = chunk["chunkSize"];
1348
            this.bext.description = this.readString_(chunkData, 256);
1349
            this.bext.originator = this.readString_(chunkData, 32);
1350
            this.bext.originatorReference = this.readString_(chunkData, 32);
1351
            this.bext.originationDate = this.readString_(chunkData, 10);
1352
            this.bext.originationTime = this.readString_(chunkData, 8);
1353
            this.bext.timeReference = [
1354
                this.read_(chunkData, uInt32_),
1355
                this.read_(chunkData, uInt32_)];
1356
            this.bext.version = this.read_(chunkData, uInt16_);
1357
            this.bext.UMID = this.readString_(chunkData, 64);
1358
            this.bext.loudnessValue = this.read_(chunkData, uInt16_);
1359
            this.bext.loudnessRange = this.read_(chunkData, uInt16_);
1360
            this.bext.maxTruePeakLevel = this.read_(chunkData, uInt16_);
1361
            this.bext.maxMomentaryLoudness = this.read_(chunkData, uInt16_);
1362
            this.bext.maxShortTermLoudness = this.read_(chunkData, uInt16_);
1363
            this.bext.reserved = this.readString_(chunkData, 180);
1364
            this.bext.codingHistory = this.readString_(
1365
                chunkData, this.bext.chunkSize - 602);
1366
        }
1367
    }
1368
1369
    /**
1370
     * Read the "ds64" chunk of a wave file.
1371
     * @param {!Array<Object>} chunks The wav file chunks.
1372
     * @throws {Error} If no "ds64" chunk is found and the file is RF64.
1373
     * @private
1374
     */
1375
    readDs64Chunk_(chunks) {
1376
        /** type {Array<!Object>} */
1377
        let chunk = this.findChunk_(chunks, "ds64");
1378
        if (chunk) {
1379
            this.head_ = 0;
1380
            let chunkData = chunk["chunkData"];
1381
            this.ds64.chunkId = chunk["chunkId"];
1382
            this.ds64.chunkSize = chunk["chunkSize"];
1383
            this.ds64.riffSizeHigh = this.read_(chunkData, uInt32_);
1384
            this.ds64.riffSizeLow = this.read_(chunkData, uInt32_);
1385
            this.ds64.dataSizeHigh = this.read_(chunkData, uInt32_);
1386
            this.ds64.dataSizeLow = this.read_(chunkData, uInt32_);
1387
            this.ds64.originationTime = this.read_(chunkData, uInt32_);
1388
            this.ds64.sampleCountHigh = this.read_(chunkData, uInt32_);
1389
            this.ds64.sampleCountLow = this.read_(chunkData, uInt32_);
1390
            //if (this.ds64.chunkSize > 28) {
1391
            //    this.ds64.tableLength = byteData_.unpack(
1392
            //        chunkData.slice(28, 32), uInt32_);
1393
            //    this.ds64.table = chunkData.slice(
1394
            //         32, 32 + this.ds64.tableLength); 
1395
            //}
1396
        } else {
1397
            if (this.container == "RF64") {
1398
                throw Error("Could not find the 'ds64' chunk");    
1399
            }
1400
        }
1401
    }
1402
1403
    /**
1404
     * Read the "LIST" chunks of a wave file.
1405
     * @param {!Array<Object>} chunks The wav file chunks.
1406
     * @private
1407
     */
1408
    readLISTChunk_(chunks) {
1409
        /** type {Array<Array<!Object>>>} */
1410
        let listChunks = this.findChunk_(chunks, "LIST", true);
1411
        if (listChunks === null) {
1412
            return;
1413
        }
1414
        for (let j=0; j<listChunks.length; j++) {
1415
            let subChunk = listChunks[j];
1416
            this.LIST.push({
1417
                "chunkId": subChunk["chunkId"],
1418
                "chunkSize": subChunk["chunkSize"],
1419
                "format": subChunk["format"],
1420
                "chunkData": subChunk["chunkData"],
1421
                "subChunks": []});
1422
            for (let x=0; x<subChunk["subChunks"].length; x++) {
1423
                this.readLISTSubChunks_(subChunk["subChunks"][x],
1424
                    subChunk["format"]);
1425
            }
1426
        }
1427
    }
1428
1429
    /**
1430
     * Read the sub chunks of a "LIST" chunk.
1431
     * @param {!Object} subChunk The "LIST" subchunks.
1432
     * @param {string} format The "LIST" format, "adtl" or "INFO".
1433
     * @private
1434
     */
1435
    readLISTSubChunks_(subChunk, format) {
1436
        // 'labl', 'note', 'ltxt', 'file'
1437
        if (format == 'adtl') {
1438
            if (["labl", "note"].indexOf(subChunk["chunkId"]) > -1) {
1439
                this.LIST[this.LIST.length - 1]["subChunks"].push({
1440
                    "chunkId": subChunk["chunkId"],
1441
                    "chunkSize": subChunk["chunkSize"],
1442
                    "dwName": byteData_.unpack(
1443
                        subChunk["chunkData"].slice(0, 4),uInt32_),
1444
                    "value": this.readZSTR_(subChunk["chunkData"].slice(4))
1445
                });
1446
            }
1447
        // RIFF 'INFO' tags like ICRD, ISFT, ICMT
1448
        // https://sno.phy.queensu.ca/~phil/exiftool/TagNames/RIFF.html#Info
1449
        } else if(format == 'INFO') {
1450
            this.LIST[this.LIST.length - 1]["subChunks"].push({
1451
                "chunkId": subChunk["chunkId"],
1452
                "chunkSize": subChunk["chunkSize"],
1453
                "value": this.readZSTR_(subChunk["chunkData"].slice(0))
1454
            });
1455
        } //else {
1456
        //    this.LIST[this.LIST.length - 1]["subChunks"].push({
1457
        //        "chunkId": subChunk["chunkId"],
1458
        //        "chunkSize": subChunk["chunkSize"],
1459
        //        "value": subChunk["chunkData"]
1460
        //    });
1461
        //}
1462
    }
1463
1464
    /**
1465
     * Read the "junk" chunk of a wave file.
1466
     * @param {!Array<Object>} chunks The wav file chunks.
1467
     * @private
1468
     */
1469
    readJunkChunk_(chunks) {
1470
        /** type {Array<!Object>} */
1471
        let chunk = this.findChunk_(chunks, "junk");
1472
        if (chunk) {
1473
            this.junk = {
1474
                "chunkId": chunk["chunkId"],
1475
                "chunkSize": chunk["chunkSize"],
1476
                "chunkData": chunk["chunkData"]
1477
            };
1478
        }
1479
    }
1480
1481
    /**
1482
     * Read bytes as a ZSTR string.
1483
     * @param {!Array<number>|!Uint8Array} bytes The bytes.
1484
     * @return {string} The string.
1485
     * @private
1486
     */
1487
    readZSTR_(bytes) {
1488
        /** type {string} */
1489
        let str = "";
1490
        for (let i=0; i<bytes.length; i++) {
1491
            if (bytes[i] === 0) {
1492
                break;
1493
            }
1494
            str += byteData_.unpack([bytes[i]], chr_);
1495
        }
1496
        return str;
1497
    }
1498
1499
    /**
1500
     * Read bytes as a string from a RIFF chunk.
1501
     * @param {!Array<number>|!Uint8Array} bytes The bytes.
1502
     * @param {number} maxSize the max size of the string.
1503
     * @return {string} The string.
1504
     * @private
1505
     */
1506
    readString_(bytes, maxSize) {
1507
        /** type {string} */
1508
        let str = "";
1509
        for (let i=0; i<maxSize; i++) {
1510
            str += byteData_.unpack([bytes[this.head_]], chr_);
1511
            this.head_++;
1512
        }
1513
        return str;
1514
    }
1515
1516
    /**
1517
     * Read a number from a chunk.
1518
     * @param {!Array<number>|!Uint8Array} bytes The chunk bytes.
1519
     * @param {!Object} bdType The type definition.
1520
     * @return {number} The number.
1521
     * @private
1522
     */
1523
    read_(bytes, bdType) {
1524
        let size = bdType["bits"] / 8;
1525
        let value = byteData_.unpack(
1526
            bytes.slice(this.head_, this.head_ + size), bdType);
1527
        this.head_ += size;
1528
        return value;
1529
    }
1530
1531
    /**
1532
     * Write a variable size string as bytes. If the string is smaller
1533
     * than the max size the output array is filled with 0s.
1534
     * @param {string} str The string to be written as bytes.
1535
     * @param {number} maxSize the max size of the string.
1536
     * @return {!Array<number>} The bytes.
1537
     * @private
1538
     */
1539
    writeString_(str, maxSize, push=true) {
1540
        /** type {!Array<number>} */   
1541
        let bytes = byteData_.packArray(str, chr_);
1542
        if (push) {
1543
            for (let i=bytes.length; i<maxSize; i++) {
1544
                bytes.push(0);
1545
            }    
1546
        }
1547
        return bytes;
1548
    }
1549
1550
    /**
1551
     * Turn the samples to bytes.
1552
     * @return {!Array<number>} The bytes.
1553
     * @private
1554
     */
1555
    samplesToBytes_() {
1556
        return byteData_.packArray(
1557
            this.data.samples, this.getSamplesType_());
1558
    }
1559
1560
    /**
1561
     * Turn bytes to samples and load them in the data.samples property.
1562
     * @param {!Array<number>} bytes The bytes.
1563
     * @private
1564
     */
1565
    samplesFromBytes_(bytes) {
1566
        this.data.samples = byteData_.unpackArray(
1567
            bytes, this.getSamplesType_());
1568
    }
1569
1570
    /**
1571
     * Get the data type definition for the samples.
1572
     * @return {!Object<string, number|boolean>} The type definition.
1573
     * @private
1574
     */
1575
    getSamplesType_() {
1576
        /** type {!Object<string, number|boolean>} */
1577
        let bdType = {
1578
            "be": this.container === "RIFX",
1579
            "bits": this.fmt.bitsPerSample == 4 ? 8 : this.fmt.bitsPerSample,
1580
            "float": this.fmt.audioFormat == 3 ? true : false
1581
        };
1582
        bdType["signed"] = bdType["bits"] == 8 ? false : true;
1583
        return bdType;
1584
    }
1585
1586
    /**
1587
     * Return the bytes of the "bext" chunk.
1588
     * @return {!Array<number>} The "bext" chunk bytes.
1589
     * @private
1590
     */
1591
    getBextBytes_() {
1592
        /** type {!Array<number>} */
1593
        let bytes = [];
1594
        if (this.bext.chunkId) {
1595
            bytes = bytes.concat(
1596
                byteData_.pack(this.bext.chunkId, fourCC_),
1597
                byteData_.pack(602 + this.bext.codingHistory.length, uInt32_),
1598
                this.writeString_(this.bext.description, 256),
1599
                this.writeString_(this.bext.originator, 32),
1600
                this.writeString_(this.bext.originatorReference, 32),
1601
                this.writeString_(this.bext.originationDate, 10),
1602
                this.writeString_(this.bext.originationTime, 8),
1603
                byteData_.pack(this.bext.timeReference[0], uInt32_),
1604
                byteData_.pack(this.bext.timeReference[1], uInt32_),
1605
                byteData_.pack(this.bext.version, uInt16_),
1606
                this.writeString_(this.bext.UMID, 64),
1607
                byteData_.pack(this.bext.loudnessValue, uInt16_),
1608
                byteData_.pack(this.bext.loudnessRange, uInt16_),
1609
                byteData_.pack(this.bext.maxTruePeakLevel, uInt16_),
1610
                byteData_.pack(this.bext.maxMomentaryLoudness, uInt16_),
1611
                byteData_.pack(this.bext.maxShortTermLoudness, uInt16_),
1612
                this.writeString_(this.bext.reserved, 180),
1613
                this.writeString_(
1614
                    this.bext.codingHistory, this.bext.codingHistory.length));
1615
        }
1616
        return bytes;
1617
    }
1618
1619
    /**
1620
     * Return the bytes of the "ds64" chunk.
1621
     * @return {!Array<number>} The "ds64" chunk bytes.
1622
     * @private
1623
     */
1624
    getDs64Bytes_() {
1625
        /** type {!Array<number>} */
1626
        let bytes = [];
1627
        if (this.ds64.chunkId) {
1628
            bytes = bytes.concat(
1629
                byteData_.pack(this.ds64.chunkId, fourCC_),
1630
                byteData_.pack(this.ds64.chunkSize, uInt32_), // 
1631
                byteData_.pack(this.ds64.riffSizeHigh, uInt32_),
1632
                byteData_.pack(this.ds64.riffSizeLow, uInt32_),
1633
                byteData_.pack(this.ds64.dataSizeHigh, uInt32_),
1634
                byteData_.pack(this.ds64.dataSizeLow, uInt32_),
1635
                byteData_.pack(this.ds64.originationTime, uInt32_),
1636
                byteData_.pack(this.ds64.sampleCountHigh, uInt32_),
1637
                byteData_.pack(this.ds64.sampleCountLow, uInt32_));          
1638
        }
1639
        //if (this.ds64.tableLength) {
1640
        //    ds64Bytes = ds64Bytes.concat(
1641
        //        byteData_.pack(this.ds64.tableLength, uInt32_),
1642
        //        this.ds64.table);
1643
        //}
1644
        return bytes;
1645
    }
1646
1647
    /**
1648
     * Return the bytes of the "cue " chunk.
1649
     * @return {!Array<number>} The "cue " chunk bytes.
1650
     * @private
1651
     */
1652
    getCueBytes_() {
1653
        /** type {!Array<number>} */
1654
        let bytes = [];
1655
        if (this.cue.chunkId) {
1656
            let cuePointsBytes = this.getCuePointsBytes_();
1657
            bytes = bytes.concat(
1658
                byteData_.pack(this.cue.chunkId, fourCC_),
1659
                byteData_.pack(cuePointsBytes.length + 4, uInt32_),
1660
                byteData_.pack(this.cue.dwCuePoints, uInt32_),
1661
                cuePointsBytes);
1662
        }
1663
        return bytes;
1664
    }
1665
1666
    /**
1667
     * Return the bytes of the "cue " points.
1668
     * @return {!Array<number>} The "cue " points as an array of bytes.
1669
     * @private
1670
     */
1671
    getCuePointsBytes_() {
1672
        /** type {!Array<number>} */
1673
        let points = [];
1674
        for (let i=0; i<this.cue.dwCuePoints; i++) {
1675
            points = points.concat(
1676
                byteData_.pack(this.cue.points[i]["dwName"], uInt32_),
1677
                byteData_.pack(this.cue.points[i]["dwPosition"], uInt32_),
1678
                byteData_.pack(this.cue.points[i]["fccChunk"], fourCC_),
1679
                byteData_.pack(this.cue.points[i]["dwChunkStart"], uInt32_),
1680
                byteData_.pack(this.cue.points[i]["dwBlockStart"], uInt32_),
1681
                byteData_.pack(this.cue.points[i]["dwSampleOffset"], uInt32_));
1682
        }
1683
        return points;
1684
    }
1685
1686
    /**
1687
     * Return the bytes of the "fact" chunk.
1688
     * @return {!Array<number>} The "fact" chunk bytes.
1689
     * @private
1690
     */
1691
    getFactBytes_() {
1692
        /** type {!Array<number>} */
1693
        let bytes = [];
1694
        if (this.fact.chunkId) {
1695
            bytes = bytes.concat(
1696
                byteData_.pack(this.fact.chunkId, fourCC_),
1697
                byteData_.pack(this.fact.chunkSize, uInt32_),
1698
                byteData_.pack(this.fact.dwSampleLength, uInt32_));
1699
        }
1700
        return bytes;
1701
    }
1702
1703
    /**
1704
     * Return the bytes of the "fmt " chunk.
1705
     * @return {!Array<number>} The "fmt" chunk bytes.
1706
     * @throws {Error} if no "fmt " chunk is present.
1707
     * @private
1708
     */
1709
    getFmtBytes_() {
1710
        if (this.fmt.chunkId) {
1711
            return [].concat(
1712
                byteData_.pack(this.fmt.chunkId, fourCC_),
1713
                byteData_.pack(this.fmt.chunkSize, uInt32_),
1714
                byteData_.pack(this.fmt.audioFormat, uInt16_),
1715
                byteData_.pack(this.fmt.numChannels, uInt16_),
1716
                byteData_.pack(this.fmt.sampleRate, uInt32_),
1717
                byteData_.pack(this.fmt.byteRate, uInt32_),
1718
                byteData_.pack(this.fmt.blockAlign, uInt16_),
1719
                byteData_.pack(this.fmt.bitsPerSample, uInt16_),
1720
                this.getFmtExtensionBytes_()
1721
            );
1722
        }
1723
        throw Error("Could not find the 'fmt ' chunk");
1724
    }
1725
1726
    /**
1727
     * Return the bytes of the fmt extension fields.
1728
     * @return {!Array<number>} The fmt extension bytes.
1729
     * @private
1730
     */
1731
    getFmtExtensionBytes_() {
1732
        /** type {!Array<number>} */
1733
        let extension = [];
1734
        if (this.fmt.chunkSize > 16) {
1735
            extension = extension.concat(
1736
                byteData_.pack(this.fmt.cbSize, uInt16_));
1737
        }
1738
        if (this.fmt.chunkSize > 18) {
1739
            extension = extension.concat(
1740
                byteData_.pack(this.fmt.validBitsPerSample, uInt16_));
1741
        }
1742
        if (this.fmt.chunkSize > 20) {
1743
            extension = extension.concat(
1744
                byteData_.pack(this.fmt.dwChannelMask, uInt32_));
1745
        }
1746
        if (this.fmt.chunkSize > 24) {
1747
            extension = extension.concat(
1748
                byteData_.pack(this.fmt.subformat[0], uInt32_),
1749
                byteData_.pack(this.fmt.subformat[1], uInt32_),
1750
                byteData_.pack(this.fmt.subformat[2], uInt32_),
1751
                byteData_.pack(this.fmt.subformat[3], uInt32_));
1752
        }
1753
        return extension;
1754
    }
1755
1756
    /**
1757
     * Return the bytes of the "LIST" chunk.
1758
     * @return {!Array<number>} The "LIST" chunk bytes.
1759
     * @export for tests
1760
     */
1761
    getLISTBytes_() {
1762
        /** type {!Array<number>} */
1763
        let bytes = [];
1764
        for (let i=0; i<this.LIST.length; i++) {
1765
            let subChunksBytes = this.getLISTSubChunksBytes_(
1766
                    this.LIST[i]["subChunks"], this.LIST[i]["format"]);
1767
            bytes = bytes.concat(
1768
                byteData_.pack(this.LIST[i]["chunkId"], fourCC_),
1769
                byteData_.pack(subChunksBytes.length + 4, uInt32_),
1770
                byteData_.pack(this.LIST[i]["format"], fourCC_),
1771
                subChunksBytes);
1772
        }
1773
        return bytes;
1774
    }
1775
1776
    /**
1777
     * Return the bytes of the sub chunks of a "LIST" chunk.
1778
     * @param {!Array<Object>} subChunks The "LIST" sub chunks.
1779
     * @param {string} format The format of the "LIST" chunk.
1780
     *      Currently supported values are "adtl" or "INFO".
1781
     * @return {!Array<number>} The sub chunk bytes.
1782
     * @private
1783
     */
1784
    getLISTSubChunksBytes_(subChunks, format) {
1785
        /** type {!Array<number>} */
1786
        let bytes = [];
1787
        for (let i=0; i<subChunks.length; i++) {
1788
            if (format == "INFO") {
1789
                bytes = bytes.concat(
1790
                    byteData_.pack(subChunks[i]["chunkId"], fourCC_),
1791
                    byteData_.pack(subChunks[i]["value"].length + 1, uInt32_),
1792
                    this.writeString_(
1793
                        subChunks[i]["value"], subChunks[i]["value"].length));
1794
                bytes.push(0);
1795
            } else if (format == "adtl") {
1796
                if (["labl", "note"].indexOf(subChunks[i]["chunkId"]) > -1) {
1797
                    bytes = bytes.concat(
1798
                        byteData_.pack(subChunks[i]["chunkId"], fourCC_),
1799
                        byteData_.pack(
1800
                            subChunks[i]["value"].length + 4 + 1, uInt32_),
1801
                        byteData_.pack(subChunks[i]["dwName"], uInt32_),
1802
                        this.writeString_(
1803
                            subChunks[i]["value"],
1804
                            subChunks[i]["value"].length));
1805
                    bytes.push(0);
1806
                }
1807
            } //else {
1808
            //    bytes = bytes.concat(
1809
            //        byteData_.pack(
1810
            //            subChunks[i]["chunkData"].length, uInt32_),
1811
            //        subChunks[i]["chunkData"]
1812
            //    );
1813
            //}
1814
            if (bytes.length % 2) {
1815
                bytes.push(0);
1816
            }
1817
        }
1818
        return bytes;
1819
    }
1820
1821
    /**
1822
     * Return the bytes of the "junk" chunk.
1823
     * @return {!Array<number>} The "junk" chunk bytes.
1824
     * @private
1825
     */
1826
    getJunkBytes_() {
1827
        /** type {!Array<number>} */
1828
        let bytes = [];
1829
        if (this.junk.chunkId) {
1830
            return bytes.concat(
1831
                byteData_.pack(this.junk.chunkId, fourCC_),
1832
                byteData_.pack(this.junk.chunkData.length, uInt32_),
1833
                this.junk.chunkData);
1834
        }
1835
        return bytes;
1836
    }
1837
1838
    /**
1839
     * Return "RIFF" if the container is "RF64", the current container name
1840
     * otherwise. Used to enforce "RIFF" when RF64 is not allowed.
1841
     * @return {string}
1842
     * @private
1843
     */
1844
    correctContainer_() {
1845
        return this.container == "RF64" ? "RIFF" : this.container;
1846
    }
1847
1848
    /**
1849
     * Set the string code of the bit depth based on the "fmt " chunk.
1850
     * @private
1851
     */
1852
    bitDepthFromFmt_() {
1853
        if (this.fmt.audioFormat == 3 && this.fmt.bitsPerSample == 32) {
1854
            this.bitDepth = "32f";
1855
        } else if (this.fmt.audioFormat == 6) {
1856
            this.bitDepth = "8a";
1857
        } else if (this.fmt.audioFormat == 7) {
1858
            this.bitDepth = "8m";
1859
        } else {
1860
            this.bitDepth = this.fmt.bitsPerSample.toString();
1861
        }
1862
    }
1863
1864
    /**
1865
     * Return a .wav file byte buffer with the data from the WaveFile object.
1866
     * The return value of this method can be written straight to disk.
1867
     * @return {!Uint8Array} The wav file bytes.
1868
     * @private
1869
     */
1870
    createWaveFile_() {
1871
        /** type {!Array<number>} */
1872
        let samplesBytes = this.samplesToBytes_();
1873
        /** type {!Array<number>} */
1874
        let fileBody = [].concat(
1875
            byteData_.pack(this.format, fourCC_),
1876
            this.getJunkBytes_(),
1877
            this.getDs64Bytes_(),
1878
            this.getBextBytes_(),
1879
            this.getFmtBytes_(),
1880
            this.getFactBytes_(),
1881
            byteData_.pack(this.data.chunkId, fourCC_),
1882
            byteData_.pack(samplesBytes.length, uInt32_),
1883
            samplesBytes,
1884
            this.getCueBytes_(),
1885
            this.getLISTBytes_());
1886
        // concat with the main header and return a .wav file
1887
        return new Uint8Array([].concat(
1888
            byteData_.pack(this.container, fourCC_),
1889
            byteData_.pack(fileBody.length, uInt32_),
1890
            fileBody));            
1891
    }
1892
}
1893
1894
module.exports = WaveFile;
1895