Passed
Branch wavefile-rw (6b0ae0)
by Rafael S.
02:21
created

WaveFileParser.toBuffer   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
1
/*
2
 * Copyright (c) 2017-2019 Rafael da Silva Rocha.
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining
5
 * a copy of this software and associated documentation files (the
6
 * "Software"), to deal in the Software without restriction, including
7
 * without limitation the rights to use, copy, modify, merge, publish,
8
 * distribute, sublicense, and/or sell copies of the Software, and to
9
 * permit persons to whom the Software is furnished to do so, subject to
10
 * the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be
13
 * included in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
25
/**
26
 * @fileoverview The WaveFileParser class.
27
 * @see https://github.com/rochars/wavefile
28
 */
29
30
import RIFFFile from './riff-file';
31
import writeString from './write-string';
32
import validateNumChannels from './validate-num-channels'; 
33
import validateSampleRate from './validate-sample-rate';
34
import {packTo, packStringTo, packString, pack} from 'byte-data';
35
36
/**
37
 * A class to read and write wav files.
38
 */
39
export default class WaveFileParser extends RIFFFile {
40
41
  /**
42
   * @param {?Uint8Array=} wavBuffer A wave file buffer.
43
   * @throws {Error} If container is not RIFF, RIFX or RF64.
44
   * @throws {Error} If format is not WAVE.
45
   * @throws {Error} If no 'fmt ' chunk is found.
46
   * @throws {Error} If no 'data' chunk is found.
47
   */
48
  constructor(wavBuffer=null) {
49
    super();
50
    /**
51
     * Audio formats.
52
     * Formats not listed here should be set to 65534,
53
     * the code for WAVE_FORMAT_EXTENSIBLE
54
     * @enum {number}
55
     * @protected
56
     */
57
    this.WAV_AUDIO_FORMATS = {
58
      '4': 17,
59
      '8': 1,
60
      '8a': 6,
61
      '8m': 7,
62
      '16': 1,
63
      '24': 1,
64
      '32': 1,
65
      '32f': 3,
66
      '64': 3
67
    };
68
    /**
69
     * The data of the 'fmt' chunk.
70
     * @type {!Object<string, *>}
71
     */
72
    this.fmt = {
73
      /** @type {string} */
74
      chunkId: '',
75
      /** @type {number} */
76
      chunkSize: 0,
77
      /** @type {number} */
78
      audioFormat: 0,
79
      /** @type {number} */
80
      numChannels: 0,
81
      /** @type {number} */
82
      sampleRate: 0,
83
      /** @type {number} */
84
      byteRate: 0,
85
      /** @type {number} */
86
      blockAlign: 0,
87
      /** @type {number} */
88
      bitsPerSample: 0,
89
      /** @type {number} */
90
      cbSize: 0,
91
      /** @type {number} */
92
      validBitsPerSample: 0,
93
      /** @type {number} */
94
      dwChannelMask: 0,
95
      /**
96
       * 4 32-bit values representing a 128-bit ID
97
       * @type {!Array<number>}
98
       */
99
      subformat: []
100
    };
101
    /**
102
     * The data of the 'fact' chunk.
103
     * @type {!Object<string, *>}
104
     */
105
    this.fact = {
106
      /** @type {string} */
107
      chunkId: '',
108
      /** @type {number} */
109
      chunkSize: 0,
110
      /** @type {number} */
111
      dwSampleLength: 0
112
    };
113
    /**
114
     * The data of the 'cue ' chunk.
115
     * @type {!Object<string, *>}
116
     */
117
    this.cue = {
118
      /** @type {string} */
119
      chunkId: '',
120
      /** @type {number} */
121
      chunkSize: 0,
122
      /** @type {number} */
123
      dwCuePoints: 0,
124
      /** @type {!Array<!Object>} */
125
      points: [],
126
    };
127
    /**
128
     * The data of the 'smpl' chunk.
129
     * @type {!Object<string, *>}
130
     */
131
    this.smpl = {
132
      /** @type {string} */
133
      chunkId: '',
134
      /** @type {number} */
135
      chunkSize: 0,
136
      /** @type {number} */
137
      dwManufacturer: 0,
138
      /** @type {number} */
139
      dwProduct: 0,
140
      /** @type {number} */
141
      dwSamplePeriod: 0,
142
      /** @type {number} */
143
      dwMIDIUnityNote: 0,
144
      /** @type {number} */
145
      dwMIDIPitchFraction: 0,
146
      /** @type {number} */
147
      dwSMPTEFormat: 0,
148
      /** @type {number} */
149
      dwSMPTEOffset: 0,
150
      /** @type {number} */
151
      dwNumSampleLoops: 0,
152
      /** @type {number} */
153
      dwSamplerData: 0,
154
      /** @type {!Array<!Object>} */
155
      loops: []
156
    };
157
    /**
158
     * The data of the 'bext' chunk.
159
     * @type {!Object<string, *>}
160
     */
161
    this.bext = {
162
      /** @type {string} */
163
      chunkId: '',
164
      /** @type {number} */
165
      chunkSize: 0,
166
      /** @type {string} */
167
      description: '', //256
168
      /** @type {string} */
169
      originator: '', //32
170
      /** @type {string} */
171
      originatorReference: '', //32
172
      /** @type {string} */
173
      originationDate: '', //10
174
      /** @type {string} */
175
      originationTime: '', //8
176
      /**
177
       * 2 32-bit values, timeReference high and low
178
       * @type {!Array<number>}
179
       */
180
      timeReference: [0, 0],
181
      /** @type {number} */
182
      version: 0, //WORD
183
      /** @type {string} */
184
      UMID: '', // 64 chars
185
      /** @type {number} */
186
      loudnessValue: 0, //WORD
187
      /** @type {number} */
188
      loudnessRange: 0, //WORD
189
      /** @type {number} */
190
      maxTruePeakLevel: 0, //WORD
191
      /** @type {number} */
192
      maxMomentaryLoudness: 0, //WORD
193
      /** @type {number} */
194
      maxShortTermLoudness: 0, //WORD
195
      /** @type {string} */
196
      reserved: '', //180
197
      /** @type {string} */
198
      codingHistory: '' // string, unlimited
199
    };
200
    /**
201
     * The data of the 'ds64' chunk.
202
     * Used only with RF64 files.
203
     * @type {!Object<string, *>}
204
     */
205
    this.ds64 = {
206
      /** @type {string} */
207
      chunkId: '',
208
      /** @type {number} */
209
      chunkSize: 0,
210
      /** @type {number} */
211
      riffSizeHigh: 0, // DWORD
212
      /** @type {number} */
213
      riffSizeLow: 0, // DWORD
214
      /** @type {number} */
215
      dataSizeHigh: 0, // DWORD
216
      /** @type {number} */
217
      dataSizeLow: 0, // DWORD
218
      /** @type {number} */
219
      originationTime: 0, // DWORD
220
      /** @type {number} */
221
      sampleCountHigh: 0, // DWORD
222
      /** @type {number} */
223
      sampleCountLow: 0 // DWORD
224
      /** @type {number} */
225
      //'tableLength': 0, // DWORD
226
      /** @type {!Array<number>} */
227
      //'table': []
228
    };
229
    /**
230
     * The data of the 'data' chunk.
231
     * @type {!Object<string, *>}
232
     */
233
    this.data = {
234
      /** @type {string} */
235
      chunkId: '',
236
      /** @type {number} */
237
      chunkSize: 0,
238
      /** @type {!Uint8Array} */
239
      samples: new Uint8Array(0)
240
    };
241
    /**
242
     * The data of the 'LIST' chunks.
243
     * Each item in this list look like this:
244
     *  {
245
     *      chunkId: '',
246
     *      chunkSize: 0,
247
     *      format: '',
248
     *      subChunks: []
249
     *   }
250
     * @type {!Array<!Object>}
251
     */
252
    this.LIST = [];
253
    /**
254
     * The data of the 'junk' chunk.
255
     * @type {!Object<string, *>}
256
     */
257
    this.junk = {
258
      /** @type {string} */
259
      chunkId: '',
260
      /** @type {number} */
261
      chunkSize: 0,
262
      /** @type {!Array<number>} */
263
      chunkData: []
264
    };
265
    /**
266
     * The bit depth code according to the samples.
267
     * @type {string}
268
     */
269
    this.bitDepth = '0';
270
    /**
271
     * @type {!Object}
272
     * @protected
273
     */
274
    this.dataType = {};
275
    // Load a file from the buffer if one was passed
276
    // when creating the object
277
    if (wavBuffer) {
278
      this.fromBuffer(wavBuffer);
279
    }
280
  }
281
282
  /**
283
   * Set up the WaveFileParser object from a byte buffer.
284
   * @param {!Uint8Array} wavBuffer The buffer.
285
   * @param {boolean=} samples True if the samples should be loaded.
286
   * @throws {Error} If container is not RIFF, RIFX or RF64.
287
   * @throws {Error} If format is not WAVE.
288
   * @throws {Error} If no 'fmt ' chunk is found.
289
   * @throws {Error} If no 'data' chunk is found.
290
   */
291
  fromBuffer(wavBuffer, samples=true) {
292
    this.clearHeader();
293
    this.head_ = 0;
294
    this.readRIFFChunk(wavBuffer);
295
    if (this.format != 'WAVE') {
296
      throw Error('Could not find the "WAVE" format identifier');
297
    }
298
    this.setSignature(wavBuffer);
299
    this.readDs64Chunk_(wavBuffer);
300
    this.readFmtChunk_(wavBuffer);
301
    this.readFactChunk_(wavBuffer);
302
    this.readBextChunk_(wavBuffer);
303
    this.readCueChunk_(wavBuffer);
304
    this.readSmplChunk_(wavBuffer);
305
    this.readDataChunk_(wavBuffer, samples);
306
    this.readJunkChunk_(wavBuffer);
307
    this.readLISTChunk_(wavBuffer);
308
    this.bitDepthFromFmt_();
309
    this.updateDataType();
310
  }
311
312
  /**
313
   * Return a byte buffer representig the WaveFileParser object as a .wav file.
314
   * The return value of this method can be written straight to disk.
315
   * @return {!Uint8Array} A wav file.
316
   * @throws {Error} If bit depth is invalid.
317
   * @throws {Error} If the number of channels is invalid.
318
   * @throws {Error} If the sample rate is invalid.
319
   */
320
  toBuffer() {
321
    this.validateWavHeader();
322
    return this.writeWavBuffer_();
323
  }
324
325
  /**
326
   * Reset some attributes of the object.
327
   * @protected
328
   */
329
  clearHeader() {
330
    this.fmt.cbSize = 0;
331
    this.fmt.validBitsPerSample = 0;
332
    this.fact.chunkId = '';
333
    this.ds64.chunkId = '';
334
  }
335
336
  /**
337
   * Validate the header of the file.
338
   * @throws {Error} If bit depth is invalid.
339
   * @throws {Error} If the number of channels is invalid.
340
   * @throws {Error} If the sample rate is invalid.
341
   * @protected
342
   */
343
  validateWavHeader() {
344
    this.validateBitDepth_();
345
    if (!validateNumChannels(this.fmt.numChannels, this.fmt.bitsPerSample)) {
346
      throw new Error('Invalid number of channels.');
347
    }
348
    if (!validateSampleRate(
349
        this.fmt.numChannels, this.fmt.bitsPerSample, this.fmt.sampleRate)) {
350
      throw new Error('Invalid sample rate.');
351
    }
352
  }
353
354
  /**
355
   * Update the type definition used to read and write the samples.
356
   * @protected
357
   */
358
  updateDataType() {
359
    this.dataType = {
360
      bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,
361
      fp: this.bitDepth == '32f' || this.bitDepth == '64',
362
      signed: this.bitDepth != '8',
363
      be: this.container == 'RIFX'
364
    };
365
    if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {
366
      this.dataType.bits = 8;
367
      this.dataType.signed = false;
368
    }
369
  }
370
371
  /**
372
   * Set the string code of the bit depth based on the 'fmt ' chunk.
373
   * @private
374
   */
375
  bitDepthFromFmt_() {
376
    if (this.fmt.audioFormat === 3 && this.fmt.bitsPerSample === 32) {
377
      this.bitDepth = '32f';
378
    } else if (this.fmt.audioFormat === 6) {
379
      this.bitDepth = '8a';
380
    } else if (this.fmt.audioFormat === 7) {
381
      this.bitDepth = '8m';
382
    } else {
383
      this.bitDepth = this.fmt.bitsPerSample.toString();
384
    }
385
  }
386
387
  /**
388
   * Return a .wav file byte buffer with the data from the WaveFileParser object.
389
   * The return value of this method can be written straight to disk.
390
   * @return {!Uint8Array} The wav file bytes.
391
   * @private
392
   */
393
  writeWavBuffer_() {
394
    this.uInt16_.be = this.container === 'RIFX';
395
    this.uInt32_.be = this.uInt16_.be;
396
    /** @type {!Array<!Array<number>>} */
397
    let fileBody = [
398
      this.getJunkBytes_(),
399
      this.getDs64Bytes_(),
400
      this.getBextBytes_(),
401
      this.getFmtBytes_(),
402
      this.getFactBytes_(),
403
      packString(this.data.chunkId),
404
      pack(this.data.samples.length, this.uInt32_),
405
      this.data.samples,
406
      this.getCueBytes_(),
407
      this.getSmplBytes_(),
408
      this.getLISTBytes_()
409
    ];
410
    /** @type {number} */
411
    let fileBodyLength = 0;
412
    for (let i=0; i<fileBody.length; i++) {
413
      fileBodyLength += fileBody[i].length;
414
    }
415
    /** @type {!Uint8Array} */
416
    let file = new Uint8Array(fileBodyLength + 12);
417
    /** @type {number} */
418
    let index = 0;
419
    index = packStringTo(this.container, file, index);
420
    index = packTo(fileBodyLength + 4, this.uInt32_, file, index);
421
    index = packStringTo(this.format, file, index);
422
    for (let i=0; i<fileBody.length; i++) {
423
      file.set(fileBody[i], index);
424
      index += fileBody[i].length;
425
    }
426
    return file;
427
  }
428
429
  /**
430
   * Return the bytes of the 'bext' chunk.
431
   * @private
432
   */
433
  getBextBytes_() {
434
    /** @type {!Array<number>} */
435
    let bytes = [];
436
    this.enforceBext_();
437
    if (this.bext.chunkId) {
438
      this.bext.chunkSize = 602 + this.bext.codingHistory.length;
439
      bytes = bytes.concat(
440
        packString(this.bext.chunkId),
441
        pack(602 + this.bext.codingHistory.length, this.uInt32_),
442
        writeString(this.bext.description, 256),
443
        writeString(this.bext.originator, 32),
444
        writeString(this.bext.originatorReference, 32),
445
        writeString(this.bext.originationDate, 10),
446
        writeString(this.bext.originationTime, 8),
447
        pack(this.bext.timeReference[0], this.uInt32_),
448
        pack(this.bext.timeReference[1], this.uInt32_),
449
        pack(this.bext.version, this.uInt16_),
450
        writeString(this.bext.UMID, 64),
451
        pack(this.bext.loudnessValue, this.uInt16_),
452
        pack(this.bext.loudnessRange, this.uInt16_),
453
        pack(this.bext.maxTruePeakLevel, this.uInt16_),
454
        pack(this.bext.maxMomentaryLoudness, this.uInt16_),
455
        pack(this.bext.maxShortTermLoudness, this.uInt16_),
456
        writeString(this.bext.reserved, 180),
457
        writeString(
458
          this.bext.codingHistory, this.bext.codingHistory.length));
459
    }
460
    return bytes;
461
  }
462
463
  /**
464
   * Make sure a 'bext' chunk is created if BWF data was created in a file.
465
   * @private
466
   */
467
  enforceBext_() {
468
    for (let prop in this.bext) {
469
      if (this.bext.hasOwnProperty(prop)) {
470
        if (this.bext[prop] && prop != 'timeReference') {
471
          this.bext.chunkId = 'bext';
472
          break;
473
        }
474
      }
475
    }
476
    if (this.bext.timeReference[0] || this.bext.timeReference[1]) {
477
      this.bext.chunkId = 'bext';
478
    }
479
  }
480
481
  /**
482
   * Return the bytes of the 'ds64' chunk.
483
   * @return {!Array<number>} The 'ds64' chunk bytes.
484
   * @private
485
   */
486
  getDs64Bytes_() {
487
    /** @type {!Array<number>} */
488
    let bytes = [];
489
    if (this.ds64.chunkId) {
490
      bytes = bytes.concat(
491
        packString(this.ds64.chunkId),
492
        pack(this.ds64.chunkSize, this.uInt32_),
493
        pack(this.ds64.riffSizeHigh, this.uInt32_),
494
        pack(this.ds64.riffSizeLow, this.uInt32_),
495
        pack(this.ds64.dataSizeHigh, this.uInt32_),
496
        pack(this.ds64.dataSizeLow, this.uInt32_),
497
        pack(this.ds64.originationTime, this.uInt32_),
498
        pack(this.ds64.sampleCountHigh, this.uInt32_),
499
        pack(this.ds64.sampleCountLow, this.uInt32_));
500
    }
501
    //if (this.ds64.tableLength) {
502
    //  ds64Bytes = ds64Bytes.concat(
503
    //    pack(this.ds64.tableLength, this.uInt32_),
504
    //    this.ds64.table);
505
    //}
506
    return bytes;
507
  }
508
509
  /**
510
   * Return the bytes of the 'cue ' chunk.
511
   * @return {!Array<number>} The 'cue ' chunk bytes.
512
   * @private
513
   */
514
  getCueBytes_() {
515
    /** @type {!Array<number>} */
516
    let bytes = [];
517
    if (this.cue.chunkId) {
518
      /** @type {!Array<number>} */
519
      let cuePointsBytes = this.getCuePointsBytes_();
520
      bytes = bytes.concat(
521
        packString(this.cue.chunkId),
522
        pack(cuePointsBytes.length + 4, this.uInt32_),
523
        pack(this.cue.dwCuePoints, this.uInt32_),
524
        cuePointsBytes);
525
    }
526
    return bytes;
527
  }
528
529
  /**
530
   * Return the bytes of the 'cue ' points.
531
   * @return {!Array<number>} The 'cue ' points as an array of bytes.
532
   * @private
533
   */
534
  getCuePointsBytes_() {
535
    /** @type {!Array<number>} */
536
    let points = [];
537
    for (let i=0; i<this.cue.dwCuePoints; i++) {
538
      points = points.concat(
539
        pack(this.cue.points[i].dwName, this.uInt32_),
540
        pack(this.cue.points[i].dwPosition, this.uInt32_),
541
        packString(this.cue.points[i].fccChunk),
542
        pack(this.cue.points[i].dwChunkStart, this.uInt32_),
543
        pack(this.cue.points[i].dwBlockStart, this.uInt32_),
544
        pack(this.cue.points[i].dwSampleOffset, this.uInt32_));
545
    }
546
    return points;
547
  }
548
549
  /**
550
   * Return the bytes of the 'smpl' chunk.
551
   * @return {!Array<number>} The 'smpl' chunk bytes.
552
   * @private
553
   */
554
  getSmplBytes_() {
555
    /** @type {!Array<number>} */
556
    let bytes = [];
557
    if (this.smpl.chunkId) {
558
      /** @type {!Array<number>} */
559
      let smplLoopsBytes = this.getSmplLoopsBytes_();
560
      bytes = bytes.concat(
561
        packString(this.smpl.chunkId),
562
        pack(smplLoopsBytes.length + 36, this.uInt32_),
563
        pack(this.smpl.dwManufacturer, this.uInt32_),
564
        pack(this.smpl.dwProduct, this.uInt32_),
565
        pack(this.smpl.dwSamplePeriod, this.uInt32_),
566
        pack(this.smpl.dwMIDIUnityNote, this.uInt32_),
567
        pack(this.smpl.dwMIDIPitchFraction, this.uInt32_),
568
        pack(this.smpl.dwSMPTEFormat, this.uInt32_),
569
        pack(this.smpl.dwSMPTEOffset, this.uInt32_),
570
        pack(this.smpl.dwNumSampleLoops, this.uInt32_),
571
        pack(this.smpl.dwSamplerData, this.uInt32_),
572
        smplLoopsBytes);
573
    }
574
    return bytes;
575
  }
576
577
  /**
578
   * Return the bytes of the 'smpl' loops.
579
   * @return {!Array<number>} The 'smpl' loops as an array of bytes.
580
   * @private
581
   */
582
  getSmplLoopsBytes_() {
583
    /** @type {!Array<number>} */
584
    let loops = [];
585
    for (let i=0; i<this.smpl.dwNumSampleLoops; i++) {
586
      loops = loops.concat(
587
        pack(this.smpl.loops[i].dwName, this.uInt32_),
588
        pack(this.smpl.loops[i].dwType, this.uInt32_),
589
        pack(this.smpl.loops[i].dwStart, this.uInt32_),
590
        pack(this.smpl.loops[i].dwEnd, this.uInt32_),
591
        pack(this.smpl.loops[i].dwFraction, this.uInt32_),
592
        pack(this.smpl.loops[i].dwPlayCount, this.uInt32_));
593
    }
594
    return loops;
595
  }
596
597
  /**
598
   * Return the bytes of the 'fact' chunk.
599
   * @return {!Array<number>} The 'fact' chunk bytes.
600
   * @private
601
   */
602
  getFactBytes_() {
603
    /** @type {!Array<number>} */
604
    let bytes = [];
605
    if (this.fact.chunkId) {
606
      bytes = bytes.concat(
607
        packString(this.fact.chunkId),
608
        pack(this.fact.chunkSize, this.uInt32_),
609
        pack(this.fact.dwSampleLength, this.uInt32_));
610
    }
611
    return bytes;
612
  }
613
614
  /**
615
   * Return the bytes of the 'fmt ' chunk.
616
   * @return {!Array<number>} The 'fmt' chunk bytes.
617
   * @throws {Error} if no 'fmt ' chunk is present.
618
   * @private
619
   */
620
  getFmtBytes_() {
621
    /** @type {!Array<number>} */
622
    let fmtBytes = [];
623
    if (this.fmt.chunkId) {
624
      return fmtBytes.concat(
625
        packString(this.fmt.chunkId),
626
        pack(this.fmt.chunkSize, this.uInt32_),
627
        pack(this.fmt.audioFormat, this.uInt16_),
628
        pack(this.fmt.numChannels, this.uInt16_),
629
        pack(this.fmt.sampleRate, this.uInt32_),
630
        pack(this.fmt.byteRate, this.uInt32_),
631
        pack(this.fmt.blockAlign, this.uInt16_),
632
        pack(this.fmt.bitsPerSample, this.uInt16_),
633
        this.getFmtExtensionBytes_());
634
    }
635
    throw Error('Could not find the "fmt " chunk');
636
  }
637
638
  /**
639
   * Return the bytes of the fmt extension fields.
640
   * @return {!Array<number>} The fmt extension bytes.
641
   * @private
642
   */
643
  getFmtExtensionBytes_() {
644
    /** @type {!Array<number>} */
645
    let extension = [];
646
    if (this.fmt.chunkSize > 16) {
647
      extension = extension.concat(
648
        pack(this.fmt.cbSize, this.uInt16_));
649
    }
650
    if (this.fmt.chunkSize > 18) {
651
      extension = extension.concat(
652
        pack(this.fmt.validBitsPerSample, this.uInt16_));
653
    }
654
    if (this.fmt.chunkSize > 20) {
655
      extension = extension.concat(
656
        pack(this.fmt.dwChannelMask, this.uInt32_));
657
    }
658
    if (this.fmt.chunkSize > 24) {
659
      extension = extension.concat(
660
        pack(this.fmt.subformat[0], this.uInt32_),
661
        pack(this.fmt.subformat[1], this.uInt32_),
662
        pack(this.fmt.subformat[2], this.uInt32_),
663
        pack(this.fmt.subformat[3], this.uInt32_));
664
    }
665
    return extension;
666
  }
667
668
  /**
669
   * Return the bytes of the 'LIST' chunk.
670
   * @return {!Array<number>} The 'LIST' chunk bytes.
671
   * @private
672
   */
673
  getLISTBytes_() {
674
    /** @type {!Array<number>} */
675
    let bytes = [];
676
    for (let i=0; i<this.LIST.length; i++) {
677
      /** @type {!Array<number>} */
678
      let subChunksBytes = this.getLISTSubChunksBytes_(
679
          this.LIST[i].subChunks, this.LIST[i].format);
680
      bytes = bytes.concat(
681
        packString(this.LIST[i].chunkId),
682
        pack(subChunksBytes.length + 4, this.uInt32_),
683
        packString(this.LIST[i].format),
684
        subChunksBytes);
685
    }
686
    return bytes;
687
  }
688
689
  /**
690
   * Return the bytes of the sub chunks of a 'LIST' chunk.
691
   * @param {!Array<!Object>} subChunks The 'LIST' sub chunks.
692
   * @param {string} format The format of the 'LIST' chunk.
693
   *    Currently supported values are 'adtl' or 'INFO'.
694
   * @return {!Array<number>} The sub chunk bytes.
695
   * @private
696
   */
697
  getLISTSubChunksBytes_(subChunks, format) {
698
    /** @type {!Array<number>} */
699
    let bytes = [];
700
    for (let i=0; i<subChunks.length; i++) {
701
      if (format == 'INFO') {
702
        bytes = bytes.concat(
703
          packString(subChunks[i].chunkId),
704
          pack(subChunks[i].value.length + 1, this.uInt32_),
705
          writeString(
706
            subChunks[i].value, subChunks[i].value.length));
707
        bytes.push(0);
708
      } else if (format == 'adtl') {
709
        if (['labl', 'note'].indexOf(subChunks[i].chunkId) > -1) {
710
          bytes = bytes.concat(
711
            packString(subChunks[i].chunkId),
712
            pack(
713
              subChunks[i].value.length + 4 + 1, this.uInt32_),
714
            pack(subChunks[i].dwName, this.uInt32_),
715
            writeString(
716
              subChunks[i].value,
717
              subChunks[i].value.length));
718
          bytes.push(0);
719
        } else if (subChunks[i].chunkId == 'ltxt') {
720
          bytes = bytes.concat(
721
            this.getLtxtChunkBytes_(subChunks[i]));
722
        }
723
      }
724
      if (bytes.length % 2) {
725
        bytes.push(0);
726
      }
727
    }
728
    return bytes;
729
  }
730
731
  /**
732
   * Return the bytes of a 'ltxt' chunk.
733
   * @param {!Object} ltxt the 'ltxt' chunk.
734
   * @private
735
   */
736
  getLtxtChunkBytes_(ltxt) {
737
    return [].concat(
738
      packString(ltxt.chunkId),
739
      pack(ltxt.value.length + 20, this.uInt32_),
740
      pack(ltxt.dwName, this.uInt32_),
741
      pack(ltxt.dwSampleLength, this.uInt32_),
742
      pack(ltxt.dwPurposeID, this.uInt32_),
743
      pack(ltxt.dwCountry, this.uInt16_),
744
      pack(ltxt.dwLanguage, this.uInt16_),
745
      pack(ltxt.dwDialect, this.uInt16_),
746
      pack(ltxt.dwCodePage, this.uInt16_),
747
      writeString(ltxt.value, ltxt.value.length));
748
  }
749
750
  /**
751
   * Return the bytes of the 'junk' chunk.
752
   * @private
753
   */
754
  getJunkBytes_() {
755
    /** @type {!Array<number>} */
756
    let bytes = [];
757
    if (this.junk.chunkId) {
758
      return bytes.concat(
759
        packString(this.junk.chunkId),
760
        pack(this.junk.chunkData.length, this.uInt32_),
761
        this.junk.chunkData);
762
    }
763
    return bytes;
764
  }
765
766
  /**
767
   * Read the 'fmt ' chunk of a wave file.
768
   * @param {!Uint8Array} buffer The wav file buffer.
769
   * @throws {Error} If no 'fmt ' chunk is found.
770
   * @private
771
   */
772
  readFmtChunk_(buffer) {
773
    /** @type {?Object} */
774
    let chunk = this.findChunk('fmt ');
775
    if (chunk) {
776
      this.head_ = chunk.chunkData.start;
777
      this.fmt.chunkId = chunk.chunkId;
778
      this.fmt.chunkSize = chunk.chunkSize;
779
      this.fmt.audioFormat = this.readNumber(buffer, this.uInt16_);
780
      this.fmt.numChannels = this.readNumber(buffer, this.uInt16_);
781
      this.fmt.sampleRate = this.readNumber(buffer, this.uInt32_);
782
      this.fmt.byteRate = this.readNumber(buffer, this.uInt32_);
783
      this.fmt.blockAlign = this.readNumber(buffer, this.uInt16_);
784
      this.fmt.bitsPerSample = this.readNumber(buffer, this.uInt16_);
785
      this.readFmtExtension_(buffer);
786
    } else {
787
      throw Error('Could not find the "fmt " chunk');
788
    }
789
  }
790
791
  /**
792
   * Read the 'fmt ' chunk extension.
793
   * @param {!Uint8Array} buffer The wav file buffer.
794
   * @private
795
   */
796
  readFmtExtension_(buffer) {
797
    if (this.fmt.chunkSize > 16) {
798
      this.fmt.cbSize = this.readNumber(buffer, this.uInt16_);
799
      if (this.fmt.chunkSize > 18) {
800
        this.fmt.validBitsPerSample = this.readNumber(buffer, this.uInt16_);
801
        if (this.fmt.chunkSize > 20) {
802
          this.fmt.dwChannelMask = this.readNumber(buffer, this.uInt32_);
803
          this.fmt.subformat = [
804
            this.readNumber(buffer, this.uInt32_),
805
            this.readNumber(buffer, this.uInt32_),
806
            this.readNumber(buffer, this.uInt32_),
807
            this.readNumber(buffer, this.uInt32_)];
808
        }
809
      }
810
    }
811
  }
812
813
  /**
814
   * Read the 'fact' chunk of a wav file.
815
   * @param {!Uint8Array} buffer The wav file buffer.
816
   * @private
817
   */
818
  readFactChunk_(buffer) {
819
    /** @type {?Object} */
820
    let chunk = this.findChunk('fact');
821
    if (chunk) {
822
      this.head_ = chunk.chunkData.start;
823
      this.fact.chunkId = chunk.chunkId;
824
      this.fact.chunkSize = chunk.chunkSize;
825
      this.fact.dwSampleLength = this.readNumber(buffer, this.uInt32_);
826
    }
827
  }
828
829
  /**
830
   * Read the 'cue ' chunk of a wave file.
831
   * @param {!Uint8Array} buffer The wav file buffer.
832
   * @private
833
   */
834
  readCueChunk_(buffer) {
835
    /** @type {?Object} */
836
    let chunk = this.findChunk('cue ');
837
    if (chunk) {
838
      this.head_ = chunk.chunkData.start;
839
      this.cue.chunkId = chunk.chunkId;
840
      this.cue.chunkSize = chunk.chunkSize;
841
      this.cue.dwCuePoints = this.readNumber(buffer, this.uInt32_);
842
      for (let i = 0; i < this.cue.dwCuePoints; i++) {
843
        this.cue.points.push({
844
          dwName: this.readNumber(buffer, this.uInt32_),
845
          dwPosition: this.readNumber(buffer, this.uInt32_),
846
          fccChunk: this.readString(buffer, 4),
847
          dwChunkStart: this.readNumber(buffer, this.uInt32_),
848
          dwBlockStart: this.readNumber(buffer, this.uInt32_),
849
          dwSampleOffset: this.readNumber(buffer, this.uInt32_),
850
        });
851
      }
852
    }
853
  }
854
855
  /**
856
   * Read the 'smpl' chunk of a wave file.
857
   * @param {!Uint8Array} buffer The wav file buffer.
858
   * @private
859
   */
860
  readSmplChunk_(buffer) {
861
    /** @type {?Object} */
862
    let chunk = this.findChunk('smpl');
863
    if (chunk) {
864
      this.head_ = chunk.chunkData.start;
865
      this.smpl.chunkId = chunk.chunkId;
866
      this.smpl.chunkSize = chunk.chunkSize;
867
      this.smpl.dwManufacturer = this.readNumber(buffer, this.uInt32_);
868
      this.smpl.dwProduct = this.readNumber(buffer, this.uInt32_);
869
      this.smpl.dwSamplePeriod = this.readNumber(buffer, this.uInt32_);
870
      this.smpl.dwMIDIUnityNote = this.readNumber(buffer, this.uInt32_);
871
      this.smpl.dwMIDIPitchFraction = this.readNumber(buffer, this.uInt32_);
872
      this.smpl.dwSMPTEFormat = this.readNumber(buffer, this.uInt32_);
873
      this.smpl.dwSMPTEOffset = this.readNumber(buffer, this.uInt32_);
874
      this.smpl.dwNumSampleLoops = this.readNumber(buffer, this.uInt32_);
875
      this.smpl.dwSamplerData = this.readNumber(buffer, this.uInt32_);
876
      for (let i = 0; i < this.smpl.dwNumSampleLoops; i++) {
877
        this.smpl.loops.push({
878
          dwName: this.readNumber(buffer, this.uInt32_),
879
          dwType: this.readNumber(buffer, this.uInt32_),
880
          dwStart: this.readNumber(buffer, this.uInt32_),
881
          dwEnd: this.readNumber(buffer, this.uInt32_),
882
          dwFraction: this.readNumber(buffer, this.uInt32_),
883
          dwPlayCount: this.readNumber(buffer, this.uInt32_),
884
        });
885
      }
886
    }
887
  }
888
889
  /**
890
   * Read the 'data' chunk of a wave file.
891
   * @param {!Uint8Array} buffer The wav file buffer.
892
   * @param {boolean} samples True if the samples should be loaded.
893
   * @throws {Error} If no 'data' chunk is found.
894
   * @private
895
   */
896
  readDataChunk_(buffer, samples) {
897
    /** @type {?Object} */
898
    let chunk = this.findChunk('data');
899
    if (chunk) {
900
      this.data.chunkId = 'data';
901
      this.data.chunkSize = chunk.chunkSize;
902
      if (samples) {
903
        this.data.samples = buffer.slice(
904
          chunk.chunkData.start,
905
          chunk.chunkData.end);
906
      }
907
    } else {
908
      throw Error('Could not find the "data" chunk');
909
    }
910
  }
911
912
  /**
913
   * Read the 'bext' chunk of a wav file.
914
   * @param {!Uint8Array} buffer The wav file buffer.
915
   * @private
916
   */
917
  readBextChunk_(buffer) {
918
    /** @type {?Object} */
919
    let chunk = this.findChunk('bext');
920
    if (chunk) {
921
      this.head_ = chunk.chunkData.start;
922
      this.bext.chunkId = chunk.chunkId;
923
      this.bext.chunkSize = chunk.chunkSize;
924
      this.bext.description = this.readString(buffer, 256);
925
      this.bext.originator = this.readString(buffer, 32);
926
      this.bext.originatorReference = this.readString(buffer, 32);
927
      this.bext.originationDate = this.readString(buffer, 10);
928
      this.bext.originationTime = this.readString(buffer, 8);
929
      this.bext.timeReference = [
930
        this.readNumber(buffer, this.uInt32_),
931
        this.readNumber(buffer, this.uInt32_)];
932
      this.bext.version = this.readNumber(buffer, this.uInt16_);
933
      this.bext.UMID = this.readString(buffer, 64);
934
      this.bext.loudnessValue = this.readNumber(buffer, this.uInt16_);
935
      this.bext.loudnessRange = this.readNumber(buffer, this.uInt16_);
936
      this.bext.maxTruePeakLevel = this.readNumber(buffer, this.uInt16_);
937
      this.bext.maxMomentaryLoudness = this.readNumber(buffer, this.uInt16_);
938
      this.bext.maxShortTermLoudness = this.readNumber(buffer, this.uInt16_);
939
      this.bext.reserved = this.readString(buffer, 180);
940
      this.bext.codingHistory = this.readString(
941
        buffer, this.bext.chunkSize - 602);
942
    }
943
  }
944
945
  /**
946
   * Read the 'ds64' chunk of a wave file.
947
   * @param {!Uint8Array} buffer The wav file buffer.
948
   * @throws {Error} If no 'ds64' chunk is found and the file is RF64.
949
   * @private
950
   */
951
  readDs64Chunk_(buffer) {
952
    /** @type {?Object} */
953
    let chunk = this.findChunk('ds64');
954
    if (chunk) {
955
      this.head_ = chunk.chunkData.start;
956
      this.ds64.chunkId = chunk.chunkId;
957
      this.ds64.chunkSize = chunk.chunkSize;
958
      this.ds64.riffSizeHigh = this.readNumber(buffer, this.uInt32_);
959
      this.ds64.riffSizeLow = this.readNumber(buffer, this.uInt32_);
960
      this.ds64.dataSizeHigh = this.readNumber(buffer, this.uInt32_);
961
      this.ds64.dataSizeLow = this.readNumber(buffer, this.uInt32_);
962
      this.ds64.originationTime = this.readNumber(buffer, this.uInt32_);
963
      this.ds64.sampleCountHigh = this.readNumber(buffer, this.uInt32_);
964
      this.ds64.sampleCountLow = this.readNumber(buffer, this.uInt32_);
965
      //if (wav.ds64.chunkSize > 28) {
966
      //  wav.ds64.tableLength = unpack(
967
      //    chunkData.slice(28, 32), uInt32_);
968
      //  wav.ds64.table = chunkData.slice(
969
      //     32, 32 + wav.ds64.tableLength);
970
      //}
971
    } else {
972
      if (this.container == 'RF64') {
973
        throw Error('Could not find the "ds64" chunk');
974
      }
975
    }
976
  }
977
978
  /**
979
   * Read the 'LIST' chunks of a wave file.
980
   * @param {!Uint8Array} buffer The wav file buffer.
981
   * @private
982
   */
983
  readLISTChunk_(buffer) {
984
    /** @type {?Object} */
985
    let listChunks = this.findChunk('LIST', true);
986
    if (listChunks !== null) {
987
      for (let j=0; j < listChunks.length; j++) {
988
        /** @type {!Object} */
989
        let subChunk = listChunks[j];
990
        this.LIST.push({
991
          chunkId: subChunk.chunkId,
992
          chunkSize: subChunk.chunkSize,
993
          format: subChunk.format,
994
          subChunks: []});
995
        for (let x=0; x<subChunk.subChunks.length; x++) {
996
          this.readLISTSubChunks_(subChunk.subChunks[x],
997
            subChunk.format, buffer);
998
        }
999
      }
1000
    }
1001
  }
1002
1003
  /**
1004
   * Read the sub chunks of a 'LIST' chunk.
1005
   * @param {!Object} subChunk The 'LIST' subchunks.
1006
   * @param {string} format The 'LIST' format, 'adtl' or 'INFO'.
1007
   * @param {!Uint8Array} buffer The wav file buffer.
1008
   * @private
1009
   */
1010
  readLISTSubChunks_(subChunk, format, buffer) {
1011
    if (format == 'adtl') {
1012
      if (['labl', 'note','ltxt'].indexOf(subChunk.chunkId) > -1) {
1013
        this.head_ = subChunk.chunkData.start;
1014
        /** @type {!Object<string, string|number>} */
1015
        let item = {
1016
          chunkId: subChunk.chunkId,
1017
          chunkSize: subChunk.chunkSize,
1018
          dwName: this.readNumber(buffer, this.uInt32_)
1019
        };
1020
        if (subChunk.chunkId == 'ltxt') {
1021
          item.dwSampleLength = this.readNumber(buffer, this.uInt32_);
1022
          item.dwPurposeID = this.readNumber(buffer, this.uInt32_);
1023
          item.dwCountry = this.readNumber(buffer, this.uInt16_);
1024
          item.dwLanguage = this.readNumber(buffer, this.uInt16_);
1025
          item.dwDialect = this.readNumber(buffer, this.uInt16_);
1026
          item.dwCodePage = this.readNumber(buffer, this.uInt16_);
1027
        }
1028
        item.value = this.readZSTR(buffer, this.head_);
1029
        this.LIST[this.LIST.length - 1].subChunks.push(item);
1030
      }
1031
    // RIFF INFO tags like ICRD, ISFT, ICMT
1032
    } else if(format == 'INFO') {
1033
      this.head_ = subChunk.chunkData.start;
1034
      this.LIST[this.LIST.length - 1].subChunks.push({
1035
        chunkId: subChunk.chunkId,
1036
        chunkSize: subChunk.chunkSize,
1037
        value: this.readZSTR(buffer, this.head_)
1038
      });
1039
    }
1040
  }
1041
1042
  /**
1043
   * Read the 'junk' chunk of a wave file.
1044
   * @param {!Uint8Array} buffer The wav file buffer.
1045
   * @private
1046
   */
1047
  readJunkChunk_(buffer) {
1048
    /** @type {?Object} */
1049
    let chunk = this.findChunk('junk');
1050
    if (chunk) {
1051
      this.junk = {
1052
        chunkId: chunk.chunkId,
1053
        chunkSize: chunk.chunkSize,
1054
        chunkData: [].slice.call(buffer.slice(
1055
          chunk.chunkData.start,
1056
          chunk.chunkData.end))
1057
      };
1058
    }
1059
  }
1060
1061
  /**
1062
   * Validate the bit depth.
1063
   * @return {boolean} True is the bit depth is valid.
1064
   * @throws {Error} If bit depth is invalid.
1065
   * @private
1066
   */
1067
  validateBitDepth_() {
1068
    if (!this.WAV_AUDIO_FORMATS[this.bitDepth]) {
1069
      if (parseInt(this.bitDepth, 10) > 8 &&
1070
          parseInt(this.bitDepth, 10) < 54) {
1071
        return true;
1072
      }
1073
      throw new Error('Invalid bit depth.');
1074
    }
1075
    return true;
1076
  }
1077
}
1078