Passed
Push — master ( 3e616d...d02cd1 )
by Rafael S.
01:00
created

index.js ➔ getSubChunks   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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