diff --git a/.claude/skills/host-objects/SKILL.md b/.claude/skills/host-objects/SKILL.md
index 28783ee56c..01cdbb658b 100644
--- a/.claude/skills/host-objects/SKILL.md
+++ b/.claude/skills/host-objects/SKILL.md
@@ -97,9 +97,18 @@ HostObjects/
├── NodeOptionsParser.h # Parses JS option objects into C++ structs
│ # Use setNumericOption (NumericOption concept) for scalar numbers
├── AudioDecoderHostObject.h/.cpp
+ ├── AudioDecodeStreamHostObject.h/.cpp # Owns a serial lane (see below)
└── AudioFileUtilsHostObject.h/.cpp
```
+**A HostObject wrapping an engine object that is not thread-safe owns a lane.** `AudioDecodeStreamHostObject` keeps an open decoder that `read`, `seek` and `close` must never touch concurrently, and whose calls must run in the order JS made them. It owns a `SerialTaskExecutor` and builds its `PromiseVendor` on it (`PromiseVendor(runtime, callInvoker, lane_)`): every promise body runs on that one worker, in call order, with no lock. A call that returns nothing to JS (`close`) is scheduled on the same lane directly, so it stays ordered with the promises. Build such a HostObject on the JS thread — inside the `PromiseResolver` when it is the result of an async open — because a lane takes a single producer. The engine logic itself lives outside `HostObjects/` (`decoding/AudioDecodeStream`), where the C++ tests can reach it.
+
+**Scheduling on a full lane blocks the JS thread.** `SerialTaskExecutor::schedule` waits when its queue (32 tasks by default) is full, and a HostObject function runs on the JS thread: a burst of unawaited `read` calls would hold it until the decoder caught up. Where JS may call without awaiting, the TypeScript wrapper forwards one operation at a time — `AudioDecodeStream.runInOrder` chains each `read`, `seek` and `close` on the one requested before it — so the lane never holds more than one operation and the burst waits in JS, in order. Keep the chain alive after a rejection (`result.then(() => undefined, () => undefined)`), or one failed read fails every later one.
+
+**A lane outlives what it served unless it is given up.** A `SerialTaskExecutor` keeps its worker thread for as long as it is referenced, and a HostObject lives until the collector reaches it: a closed decode stream kept an idle thread until then. `AudioDecodeStreamHostObject::close` schedules the close, then resets its `PromiseVendor` and its lane — the lane's deleter lets the close run and joins the worker on a thread of its own — and `read` / `seek` throw once the vendor is gone. The TypeScript wrapper rejects them itself after `close()`, so nothing reaches the native object in that state. Promise functions JS has not collected yet may still hold the vendor for a while.
+
+**A HostObject destructor runs inside the garbage collector, on a thread it does not choose: it must not wait.** Dropping the last reference to a `SerialTaskExecutor` drains its queue and joins its worker, and that last reference is not always the HostObject's — the promise executor function `PromiseVendor` hands to JS captures the executor too, until JS collects it. `AudioDecodeStreamHostObject` therefore builds its lane with a deleter that destroys it on a detached thread (`makeLane`), and its destructor hands the stream to a detached thread as well, because closing a decoder tears a codec down. An open decoder is also invisible to the collector unless it is reported: the stream's JS object carries a nominal `setExternalMemoryPressure`, plus the encoded bytes of an in-memory source.
+
---
## Macro System
diff --git a/.claude/skills/utilities/SKILL.md b/.claude/skills/utilities/SKILL.md
index 57fbb27b0d..4f9895313f 100644
--- a/.claude/skills/utilities/SKILL.md
+++ b/.claude/skills/utilities/SKILL.md
@@ -237,7 +237,7 @@ RAII mutex wrapper that can hold `nullptr` (no-op). Supports `Locker::tryLock(mu
### Other `core/utils/` classes
-- **`AudioDecoder.h`** — decodes audio files to `AudioBuffer` (FFmpeg, conditional). Read the header.
+- Decoding lives in `common/cpp/audioapi/decoding/`, not here. `AudioDecoding.h` decodes a whole source to an `AudioBuffer` (`decodeWithFilePath`, `decodeWithMemoryBlock`) and exposes the loop both paths share, `audiodecoding::decodeFrames(decoder, maxFrames)`: it reads up to `maxFrames` from the decoder's current position and returns `nullptr` once nothing is left. `AudioDecodeStream.h` keeps a decoder open to pull bounded chunks (`read`, `seek`, `close`); it is not thread-safe, its owner serializes the calls. Reuse `decodeFrames` instead of writing another `readPcmFrames` loop: successive calls are sample-exact with one whole decode, which `AudioDecodeStreamTest` checks for several chunk sizes, with and without resampling.
- **`AudioFileWriter.h`** — writes PCM to audio files. Read the header.
- **`AudioRecorderCallback.h`** — callback adapter for the platform recorder. Internal.
- **`worklets/WorkletsRunner.h`** — manages JS worklet execution on the audio thread. Internal.
diff --git a/packages/audiodocs/docs/utils/decoding.mdx b/packages/audiodocs/docs/utils/decoding.mdx
index c188ffb486..b5cbccbf25 100644
--- a/packages/audiodocs/docs/utils/decoding.mdx
+++ b/packages/audiodocs/docs/utils/decoding.mdx
@@ -2,13 +2,13 @@
sidebar_position: 1
---
-import { Optional } from '@site/src/components/Badges';
+import { Optional, ReadOnly } from '@site/src/components/Badges';
import DecodeAudioDataDocs from '@site/src/components/DecodeAudioDataDocs/DecodeAudioDataDocs';
# Decoding
You can decode audio data independently, without creating an [`AudioContext`](../core/audio-context.mdx), using the exported functions [`decodeAudioData`](./decoding.mdx#decodeaudiodata),
-[`decodePCMInBase64`](./decoding.mdx#decodepcminbase64), and [`getAudioDuration`](./decoding.mdx#getaudioduration).
+[`decodePCMInBase64`](./decoding.mdx#decodepcminbase64), [`getAudioDuration`](./decoding.mdx#getaudioduration), and [`openAudioDecodeStream`](./decoding.mdx#openaudiodecodestream).
If you already have an audio context, you can decode audio data directly using its [`decodeAudioData`](../core/base-audio-context.mdx#decodeaudiodata) function;
the decoded audio will then be automatically resampled to match the context's `sampleRate`.
@@ -28,6 +28,11 @@ Supported file formats:
- caf (ios)
:::
+:::info
+On mobile, a local file is named by its path or by a `file://` URI. A URI is percent-encoded: `file:///tmp/my%20clip.wav` opens `my clip.wav`.
+A path is used as written, so the `%20` of `/tmp/clip%20mix.wav` is part of the file name.
+:::
+
## Methods
### `decodeAudioData`
@@ -119,3 +124,137 @@ const data = ... // data encoded in base64 string
const buffer = await decodeAudioData(data, 4800, 2, true);
```
+
+### `openAudioDecodeStream`
+
+Opens an audio source to decode it a few frames at a time, instead of as one [`AudioBuffer`](../sources/audio-buffer.mdx).
+Use it for work that goes through the audio once — waveforms, spectra, loudness, beat detection, speech recognition.
+
+:::tip
+[`decodeAudioData`](./decoding.mdx#decodeaudiodata) holds the whole source decoded: about 21 MB per minute of stereo sound at 44.1 kHz, whatever the size of the file.
+A stream only holds the chunk being read.
+:::
+
+| Parameter | Type | Description |
+| :---: | :---: | :---- |
+| `input` | `ArrayBuffer` \| `string` \| `number` | The inputs [`decodeAudioData`](./decoding.mdx#decodeaudiodata) takes: encoded audio bytes, a local path or `file://` URI, a remote URL, or an asset module id. |
+| `options` | [`AudioDecodeStreamOptions`](./decoding.mdx#audiodecodestreamoptions) | Output sample rate and download options. |
+
+#### Returns `Promise`
+
+Rejects when the source cannot be opened, with the errors [`decodeAudioData`](./decoding.mdx#decodeaudiodata) rejects with,
+and with a `RangeError` when `sampleRate` is not a number between `3000` and `768000`.
+
+:::info
+A remote source is downloaded before it is opened, and encoded bytes are kept in memory while the stream is open.
+That is the size of the file, not of its decoded audio. To keep memory lowest, open a local file.
+:::
+
+#### `AudioDecodeStreamOptions`
+
+| Parameter | Type | Default | Description |
+| :---: | :---: | :---: | :---- |
+| `sampleRate` | `number` | source rate | Sample rate of the decoded audio, in Hz. On web the default is `44100`. |
+| `fetchOptions` | [`RequestInit`](https://github.com/facebook/react-native/blob/ac06f3bdc76a9fd7c65ab899e82bff5cad9b94b6/packages/react-native/src/types/globals.d.ts#L265) | — | Fetch options for a remote `input` (for example, auth headers). |
+
+
+Example computing a waveform without holding the decoded file
+```tsx
+import { openAudioDecodeStream } from 'react-native-audio-api';
+
+const stream = await openAudioDecodeStream('file:///tmp/set.mp3', {
+ sampleRate: 22050,
+});
+
+const peaks: number[] = [];
+try {
+ let chunk = await stream.read(4096);
+ while (chunk !== null) {
+ const samples = chunk.getChannelData(0);
+ let peak = 0;
+ for (let i = 0; i < samples.length; i += 1) {
+ peak = Math.max(peak, Math.abs(samples[i]));
+ }
+ peaks.push(peak);
+ chunk = await stream.read(4096);
+ }
+} finally {
+ stream.close();
+}
+```
+
+
+## `AudioDecodeStream`
+
+Returned by [`openAudioDecodeStream`](./decoding.mdx#openaudiodecodestream).
+
+### Properties
+
+| Name | Type | Description |
+| :----: | :----: | :-------- |
+| `sampleRate` | `number` | Sample rate of the decoded audio, in Hz: the requested one, or the default of [`AudioDecodeStreamOptions`](./decoding.mdx#audiodecodestreamoptions). |
+| `numberOfChannels` | `number` | Number of channels of the decoded audio. |
+| `duration` | `number` | Duration reported by the source, in seconds; `0` when it is unknown. |
+
+### Methods
+
+#### `read`
+
+Decodes the next frames of the source. Each read continues where the previous one stopped, and reads run one at a time, in the order they were requested.
+Reads requested together wait for one another without blocking the JS thread.
+
+The chunks of a stream, put end to end, hold exactly the samples [`decodeAudioData`](./decoding.mdx#decodeaudiodata) returns for the same source and sample rate, whatever the chunk size.
+
+| Parameter | Type | Description |
+| :---: | :---: | :---- |
+| `frameCount` | `number` | Number of frames to decode. A positive integer. A few thousand frames is a good chunk; a value larger than what is left returns what is left. |
+
+##### Returns `Promise`
+
+An [`AudioBuffer`](../sources/audio-buffer.mdx) of `frameCount` frames, shorter only when the source ends inside it, and `null` once the source has ended.
+
+A source the decoder fails on midway also ends with `null`, as [`decodeAudioData`](./decoding.mdx#decodeaudiodata) returns what was decoded before the failure.
+A count of frames read well below `duration * sampleRate` hints at a truncated source. It is only a hint:
+`duration` is `0` when the source does not report one, and the duration of a container is an estimate.
+
+##### Errors
+
+| Error type | Description |
+| :---: | :---- |
+| `RangeError` | `frameCount` is not a positive integer. |
+
+#### `seek`
+
+Moves the read position.
+
+| Parameter | Type | Description |
+| :---: | :---: | :---- |
+| `seconds` | `number` | Position to read from, in seconds. |
+
+##### Returns `Promise`
+
+##### Errors
+
+| Error type | Description |
+| :---: | :---- |
+| `RangeError` | `seconds` is negative or not finite. |
+
+:::caution
+The next read starts where the decoder can resume, which depends on the format and on the platform: exactly at `seconds` for PCM, and at a nearby position for compressed formats, which can be noticeably earlier or later.
+Only sequential reads are sample-exact: to read the same audio twice, prefer reading from the start again (`seek(0)`) over seeking into the middle.
+Seek within the duration of the source; what a position past its end reads is not specified.
+:::
+
+#### `close`
+
+Releases the decoder once the reads already requested have settled. Reads and seeks requested afterwards reject.
+An open stream holds a decoder and a thread of its own: close it as soon as you are done with it. A stream that is never closed is only released when it is garbage collected.
+
+##### Returns `undefined`
+
+### Remarks
+
+#### Web
+
+A browser only decodes a source as a whole. On web, `openAudioDecodeStream` decodes the source with the browser's `decodeAudioData` and the stream hands out slices of the result:
+the API is the same, the memory saving is not.
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecodeStreamHostObject.cpp b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecodeStreamHostObject.cpp
new file mode 100644
index 0000000000..9bb8483259
--- /dev/null
+++ b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecodeStreamHostObject.cpp
@@ -0,0 +1,144 @@
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace audioapi {
+
+namespace {
+
+/// @brief A lane that is destroyed on a thread of its own. Destroying a `SerialTaskExecutor`
+/// waits for the tasks still queued, and its last owner can be the garbage collector: the
+/// host object, or a promise executor function JS has not collected yet.
+std::shared_ptr makeLane() {
+ return {new SerialTaskExecutor(), [](SerialTaskExecutor *lane) {
+ std::thread([lane]() { delete lane; }).detach();
+ }};
+}
+
+} // namespace
+
+AudioDecodeStreamHostObject::AudioDecodeStreamHostObject(
+ jsi::Runtime *runtime,
+ const std::shared_ptr &callInvoker,
+ std::shared_ptr stream)
+ : stream_(std::move(stream)),
+ lane_(makeLane()),
+ promiseVendor_(std::make_shared(runtime, callInvoker, lane_)) {
+ addGetters(
+ JSI_EXPORT_PROPERTY_GETTER(AudioDecodeStreamHostObject, sampleRate),
+ JSI_EXPORT_PROPERTY_GETTER(AudioDecodeStreamHostObject, numberOfChannels),
+ JSI_EXPORT_PROPERTY_GETTER(AudioDecodeStreamHostObject, duration));
+ addFunctions(
+ JSI_EXPORT_FUNCTION(AudioDecodeStreamHostObject, read),
+ JSI_EXPORT_FUNCTION(AudioDecodeStreamHostObject, seek),
+ JSI_EXPORT_FUNCTION(AudioDecodeStreamHostObject, close));
+}
+
+AudioDecodeStreamHostObject::~AudioDecodeStreamHostObject() {
+ // Dropping the last reference to the stream closes its decoder, which can take a codec
+ // teardown: not inside the garbage collector. Reads still queued hold references of their
+ // own and release them on the lane.
+ std::thread([stream = std::move(stream_)]() mutable { stream.reset(); }).detach();
+}
+
+jsi::Object AudioDecodeStreamHostObject::createJsObject(
+ jsi::Runtime &runtime,
+ const std::shared_ptr &hostObject) {
+ auto object = jsi::Object::createFromHostObject(runtime, hostObject);
+ object.setExternalMemoryPressure(
+ runtime, OPEN_DECODER_MEMORY_PRESSURE + hostObject->stream_->encodedSizeInBytes());
+ return object;
+}
+
+namespace {
+
+PromiseResolver rejectWithMessage(std::string message) {
+ return [message = std::move(message)](jsi::Runtime &) {
+ return message;
+ };
+}
+
+} // namespace
+
+JSI_PROPERTY_GETTER_IMPL(AudioDecodeStreamHostObject, sampleRate) {
+ return {stream_->sampleRate()};
+}
+
+JSI_PROPERTY_GETTER_IMPL(AudioDecodeStreamHostObject, numberOfChannels) {
+ return {stream_->numberOfChannels()};
+}
+
+JSI_PROPERTY_GETTER_IMPL(AudioDecodeStreamHostObject, duration) {
+ return {stream_->duration()};
+}
+
+// Scheduling on the lane waits when its queue is full, and these run on the JS thread. The
+// TypeScript `AudioDecodeStream` forwards one operation at a time, so the queue never holds
+// more than that operation and a `close`.
+JSI_HOST_FUNCTION_IMPL(AudioDecodeStreamHostObject, read) {
+ if (promiseVendor_ == nullptr) {
+ throw jsi::JSError(runtime, "Cannot read from a closed decode stream");
+ }
+
+ // Zero, which the stream rejects, for anything that is not a positive frame count.
+ const double requested = args[0].getNumber();
+ const auto frameCount =
+ requested >= 1.0 ? static_cast(std::min(requested, MAX_FRAME_COUNT)) : size_t{0};
+
+ return promiseVendor_->createAsyncPromise([stream = stream_, frameCount]() -> PromiseResolver {
+ auto result = stream->read(frameCount);
+ if (result.is_err()) {
+ return rejectWithMessage(result.unwrap_err());
+ }
+
+ return [buffer = result.unwrap()](jsi::Runtime &runtime) -> jsi::Value {
+ if (buffer == nullptr) {
+ return jsi::Value::null();
+ }
+ return AudioBufferHostObject::createJsObject(runtime, buffer);
+ };
+ });
+}
+
+JSI_HOST_FUNCTION_IMPL(AudioDecodeStreamHostObject, seek) {
+ if (promiseVendor_ == nullptr) {
+ throw jsi::JSError(runtime, "Cannot seek in a closed decode stream");
+ }
+
+ const auto seconds = args[0].getNumber();
+
+ return promiseVendor_->createAsyncPromise([stream = stream_, seconds]() -> PromiseResolver {
+ auto result = stream->seek(seconds);
+ if (result.is_err()) {
+ return rejectWithMessage(result.unwrap_err());
+ }
+
+ return [](jsi::Runtime &) {
+ return jsi::Value::undefined();
+ };
+ });
+}
+
+JSI_HOST_FUNCTION_IMPL(AudioDecodeStreamHostObject, close) {
+ if (lane_ == nullptr) {
+ return jsi::Value::undefined();
+ }
+
+ lane_->schedule([stream = stream_]() { stream->close(); });
+ // Nothing runs on the lane after a close, so it is let go now rather than when the
+ // collector reaches this object: a closed stream does not keep a worker thread. Its deleter
+ // lets the close run, then joins the worker on a thread of its own.
+ promiseVendor_.reset();
+ lane_.reset();
+ return jsi::Value::undefined();
+}
+
+} // namespace audioapi
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecodeStreamHostObject.h b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecodeStreamHostObject.h
new file mode 100644
index 0000000000..88a8dd4f0f
--- /dev/null
+++ b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecodeStreamHostObject.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+namespace audioapi {
+using namespace facebook;
+
+/// @brief JS handle on an open `AudioDecodeStream`.
+/// @note `read`, `seek` and `close` run on a lane owned by this object, in the order JS called
+/// them: the stream is never touched by two threads at once, and a `close` waits for the reads
+/// requested before it. `close` gives the lane up: `read` and `seek` throw afterwards.
+class AudioDecodeStreamHostObject : public HostObject {
+ public:
+ explicit AudioDecodeStreamHostObject(
+ jsi::Runtime *runtime,
+ const std::shared_ptr &callInvoker,
+ std::shared_ptr stream);
+ /// @note Runs inside the garbage collector, so it waits for nothing: the lane and the
+ /// decoder are released on threads of their own.
+ ~AudioDecodeStreamHostObject() override;
+ DELETE_COPY_AND_MOVE(AudioDecodeStreamHostObject);
+
+ /// The JS object for @p hostObject, reporting what the open stream holds as external memory
+ /// pressure, so a stream left open weighs on the collector.
+ static jsi::Object createJsObject(
+ jsi::Runtime &runtime,
+ const std::shared_ptr &hostObject);
+
+ JSI_PROPERTY_GETTER_DECL(sampleRate);
+ JSI_PROPERTY_GETTER_DECL(numberOfChannels);
+ JSI_PROPERTY_GETTER_DECL(duration);
+
+ JSI_HOST_FUNCTION_DECL(read);
+ JSI_HOST_FUNCTION_DECL(seek);
+ JSI_HOST_FUNCTION_DECL(close);
+
+ private:
+ /// An open decoder holds a codec, a file descriptor and a thread, which no byte count
+ /// reflects: a nominal amount stands for them.
+ static constexpr size_t OPEN_DECODER_MEMORY_PRESSURE = 1024 * 1024;
+ /// Frame counts above this are requests for "everything left". Clamping them keeps the
+ /// conversion from a JS number defined on every ABI.
+ static constexpr double MAX_FRAME_COUNT = 2147483647.0;
+
+ std::shared_ptr stream_;
+ std::shared_ptr lane_;
+ std::shared_ptr promiseVendor_;
+};
+} // namespace audioapi
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.cpp b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.cpp
index 56768d91af..9878b82398 100644
--- a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.cpp
+++ b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.cpp
@@ -1,5 +1,7 @@
#include
+#include
#include
+#include
#include
#include
@@ -12,12 +14,15 @@
namespace audioapi {
AudioDecoderHostObject::AudioDecoderHostObject(
jsi::Runtime *runtime,
- const std::shared_ptr &callInvoker) {
+ const std::shared_ptr &callInvoker)
+ : callInvoker_(callInvoker) {
promiseVendor_ = std::make_shared(runtime, callInvoker);
addFunctions(
JSI_EXPORT_FUNCTION(AudioDecoderHostObject, decodeWithPCMInBase64),
JSI_EXPORT_FUNCTION(AudioDecoderHostObject, decodeWithFilePath),
- JSI_EXPORT_FUNCTION(AudioDecoderHostObject, decodeWithMemoryBlock));
+ JSI_EXPORT_FUNCTION(AudioDecoderHostObject, decodeWithMemoryBlock),
+ JSI_EXPORT_FUNCTION(AudioDecoderHostObject, openStreamWithFilePath),
+ JSI_EXPORT_FUNCTION(AudioDecoderHostObject, openStreamWithMemoryBlock));
}
namespace {
@@ -34,6 +39,22 @@ PromiseResolver resolveWithAudioBuffer(std::shared_ptr buffer) {
};
}
+// The host object is built on the JS thread, where the resolver runs: its lane must be fed by
+// that thread only.
+PromiseResolver resolveWithDecodeStream(
+ audiodecoding::AudioDecodeStream::OpenResult &&openResult,
+ const std::shared_ptr &callInvoker) {
+ if (openResult.is_err()) {
+ return rejectWithMessage(openResult.unwrap_err());
+ }
+
+ std::shared_ptr stream = std::move(openResult).unwrap();
+ return [stream = std::move(stream), callInvoker](jsi::Runtime &runtime) {
+ return AudioDecodeStreamHostObject::createJsObject(
+ runtime, std::make_shared(&runtime, callInvoker, stream));
+ };
+}
+
} // namespace
JSI_HOST_FUNCTION_IMPL(AudioDecoderHostObject, decodeWithMemoryBlock) {
@@ -74,6 +95,37 @@ JSI_HOST_FUNCTION_IMPL(AudioDecoderHostObject, decodeWithFilePath) {
return promise;
}
+JSI_HOST_FUNCTION_IMPL(AudioDecoderHostObject, openStreamWithMemoryBlock) {
+ auto arrayBuffer =
+ args[0].getObject(runtime).getPropertyAsObject(runtime, "buffer").getArrayBuffer(runtime);
+ const auto *data = arrayBuffer.data(runtime);
+ const auto size = arrayBuffer.size(runtime);
+ auto sampleRate = static_cast(args[1].getNumber());
+
+ // Copied here, on the JS thread: the caller may reuse its buffer as soon as this returns.
+ // The copy is then handed over to the stream rather than copied again.
+ return promiseVendor_->createAsyncPromise(
+ [bytes = std::vector(data, data + size),
+ sampleRate,
+ callInvoker = callInvoker_]() mutable -> PromiseResolver {
+ return resolveWithDecodeStream(
+ audiodecoding::AudioDecodeStream::openWithMemoryBlock(std::move(bytes), sampleRate),
+ callInvoker);
+ });
+}
+
+JSI_HOST_FUNCTION_IMPL(AudioDecoderHostObject, openStreamWithFilePath) {
+ auto sourcePath = args[0].getString(runtime).utf8(runtime);
+ auto sampleRate = static_cast(args[1].getNumber());
+
+ return promiseVendor_->createAsyncPromise(
+ [sourcePath, sampleRate, callInvoker = callInvoker_]() -> PromiseResolver {
+ return resolveWithDecodeStream(
+ audiodecoding::AudioDecodeStream::openWithFilePath(sourcePath, sampleRate),
+ callInvoker);
+ });
+}
+
JSI_HOST_FUNCTION_IMPL(AudioDecoderHostObject, decodeWithPCMInBase64) {
auto b64 = args[0].getString(runtime).utf8(runtime);
auto inputSampleRate = static_cast(args[1].getNumber());
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.h b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.h
index 0e126b6a73..35ef9d3bf7 100644
--- a/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.h
+++ b/packages/react-native-audio-api/common/cpp/audioapi/HostObjects/utils/AudioDecoderHostObject.h
@@ -17,8 +17,11 @@ class AudioDecoderHostObject : public HostObject {
JSI_HOST_FUNCTION_DECL(decodeWithMemoryBlock);
JSI_HOST_FUNCTION_DECL(decodeWithFilePath);
JSI_HOST_FUNCTION_DECL(decodeWithPCMInBase64);
+ JSI_HOST_FUNCTION_DECL(openStreamWithMemoryBlock);
+ JSI_HOST_FUNCTION_DECL(openStreamWithFilePath);
private:
+ std::shared_ptr callInvoker_;
std::shared_ptr promiseVendor_;
};
} // namespace audioapi
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecodeStream.cpp b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecodeStream.cpp
new file mode 100644
index 0000000000..bdeabaed78
--- /dev/null
+++ b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecodeStream.cpp
@@ -0,0 +1,118 @@
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace audioapi::audiodecoding {
+
+namespace {
+
+/// The highest rate the Web Audio API lets a context run at.
+constexpr float MAX_OUTPUT_SAMPLE_RATE = 768000.0F;
+constexpr auto INVALID_SAMPLE_RATE_MESSAGE = "Cannot open a decode stream: invalid sample rate";
+
+/// Whether @p sampleRate can be handed to a decoder: `0` keeps the rate of the source.
+/// Converting a NaN, an infinity or a value out of range to `int` is undefined behavior.
+bool isOutputSampleRate(float sampleRate) {
+ return std::isfinite(sampleRate) && sampleRate >= 0.0F && sampleRate <= MAX_OUTPUT_SAMPLE_RATE;
+}
+
+} // namespace
+
+AudioDecodeStream::OpenResult AudioDecodeStream::openWithFilePath(
+ const std::string &path,
+ float sampleRate) {
+ if (!isOutputSampleRate(sampleRate)) {
+ return Err(INVALID_SAMPLE_RATE_MESSAGE);
+ }
+ return open(
+ decoding::LocalFileSource{.path = path, .sampleRate = static_cast(sampleRate)},
+ 0,
+ "Cannot decode file: unsupported or invalid audio format");
+}
+
+AudioDecodeStream::OpenResult AudioDecodeStream::openWithMemoryBlock(
+ std::vector encodedBytes,
+ float sampleRate) {
+ constexpr auto errorMessage = "Cannot decode audio data: unsupported or invalid audio format";
+ if (!isOutputSampleRate(sampleRate)) {
+ return Err(INVALID_SAMPLE_RATE_MESSAGE);
+ }
+ if (encodedBytes.empty()) {
+ return Err(errorMessage);
+ }
+ const size_t size = encodedBytes.size();
+ return open(
+ decoding::EncodedMemorySource{
+ .data = std::move(encodedBytes), .sampleRate = static_cast(sampleRate)},
+ size,
+ errorMessage);
+}
+
+AudioDecodeStream::OpenResult AudioDecodeStream::open(
+ const decoding::DecoderSource &source,
+ size_t encodedSizeInBytes,
+ const char *errorMessage) {
+ auto decoderResult = decoding::createDecoder(source);
+ if (decoderResult.is_err()) {
+ return Err(errorMessage);
+ }
+ return Ok(
+ std::unique_ptr(
+ new AudioDecodeStream(std::move(decoderResult).unwrap(), encodedSizeInBytes)));
+}
+
+AudioDecodeStream::AudioDecodeStream(decoding::DecoderPtr decoder, size_t encodedSizeInBytes)
+ : decoder_(std::move(decoder)),
+ numberOfChannels_(std::max(1, decoder_->outputChannels())),
+ sampleRate_(static_cast(decoder_->outputSampleRate())),
+ duration_(resolveDurationFromDecoder(*decoder_).unwrap_or(0.0F)),
+ encodedSizeInBytes_(encodedSizeInBytes) {
+ // A stream is read as fast as its consumer asks, like a whole-file decode, never paced by
+ // playback.
+ decoder_->setPreferThroughput(true);
+}
+
+AudioDecodeStream::~AudioDecodeStream() {
+ close();
+}
+
+AudioBufferResult AudioDecodeStream::read(size_t frameCount) {
+ if (decoder_ == nullptr) {
+ return Err("Cannot read from a closed decode stream");
+ }
+ if (frameCount == 0) {
+ return Err("Cannot read: frameCount must be positive");
+ }
+ return Ok(decodeFrames(*decoder_, frameCount));
+}
+
+AudioDecodeStream::SeekResult AudioDecodeStream::seek(double seconds) {
+ if (decoder_ == nullptr) {
+ return Err("Cannot seek in a closed decode stream");
+ }
+ if (!std::isfinite(seconds) || seconds < 0.0) {
+ return Err("Cannot seek: position must be a non-negative number of seconds");
+ }
+ auto result = decoder_->seekToTime(seconds);
+ if (result.is_err()) {
+ return Err("Cannot seek: " + result.unwrap_err());
+ }
+ return Ok(None);
+}
+
+void AudioDecodeStream::close() {
+ if (decoder_ == nullptr) {
+ return;
+ }
+ decoder_->close();
+ decoder_.reset();
+}
+
+} // namespace audioapi::audiodecoding
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecodeStream.h b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecodeStream.h
new file mode 100644
index 0000000000..9173944b76
--- /dev/null
+++ b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecodeStream.h
@@ -0,0 +1,78 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+namespace audioapi::audiodecoding {
+
+/// @brief A decoder kept open so its PCM can be pulled a bounded number of frames at a time,
+/// instead of decoding the whole source into one buffer. Memory then follows the size of a
+/// read, not the duration of the source.
+/// @note Not thread-safe. `read`, `seek` and `close` must never run concurrently; the owner
+/// serializes them. The format getters return values fixed at open and are safe from any thread.
+class AudioDecodeStream {
+ public:
+ using OpenResult = Result, std::string>;
+ using SeekResult = Result;
+
+ /// @param sampleRate Output sample rate; 0 keeps the rate of the source.
+ [[nodiscard]] static OpenResult openWithFilePath(const std::string &path, float sampleRate);
+ /// @note Takes ownership of @p encodedBytes and keeps them for as long as the stream is open.
+ [[nodiscard]] static OpenResult openWithMemoryBlock(
+ std::vector encodedBytes,
+ float sampleRate);
+
+ ~AudioDecodeStream();
+ DELETE_COPY_AND_MOVE(AudioDecodeStream);
+
+ /// @brief Decodes the next @p frameCount frames.
+ /// @return A buffer of @p frameCount frames, shorter only when the stream ends inside it;
+ /// `nullptr` once the stream has ended. An error after `close`.
+ /// @note The decoder backends report a decoding failure as an end of stream, so a source
+ /// that fails midway also ends with `nullptr`, as it does when decoded whole.
+ [[nodiscard]] AudioBufferResult read(size_t frameCount);
+
+ /// @brief Moves the read position. How close the decoder lands to @p seconds depends on the
+ /// format: compressed formats seek to a frame boundary.
+ [[nodiscard]] SeekResult seek(double seconds);
+
+ /// @brief Releases the decoder. Idempotent.
+ void close();
+
+ [[nodiscard]] int numberOfChannels() const {
+ return numberOfChannels_;
+ }
+ [[nodiscard]] float sampleRate() const {
+ return sampleRate_;
+ }
+ /// @brief Duration reported by the container, in seconds; 0 when it is unknown.
+ [[nodiscard]] float duration() const {
+ return duration_;
+ }
+ /// @brief Bytes of encoded audio the stream keeps in memory; 0 for a file.
+ [[nodiscard]] size_t encodedSizeInBytes() const {
+ return encodedSizeInBytes_;
+ }
+
+ private:
+ AudioDecodeStream(decoding::DecoderPtr decoder, size_t encodedSizeInBytes);
+
+ [[nodiscard]] static OpenResult
+ open(const decoding::DecoderSource &source, size_t encodedSizeInBytes, const char *errorMessage);
+
+ decoding::DecoderPtr decoder_;
+ const int numberOfChannels_;
+ const float sampleRate_;
+ const float duration_;
+ const size_t encodedSizeInBytes_;
+};
+
+} // namespace audioapi::audiodecoding
diff --git a/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.cpp b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.cpp
index 6565ab88f9..a9b64223d0 100644
--- a/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.cpp
+++ b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.cpp
@@ -7,6 +7,7 @@
#include
#include
#include
+#include
#include