@ac-kit/format-wav 0.0.0-stage → 0.1.1

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.
Files changed (84) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +28 -0
  3. package/README.md +146 -2
  4. package/dist/decode/decode-wav-stream.d.ts +29 -0
  5. package/dist/decode/decode-wav-stream.d.ts.map +1 -0
  6. package/dist/decode/decode-wav-stream.js +70 -0
  7. package/dist/decode/decode-wav-stream.js.map +1 -0
  8. package/dist/decode/parse-wav.d.ts +58 -0
  9. package/dist/decode/parse-wav.d.ts.map +1 -0
  10. package/dist/decode/parse-wav.js +91 -0
  11. package/dist/decode/parse-wav.js.map +1 -0
  12. package/dist/decode/wav-decoder.d.ts +189 -0
  13. package/dist/decode/wav-decoder.d.ts.map +1 -0
  14. package/dist/decode/wav-decoder.js +709 -0
  15. package/dist/decode/wav-decoder.js.map +1 -0
  16. package/dist/decode/wav-warning.d.ts +46 -0
  17. package/dist/decode/wav-warning.d.ts.map +1 -0
  18. package/dist/decode/wav-warning.js +2 -0
  19. package/dist/decode/wav-warning.js.map +1 -0
  20. package/dist/encode/_sample-block.d.ts +12 -0
  21. package/dist/encode/_sample-block.d.ts.map +1 -0
  22. package/dist/encode/_sample-block.js +50 -0
  23. package/dist/encode/_sample-block.js.map +1 -0
  24. package/dist/encode/_wav-layout.d.ts +69 -0
  25. package/dist/encode/_wav-layout.d.ts.map +1 -0
  26. package/dist/encode/_wav-layout.js +272 -0
  27. package/dist/encode/_wav-layout.js.map +1 -0
  28. package/dist/encode/create-wav-writable-stream.d.ts +31 -0
  29. package/dist/encode/create-wav-writable-stream.d.ts.map +1 -0
  30. package/dist/encode/create-wav-writable-stream.js +82 -0
  31. package/dist/encode/create-wav-writable-stream.js.map +1 -0
  32. package/dist/encode/encode-wav.d.ts +21 -0
  33. package/dist/encode/encode-wav.d.ts.map +1 -0
  34. package/dist/encode/encode-wav.js +26 -0
  35. package/dist/encode/encode-wav.js.map +1 -0
  36. package/dist/encode/wav-encode-stream.d.ts +28 -0
  37. package/dist/encode/wav-encode-stream.d.ts.map +1 -0
  38. package/dist/encode/wav-encode-stream.js +46 -0
  39. package/dist/encode/wav-encode-stream.js.map +1 -0
  40. package/dist/encode/wav-encoder.d.ts +128 -0
  41. package/dist/encode/wav-encoder.d.ts.map +1 -0
  42. package/dist/encode/wav-encoder.js +125 -0
  43. package/dist/encode/wav-encoder.js.map +1 -0
  44. package/dist/errors.d.ts +39 -0
  45. package/dist/errors.d.ts.map +1 -0
  46. package/dist/errors.js +50 -0
  47. package/dist/errors.js.map +1 -0
  48. package/dist/format/_fmt-chunk.d.ts +36 -0
  49. package/dist/format/_fmt-chunk.d.ts.map +1 -0
  50. package/dist/format/_fmt-chunk.js +191 -0
  51. package/dist/format/_fmt-chunk.js.map +1 -0
  52. package/dist/format/wav-format-chunk.d.ts +34 -0
  53. package/dist/format/wav-format-chunk.d.ts.map +1 -0
  54. package/dist/format/wav-format-chunk.js +2 -0
  55. package/dist/format/wav-format-chunk.js.map +1 -0
  56. package/dist/format/wav-format.d.ts +113 -0
  57. package/dist/format/wav-format.d.ts.map +1 -0
  58. package/dist/format/wav-format.js +125 -0
  59. package/dist/format/wav-format.js.map +1 -0
  60. package/dist/format/wav-speaker.d.ts +52 -0
  61. package/dist/format/wav-speaker.d.ts.map +1 -0
  62. package/dist/format/wav-speaker.js +99 -0
  63. package/dist/format/wav-speaker.js.map +1 -0
  64. package/dist/index.d.ts +15 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +15 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/riff/_info.d.ts +24 -0
  69. package/dist/riff/_info.d.ts.map +1 -0
  70. package/dist/riff/_info.js +98 -0
  71. package/dist/riff/_info.js.map +1 -0
  72. package/dist/riff/_riff.d.ts +28 -0
  73. package/dist/riff/_riff.d.ts.map +1 -0
  74. package/dist/riff/_riff.js +63 -0
  75. package/dist/riff/_riff.js.map +1 -0
  76. package/dist/riff/wav-chunk.d.ts +27 -0
  77. package/dist/riff/wav-chunk.d.ts.map +1 -0
  78. package/dist/riff/wav-chunk.js +2 -0
  79. package/dist/riff/wav-chunk.js.map +1 -0
  80. package/dist/samples/wav-samples.d.ts +77 -0
  81. package/dist/samples/wav-samples.d.ts.map +1 -0
  82. package/dist/samples/wav-samples.js +268 -0
  83. package/dist/samples/wav-samples.js.map +1 -0
  84. package/package.json +66 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,77 @@
1
+ # @ac-kit/format-wav
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [5c203e7]
8
+ - Updated dependencies [5c203e7]
9
+ - Updated dependencies [5c203e7]
10
+ - Updated dependencies [5c203e7]
11
+ - @ac-kit/core@0.14.0
12
+ - @ac-kit/format-core@0.5.1
13
+ - @ac-kit/format-uuid@0.3.1
14
+
15
+ ## 0.1.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 0b4fe43: New package: WAV audio files (RIFF/WAVE), read and written.
20
+
21
+ - `createWavFormat` builds and checks a `WavFormat`: integer PCM of 8, 16, 24
22
+ or 32 bits, IEEE float of 32 or 64 bits, and `WAVE_FORMAT_EXTENSIBLE` with
23
+ valid bits, a channel mask (`WavSpeaker`, `WavChannelLayout`,
24
+ `wavChannelSpeakers`) and a sub-format (`WAV_SUBFORMAT_*`, Ambisonic
25
+ B-format included), extensible by Microsoft's rule unless told otherwise.
26
+ - `readWavSamples`, `writeWavSamples`, `readWavInterleavedSamples` and
27
+ `writeWavInterleavedSamples` convert between sample bytes and caller-owned
28
+ `Float32Array`, `Float64Array` or `Int32Array` arrays, allocating nothing:
29
+ integers read as x / 2^(bits − 1) and written back rounded ties to even and
30
+ clipped, so a file read and written back is unchanged byte for byte.
31
+ - `parseWav` (and `tryParseWav`) reads a file in memory: the format, the raw
32
+ `fmt` fields (`WavFormatChunk`, for formats it does not convert), the
33
+ samples as a view, the `fact` frame count, `LIST`/`INFO` entries and every
34
+ other chunk. `WavDecoder` is the same reader fed arrays of any size,
35
+ handing samples over as views, whole frames at a time, and holding only
36
+ what `keepChunk` and `maxChunkByteLength` allow; `decodeWavStream` drives it
37
+ over a `ReadableStream` or an iterable, with an `AbortSignal`. `RIFF`,
38
+ `RF64` and `BW64` containers are read.
39
+ - The readers read past the defects real files carry — placeholder sizes, a
40
+ RIFF size that disagrees, a missing pad byte, truncated data, partial frames,
41
+ trailing bytes — reporting each as a `WavWarning`; `strict` refuses them.
42
+ Malformed files throw `WavFormatError` with the byte offset; sizes past a
43
+ limit, `WavLimitError`.
44
+ - `encodeWav` writes a whole file into one array. `WavEncoder` writes block by
45
+ block without I/O: with a frame count its header is final, without one
46
+ `finish()` returns the patches for the sizes. `WavEncodeStream` streams to
47
+ any destination given the frame count (more or fewer frames is a
48
+ `WavFrameCountError`); `createWavWritableStream` writes to a
49
+ `SeekableByteSink` and puts the sizes in on close. Every writer adds the
50
+ `fact` chunk and pad bytes the specification asks for, and writes `RF64`
51
+ past 4 GiB, upgrading in place through a reserved `JUNK` chunk when the
52
+ length was not known (`rf64: "auto" | "never" | "always"`).
53
+
54
+ ### Patch Changes
55
+
56
+ - Updated dependencies [0b4fe43]
57
+ - Updated dependencies [0b4fe43]
58
+ - Updated dependencies [0b4fe43]
59
+ - Updated dependencies [0b4fe43]
60
+ - Updated dependencies [0b4fe43]
61
+ - Updated dependencies [0b4fe43]
62
+ - Updated dependencies [0b4fe43]
63
+ - Updated dependencies [0b4fe43]
64
+ - Updated dependencies [0b4fe43]
65
+ - Updated dependencies [0b4fe43]
66
+ - Updated dependencies [0b4fe43]
67
+ - Updated dependencies [0b4fe43]
68
+ - Updated dependencies [0b4fe43]
69
+ - Updated dependencies [0b4fe43]
70
+ - Updated dependencies [0b4fe43]
71
+ - Updated dependencies [0b4fe43]
72
+ - Updated dependencies [0b4fe43]
73
+ - Updated dependencies [0b4fe43]
74
+ - Updated dependencies [0b4fe43]
75
+ - @ac-kit/core@0.13.0
76
+ - @ac-kit/format-core@0.5.0
77
+ - @ac-kit/format-uuid@0.3.0
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024-2026 Anthony Champagne and contributors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @ac-kit/format-wav
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ WAV audio files (RIFF/WAVE): integer PCM of 8, 16, 24 and 32 bits, IEEE
4
+ float of 32 and 64 bits, `WAVE_FORMAT_EXTENSIBLE` with its channel mask,
5
+ valid bits and sub-format, and the 64-bit `RF64` and `BW64` containers. Read
6
+ whole or streamed over chunks; written whole, streamed when the length is
7
+ known, or to a seekable sink that receives the sizes once the recording ends.
8
+
9
+ ```ts
10
+ import {
11
+ createWavFormat,
12
+ encodeWav,
13
+ parseWav,
14
+ readWavSamples,
15
+ } from "@ac-kit/format-wav";
16
+
17
+ // Write: one channel of normalised samples as 16-bit PCM.
18
+ const format = createWavFormat({
19
+ encoding: "pcm",
20
+ channelCount: 1,
21
+ sampleRate: 48_000,
22
+ bitsPerSample: 16,
23
+ });
24
+ const bytes = encodeWav({ format, samples: [samples] });
25
+
26
+ // Read: the format, then the samples, into arrays you own.
27
+ const file = parseWav(bytes);
28
+ const channels = Array.from(
29
+ { length: file.format!.channelCount },
30
+ () => new Float32Array(file.frameCount),
31
+ );
32
+ readWavSamples(file.format!, file.data, channels);
33
+ ```
34
+
35
+ Portable: it reads no platform global beyond `TextDecoder`, `DataView` and Web
36
+ Streams.
37
+
38
+ ## Formats
39
+
40
+ `createWavFormat` builds a `WavFormat` and checks it: `encoding` (`"pcm"` or
41
+ `"float"`), `channelCount`, `sampleRate`, `bitsPerSample` (8, 16, 24 or 32 for
42
+ PCM; 32 or 64 for float), and, for `WAVE_FORMAT_EXTENSIBLE`,
43
+ `validBitsPerSample`, `channelMask` (`WavSpeaker` bits, or a
44
+ `WavChannelLayout` such as `FIVE_POINT_ONE`) and `subFormat` (the
45
+ `WAV_SUBFORMAT_*` GUIDs, Ambisonic B-format included). It writes an extensible
46
+ chunk when Microsoft's rule asks for one — more than two channels, more than 16
47
+ bits, fewer valid bits than bits, or a mask — unless `extensible` says
48
+ otherwise. `wavChannelSpeakers(mask, count)` gives the speaker of each channel.
49
+
50
+ A decoder reports a `WavFormat` only for samples it converts; any other format
51
+ (ADPCM, A-law, MP3) is `null`, beside a `WavFormatChunk` holding every field of
52
+ the `fmt` chunk as written, and the data is still handed over, as blocks.
53
+
54
+ ## Samples
55
+
56
+ The conversions read into arrays you allocate and write from arrays you own,
57
+ allocating nothing: `readWavSamples(format, bytes, channels, frameOffset?)`
58
+ deinterleaves into one array per channel (a `null` one is skipped; an
59
+ `AudioBuffer`'s `getChannelData(n)` works), `writeWavSamples(format, channels,
60
+ bytes, { frameOffset?, frameCount? })` is the reverse, and
61
+ `readWavInterleavedSamples`/`writeWavInterleavedSamples` keep the file's
62
+ order.
63
+
64
+ An integer sample is divided by 2^(bits − 1), so the most negative is −1 and the
65
+ largest just below 1, and written back by multiplying by 2^(valid − 1),
66
+ rounding ties to even and clipping: what FFmpeg does, and the inverse of the
67
+ reading, so a file read and written back is unchanged byte for byte. An
68
+ `Int32Array` reads and writes the integers themselves, at the scale of their
69
+ valid bits. A `NaN` bound for an integer sample is a `RangeError`; a float
70
+ format stores it.
71
+
72
+ ## Reading
73
+
74
+ `parseWav(bytes)` reads a file in memory into a `WavFile`: `container`,
75
+ `format`, `formatChunk`, `frameCount`, `data` (a view of the input),
76
+ `factFrameCount`, `info` (the `LIST`/`INFO` entries, UTF-8 or Windows-1252),
77
+ `chunks` and `trailingChunks` (every other chunk, before and after the data),
78
+ and `warnings`. `tryParseWav` answers `null` where `parseWav` throws.
79
+
80
+ `WavDecoder` is the same reader fed the file in arrays of any size: `write`
81
+ returns the `WavItem`s each array completes — `format`, `fact`, `data`,
82
+ `samples` (whole frames, as views of the input), `info`, `chunk`, `warning` —
83
+ and `end` the last ones. It holds only headers, a split frame, and the chunks
84
+ `keepChunk` asks for, up to `maxChunkByteLength`. `decodeWavStream(source,
85
+ { signal })` drives it over a `ReadableStream` or any iterable of arrays.
86
+
87
+ Both read past the defects real files carry, as most readers do, and report
88
+ each as a `WavWarning`: placeholder sizes left by a writer that could not seek
89
+ back, a RIFF size that disagrees with the chunks, an odd chunk without its pad
90
+ byte (found by the next header starting a byte early), a truncated `data`
91
+ chunk, a partial frame, bytes after the RIFF chunk. `strict: true` refuses
92
+ them. Malformed structure is a `WavFormatError` carrying the byte offset; a
93
+ size past a limit, a `WavLimitError`.
94
+
95
+ ## Writing
96
+
97
+ `encodeWav({ format, samples, info?, chunks?, trailingChunks?, rf64? })` writes
98
+ a whole file into one array allocated at its final size. `samples` is a
99
+ `WavSampleBlock`: bytes already in the file's format, interleaved normalised
100
+ floats, or one float array per channel.
101
+
102
+ `WavEncoder` writes a file a block at a time and performs no I/O. With
103
+ `frameCount`, its `header` is final and the bytes can go anywhere; without, the
104
+ header holds placeholders, and `finish()` returns the `patches` that put the
105
+ sizes in place. Two writers drive it:
106
+
107
+ - `WavEncodeStream`, a `TransformStream` of blocks to bytes, for a destination
108
+ that cannot be rewound: `frameCount` is required, and writing more or fewer
109
+ frames is a `WavFrameCountError`.
110
+ - `createWavWritableStream(sink, format, { signal })`, a `WritableStream` of
111
+ blocks to a `SeekableByteSink` (`@ac-kit/format-core`: a file, a buffer),
112
+ which writes the sizes back on `close()`. A recording of unknown length:
113
+
114
+ ```ts
115
+ import { open } from "node:fs/promises";
116
+
117
+ import { createWavWritableStream } from "@ac-kit/format-wav";
118
+
119
+ const handle = await open("take.wav", "w");
120
+ await microphoneBlocks.pipeTo(
121
+ createWavWritableStream(
122
+ {
123
+ write: async (bytes) => void (await handle.write(bytes)),
124
+ writeAt: async (bytes, position) =>
125
+ void (await handle.write(bytes, 0, bytes.length, position)),
126
+ },
127
+ format,
128
+ ),
129
+ { signal },
130
+ );
131
+ await handle.close();
132
+ ```
133
+
134
+ Every writer adds a `fact` chunk for any format but plain PCM, as the RIFF
135
+ specification asks, and the pad byte after odd-sized data. Past 4 GiB a file is
136
+ `RF64`: written so from the start when `frameCount` says it will be, and
137
+ otherwise upgraded in place through a `JUNK` chunk the header reserves for the
138
+ `ds64` one (`rf64: "never"` writes neither, and stops at 4 GiB).
139
+
140
+ A file whose writer stopped before `close()` — a crash, a full disk — keeps
141
+ the placeholder sizes of its header, which the readers take for a file of
142
+ unknown length: every frame written reads back, with `riffSizeMismatch` and
143
+ `dataSizeUnknown` warnings.
144
+
145
+ See the
146
+ [generated API docs](https://anthochamp.pages.grenadine.io/node-essentials/api/format-wav/)
147
+ for the full reference.
@@ -0,0 +1,29 @@
1
+ import { type MaybeAsyncIterable } from "@ac-kit/core";
2
+ import { type WavDecoderOptions, type WavItem } from "./wav-decoder.js";
3
+ /** Options of {@link decodeWavStream}. */
4
+ export interface DecodeWavStreamOptions extends WavDecoderOptions {
5
+ /**
6
+ * Aborting it stops the decoding with its reason, cancelling a
7
+ * `ReadableStream` source or returning an iterator one, without waiting for
8
+ * the read in progress.
9
+ */
10
+ readonly signal?: AbortSignal;
11
+ }
12
+ /**
13
+ * Decodes a WAV file from a stream of byte arrays: a `ReadableStream` (a
14
+ * `fetch` body, a file stream) or any iterable or async iterable of arrays.
15
+ * Yields the {@link WavItem}s of a {@link WavDecoder} as each array completes
16
+ * them, the samples as views of the arrays, and ends with `end`. Holds only
17
+ * what the decoder holds; pulls the next array only when the consumer asks for
18
+ * the next item.
19
+ *
20
+ * @throws {WavFormatError} When the file is malformed, or, in strict mode, has
21
+ * a defect.
22
+ * @throws {WavLimitError} When a size is past a limit.
23
+ * @throws When `options.signal` aborts, its reason; the source's own error.
24
+ * Whenever the decoding stops before the end of the source — an error, an
25
+ * abort, or a consumer that stops iterating — the source is cancelled (a
26
+ * stream) or returned (an iterator).
27
+ */
28
+ export declare function decodeWavStream(source: ReadableStream<Uint8Array> | MaybeAsyncIterable<Uint8Array>, options?: DecodeWavStreamOptions): AsyncGenerator<WavItem, void, undefined>;
29
+ //# sourceMappingURL=decode-wav-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decode-wav-stream.d.ts","sourceRoot":"","sources":["../../src/decode/decode-wav-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,kBAAkB,EAGvB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACN,KAAK,iBAAiB,EAEtB,KAAK,OAAO,EACZ,MAAM,kBAAkB,CAAC;AAE1B,0CAA0C;AAC1C,MAAM,WAAW,sBAAuB,SAAQ,iBAAiB;IAChE;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B;AA0CD;;;;;;;;;;;;;;;GAeG;AACH,wBAAuB,eAAe,CACrC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GAAG,kBAAkB,CAAC,UAAU,CAAC,EACnE,OAAO,CAAC,EAAE,sBAAsB,GAC9B,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,CAwB1C"}
@@ -0,0 +1,70 @@
1
+ import { raceAbortSignal, readStreamChunks, } from "@ac-kit/core";
2
+ import { WavDecoder, } from "./wav-decoder.js";
3
+ function isReadableStream_(source) {
4
+ return typeof source.getReader === "function";
5
+ }
6
+ async function* chunksOf_(source, signal) {
7
+ const iterator = Symbol.asyncIterator in source
8
+ ? source[Symbol.asyncIterator]()
9
+ : source[Symbol.iterator]();
10
+ let isDone = false;
11
+ try {
12
+ for (;;) {
13
+ signal?.throwIfAborted();
14
+ const result = await raceAbortSignal(Promise.resolve(iterator.next()), signal);
15
+ if (result.done === true) {
16
+ isDone = true;
17
+ return;
18
+ }
19
+ yield result.value;
20
+ }
21
+ }
22
+ finally {
23
+ if (!isDone) {
24
+ // Fire and forget: a source stuck in a read must not hold up the abort.
25
+ void Promise.resolve(iterator.return?.()).catch(() => { });
26
+ }
27
+ }
28
+ }
29
+ /**
30
+ * Decodes a WAV file from a stream of byte arrays: a `ReadableStream` (a
31
+ * `fetch` body, a file stream) or any iterable or async iterable of arrays.
32
+ * Yields the {@link WavItem}s of a {@link WavDecoder} as each array completes
33
+ * them, the samples as views of the arrays, and ends with `end`. Holds only
34
+ * what the decoder holds; pulls the next array only when the consumer asks for
35
+ * the next item.
36
+ *
37
+ * @throws {WavFormatError} When the file is malformed, or, in strict mode, has
38
+ * a defect.
39
+ * @throws {WavLimitError} When a size is past a limit.
40
+ * @throws When `options.signal` aborts, its reason; the source's own error.
41
+ * Whenever the decoding stops before the end of the source — an error, an
42
+ * abort, or a consumer that stops iterating — the source is cancelled (a
43
+ * stream) or returned (an iterator).
44
+ */
45
+ export async function* decodeWavStream(source, options) {
46
+ const signal = options?.signal;
47
+ const decoder = new WavDecoder(options);
48
+ const isStream = isReadableStream_(source);
49
+ const chunks = isStream
50
+ ? readStreamChunks(source, signal)
51
+ : chunksOf_(source, signal);
52
+ let isComplete = false;
53
+ try {
54
+ signal?.throwIfAborted();
55
+ for await (const chunk of chunks) {
56
+ yield* decoder.write(chunk);
57
+ signal?.throwIfAborted();
58
+ }
59
+ isComplete = true;
60
+ yield* decoder.end();
61
+ }
62
+ finally {
63
+ // Stopped early — an error, an abort, or a consumer that stopped
64
+ // asking: the producer stops too. The iteration has released its lock.
65
+ if (!isComplete && isStream) {
66
+ void source.cancel(signal?.reason).catch(() => { });
67
+ }
68
+ }
69
+ }
70
+ //# sourceMappingURL=decode-wav-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decode-wav-stream.js","sourceRoot":"","sources":["../../src/decode/decode-wav-stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,eAAe,EACf,gBAAgB,GAChB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAEN,UAAU,GAEV,MAAM,kBAAkB,CAAC;AAY1B,SAAS,iBAAiB,CACzB,MAAmE;IAEnE,OAAO,OAAQ,MAAkC,CAAC,SAAS,KAAK,UAAU,CAAC;AAC5E,CAAC;AAED,KAAK,SAAS,CAAC,CAAC,SAAS,CACxB,MAAsC,EACtC,MAA+B;IAE/B,MAAM,QAAQ,GACb,MAAM,CAAC,aAAa,IAAI,MAAM;QAC7B,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE;QAChC,CAAC,CAAC,MAAM,CAAC,MAAM,CAA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,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC5B,MAAM,EAAE,cAAc,EAAE,CAAC;QAC1B,CAAC;QACD,UAAU,GAAG,IAAI,CAAC;QAClB,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;IACtB,CAAC;YAAS,CAAC;QACV,iEAAiE;QACjE,uEAAuE;QACvE,IAAI,CAAC,UAAU,IAAI,QAAQ,EAAE,CAAC;YAC7B,KAAK,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACpD,CAAC;IACF,CAAC;AACF,CAAC"}
@@ -0,0 +1,58 @@
1
+ import type { WavFormatChunk } from "../format/wav-format-chunk.js";
2
+ import type { WavFormat } from "../format/wav-format.js";
3
+ import type { WavChunk, WavInfoEntry } from "../riff/wav-chunk.js";
4
+ import { type WavContainer } from "./wav-decoder.js";
5
+ import type { WavWarning } from "./wav-warning.js";
6
+ /** A WAV file read whole by {@link parseWav}. */
7
+ export interface WavFile {
8
+ /** `RIFF`, `RF64` or `BW64`. */
9
+ readonly container: WavContainer;
10
+ /** The sample format, or `null` for one this package does not convert. */
11
+ readonly format: WavFormat | null;
12
+ /** The `fmt ` chunk's fields as written. */
13
+ readonly formatChunk: WavFormatChunk;
14
+ /** Whole frames (or blocks, for a format not converted) in {@link data}. */
15
+ readonly frameCount: number;
16
+ /**
17
+ * The samples, whole frames: a view over the input, never a copy. For
18
+ * {@link readWavSamples} and {@link readWavInterleavedSamples}.
19
+ */
20
+ readonly data: Uint8Array;
21
+ /** The `fact` chunk's frame count, or `null` without one. */
22
+ readonly factFrameCount: number | null;
23
+ /** The entries of every `LIST`/`INFO` chunk, in file order. */
24
+ readonly info: readonly WavInfoEntry[];
25
+ /**
26
+ * Every other chunk before the `data` chunk, in file order, as views over the
27
+ * input: what {@link encodeWav}'s `chunks` takes back. Excludes what the
28
+ * encoder writes itself: `fmt `, `fact`, `data`, `ds64`, `LIST`/`INFO`.
29
+ */
30
+ readonly chunks: readonly WavChunk[];
31
+ /** The same after the `data` chunk, for {@link encodeWav}'s `trailingChunks`. */
32
+ readonly trailingChunks: readonly WavChunk[];
33
+ /** The defects read past, in file order; empty in strict mode. */
34
+ readonly warnings: readonly WavWarning[];
35
+ }
36
+ /** Options of {@link parseWav}. */
37
+ export interface ParseWavOptions {
38
+ /**
39
+ * Refuse every defect a {@link WavWarning} would report, with a
40
+ * {@link WavFormatError}. Default `false`.
41
+ */
42
+ readonly strict?: boolean;
43
+ }
44
+ /**
45
+ * Reads a whole WAV file in memory: its format, its samples and every other
46
+ * chunk, as views over `bytes`, copying nothing but a kept `LIST` chunk of a
47
+ * type other than `INFO`. The same reading as {@link WavDecoder}, which this
48
+ * runs over the one array: the same defects read past and reported in
49
+ * `warnings`, the same errors. Linear in the bytes.
50
+ *
51
+ * @throws {WavFormatError} When the file is malformed, or, in strict mode, has
52
+ * a defect.
53
+ * @throws {WavLimitError} When an RF64 size is past 2^53.
54
+ */
55
+ export declare function parseWav(bytes: Uint8Array, options?: ParseWavOptions): WavFile;
56
+ /** Like {@link parseWav}, answering `null` for a file it would refuse. */
57
+ export declare function tryParseWav(bytes: Uint8Array, options?: ParseWavOptions): WavFile | null;
58
+ //# sourceMappingURL=parse-wav.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-wav.d.ts","sourceRoot":"","sources":["../../src/decode/parse-wav.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,KAAK,YAAY,EAAc,MAAM,kBAAkB,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,iDAAiD;AACjD,MAAM,WAAW,OAAO;IACvB,gCAAgC;IAChC,QAAQ,CAAC,SAAS,EAAE,YAAY,CAAC;IAEjC,0EAA0E;IAC1E,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI,CAAC;IAElC,4CAA4C;IAC5C,QAAQ,CAAC,WAAW,EAAE,cAAc,CAAC;IAErC,4EAA4E;IAC5E,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAE5B;;;OAGG;IACH,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAE1B,6DAA6D;IAC7D,QAAQ,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAEvC,+DAA+D;IAC/D,QAAQ,CAAC,IAAI,EAAE,SAAS,YAAY,EAAE,CAAC;IAEvC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,SAAS,QAAQ,EAAE,CAAC;IAErC,iFAAiF;IACjF,QAAQ,CAAC,cAAc,EAAE,SAAS,QAAQ,EAAE,CAAC;IAE7C,kEAAkE;IAClE,QAAQ,CAAC,QAAQ,EAAE,SAAS,UAAU,EAAE,CAAC;CACzC;AAED,mCAAmC;AACnC,MAAM,WAAW,eAAe;IAC/B;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;CAC1B;AAMD;;;;;;;;;;GAUG;AACH,wBAAgB,QAAQ,CACvB,KAAK,EAAE,UAAU,EACjB,OAAO,CAAC,EAAE,eAAe,GACvB,OAAO,CA8DT;AAED,0EAA0E;AAC1E,wBAAgB,WAAW,CAC1B,KAAK,EAAE,UAAU,EACjB,OAAO,CAAC,EAAE,eAAe,GACvB,OAAO,GAAG,IAAI,CAShB"}
@@ -0,0 +1,91 @@
1
+ import { concatBytes } from "@ac-kit/core";
2
+ import { WavFormatError, WavLimitError } from "../errors.js";
3
+ import { ID_FACT_ } from "../riff/_riff.js";
4
+ import { WavDecoder } from "./wav-decoder.js";
5
+ function keepAllButFact_(id) {
6
+ return id !== ID_FACT_;
7
+ }
8
+ /**
9
+ * Reads a whole WAV file in memory: its format, its samples and every other
10
+ * chunk, as views over `bytes`, copying nothing but a kept `LIST` chunk of a
11
+ * type other than `INFO`. The same reading as {@link WavDecoder}, which this
12
+ * runs over the one array: the same defects read past and reported in
13
+ * `warnings`, the same errors. Linear in the bytes.
14
+ *
15
+ * @throws {WavFormatError} When the file is malformed, or, in strict mode, has
16
+ * a defect.
17
+ * @throws {WavLimitError} When an RF64 size is past 2^53.
18
+ */
19
+ export function parseWav(bytes, options) {
20
+ const decoder = new WavDecoder({
21
+ strict: options?.strict ?? false,
22
+ keepChunk: keepAllButFact_,
23
+ maxChunkByteLength: Number.POSITIVE_INFINITY,
24
+ });
25
+ const items = [...decoder.write(bytes), ...decoder.end()];
26
+ let header = null;
27
+ let factFrameCount = null;
28
+ let frameCount = 0;
29
+ const samples = [];
30
+ const info = [];
31
+ const chunks = [];
32
+ const trailingChunks = [];
33
+ const warnings = [];
34
+ let dataSeen = false;
35
+ for (const item of items) {
36
+ switch (item.type) {
37
+ case "format":
38
+ header = item;
39
+ break;
40
+ case "fact":
41
+ factFrameCount = item.frameCount;
42
+ break;
43
+ case "data":
44
+ dataSeen = true;
45
+ break;
46
+ case "samples":
47
+ samples.push(item.bytes);
48
+ frameCount += item.frameCount;
49
+ break;
50
+ case "info":
51
+ info.push(...item.entries);
52
+ break;
53
+ case "chunk":
54
+ (dataSeen ? trailingChunks : chunks).push(item.chunk);
55
+ break;
56
+ case "warning":
57
+ warnings.push(item.warning);
58
+ break;
59
+ default:
60
+ break;
61
+ }
62
+ }
63
+ // The decoder ends with an error unless a data chunk followed a fmt one.
64
+ const { container, format, formatChunk } = header;
65
+ return {
66
+ container,
67
+ format,
68
+ formatChunk,
69
+ frameCount,
70
+ // One array in, so the samples come as at most one view of it.
71
+ data: samples.length === 1 ? samples[0] : concatBytes(samples),
72
+ factFrameCount,
73
+ info,
74
+ chunks,
75
+ trailingChunks,
76
+ warnings,
77
+ };
78
+ }
79
+ /** Like {@link parseWav}, answering `null` for a file it would refuse. */
80
+ export function tryParseWav(bytes, options) {
81
+ try {
82
+ return parseWav(bytes, options);
83
+ }
84
+ catch (error) {
85
+ if (error instanceof WavFormatError || error instanceof WavLimitError) {
86
+ return null;
87
+ }
88
+ throw error;
89
+ }
90
+ }
91
+ //# sourceMappingURL=parse-wav.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse-wav.js","sourceRoot":"","sources":["../../src/decode/parse-wav.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7D,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAqB,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAoDjE,SAAS,eAAe,CAAC,EAAU;IAClC,OAAO,EAAE,KAAK,QAAQ,CAAC;AACxB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,QAAQ,CACvB,KAAiB,EACjB,OAAyB;IAEzB,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC;QAC9B,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,KAAK;QAChC,SAAS,EAAE,eAAe;QAC1B,kBAAkB,EAAE,MAAM,CAAC,iBAAiB;KAC5C,CAAC,CAAC;IACH,MAAM,KAAK,GAAG,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAC1D,IAAI,MAAM,GAA+D,IAAI,CAAC;IAC9E,IAAI,cAAc,GAAkB,IAAI,CAAC;IACzC,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,MAAM,OAAO,GAAiB,EAAE,CAAC;IACjC,MAAM,IAAI,GAAmB,EAAE,CAAC;IAChC,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,MAAM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