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 #include #include @@ -60,45 +61,89 @@ constexpr size_t GROWTH_DENOMINATOR = 2; // allocation stays); more than that is worth an exact-size copy. constexpr size_t IN_PLACE_TRIM_SLACK_DIVISOR = 8; -size_t initialDecodeCapacity(size_t estimatedFrames, float sampleRate, size_t chunkFrames) { +// A request up to this many frames is allocated as asked: a chunked read then never +// reallocates, and at 1.4 s of 48 kHz audio it cannot be a large allocation. +constexpr size_t EAGER_REQUEST_FRAMES = 16 * decoding::AudioDecoderBackend::CHUNK_SIZE; + +// Frames to allocate before decoding. A larger request is bounded by the decoder's estimate of +// the source, so asking for far more than a short source holds (decoding a whole file asks for +// everything) allocates for the source, not for the request, and grows on demand. +size_t initialDecodeCapacity( + size_t requestedFrames, + size_t estimatedFrames, + float sampleRate, + size_t chunkFrames) { + if (requestedFrames <= EAGER_REQUEST_FRAMES) { + return requestedFrames; + } const auto maxTrustedEstimate = static_cast(std::max(1.0F, sampleRate) * MAX_TRUSTED_ESTIMATE_SECONDS); const size_t trustedEstimate = std::min(estimatedFrames, maxTrustedEstimate); - return trustedEstimate + trustedEstimate / ESTIMATE_HEADROOM_DIVISOR + chunkFrames; + return std::min( + requestedFrames, trustedEstimate + trustedEstimate / ESTIMATE_HEADROOM_DIVISOR + chunkFrames); } -size_t grownDecodeCapacity(size_t currentCapacity, size_t requiredFrames) { - return std::max(requiredFrames, currentCapacity * GROWTH_NUMERATOR / GROWTH_DENOMINATOR); +size_t grownDecodeCapacity(size_t currentCapacity, size_t requiredFrames, size_t maxFrames) { + const size_t grown = + std::max(requiredFrames, currentCapacity * GROWTH_NUMERATOR / GROWTH_DENOMINATOR); + return std::min(grown, maxFrames); } -// Decodes straight into the returned planar buffer, sized up front from the -// decoder's frame estimate, so peak memory stays near one copy of the PCM. AudioBufferResult decodeAll(decoding::AudioDecoderBackend &decoder) { - constexpr size_t chunkFrames = decoding::AudioDecoderBackend::CHUNK_SIZE; decoder.setPreferThroughput(true); + auto audioBuffer = decodeFrames(decoder, std::numeric_limits::max()); + if (audioBuffer == nullptr) { + return Err("Failed to decode any frames"); + } + return Ok(std::move(audioBuffer)); +} + +AudioDurationResult probeDurationFromSource( + const decoding::DecoderSource &source, + const char *errorMessage) { + return withDecoderFromSource( + source, errorMessage, resolveDurationFromDecoder); +} + +AudioBufferResult decodeFromSource( + const decoding::DecoderSource &source, + const char *errorMessage) { + return withDecoderFromSource(source, errorMessage, decodeAll); +} + +} // namespace + +// Decodes straight into the returned planar buffer, sized up front, so peak memory stays near +// one copy of the PCM. +std::shared_ptr decodeFrames( + decoding::AudioDecoderBackend &decoder, + size_t maxFrames) { + constexpr size_t chunkFrames = decoding::AudioDecoderBackend::CHUNK_SIZE; const int channels = std::max(1, decoder.outputChannels()); const auto outputSampleRate = static_cast(decoder.outputSampleRate()); - const size_t initialCapacity = - initialDecodeCapacity(decoder.getTotalPcmFrameCount(), outputSampleRate, chunkFrames); + const size_t initialCapacity = initialDecodeCapacity( + maxFrames, decoder.getTotalPcmFrameCount(), outputSampleRate, chunkFrames); auto audioBuffer = std::make_shared(initialCapacity, channels, outputSampleRate); std::vector chunk(chunkFrames * static_cast(channels)); size_t framesDecoded = 0; - while (true) { - const size_t framesRead = decoder.readPcmFrames(chunk.data(), chunkFrames); + while (framesDecoded < maxFrames) { + const size_t framesWanted = std::min(chunkFrames, maxFrames - framesDecoded); + const size_t framesRead = decoder.readPcmFrames(chunk.data(), framesWanted); if (framesRead == 0) { break; } if (framesDecoded + framesRead > audioBuffer->getSize()) { - audioBuffer->resize(grownDecodeCapacity(audioBuffer->getSize(), framesDecoded + framesRead)); + audioBuffer->resize( + grownDecodeCapacity(audioBuffer->getSize(), framesDecoded + framesRead, maxFrames)); } audioBuffer->deinterleaveFrom(chunk.data(), framesDecoded, framesRead); framesDecoded += framesRead; } if (framesDecoded == 0) { - return Err("Failed to decode any frames"); + return nullptr; } const size_t capacity = audioBuffer->getSize(); @@ -109,24 +154,9 @@ AudioBufferResult decodeAll(decoding::AudioDecoderBackend &decoder) { exact->copy(*audioBuffer, 0, 0, framesDecoded); audioBuffer = std::move(exact); } - return Ok(std::move(audioBuffer)); -} - -AudioDurationResult probeDurationFromSource( - const decoding::DecoderSource &source, - const char *errorMessage) { - return withDecoderFromSource( - source, errorMessage, resolveDurationFromDecoder); -} - -AudioBufferResult decodeFromSource( - const decoding::DecoderSource &source, - const char *errorMessage) { - return withDecoderFromSource(source, errorMessage, decodeAll); + return audioBuffer; } -} // namespace - bool pathHasExtension(const std::string &path, const std::vector &extensions) { return decoding::pathHasExtension(path, extensions); } diff --git a/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.h b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.h index a86e44c5c6..514964d2ea 100644 --- a/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.h +++ b/packages/react-native-audio-api/common/cpp/audioapi/decoding/AudioDecoding.h @@ -23,6 +23,15 @@ decodeWithMemoryBlock(const void *data, size_t size, float sampleRate); int inputChannelCount, bool interleaved); +/// @brief Decodes up to @p maxFrames PCM frames from the current position of @p decoder. +/// @return A planar buffer holding exactly the frames decoded: @p maxFrames of them unless the +/// stream ended first. `nullptr` when the decoder has no frame left. +/// @note Successive calls continue where the previous one stopped, so the buffers of any +/// sequence of calls, concatenated, hold the same samples as a single unbounded call. +[[nodiscard]] std::shared_ptr decodeFrames( + decoding::AudioDecoderBackend &decoder, + size_t maxFrames); + [[nodiscard]] bool pathHasExtension( const std::string &path, const std::vector &extensions); diff --git a/packages/react-native-audio-api/common/cpp/test/src/decoding/AudioDecodeStreamTest.cpp b/packages/react-native-audio-api/common/cpp/test/src/decoding/AudioDecodeStreamTest.cpp new file mode 100644 index 0000000000..ef1b490f4a --- /dev/null +++ b/packages/react-native-audio-api/common/cpp/test/src/decoding/AudioDecodeStreamTest.cpp @@ -0,0 +1,319 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace audioapi; + +// NOLINTBEGIN + +namespace { + +constexpr uint32_t sampleRate = 48000; +constexpr uint16_t channelCount = 2; +constexpr size_t frameCount = sampleRate / 2; + +/// A path of its own for each test of each process: instances of a parameterized test, and +/// `ctest -j` runs of the same binary, would otherwise write and remove the same file. +std::string testFilePath(const std::string &name) { + const auto *test = ::testing::UnitTest::GetInstance()->current_test_info(); + std::string scope = std::string(test->test_suite_name()) + "-" + test->name(); + std::replace(scope.begin(), scope.end(), '/', '-'); + return ::testing::TempDir() + std::to_string(::getpid()) + "-" + scope + "-" + name; +} + +float leftSampleAt(size_t frame) { + return static_cast(frame) / static_cast(frameCount); +} + +/// A stereo ramp: every frame is distinguishable, and the right channel mirrors the left. +std::string writeRampWavFile(const std::string &name) { + const std::string path = testFilePath(name); + std::remove(path.c_str()); + + std::vector frames(frameCount * channelCount); + for (size_t frame = 0; frame < frameCount; ++frame) { + frames[frame * channelCount] = leftSampleAt(frame); + frames[frame * channelCount + 1] = -leftSampleAt(frame); + } + test::writeFloatWavFile(path, frames, sampleRate, channelCount); + return path; +} + +std::vector readFileBytes(const std::string &path) { + std::ifstream input(path, std::ios::binary); + EXPECT_TRUE(input.is_open()); + return std::vector( + std::istreambuf_iterator(input), std::istreambuf_iterator()); +} + +std::unique_ptr openStream( + const std::string &path, + float outputSampleRate = 0.0F) { + auto result = audiodecoding::AudioDecodeStream::openWithFilePath(path, outputSampleRate); + EXPECT_TRUE(result.is_ok()); + return result.is_ok() ? std::move(result).unwrap() : nullptr; +} + +void appendChannels(std::vector> &channels, const AudioBuffer &buffer) { + channels.resize(buffer.getNumberOfChannels()); + for (size_t channel = 0; channel < buffer.getNumberOfChannels(); ++channel) { + const auto samples = buffer.getChannel(channel)->span(); + channels[channel].insert(channels[channel].end(), samples.begin(), samples.end()); + } +} + +/// Reads @p stream to its end in chunks of @p chunkFrames, concatenating the channels. +std::vector> readToEnd( + audiodecoding::AudioDecodeStream &stream, + size_t chunkFrames) { + std::vector> channels; + while (true) { + auto result = stream.read(chunkFrames); + EXPECT_TRUE(result.is_ok()); + if (result.is_err() || result.unwrap() == nullptr) { + return channels; + } + EXPECT_LE(result.unwrap()->getSize(), chunkFrames); + appendChannels(channels, *result.unwrap()); + } +} + +std::vector> decodeWhole(const std::string &path, float outputSampleRate) { + auto result = audiodecoding::decodeWithFilePath(path, outputSampleRate); + EXPECT_TRUE(result.is_ok()); + std::vector> channels; + if (result.is_ok()) { + appendChannels(channels, *result.unwrap()); + } + return channels; +} + +} // namespace + +TEST(AudioDecodeStreamTest, ReportsTheFormatOfTheSource) { + const std::string path = writeRampWavFile("decode-stream-format.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + EXPECT_EQ(stream->numberOfChannels(), static_cast(channelCount)); + EXPECT_FLOAT_EQ(stream->sampleRate(), static_cast(sampleRate)); + EXPECT_NEAR(stream->duration(), 0.5F, 0.001F); + EXPECT_EQ(stream->encodedSizeInBytes(), 0U); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, ReportsTheRequestedSampleRate) { + const std::string path = writeRampWavFile("decode-stream-rate.wav"); + auto stream = openStream(path, 22050.0F); + ASSERT_NE(stream, nullptr); + + EXPECT_FLOAT_EQ(stream->sampleRate(), 22050.0F); + + std::remove(path.c_str()); +} + +class AudioDecodeStreamChunkTest : public ::testing::TestWithParam {}; + +// The property analysis relies on: whatever the chunk size, the chunks put end to end are the +// samples a whole-file decode returns. +TEST_P(AudioDecodeStreamChunkTest, ChunksConcatenateToTheWholeDecode) { + const std::string path = writeRampWavFile("decode-stream-chunks.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + EXPECT_EQ(readToEnd(*stream, GetParam()), decodeWhole(path, 0.0F)); + + std::remove(path.c_str()); +} + +TEST_P(AudioDecodeStreamChunkTest, ChunksConcatenateToTheWholeDecodeWhenResampling) { + const std::string path = writeRampWavFile("decode-stream-chunks-resampled.wav"); + constexpr float outputSampleRate = 22050.0F; + auto stream = openStream(path, outputSampleRate); + ASSERT_NE(stream, nullptr); + + EXPECT_EQ(readToEnd(*stream, GetParam()), decodeWhole(path, outputSampleRate)); + + std::remove(path.c_str()); +} + +INSTANTIATE_TEST_SUITE_P( + ChunkSizes, + AudioDecodeStreamChunkTest, + ::testing::Values( + 1, + 1000, + decoding::AudioDecoderBackend::CHUNK_SIZE, + // not a multiple of the decoder's own chunk + decoding::AudioDecoderBackend::CHUNK_SIZE + 904, + // longer than the source: one short chunk + frameCount + 10)); + +TEST(AudioDecodeStreamTest, ReturnsAShortLastChunkThenNoBuffer) { + const std::string path = writeRampWavFile("decode-stream-end.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + constexpr size_t chunkFrames = 10000; + + auto first = stream->read(chunkFrames); + ASSERT_TRUE(first.is_ok()); + ASSERT_NE(first.unwrap(), nullptr); + EXPECT_EQ(first.unwrap()->getSize(), chunkFrames); + + auto second = stream->read(chunkFrames); + ASSERT_TRUE(second.is_ok()); + ASSERT_NE(second.unwrap(), nullptr); + EXPECT_EQ(second.unwrap()->getSize(), chunkFrames); + + auto last = stream->read(chunkFrames); + ASSERT_TRUE(last.is_ok()); + ASSERT_NE(last.unwrap(), nullptr); + EXPECT_EQ(last.unwrap()->getSize(), frameCount - 2 * chunkFrames); + + auto afterEnd = stream->read(chunkFrames); + ASSERT_TRUE(afterEnd.is_ok()); + EXPECT_EQ(afterEnd.unwrap(), nullptr); + + std::remove(path.c_str()); +} + +// A request far longer than the source must return the source, whichever branch sizes the +// buffer: a plain large request, and one past what a duration estimate is trusted for. +TEST(AudioDecodeStreamTest, ReturnsTheWholeSourceForAnOversizedRequest) { + const std::string path = writeRampWavFile("decode-stream-oversized.wav"); + constexpr size_t tenMinutes = static_cast(sampleRate) * 60 * 10; + + for (const size_t request : {tenMinutes, std::numeric_limits::max()}) { + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + auto result = stream->read(request); + ASSERT_TRUE(result.is_ok()); + ASSERT_NE(result.unwrap(), nullptr); + EXPECT_EQ(result.unwrap()->getSize(), frameCount); + + auto afterEnd = stream->read(request); + ASSERT_TRUE(afterEnd.is_ok()); + EXPECT_EQ(afterEnd.unwrap(), nullptr); + } + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, SeekMovesTheReadPosition) { + const std::string path = writeRampWavFile("decode-stream-seek.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + constexpr size_t targetFrame = frameCount / 2; + + ASSERT_TRUE(stream->read(1000).is_ok()); + auto seek = stream->seek(static_cast(targetFrame) / sampleRate); + ASSERT_TRUE(seek.is_ok()) << seek.unwrap_err(); + + auto result = stream->read(16); + ASSERT_TRUE(result.is_ok()); + ASSERT_NE(result.unwrap(), nullptr); + EXPECT_FLOAT_EQ((*result.unwrap()->getChannel(0))[0], leftSampleAt(targetFrame)); + EXPECT_FLOAT_EQ((*result.unwrap()->getChannel(1))[0], -leftSampleAt(targetFrame)); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, SeekBackAfterTheEndReadsAgain) { + const std::string path = writeRampWavFile("decode-stream-rewind.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + const auto firstPass = readToEnd(*stream, 4096); + ASSERT_TRUE(stream->seek(0.0).is_ok()); + + EXPECT_EQ(readToEnd(*stream, 4096), firstPass); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, RejectsAnInvalidSeekPosition) { + const std::string path = writeRampWavFile("decode-stream-bad-seek.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + EXPECT_TRUE(stream->seek(-1.0).is_err()); + EXPECT_TRUE(stream->seek(std::numeric_limits::quiet_NaN()).is_err()); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, RejectsAReadOfNoFrame) { + const std::string path = writeRampWavFile("decode-stream-zero.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + EXPECT_TRUE(stream->read(0).is_err()); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, RejectsReadAndSeekOnceClosed) { + const std::string path = writeRampWavFile("decode-stream-closed.wav"); + auto stream = openStream(path); + ASSERT_NE(stream, nullptr); + + stream->close(); + stream->close(); + + EXPECT_TRUE(stream->read(1000).is_err()); + EXPECT_TRUE(stream->seek(0.0).is_err()); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, ReadsFromAMemoryBlock) { + const std::string path = writeRampWavFile("decode-stream-memory.wav"); + const auto bytes = readFileBytes(path); + + auto result = audiodecoding::AudioDecodeStream::openWithMemoryBlock(bytes, 0); + ASSERT_TRUE(result.is_ok()) << result.unwrap_err(); + auto stream = std::move(result).unwrap(); + + EXPECT_EQ(stream->encodedSizeInBytes(), bytes.size()); + EXPECT_EQ(readToEnd(*stream, 5000), decodeWhole(path, 0.0F)); + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, RejectsASampleRateNoDecoderCanTake) { + const std::string path = writeRampWavFile("decode-stream-sample-rate.wav"); + const auto bytes = readFileBytes(path); + + for (const float rate : + {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), + -1.0F, + 1.0e12F}) { + EXPECT_TRUE(audiodecoding::AudioDecodeStream::openWithFilePath(path, rate).is_err()); + EXPECT_TRUE(audiodecoding::AudioDecodeStream::openWithMemoryBlock(bytes, rate).is_err()); + } + + std::remove(path.c_str()); +} + +TEST(AudioDecodeStreamTest, RejectsASourceThatCannotBeDecoded) { + const std::vector invalid = {0x00, 0x01, 0x02}; + + EXPECT_TRUE(audiodecoding::AudioDecodeStream::openWithFilePath("", 0).is_err()); + EXPECT_TRUE(audiodecoding::AudioDecodeStream::openWithMemoryBlock({}, 0).is_err()); + EXPECT_TRUE(audiodecoding::AudioDecodeStream::openWithMemoryBlock(invalid, 0).is_err()); +} + +// NOLINTEND diff --git a/packages/react-native-audio-api/common/cpp/test/src/decoding/DecodeFramesTest.cpp b/packages/react-native-audio-api/common/cpp/test/src/decoding/DecodeFramesTest.cpp new file mode 100644 index 0000000000..ff0d22d4b4 --- /dev/null +++ b/packages/react-native-audio-api/common/cpp/test/src/decoding/DecodeFramesTest.cpp @@ -0,0 +1,136 @@ +#include +#include +#include + +#include +#include +#include +#include + +using namespace audioapi; + +// NOLINTBEGIN + +namespace { + +constexpr size_t unbounded = std::numeric_limits::max(); + +/// A mono source of @p totalFrames frames whose samples count the frames, so a decoded buffer +/// shows which frames it holds. It can announce a length that is not its real one, and return +/// fewer frames per read than asked, as a real decoder may. +class CountingDecoder : public decoding::AudioDecoderBackend { + public: + CountingDecoder(size_t totalFrames, size_t announcedFrames, size_t maxFramesPerRead = unbounded) + : totalFrames_(totalFrames), maxFramesPerRead_(maxFramesPerRead) { + outputChannels_ = 1; + outputSampleRate_ = 48000; + totalPcmFrames_ = announcedFrames; + } + + size_t readPcmFrames(float *outInterleaved, size_t frameCount) override { + largestRequest_ = std::max(largestRequest_, frameCount); + const size_t frames = std::min({frameCount, maxFramesPerRead_, totalFrames_ - position_}); + for (size_t i = 0; i < frames; ++i) { + outInterleaved[i] = static_cast(position_ + i); + } + position_ += frames; + return frames; + } + + decoding::DecoderResult seekToTime(double /*seconds*/) override { + return Ok(None); + } + void close() override {} + bool isOpen() const override { + return true; + } + + size_t largestRequest() const { + return largestRequest_; + } + + private: + size_t totalFrames_; + size_t maxFramesPerRead_; + size_t position_ = 0; + size_t largestRequest_ = 0; +}; + +void expectFrames(const std::shared_ptr &buffer, size_t firstFrame, size_t count) { + ASSERT_NE(buffer, nullptr); + ASSERT_EQ(buffer->getSize(), count); + const auto samples = buffer->getChannel(0)->span(); + for (size_t i = 0; i < count; ++i) { + ASSERT_FLOAT_EQ(samples[i], static_cast(firstFrame + i)) << "frame " << i; + } +} + +} // namespace + +TEST(DecodeFramesTest, DecodesEverythingWhenTheLengthIsAnnounced) { + CountingDecoder decoder(100000, 100000); + + expectFrames(audiodecoding::decodeFrames(decoder, unbounded), 0, 100000); +} + +TEST(DecodeFramesTest, GrowsWhenTheLengthIsUnknown) { + CountingDecoder decoder(200000, 0); + + expectFrames(audiodecoding::decodeFrames(decoder, unbounded), 0, 200000); +} + +TEST(DecodeFramesTest, GrowsWhenTheSourceIsLongerThanAnnounced) { + CountingDecoder decoder(50000, 1000); + + expectFrames(audiodecoding::decodeFrames(decoder, unbounded), 0, 50000); +} + +TEST(DecodeFramesTest, ReturnsAShortSourceForALargeRequest) { + CountingDecoder decoder(3000, 3000); + + expectFrames(audiodecoding::decodeFrames(decoder, 5000000), 0, 3000); +} + +TEST(DecodeFramesTest, ReturnsAShortSourceThatAnnouncesTooMuch) { + CountingDecoder decoder(3000, 10000000); + + expectFrames(audiodecoding::decodeFrames(decoder, 5000000), 0, 3000); +} + +TEST(DecodeFramesTest, GrowsUpToALargeRequestWhenTheLengthIsUnknown) { + CountingDecoder decoder(1000000, 0); + + expectFrames(audiodecoding::decodeFrames(decoder, 300000), 0, 300000); +} + +TEST(DecodeFramesTest, StopsAtTheRequestAndContinuesFromThere) { + CountingDecoder decoder(10000, 10000); + + expectFrames(audiodecoding::decodeFrames(decoder, 5000), 0, 5000); + expectFrames(audiodecoding::decodeFrames(decoder, 3000), 5000, 3000); + expectFrames(audiodecoding::decodeFrames(decoder, 5000), 8000, 2000); + EXPECT_EQ(audiodecoding::decodeFrames(decoder, 5000), nullptr); +} + +TEST(DecodeFramesTest, NeverAsksTheDecoderForMoreThanTheRequest) { + CountingDecoder decoder(10000, 10000); + + expectFrames(audiodecoding::decodeFrames(decoder, 10), 0, 10); + EXPECT_LE(decoder.largestRequest(), 10U); +} + +TEST(DecodeFramesTest, KeepsReadingADecoderThatReturnsShortReads) { + CountingDecoder decoder(10000, 10000, 100); + + expectFrames(audiodecoding::decodeFrames(decoder, 1000), 0, 1000); + expectFrames(audiodecoding::decodeFrames(decoder, unbounded), 1000, 9000); +} + +TEST(DecodeFramesTest, ReturnsNoBufferForAnEmptySource) { + CountingDecoder decoder(0, 0); + + EXPECT_EQ(audiodecoding::decodeFrames(decoder, 4096), nullptr); + EXPECT_EQ(audiodecoding::decodeFrames(decoder, unbounded), nullptr); +} + +// NOLINTEND diff --git a/packages/react-native-audio-api/src/api.ts b/packages/react-native-audio-api/src/api.ts index 6733af01e8..f50e6d25a7 100644 --- a/packages/react-native-audio-api/src/api.ts +++ b/packages/react-native-audio-api/src/api.ts @@ -5,7 +5,12 @@ export { default as AudioBuffer } from './core/AudioBuffer'; export { default as AudioBufferQueueSourceNode } from './core/AudioBufferQueueSourceNode'; export { default as AudioBufferSourceNode } from './core/AudioBufferSourceNode'; export { default as AudioContext } from './core/AudioContext'; -export { decodeAudioData, decodePCMInBase64 } from './core/AudioDecoder'; +export { + decodeAudioData, + decodePCMInBase64, + openAudioDecodeStream, +} from './core/AudioDecoder'; +export { default as AudioDecodeStream } from './core/AudioDecodeStream'; export { concatAudioFiles, getAudioDuration } from './core/AudioFileUtils'; export { default as AudioDestinationNode } from './core/AudioDestinationNode'; export { default as AudioListener } from './core/AudioListener'; diff --git a/packages/react-native-audio-api/src/api.web.ts b/packages/react-native-audio-api/src/api.web.ts index b96deb07cf..4882114e2e 100644 --- a/packages/react-native-audio-api/src/api.web.ts +++ b/packages/react-native-audio-api/src/api.web.ts @@ -29,7 +29,9 @@ export { decodeAudioData, decodePCMInBase64, getAudioDuration, + openAudioDecodeStream, } from './web-core/AudioDecoder.web'; +export { default as AudioDecodeStream } from './web-core/AudioDecodeStream.web'; export * from './web-core/custom'; diff --git a/packages/react-native-audio-api/src/core/AudioDecodeStream.ts b/packages/react-native-audio-api/src/core/AudioDecodeStream.ts new file mode 100644 index 0000000000..989092a195 --- /dev/null +++ b/packages/react-native-audio-api/src/core/AudioDecodeStream.ts @@ -0,0 +1,116 @@ +import { AudioApiError } from '../errors'; +import { IAudioDecodeStream } from '../jsi-interfaces'; +import { + assertValidDecodeStreamFrameCount, + assertValidDecodeStreamPosition, +} from '../utils/validation'; +import AudioBuffer from './AudioBuffer'; + +/** + * An audio source kept open to be decoded a few frames at a time, instead of as + * one `AudioBuffer`. Memory follows the size of a read, not the duration of the + * source. + * + * Reads are sequential: each one continues where the previous one stopped, so + * the chunks of a stream, put end to end, hold the samples `decodeAudioData` + * returns for the same source and sample rate. + */ +export default class AudioDecodeStream { + /** Sample rate of the decoded audio, in Hz. */ + readonly sampleRate: number; + readonly numberOfChannels: number; + /** Duration reported by the source, in seconds; 0 when it is unknown. */ + readonly duration: number; + + /** @internal */ + private readonly stream: IAudioDecodeStream; + + /** + * Settles when the operation requested last has. Each operation waits for it + * before reaching the native stream, whose serial lane then holds one of them + * at a time: a burst of reads waits here, instead of blocking the JS thread + * on a full lane. + * + * @internal + */ + private lastOperation: Promise = Promise.resolve(); + + /** @internal */ + private closed: boolean = false; + + /** @internal */ + constructor(stream: IAudioDecodeStream) { + this.stream = stream; + this.sampleRate = stream.sampleRate; + this.numberOfChannels = stream.numberOfChannels; + this.duration = stream.duration; + } + + /** + * Decodes the next `frameCount` frames. + * + * Resolves with a buffer of `frameCount` frames, shorter only when the source + * ends inside it, and with `null` once the source has ended. Reads run one at + * a time, in the order they were requested. + * + * @throws RangeError When `frameCount` is not a positive integer. + */ + public async read(frameCount: number): Promise { + assertValidDecodeStreamFrameCount(frameCount); + this.assertOpen('read from'); + + return this.runInOrder(async () => { + const buffer = await this.stream.read(frameCount); + return buffer === null ? null : new AudioBuffer(buffer); + }); + } + + /** + * Moves the read position to `seconds`. Compressed formats seek to the + * nearest position they can decode from, so the next read may start a few + * frames away from it. + * + * @throws RangeError When `seconds` is negative or not finite. + */ + public async seek(seconds: number): Promise { + assertValidDecodeStreamPosition(seconds); + this.assertOpen('seek in'); + + return this.runInOrder(() => this.stream.seek(seconds)); + } + + /** + * Releases the decoder once the reads already requested have settled. Reads + * and seeks requested afterwards reject. + */ + public close(): void { + if (this.closed) { + return; + } + this.closed = true; + + this.runInOrder(() => Promise.resolve(this.stream.close())).catch( + // Nothing awaits a close: a failure has no caller to reach. + () => undefined + ); + } + + private assertOpen(action: 'read from' | 'seek in'): void { + if (this.closed) { + throw new AudioApiError(`Cannot ${action} a closed decode stream`); + } + } + + /** Runs `operation` once every operation requested before it has settled. */ + private runInOrder( + operation: () => Promise + ): Promise { + const result = this.lastOperation.then(operation); + // A failed operation must not fail the ones requested after it. + this.lastOperation = result.then( + () => undefined, + () => undefined + ); + return result; + } +} diff --git a/packages/react-native-audio-api/src/core/AudioDecoder.ts b/packages/react-native-audio-api/src/core/AudioDecoder.ts index b228d39708..d7ae2e4916 100644 --- a/packages/react-native-audio-api/src/core/AudioDecoder.ts +++ b/packages/react-native-audio-api/src/core/AudioDecoder.ts @@ -3,11 +3,18 @@ import { NativeAudioAPIModule } from '../specs'; import { AudioApiError } from '../errors'; import { IAudioDecoder } from '../jsi-interfaces'; -import { DecodeDataInput } from '../types'; +import { AudioDecodeStreamOptions, DecodeDataInput } from '../types'; import { isRemoteSource, resolveLocalFilePath } from '../utils/paths'; import { base64ToArrayBuffer } from '../utils'; -import { assertSupportedDecodeStringSource } from '../utils/validation'; +import { + assertSupportedDecodeStringSource, + assertValidDecodeStreamSampleRate, +} from '../utils/validation'; import AudioBuffer from './AudioBuffer'; +import AudioDecodeStream from './AudioDecodeStream'; + +/** The encoded bytes of a source, or the path of the local file holding them. */ +type EncodedSource = ArrayBuffer | string; class AudioDecoder { private static instance: AudioDecoder | null = null; @@ -24,18 +31,19 @@ class AudioDecoder { ): Promise { const rate = sampleRate ?? 0; + // Before any await: the native side copies the bytes when it is called, and + // the caller may reuse its buffer as soon as this function returns. if (input instanceof ArrayBuffer) { return this.decodeFromArrayBuffer(input, rate); } - const stringSource = this.resolveToStringSource(input); - assertSupportedDecodeStringSource(stringSource); - - if (isRemoteSource(stringSource)) { - return this.decodeFromRemoteUrl(stringSource, rate, fetchOptions); + const source = await this.loadEncodedSource(input, fetchOptions); + if (source instanceof ArrayBuffer) { + return this.decodeFromArrayBuffer(source, rate); } - return this.decodeFromLocalFile(stringSource, rate); + const buffer = await this.decoder.decodeWithFilePath(source, rate); + return new AudioBuffer(buffer); } private async decodeFromArrayBuffer( @@ -59,25 +67,34 @@ class AudioDecoder { return uri ?? ''; } - private async decodeFromRemoteUrl( - url: string, - sampleRate: number, + /** + * Resolves a string or asset input to what the native decoder opens: the + * encoded bytes held in memory, or the path of a local file. + */ + private async loadEncodedSource( + input: number | string, fetchOptions?: RequestInit - ): Promise { - const arrayBuffer = await fetch(url, fetchOptions).then((res) => - res.arrayBuffer() - ); - return this.decodeFromArrayBuffer(arrayBuffer, sampleRate); - } + ): Promise { + const stringSource = this.resolveToStringSource(input); + assertSupportedDecodeStringSource(stringSource); - private async decodeFromLocalFile( - stringSource: string, - sampleRate: number - ): Promise { + if (isRemoteSource(stringSource)) { + const response = await fetch(stringSource, fetchOptions); + if (!response.ok) { + throw new AudioApiError( + `Failed to download audio data: HTTP ${response.status}` + ); + } + return response.arrayBuffer(); + } + + // A bundled asset is named after its resource (asset_example_file): a + // file:// URI or an absolute path is a file, which the reader of bundled + // assets cannot open. + const isFile = + stringSource.startsWith('file://') || stringSource.startsWith('/'); const useAndroidBundledAssetReader = - Platform.OS === 'android' && - !stringSource.startsWith('file://') && - !__DEV__; + Platform.OS === 'android' && !isFile && !__DEV__; // special workaround, because android bundled assets are passed as f.e. asset_example_file // which has to be handled on native side and extension is not passed with it so decode using memory @@ -86,13 +103,10 @@ class AudioDecoder { await NativeAudioAPIModule.readAndroidReleaseAssetBytesAsBase64( stringSource ); - const arrayBuffer = base64ToArrayBuffer(base64Payload); - return this.decodeFromArrayBuffer(arrayBuffer, sampleRate); + return base64ToArrayBuffer(base64Payload); } - const filePath = resolveLocalFilePath(stringSource); - const buffer = await this.decoder.decodeWithFilePath(filePath, sampleRate); - return new AudioBuffer(buffer); + return resolveLocalFilePath(stringSource); } public static getInstance(): AudioDecoder { @@ -121,6 +135,44 @@ class AudioDecoder { return audioBuffer; } + public async openDecodeStreamInstance( + input: DecodeDataInput, + options: AudioDecodeStreamOptions = {} + ): Promise { + // The native side converts the rate to an integer, which is undefined for + // a NaN, an infinity or a value out of range. + assertValidDecodeStreamSampleRate(options.sampleRate); + const sampleRate = options.sampleRate ?? 0; + + // Before any await, for the reason given in decodeAudioDataImplementation. + if (input instanceof ArrayBuffer) { + return this.openStreamFromArrayBuffer(input, sampleRate); + } + + const source = await this.loadEncodedSource(input, options.fetchOptions); + if (source instanceof ArrayBuffer) { + return this.openStreamFromArrayBuffer(source, sampleRate); + } + + const stream = await this.decoder.openStreamWithFilePath( + source, + sampleRate + ); + return new AudioDecodeStream(stream); + } + + private async openStreamFromArrayBuffer( + arrayBuffer: ArrayBuffer, + sampleRate: number + ): Promise { + const stream = await this.decoder.openStreamWithMemoryBlock( + // @ts-ignore internal function + new Uint8Array(arrayBuffer), + sampleRate + ); + return new AudioDecodeStream(stream); + } + public async decodePCMInBase64Instance( base64String: string, inputSampleRate: number, @@ -149,6 +201,18 @@ export async function decodeAudioData( ); } +/** + * Opens `input` to decode it a few frames at a time instead of as one + * `AudioBuffer`. Takes the inputs `decodeAudioData` takes; close the stream + * once done with it. + */ +export async function openAudioDecodeStream( + input: DecodeDataInput, + options?: AudioDecodeStreamOptions +): Promise { + return AudioDecoder.getInstance().openDecodeStreamInstance(input, options); +} + export async function decodePCMInBase64( base64String: string, inputSampleRate: number, diff --git a/packages/react-native-audio-api/src/jsi-interfaces.ts b/packages/react-native-audio-api/src/jsi-interfaces.ts index 48a015e24d..bf9cdbe88b 100644 --- a/packages/react-native-audio-api/src/jsi-interfaces.ts +++ b/packages/react-native-audio-api/src/jsi-interfaces.ts @@ -397,6 +397,25 @@ export interface IAudioDecoder { inputChannelCount: number, interleaved?: boolean ) => Promise; + openStreamWithMemoryBlock: ( + arrayBuffer: ArrayBuffer, + sampleRate: number + ) => Promise; + openStreamWithFilePath: ( + sourcePath: string, + sampleRate: number + ) => Promise; +} + +export interface IAudioDecodeStream { + readonly sampleRate: number; + readonly numberOfChannels: number; + readonly duration: number; + + /** Resolves with `null` once the source has ended. */ + read: (frameCount: number) => Promise; + seek: (seconds: number) => Promise; + close: () => void; } export interface IAudioFileUtils { diff --git a/packages/react-native-audio-api/src/mock/index.ts b/packages/react-native-audio-api/src/mock/index.ts index 4f0b989da9..8e10117fb5 100644 --- a/packages/react-native-audio-api/src/mock/index.ts +++ b/packages/react-native-audio-api/src/mock/index.ts @@ -22,6 +22,7 @@ import type { ConstantSourceOptions, ConvolverOptions, DelayOptions, + AudioDecodeStreamOptions, DecodeDataInput, GainOptions, OscillatorOptions, @@ -1121,6 +1122,96 @@ const decodeAudioData = (_audioData: ArrayBuffer): Promise => { ); }; +/** Hands out the one second of silence the mocked `decodeAudioData` returns. */ +class AudioDecodeStreamMock { + public readonly sampleRate: number; + public readonly numberOfChannels: number = 2; + public readonly duration: number = 1; + + private position: number = 0; + private closed: boolean = false; + + constructor(sampleRate: number = 44100) { + this.sampleRate = sampleRate; + } + + private get length(): number { + return this.duration * this.sampleRate; + } + + read(frameCount: number): Promise { + if (!Number.isSafeInteger(frameCount) || frameCount <= 0) { + return Promise.reject( + new RangeErrorMock( + `frameCount must be a positive integer: ${frameCount}` + ) + ); + } + if (this.closed) { + return Promise.reject( + new AudioApiErrorMock('Cannot read from a closed decode stream') + ); + } + + const length = Math.min(frameCount, this.length - this.position); + if (length <= 0) { + return Promise.resolve(null); + } + + this.position += length; + return Promise.resolve( + new AudioBufferMock({ + numberOfChannels: this.numberOfChannels, + length, + sampleRate: this.sampleRate, + }) + ); + } + + seek(seconds: number): Promise { + if (!Number.isFinite(seconds) || seconds < 0) { + return Promise.reject( + new RangeErrorMock( + `seconds must be a non-negative finite number: ${seconds}` + ) + ); + } + if (this.closed) { + return Promise.reject( + new AudioApiErrorMock('Cannot seek in a closed decode stream') + ); + } + + this.position = Math.min( + Math.round(seconds * this.sampleRate), + this.length + ); + return Promise.resolve(); + } + + close(): void { + this.closed = true; + } +} + +const openAudioDecodeStream = ( + _input: DecodeDataInput, + options?: AudioDecodeStreamOptions +): Promise => { + const sampleRate = options?.sampleRate; + if ( + sampleRate !== undefined && + (!Number.isFinite(sampleRate) || sampleRate < 3000 || sampleRate > 768000) + ) { + return Promise.reject( + new RangeErrorMock( + `sampleRate must be a number in [3000, 768000]: ${sampleRate}` + ) + ); + } + return Promise.resolve(new AudioDecodeStreamMock(sampleRate)); +}; + const decodePCMInBase64 = (_base64Data: string): Promise => { return Promise.resolve( new AudioBufferMock({ @@ -1323,6 +1414,7 @@ class AudioApiErrorMock extends Error { // Export classes with original API names (for compatibility) export const AnalyserNode = AnalyserNodeMock; export const AudioBuffer = AudioBufferMock; +export const AudioDecodeStream = AudioDecodeStreamMock; export const AudioBufferQueueSourceNode = AudioBufferQueueSourceNodeMock; export const AudioBufferSourceNode = AudioBufferSourceNodeMock; export const AudioContext = AudioContextMock; @@ -1368,6 +1460,7 @@ export { decodeAudioData, decodePCMInBase64, getAudioDuration, + openAudioDecodeStream, setMockSystemVolume, useSystemVolume, }; @@ -1375,6 +1468,7 @@ export { // Type exports to allow using classes as types export type AnalyserNode = AnalyserNodeMock; export type AudioBuffer = AudioBufferMock; +export type AudioDecodeStream = AudioDecodeStreamMock; export type AudioBufferQueueSourceNode = AudioBufferQueueSourceNodeMock; export type AudioBufferSourceNode = AudioBufferSourceNodeMock; export type AudioContext = AudioContextMock; @@ -1437,6 +1531,7 @@ export { export default { AnalyserNode: AnalyserNodeMock, AudioBuffer: AudioBufferMock, + AudioDecodeStream: AudioDecodeStreamMock, AudioBufferQueueSourceNode: AudioBufferQueueSourceNodeMock, AudioBufferSourceNode: AudioBufferSourceNodeMock, AudioContext: AudioContextMock, @@ -1466,6 +1561,7 @@ export default { decodeAudioData, decodePCMInBase64, getAudioDuration, + openAudioDecodeStream, changePlaybackSpeed, concatAudioFiles, useSystemVolume, diff --git a/packages/react-native-audio-api/src/types.ts b/packages/react-native-audio-api/src/types.ts index ec1722a4c7..ba3a31b018 100644 --- a/packages/react-native-audio-api/src/types.ts +++ b/packages/react-native-audio-api/src/types.ts @@ -347,6 +347,16 @@ export interface WaveShaperOptions extends AudioNodeOptions { } export type DecodeDataInput = number | string | ArrayBuffer; + +export interface AudioDecodeStreamOptions { + /** + * Sample rate of the decoded audio, in Hz. Defaults to the sample rate of the + * source; on web, where the browser resamples what it decodes, to 44100. + */ + sampleRate?: number; + /** Options of the request that downloads a remote source. */ + fetchOptions?: RequestInit; +} export type AudioDurationInput = string | ArrayBuffer; export enum AutomationEventType { diff --git a/packages/react-native-audio-api/src/utils/paths.ts b/packages/react-native-audio-api/src/utils/paths.ts index eb99481c44..6b5718c6ff 100644 --- a/packages/react-native-audio-api/src/utils/paths.ts +++ b/packages/react-native-audio-api/src/utils/paths.ts @@ -2,14 +2,20 @@ export function isRemoteSource(url: string): boolean { return url.startsWith('http://') || url.startsWith('https://'); } +/** + * The path of the file a local source names. A `file://` URI is + * percent-encoded, a bare path is not: `%20` in one is part of the file name. + */ export function resolveLocalFilePath(stringSource: string): string { - const stripped = stringSource.startsWith('file://') - ? stringSource.slice('file://'.length) - : stringSource; + if (!stringSource.startsWith('file://')) { + return stringSource; + } + + const encodedPath = stringSource.slice('file://'.length); try { - return decodeURIComponent(stripped); + return decodeURIComponent(encodedPath); } catch { - return stripped; + return encodedPath; } } diff --git a/packages/react-native-audio-api/src/utils/validation/decodeStream.ts b/packages/react-native-audio-api/src/utils/validation/decodeStream.ts new file mode 100644 index 0000000000..91e433867b --- /dev/null +++ b/packages/react-native-audio-api/src/utils/validation/decodeStream.ts @@ -0,0 +1,39 @@ +import { RangeError } from '../../errors'; +import { + MAX_SUPPORTED_SAMPLE_RATE, + MIN_SUPPORTED_SAMPLE_RATE, +} from './sampleRate'; + +/** An omitted sample rate keeps the default: only a given one is checked. */ +export function assertValidDecodeStreamSampleRate( + sampleRate: number | undefined +): void { + if (sampleRate === undefined) { + return; + } + if ( + !Number.isFinite(sampleRate) || + sampleRate < MIN_SUPPORTED_SAMPLE_RATE || + sampleRate > MAX_SUPPORTED_SAMPLE_RATE + ) { + throw new RangeError( + `sampleRate must be a number in [${MIN_SUPPORTED_SAMPLE_RATE}, ${MAX_SUPPORTED_SAMPLE_RATE}]: ${sampleRate}` + ); + } +} + +export function assertValidDecodeStreamFrameCount(frameCount: number): void { + if (!Number.isSafeInteger(frameCount) || frameCount <= 0) { + throw new RangeError( + `frameCount must be a positive integer: ${frameCount}` + ); + } +} + +export function assertValidDecodeStreamPosition(seconds: number): void { + if (!Number.isFinite(seconds) || seconds < 0) { + throw new RangeError( + `seconds must be a non-negative finite number: ${seconds}` + ); + } +} diff --git a/packages/react-native-audio-api/src/utils/validation/index.ts b/packages/react-native-audio-api/src/utils/validation/index.ts index acaf96308e..facc5fb0de 100644 --- a/packages/react-native-audio-api/src/utils/validation/index.ts +++ b/packages/react-native-audio-api/src/utils/validation/index.ts @@ -43,3 +43,9 @@ export { assertSupportedDecodeStringSource, assertUnsupportedDecodeStringFormats, } from './decodeSource'; + +export { + assertValidDecodeStreamFrameCount, + assertValidDecodeStreamPosition, + assertValidDecodeStreamSampleRate, +} from './decodeStream'; diff --git a/packages/react-native-audio-api/src/web-core/AudioDecodeStream.web.ts b/packages/react-native-audio-api/src/web-core/AudioDecodeStream.web.ts new file mode 100644 index 0000000000..ebd0fb4ecd --- /dev/null +++ b/packages/react-native-audio-api/src/web-core/AudioDecodeStream.web.ts @@ -0,0 +1,83 @@ +import { AudioApiError } from '../errors'; +import { + assertValidDecodeStreamFrameCount, + assertValidDecodeStreamPosition, +} from '../utils/validation'; +import AudioBuffer from './AudioBuffer.web'; + +/** + * Web counterpart of the native decode stream. A browser only decodes a source + * as a whole, so the stream keeps the decoded audio and hands out slices of it: + * the API is the native one, the memory saving is not. + */ +export default class AudioDecodeStream { + readonly sampleRate: number; + readonly numberOfChannels: number; + readonly duration: number; + + private decoded: AudioBuffer | null; + private position: number = 0; + + /** @internal */ + constructor(decoded: AudioBuffer) { + this.decoded = decoded; + this.sampleRate = decoded.sampleRate; + this.numberOfChannels = decoded.numberOfChannels; + this.duration = decoded.duration; + } + + public read(frameCount: number): Promise { + // a throw inside the executor rejects the promise + return new Promise((resolve) => { + assertValidDecodeStreamFrameCount(frameCount); + resolve(this.readChunk(frameCount)); + }); + } + + public seek(seconds: number): Promise { + return new Promise((resolve) => { + assertValidDecodeStreamPosition(seconds); + const decoded = this.openDecodedAudio('seek in'); + this.position = Math.min( + Math.round(seconds * this.sampleRate), + decoded.length + ); + resolve(); + }); + } + + private readChunk(frameCount: number): AudioBuffer | null { + const decoded = this.openDecodedAudio('read from'); + const length = Math.min(frameCount, decoded.length - this.position); + if (length <= 0) { + return null; + } + + const chunk = new AudioBuffer({ + length, + numberOfChannels: this.numberOfChannels, + sampleRate: this.sampleRate, + }); + for (let channel = 0; channel < this.numberOfChannels; channel += 1) { + chunk.copyToChannel( + decoded + .getChannelData(channel) + .subarray(this.position, this.position + length), + channel + ); + } + this.position += length; + return chunk; + } + + private openDecodedAudio(action: 'read from' | 'seek in'): AudioBuffer { + if (this.decoded === null) { + throw new AudioApiError(`Cannot ${action} a closed decode stream`); + } + return this.decoded; + } + + public close(): void { + this.decoded = null; + } +} diff --git a/packages/react-native-audio-api/src/web-core/AudioDecoder.web.ts b/packages/react-native-audio-api/src/web-core/AudioDecoder.web.ts index 7a7af10238..815dc7f8aa 100644 --- a/packages/react-native-audio-api/src/web-core/AudioDecoder.web.ts +++ b/packages/react-native-audio-api/src/web-core/AudioDecoder.web.ts @@ -1,7 +1,13 @@ import { AudioApiError } from '../errors'; -import { AudioDurationInput, DecodeDataInput } from '../types'; +import { + AudioDecodeStreamOptions, + AudioDurationInput, + DecodeDataInput, +} from '../types'; import { base64ToArrayBuffer } from '../utils'; +import { assertValidDecodeStreamSampleRate } from '../utils/validation'; import AudioBuffer from './AudioBuffer.web'; +import AudioDecodeStream from './AudioDecodeStream.web'; import OfflineAudioContext from './OfflineAudioContext.web'; const MAX_INT16_VALUE = 32768.0; @@ -55,10 +61,13 @@ export default class AudioDecoder { sampleRate: number, fetchOptions?: RequestInit ): Promise { - const arrayBuffer = await fetch(url, fetchOptions).then((res) => - res.arrayBuffer() - ); - return this.decodeFromArrayBuffer(arrayBuffer, sampleRate); + const response = await fetch(url, fetchOptions); + if (!response.ok) { + throw new AudioApiError( + `Failed to download audio data: HTTP ${response.status}` + ); + } + return this.decodeFromArrayBuffer(await response.arrayBuffer(), sampleRate); } public async decodeAudioDataInstance( @@ -79,6 +88,20 @@ export default class AudioDecoder { return audioBuffer; } + public async openDecodeStreamInstance( + input: DecodeDataInput, + options: AudioDecodeStreamOptions = {} + ): Promise { + assertValidDecodeStreamSampleRate(options.sampleRate); + + const decoded = await this.decodeAudioDataInstance( + input, + options.sampleRate, + options.fetchOptions + ); + return new AudioDecodeStream(decoded); + } + public async decodePCMInBase64Instance( base64String: string, inputSampleRate: number, @@ -217,6 +240,13 @@ export async function decodeAudioData( ); } +export async function openAudioDecodeStream( + input: DecodeDataInput, + options?: AudioDecodeStreamOptions +): Promise { + return AudioDecoder.getInstance().openDecodeStreamInstance(input, options); +} + export async function decodePCMInBase64( base64String: string, inputSampleRate: number, diff --git a/packages/react-native-audio-api/tests/audio-decode-stream.test.ts b/packages/react-native-audio-api/tests/audio-decode-stream.test.ts new file mode 100644 index 0000000000..7895a6bd2e --- /dev/null +++ b/packages/react-native-audio-api/tests/audio-decode-stream.test.ts @@ -0,0 +1,480 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ + +import type { + IAudioBuffer, + IAudioDecodeStream, + IAudioDecoder, +} from '../src/jsi-interfaces'; + +type AudioDecoderExports = typeof import('../src/core/AudioDecoder'); +type WebAudioDecodeStreamExports = + typeof import('../src/web-core/AudioDecodeStream.web'); +type WebAudioBufferExports = typeof import('../src/web-core/AudioBuffer.web'); + +jest.mock('react-native', () => ({ + Image: { + resolveAssetSource: jest.fn((input: number) => ({ + uri: `file:///asset-${input}.wav`, + })), + }, + Platform: { + OS: 'ios', + }, + TurboModuleRegistry: { + get: jest.fn(() => ({ + install: jest.fn(), + readAndroidReleaseAssetBytesAsBase64: jest.fn(), + })), + }, +})); + +const createNativeBuffer = (length: number): IAudioBuffer => + ({ + length, + duration: length / 44100, + sampleRate: 44100, + numberOfChannels: 2, + getChannelData: jest.fn(), + copyFromChannel: jest.fn(), + copyToChannel: jest.fn(), + }) as unknown as IAudioBuffer; + +const createNativeStream = () => + ({ + sampleRate: 44100, + numberOfChannels: 2, + duration: 12.5, + read: jest.fn(), + seek: jest.fn().mockResolvedValue(undefined), + close: jest.fn(), + }) as unknown as jest.Mocked; + +const installDecoder = (stream: IAudioDecodeStream) => { + const decoder = { + decodeWithMemoryBlock: jest.fn(), + decodeWithFilePath: jest.fn(), + decodeWithPCMInBase64: jest.fn(), + openStreamWithMemoryBlock: jest.fn().mockResolvedValue(stream), + openStreamWithFilePath: jest.fn().mockResolvedValue(stream), + } as unknown as jest.Mocked; + globalThis.createAudioDecoder = jest.fn(() => decoder); + return decoder; +}; + +/** Lets the operations a stream has queued reach the native stream. */ +const settleOperations = () => + new Promise((resolve) => setImmediate(resolve)); + +const loadAudioDecoder = (): AudioDecoderExports => { + return require('../src/core/AudioDecoder') as AudioDecoderExports; +}; + +describe('openAudioDecodeStream', () => { + beforeEach(() => { + jest.resetModules(); + }); + + it('opens a local file at the requested sample rate', async () => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + + const stream = await openAudioDecodeStream('file:///tmp/audio%20file.wav', { + sampleRate: 22050, + }); + + expect(decoder.openStreamWithFilePath).toHaveBeenCalledWith( + '/tmp/audio file.wav', + 22050 + ); + expect(stream.sampleRate).toBe(44100); + expect(stream.numberOfChannels).toBe(2); + expect(stream.duration).toBe(12.5); + }); + + it('keeps the percent sequences of a bare path, which name the file', async () => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + + await openAudioDecodeStream('/tmp/clip%20mix.wav'); + + expect(decoder.openStreamWithFilePath).toHaveBeenCalledWith( + '/tmp/clip%20mix.wav', + 0 + ); + }); + + it('opens encoded bytes held in memory', async () => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + const arrayBuffer = new ArrayBuffer(8); + + await openAudioDecodeStream(arrayBuffer); + + expect(decoder.openStreamWithMemoryBlock).toHaveBeenCalledTimes(1); + const [bytes, sampleRate] = decoder.openStreamWithMemoryBlock.mock + .calls[0] as unknown as [Uint8Array, number]; + expect(bytes.buffer).toBe(arrayBuffer); + expect(sampleRate).toBe(0); + }); + + // The native side copies the bytes when it is called: a caller may reuse its + // buffer as soon as the function has returned, without awaiting it. + it('hands encoded bytes to the decoder before returning', async () => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + + const opening = openAudioDecodeStream(new ArrayBuffer(8)); + + expect(decoder.openStreamWithMemoryBlock).toHaveBeenCalledTimes(1); + await opening; + }); + + it('keeps handing encoded bytes to decodeAudioData before returning', async () => { + const decoder = installDecoder(createNativeStream()); + decoder.decodeWithMemoryBlock.mockResolvedValue(createNativeBuffer(8)); + const { decodeAudioData } = loadAudioDecoder(); + + const decoding = decodeAudioData(new ArrayBuffer(8)); + + expect(decoder.decodeWithMemoryBlock).toHaveBeenCalledTimes(1); + await decoding; + }); + + it('downloads a remote source before opening it', async () => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + const arrayBuffer = new ArrayBuffer(8); + const fetchOptions = { headers: { Authorization: 'token' } }; + const fetchMock = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + arrayBuffer: () => Promise.resolve(arrayBuffer), + }); + globalThis.fetch = fetchMock as unknown as typeof fetch; + + await openAudioDecodeStream('https://example.com/audio.mp3', { + fetchOptions, + }); + + expect(fetchMock).toHaveBeenCalledWith( + 'https://example.com/audio.mp3', + fetchOptions + ); + expect(decoder.openStreamWithMemoryBlock).toHaveBeenCalledTimes(1); + expect(decoder.openStreamWithFilePath).not.toHaveBeenCalled(); + }); + + // An error page is not audio: it would fail later, as an invalid format. + it('rejects a download the server refused, with its status', async () => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + globalThis.fetch = jest.fn().mockResolvedValue({ + ok: false, + status: 404, + arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)), + }) as unknown as typeof fetch; + + await expect( + openAudioDecodeStream('https://example.com/missing.mp3') + ).rejects.toThrow('HTTP 404'); + expect(decoder.openStreamWithMemoryBlock).not.toHaveBeenCalled(); + }); + + // The native side converts the rate to an integer, which is undefined for + // these values. + it.each([Number.NaN, Number.POSITIVE_INFINITY, -44100, 0, 1e12])( + 'rejects a sample rate of %p without reaching the decoder', + async (sampleRate) => { + const decoder = installDecoder(createNativeStream()); + const { openAudioDecodeStream } = loadAudioDecoder(); + + await expect( + openAudioDecodeStream('/tmp/audio.wav', { sampleRate }) + ).rejects.toThrow('sampleRate must be a number in [3000, 768000]'); + await expect( + openAudioDecodeStream(new ArrayBuffer(8), { sampleRate }) + ).rejects.toThrow('sampleRate must be a number in [3000, 768000]'); + expect(decoder.openStreamWithFilePath).not.toHaveBeenCalled(); + expect(decoder.openStreamWithMemoryBlock).not.toHaveBeenCalled(); + } + ); + + // In an Android release build, a bundled asset comes as the name of its + // resource, read through the native module: a path is not one. + it('opens an absolute path as a file in an Android release build', async () => { + const decoder = installDecoder(createNativeStream()); + const reactNative = require('react-native') as { + Platform: { OS: string }; + }; + reactNative.Platform.OS = 'android'; + const globalWithDev = globalThis as { __DEV__?: boolean }; + const wasDev = globalWithDev.__DEV__; + globalWithDev.__DEV__ = false; + const { openAudioDecodeStream } = loadAudioDecoder(); + + await openAudioDecodeStream('/data/user/0/app/files/audio.wav'); + globalWithDev.__DEV__ = wasDev; + + expect(decoder.openStreamWithFilePath).toHaveBeenCalledWith( + '/data/user/0/app/files/audio.wav', + 0 + ); + expect(decoder.openStreamWithMemoryBlock).not.toHaveBeenCalled(); + }); + + it('rejects when the source cannot be opened', async () => { + const decoder = installDecoder(createNativeStream()); + decoder.openStreamWithFilePath.mockRejectedValue( + new Error('Cannot decode file: unsupported or invalid audio format') + ); + const { openAudioDecodeStream } = loadAudioDecoder(); + + await expect(openAudioDecodeStream('/tmp/broken.wav')).rejects.toThrow( + 'Cannot decode file' + ); + }); +}); + +describe('AudioDecodeStream', () => { + beforeEach(() => { + jest.resetModules(); + }); + + const openStream = async (nativeStream: IAudioDecodeStream) => { + installDecoder(nativeStream); + return loadAudioDecoder().openAudioDecodeStream('/tmp/audio.wav'); + }; + + it('wraps each chunk in an AudioBuffer', async () => { + const nativeStream = createNativeStream(); + nativeStream.read.mockResolvedValue(createNativeBuffer(4096)); + const stream = await openStream(nativeStream); + + const chunk = await stream.read(4096); + + expect(nativeStream.read).toHaveBeenCalledWith(4096); + expect(chunk?.length).toBe(4096); + expect(chunk?.numberOfChannels).toBe(2); + }); + + it('resolves null once the source has ended', async () => { + const nativeStream = createNativeStream(); + nativeStream.read.mockResolvedValue(null); + const stream = await openStream(nativeStream); + + await expect(stream.read(4096)).resolves.toBeNull(); + }); + + it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, 2 ** 60])( + 'rejects a read of %p frames without reaching the decoder', + async (frameCount) => { + const nativeStream = createNativeStream(); + const stream = await openStream(nativeStream); + + await expect(stream.read(frameCount)).rejects.toThrow( + 'frameCount must be a positive integer' + ); + expect(nativeStream.read).not.toHaveBeenCalled(); + } + ); + + it('seeks to a position in seconds', async () => { + const nativeStream = createNativeStream(); + const stream = await openStream(nativeStream); + + await stream.seek(1.5); + + expect(nativeStream.seek).toHaveBeenCalledWith(1.5); + }); + + it.each([-1, Number.NaN, Number.POSITIVE_INFINITY])( + 'rejects a seek to %p without reaching the decoder', + async (seconds) => { + const nativeStream = createNativeStream(); + const stream = await openStream(nativeStream); + + await expect(stream.seek(seconds)).rejects.toThrow( + 'seconds must be a non-negative finite number' + ); + expect(nativeStream.seek).not.toHaveBeenCalled(); + } + ); + + it('closes the native stream', async () => { + const nativeStream = createNativeStream(); + const stream = await openStream(nativeStream); + + stream.close(); + await settleOperations(); + + expect(nativeStream.close).toHaveBeenCalledTimes(1); + }); + + // The native lane blocks its caller, the JS thread, once its queue is full: + // a burst of reads must wait in JS. + it('hands the native stream one operation at a time, in order', async () => { + const nativeStream = createNativeStream(); + const pendingReads: Array<(buffer: IAudioBuffer | null) => void> = []; + nativeStream.read.mockImplementation( + () => new Promise((resolve) => pendingReads.push(resolve)) + ); + const stream = await openStream(nativeStream); + + const reads = [1024, 2048, 4096].map((frameCount) => + stream.read(frameCount) + ); + stream.close(); + await settleOperations(); + + expect(nativeStream.read.mock.calls).toEqual([[1024]]); + + pendingReads[0]!(createNativeBuffer(1024)); + await settleOperations(); + expect(nativeStream.read.mock.calls).toEqual([[1024], [2048]]); + expect(nativeStream.close).not.toHaveBeenCalled(); + + pendingReads[1]!(createNativeBuffer(2048)); + await settleOperations(); + pendingReads[2]!(null); + + const chunks = await Promise.all(reads); + expect(chunks.map((chunk) => chunk?.length ?? null)).toEqual([ + 1024, + 2048, + null, + ]); + await settleOperations(); + expect(nativeStream.close).toHaveBeenCalledTimes(1); + }); + + // The native stream gives its worker thread up when it is closed: nothing + // may reach it afterwards. + it('rejects reads and seeks once closed, without reaching the native stream', async () => { + const nativeStream = createNativeStream(); + const stream = await openStream(nativeStream); + + stream.close(); + stream.close(); + + await expect(stream.read(512)).rejects.toThrow( + 'Cannot read from a closed decode stream' + ); + await expect(stream.seek(1)).rejects.toThrow( + 'Cannot seek in a closed decode stream' + ); + await settleOperations(); + expect(nativeStream.read).not.toHaveBeenCalled(); + expect(nativeStream.seek).not.toHaveBeenCalled(); + expect(nativeStream.close).toHaveBeenCalledTimes(1); + }); + + it('keeps reading after a read has failed', async () => { + const nativeStream = createNativeStream(); + nativeStream.read + .mockRejectedValueOnce(new Error('Cannot decode')) + .mockResolvedValueOnce(createNativeBuffer(512)); + const stream = await openStream(nativeStream); + + const failed = stream.read(512); + const next = stream.read(512); + + await expect(failed).rejects.toThrow('Cannot decode'); + await expect(next).resolves.toMatchObject({ length: 512 }); + }); +}); + +describe('AudioDecodeStream on web', () => { + const originalAudioBuffer = globalThis.AudioBuffer; + + /** The part of the browser AudioBuffer the web stream relies on. */ + class BrowserAudioBufferStub { + readonly length: number; + readonly sampleRate: number; + readonly numberOfChannels: number; + readonly duration: number; + private readonly channels: Float32Array[]; + + constructor(options: { + length: number; + numberOfChannels: number; + sampleRate: number; + }) { + this.length = options.length; + this.sampleRate = options.sampleRate; + this.numberOfChannels = options.numberOfChannels; + this.duration = options.length / options.sampleRate; + this.channels = Array.from( + { length: options.numberOfChannels }, + () => new Float32Array(options.length) + ); + } + + getChannelData(channel: number): Float32Array { + return this.channels[channel]; + } + + copyToChannel(source: Float32Array, channel: number): void { + this.channels[channel].set(source); + } + } + + const sampleRate = 8000; + const length = 10; + + const createStream = () => { + const { default: AudioBuffer } = + require('../src/web-core/AudioBuffer.web') as WebAudioBufferExports; + const { default: AudioDecodeStream } = + require('../src/web-core/AudioDecodeStream.web') as WebAudioDecodeStreamExports; + + const decoded = new AudioBuffer({ + length, + numberOfChannels: 1, + sampleRate, + }); + decoded.getChannelData(0).set(Array.from({ length }, (_, i) => i)); + return new AudioDecodeStream(decoded); + }; + + beforeEach(() => { + jest.resetModules(); + (globalThis as unknown as { AudioBuffer: unknown }).AudioBuffer = + BrowserAudioBufferStub; + }); + + afterEach(() => { + (globalThis as unknown as { AudioBuffer: unknown }).AudioBuffer = + originalAudioBuffer; + }); + + it('hands out the decoded audio in consecutive chunks', async () => { + const stream = createStream(); + + const first = await stream.read(4); + const second = await stream.read(4); + const last = await stream.read(4); + + expect(Array.from(first!.getChannelData(0))).toEqual([0, 1, 2, 3]); + expect(Array.from(second!.getChannelData(0))).toEqual([4, 5, 6, 7]); + expect(Array.from(last!.getChannelData(0))).toEqual([8, 9]); + await expect(stream.read(4)).resolves.toBeNull(); + }); + + it('reads from the position it was moved to', async () => { + const stream = createStream(); + + await stream.seek(6 / sampleRate); + const chunk = await stream.read(2); + + expect(Array.from(chunk!.getChannelData(0))).toEqual([6, 7]); + }); + + it('rejects reads and seeks once closed', async () => { + const stream = createStream(); + + stream.close(); + + await expect(stream.read(4)).rejects.toThrow('closed decode stream'); + await expect(stream.seek(0)).rejects.toThrow('closed decode stream'); + }); +}); diff --git a/packages/react-native-audio-api/tests/audio-decoder.test.ts b/packages/react-native-audio-api/tests/audio-decoder.test.ts index 029c7ba8a2..b5960f32a1 100644 --- a/packages/react-native-audio-api/tests/audio-decoder.test.ts +++ b/packages/react-native-audio-api/tests/audio-decoder.test.ts @@ -129,6 +129,22 @@ describe('getAudioDuration', () => { ); }); + it('keeps the percent sequences of a bare path, which name the file', async () => { + const fileUtils = createFileUtils(); + installFileUtils(fileUtils); + installDecoder(createDecoder()); + + const { getAudioDuration } = loadAudioFileUtils(); + + await getAudioDuration('/tmp/clip%20mix.wav'); + + expect(fileUtils.probeDuration).toHaveBeenCalledWith( + '/tmp/clip%20mix.wav', + 0, + undefined + ); + }); + it('probes ArrayBuffer input through audio file utils', async () => { const fileUtils = createFileUtils(8.25); installFileUtils(fileUtils); diff --git a/packages/react-native-audio-api/tests/mock.test.ts b/packages/react-native-audio-api/tests/mock.test.ts index e1752bdcb7..5cefe3be61 100644 --- a/packages/react-native-audio-api/tests/mock.test.ts +++ b/packages/react-native-audio-api/tests/mock.test.ts @@ -273,6 +273,47 @@ describe('React Native Audio API Mocks', () => { }); describe('Utility Functions', () => { + it('should open a decode stream at the requested sample rate', async () => { + const stream = await MockAPI.openAudioDecodeStream(new ArrayBuffer(8), { + sampleRate: 22050, + }); + + expect(stream.sampleRate).toBe(22050); + await expect(stream.read(30000)).resolves.toMatchObject({ + length: 22050, + sampleRate: 22050, + }); + }); + + it('should reject a decode stream at an invalid sample rate', async () => { + await expect( + MockAPI.openAudioDecodeStream(new ArrayBuffer(8), { + sampleRate: Number.NaN, + }) + ).rejects.toThrow('sampleRate must be a number'); + }); + + it('should hand out a decode stream in chunks until it ends', async () => { + const stream = await MockAPI.openAudioDecodeStream(new ArrayBuffer(8)); + + expect(stream.sampleRate).toBe(44100); + expect(stream.numberOfChannels).toBe(2); + expect(stream.duration).toBe(1); + + const first = await stream.read(40000); + const last = await stream.read(40000); + + expect(first?.length).toBe(40000); + expect(last?.length).toBe(4100); + await expect(stream.read(40000)).resolves.toBeNull(); + + await stream.seek(0.5); + expect((await stream.read(40000))?.length).toBe(22050); + + stream.close(); + await expect(stream.read(40000)).rejects.toThrow('closed decode stream'); + }); + it('should decode audio data', async () => { const arrayBuffer = new ArrayBuffer(1024); const buffer = await MockAPI.decodeAudioData(arrayBuffer);