Passed
Push — master ( da23c8...3e616d )
by Rafael S.
57s
created

index.js ➔ getChunkSize   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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