Passed
Push — master ( d02cd1...f70b7c )
by Rafael S.
01:04
created

index.js ➔ riffChunks   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
/*!
2
 * riff-chunks
3
 * Get the chunks of RIFF and RIFX files.
4
 * Copyright (c) 2017 Rafael da Silva Rocha.
5
 * https://github.com/rochars/riff-chunks
6
 *
7
 */
8
9
const byteData = require("byte-data");
10
11
/**
12
 * Get the chunks of a RIFF/RIFX file.
13
 * @param {Uint8Array|!Array<number>} buffer The file bytes.
14
 * @return {Object}
15
 */
16
function riffChunks(buffer) {
17
    let chunkId = getChunkId(buffer, 0);
18
    let bigEndian = chunkId == "RIFX";
19
    return {
20
        "chunkId": chunkId,
21
        "chunkSize": getChunkSize(buffer, 0, bigEndian),
22
        "format": byteData.fromBytes(buffer.slice(8, 12), 8, byteData.str),
23
        "subChunks": getSubChunks(buffer, bigEndian)
24
    };
25
}
26
27
/**
28
 * Get the sub chunks of a RIFF file.
29
 * @param {Uint8Array|!Array<number>} buffer the RIFF file bytes.
30
 * @param {boolean} bigEndian true if its RIFX.
31
 * @return {Object}
32
 */
33
function getSubChunks(buffer, bigEndian) {
34
    let chunks = [];
35
    let i = 12;
36
    while(i < buffer.length) {
37
        chunks.push(getSubChunk(buffer, i, bigEndian));
38
        i += 8 + chunks[chunks.length - 1].subChunkSize;
39
    }
40
    return chunks;
41
}
42
43
function getSubChunk(buffer, index, bigEndian) {
44
    let chunk = {
45
        "subChunkId": getChunkId(buffer, index),
46
        "subChunkSize": getChunkSize(buffer, index, bigEndian)
47
    };
48
    if (chunk.subChunkId == "LIST") {
49
        chunk.subChunks = getSubChunks(
50
            buffer.slice(index, index + chunk.subChunkSize), bigEndian);
51
    } else {
52
        chunk.subChunkData = buffer.slice(
53
            index + 8, index + 8 + chunk.subChunkSize);
54
    }
55
    return chunk;
56
}
57
58
/**
59
 * Return the FourCC of a chunk.
60
 * @param {Uint8Array|!Array<number>} buffer the RIFF file bytes.
61
 * @param {number} index The start index of the chunk.
62
 * @return {string}
63
 */
64
function getChunkId(buffer, index) {
65
    return byteData.fromBytes(
66
        buffer.slice(index, index + 4), 8, byteData.str);
67
}
68
69
/**
70
 * Return the size of a chunk.
71
 * @param {Uint8Array|!Array<number>} buffer the RIFF file bytes.
72
 * @param {number} index The start index of the chunk.
73
 * @return {number}
74
 */
75
function getChunkSize(buffer, index, bigEndian) {
76
    return byteData.fromBytes(
77
        buffer.slice(index + 4, index + 8),
78
        32,
79
        {'be': bigEndian, "single": true});
80
}
81
82
module.exports = riffChunks;
83