@audio/caf-decode 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 audiojs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # caf-decode
2
+
3
+ Decode Core Audio Format (CAF) audio to PCM float samples.
4
+
5
+ Part of [audio-decode](https://github.com/audiojs/audio-decode).
6
+
7
+ ## Install
8
+
9
+ ```
10
+ npm i @audio/caf-decode
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```js
16
+ import decode from '@audio/caf-decode'
17
+
18
+ let { channelData, sampleRate } = await decode(cafBuffer)
19
+ ```
20
+
21
+ ### Streaming
22
+
23
+ ```js
24
+ import { decoder } from '@audio/caf-decode'
25
+
26
+ let dec = await decoder()
27
+ let result = dec.decode(chunk)
28
+ dec.free()
29
+ ```
30
+
31
+ ## API
32
+
33
+ ### `decode(src): Promise<AudioData>`
34
+
35
+ Whole-file decode. Accepts `Uint8Array` or `ArrayBuffer`.
36
+
37
+ ### `decoder(): Promise<CAFDecoder>`
38
+
39
+ Creates a decoder instance.
40
+
41
+ - **`dec.decode(data)`** — decode chunk, returns `{ channelData, sampleRate }`
42
+ - **`dec.flush()`** — flush (returns empty — CAF is stateless)
43
+ - **`dec.free()`** — release resources
44
+
45
+ ## Formats
46
+
47
+ - `lpcm` — 8, 16, 24, 32-bit signed integer (LE/BE), 32/64-bit float (LE/BE)
48
+ - `alaw` — G.711 A-law
49
+ - `ulaw` — G.711 mu-law
50
+
51
+ ## License
52
+
53
+ MIT
54
+
55
+ <a href="https://github.com/krishnized/license/">ॐ</a>
@@ -0,0 +1,16 @@
1
+ interface AudioData {
2
+ channelData: Float32Array[];
3
+ sampleRate: number;
4
+ }
5
+
6
+ interface CAFDecoder {
7
+ decode(data: Uint8Array): AudioData;
8
+ flush(): AudioData;
9
+ free(): void;
10
+ }
11
+
12
+ /** Whole-file decode of CAF audio */
13
+ export default function decode(src: ArrayBuffer | Uint8Array): Promise<AudioData>;
14
+
15
+ /** Create decoder instance */
16
+ export function decoder(): Promise<CAFDecoder>;
package/caf-decode.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * CAF (Core Audio Format) decoder
3
+ * Decodes CAF containers with lpcm, alaw, ulaw audio to Float32 PCM
4
+ *
5
+ * let { channelData, sampleRate } = await decode(cafbuf)
6
+ */
7
+
8
+ const EMPTY = Object.freeze({ channelData: [], sampleRate: 0 })
9
+
10
+ /**
11
+ * Whole-file decode
12
+ * @param {Uint8Array|ArrayBuffer} src
13
+ * @returns {Promise<{channelData: Float32Array[], sampleRate: number}>}
14
+ */
15
+ export default async function decode(src) {
16
+ let dec = await decoder()
17
+ try { return dec.decode(src) }
18
+ finally { dec.free() }
19
+ }
20
+
21
+ /**
22
+ * Create decoder instance
23
+ * @returns {Promise<{decode(chunk: Uint8Array): {channelData, sampleRate}, flush(), free()}>}
24
+ */
25
+ export async function decoder() {
26
+ return new CAFDecoder()
27
+ }
28
+
29
+ class CAFDecoder {
30
+ constructor() { this.done = false }
31
+
32
+ decode(data) {
33
+ if (this.done) throw Error('Decoder already freed')
34
+ if (!data || !data.byteLength) return EMPTY
35
+
36
+ let buf = data instanceof Uint8Array ? data : new Uint8Array(data)
37
+ if (buf.length < 8) return EMPTY
38
+
39
+ return decodeCAF(buf)
40
+ }
41
+
42
+ flush() { return EMPTY }
43
+
44
+ free() { this.done = true }
45
+ }
46
+
47
+ function decodeCAF(buf) {
48
+ let dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
49
+
50
+ // File header: 'caff'(4) + version(2) + flags(2)
51
+ if (buf[0] !== 0x63 || buf[1] !== 0x61 || buf[2] !== 0x66 || buf[3] !== 0x66) throw Error('Not a CAF file')
52
+ if (dv.getUint16(4, false) !== 1) throw Error('Unsupported CAF version')
53
+
54
+ let off = 8, desc = null, dataStart = -1, dataLen = -1
55
+
56
+ // Parse chunks
57
+ while (off + 12 <= buf.length) {
58
+ let type = String.fromCharCode(buf[off], buf[off + 1], buf[off + 2], buf[off + 3])
59
+ // size is int64 BE — read high/low 32
60
+ let sizeHi = dv.getUint32(off + 4, false)
61
+ let sizeLo = dv.getUint32(off + 8, false)
62
+ let size = sizeHi * 0x100000000 + sizeLo
63
+ off += 12
64
+
65
+ if (type === 'desc' && off + 32 <= buf.length) {
66
+ desc = {
67
+ sampleRate: dv.getFloat64(off, false),
68
+ formatID: String.fromCharCode(buf[off + 8], buf[off + 9], buf[off + 10], buf[off + 11]),
69
+ formatFlags: dv.getUint32(off + 12, false),
70
+ bytesPerPacket: dv.getUint32(off + 16, false),
71
+ framesPerPacket: dv.getUint32(off + 20, false),
72
+ channelsPerFrame: dv.getUint32(off + 24, false),
73
+ bitsPerChannel: dv.getUint32(off + 28, false)
74
+ }
75
+ } else if (type === 'data') {
76
+ // skip 4-byte editCount
77
+ dataStart = off + 4
78
+ // size -1 (0xFFFFFFFFFFFFFFFF) means rest of file
79
+ dataLen = (sizeHi === 0xFFFFFFFF && sizeLo === 0xFFFFFFFF) ? buf.length - dataStart : size - 4
80
+ }
81
+
82
+ if (size < 0) break
83
+ // -1 size: skip to end
84
+ if (sizeHi === 0xFFFFFFFF && sizeLo === 0xFFFFFFFF) break
85
+ off += size
86
+ }
87
+
88
+ if (!desc) throw Error('CAF: missing desc chunk')
89
+ if (dataStart < 0) throw Error('CAF: missing data chunk')
90
+ if (!desc.channelsPerFrame) throw Error('CAF: 0 channels')
91
+ if (!desc.sampleRate) throw Error('CAF: 0 sample rate')
92
+
93
+ let audioEnd = Math.min(dataStart + dataLen, buf.length)
94
+ let audioData = buf.subarray(dataStart, audioEnd)
95
+
96
+ let { formatID, formatFlags, channelsPerFrame: ch, bitsPerChannel: bits, sampleRate } = desc
97
+
98
+ let samples
99
+ if (formatID === 'lpcm') samples = decodeLPCM(audioData, formatFlags, bits, ch)
100
+ else if (formatID === 'alaw') samples = decodeAlaw(audioData, ch)
101
+ else if (formatID === 'ulaw') samples = decodeUlaw(audioData, ch)
102
+ else throw Error('CAF: unsupported format ' + formatID)
103
+
104
+ return { channelData: samples, sampleRate }
105
+ }
106
+
107
+ function decodeLPCM(data, flags, bits, ch) {
108
+ let isFloat = flags & 1, isLE = flags & 2
109
+ let bytesPerSample = bits >> 3
110
+ let totalSamples = (data.length / bytesPerSample) | 0
111
+ let framesCount = (totalSamples / ch) | 0
112
+ if (!framesCount) return []
113
+
114
+ let dv = new DataView(data.buffer, data.byteOffset, data.byteLength)
115
+ let channelData = Array.from({ length: ch }, () => new Float32Array(framesCount))
116
+
117
+ if (isFloat && bits === 32) {
118
+ for (let i = 0, off = 0; i < framesCount; i++)
119
+ for (let c = 0; c < ch; c++, off += 4)
120
+ channelData[c][i] = dv.getFloat32(off, !!isLE)
121
+ } else if (isFloat && bits === 64) {
122
+ for (let i = 0, off = 0; i < framesCount; i++)
123
+ for (let c = 0; c < ch; c++, off += 8)
124
+ channelData[c][i] = dv.getFloat64(off, !!isLE)
125
+ } else if (bits === 32) {
126
+ let norm = 1 / 2147483648
127
+ for (let i = 0, off = 0; i < framesCount; i++)
128
+ for (let c = 0; c < ch; c++, off += 4)
129
+ channelData[c][i] = dv.getInt32(off, !!isLE) * norm
130
+ } else if (bits === 24) {
131
+ let norm = 1 / 8388608
132
+ for (let i = 0, off = 0; i < framesCount; i++)
133
+ for (let c = 0; c < ch; c++, off += 3) {
134
+ let s
135
+ if (!isLE) s = (data[off] << 16) | (data[off + 1] << 8) | data[off + 2]
136
+ else s = data[off] | (data[off + 1] << 8) | (data[off + 2] << 16)
137
+ if (s & 0x800000) s |= ~0xFFFFFF
138
+ channelData[c][i] = s * norm
139
+ }
140
+ } else if (bits === 16) {
141
+ let norm = 1 / 32768
142
+ for (let i = 0, off = 0; i < framesCount; i++)
143
+ for (let c = 0; c < ch; c++, off += 2)
144
+ channelData[c][i] = dv.getInt16(off, !!isLE) * norm
145
+ } else if (bits === 8) {
146
+ let norm = 1 / 128
147
+ for (let i = 0, off = 0; i < framesCount; i++)
148
+ for (let c = 0; c < ch; c++, off++)
149
+ channelData[c][i] = dv.getInt8(off) * norm
150
+ } else {
151
+ throw Error('CAF: unsupported LPCM bit depth ' + bits)
152
+ }
153
+
154
+ return channelData
155
+ }
156
+
157
+ function alawDecode(val) {
158
+ val ^= 0x55
159
+ let sign = val & 0x80, seg = (val >> 4) & 7, quant = val & 0x0F
160
+ let sample = seg ? ((quant << 1) | 0x21) << (seg - 1) : (quant << 1) | 1
161
+ return (sign ? -sample : sample) / 32768
162
+ }
163
+
164
+ function ulawDecode(val) {
165
+ val = ~val & 0xFF
166
+ let sign = val & 0x80, exp = (val >> 4) & 7, mant = val & 0x0F
167
+ let sample = ((mant << 1) | 0x21) << exp
168
+ return (sign ? -(sample - 33) : (sample - 33)) / 32768
169
+ }
170
+
171
+ function decodeAlaw(data, ch) {
172
+ let framesCount = (data.length / ch) | 0
173
+ if (!framesCount) return []
174
+ let channelData = Array.from({ length: ch }, () => new Float32Array(framesCount))
175
+ for (let i = 0, off = 0; i < framesCount; i++)
176
+ for (let c = 0; c < ch; c++, off++)
177
+ channelData[c][i] = alawDecode(data[off])
178
+ return channelData
179
+ }
180
+
181
+ function decodeUlaw(data, ch) {
182
+ let framesCount = (data.length / ch) | 0
183
+ if (!framesCount) return []
184
+ let channelData = Array.from({ length: ch }, () => new Float32Array(framesCount))
185
+ for (let i = 0, off = 0; i < framesCount; i++)
186
+ for (let c = 0; c < ch; c++, off++)
187
+ channelData[c][i] = ulawDecode(data[off])
188
+ return channelData
189
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@audio/caf-decode",
3
+ "version": "1.0.0",
4
+ "description": "Decode CAF (Core Audio Format) audio to PCM samples",
5
+ "type": "module",
6
+ "main": "caf-decode.js",
7
+ "types": "caf-decode.d.ts",
8
+ "exports": {
9
+ ".": "./caf-decode.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "caf-decode.js",
14
+ "caf-decode.d.ts",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "test": "node test.js"
19
+ },
20
+ "keywords": [
21
+ "caf",
22
+ "core-audio",
23
+ "apple",
24
+ "audio",
25
+ "decode",
26
+ "decoder",
27
+ "pcm"
28
+ ],
29
+ "publishConfig": { "access": "public" },
30
+ "license": "MIT",
31
+ "author": "audiojs",
32
+ "homepage": "https://github.com/audiojs/caf-decode#readme",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/audiojs/caf-decode.git"
36
+ },
37
+ "engines": { "node": ">=16" },
38
+ "bugs": "https://github.com/audiojs/caf-decode/issues"
39
+ }