diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 245fba8..83822e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,10 @@ jobs: - name: Unit tests run: yarn test:unit + # The Android C++ helpers that need no NDK, under ASan and UBSan. + - name: C++ host tests + run: yarn test:cpp + - name: Build the package run: yarn build diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 39300c7..e440fc4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,7 +39,12 @@ or pick "My Mac (Designed for iPad)" in Xcode and run it from there. ## Testing **Unit tests** (`yarn test:unit`, `src/__tests__/unit`) cover the -`WritableStream` and Mediabunny writing through it, in Node. +`WritableStream` and Mediabunny writing through it, in Node. `yarn test:jvm` +runs the JVM tests of the Android encoder rules (`EncoderRules.java`, under +`android/src/test/java`) through the example app's Gradle. `yarn test:cpp` +builds the host tests of the Android C++ helpers that need no NDK +(`android/src/test/cpp/*_test.cpp`) with clang, under AddressSanitizer and +UndefinedBehaviorSanitizer, and runs them. **End-to-end tests** (`src/__tests__/WebCodecs.spec.ts`) run on a simulator or emulator with the example app, and check the files with ffprobe and @@ -50,6 +55,14 @@ ffmpeg on the host: 2. Launch the app on a simulator or emulator. 3. At the repository root, run `yarn test`. +To share the machine with other projects, start Metro on another port +(`yarn start --port 8102`) and give Metro and `yarn test` the same +`E2E_PORT` (for example `E2E_PORT=4300`, with Metro's `--reset-cache`). +The app reaches the test server on `localhost`, through `adb reverse` on +Android; where that does not work, start Metro with +`E2E_ANDROID_HOST=10.0.2.2` (the emulator's address for this machine). With +several Android devices attached, set `ANDROID_SERIAL` for `yarn test`. + They cover: - 60 frames at 128×128 in memory: H.264, no B-frames, BT.709 tags, colors diff --git a/README.md b/README.md index 4f16890..94ec750 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,8 @@ const FRAME_COUNT = 7 * FRAME_RATE; // a 7 s video const BITRATE = 8_000_000; // bits per second (8 Mbps) const MICROSECONDS_PER_SECOND = 1_000_000; // WebCodecs times are in µs const FRAME_DURATION = MICROSECONDS_PER_SECOND / FRAME_RATE; +// RNWebGPU is the global react-native-webgpu installs; `device` is your +// GPUDevice (navigator.gpu.requestAdapter(), then requestDevice()). const file = createFileWritable("export.mp4"); // in the cache directory const output = new Output({ @@ -190,11 +192,12 @@ for (let i = 0; i < FRAME_COUNT; i++) { buffer.release(); const frame = new VideoFrame(surface, { - timestamp: i * FRAME_DURATION, + timestamp: i * FRAME_DURATION, // must grow from frame to frame duration: FRAME_DURATION, fence: fences[0], // the encoder waits for it natively }); - const sample = new VideoSample(frame); + // Mediabunny is typed for the DOM's VideoFrame; this one stands in for it. + const sample = new VideoSample(frame as unknown as globalThis.VideoFrame); try { await video.add(sample); // resolves once the encoder has room } finally { diff --git a/android/build.gradle b/android/build.gradle index 3209fb4..0f67d45 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -94,4 +94,6 @@ repositories { dependencies { implementation "com.facebook.react:react-native:+" implementation project(":react-native-nitro-modules") + // Plain JVM tests of the pure rules (EncoderRules): `yarn test:jvm`. + testImplementation "junit:junit:4.13.2" } diff --git a/android/src/main/cpp/Audio.hpp b/android/src/main/cpp/Audio.hpp index fc6c207..640b85a 100644 --- a/android/src/main/cpp/Audio.hpp +++ b/android/src/main/cpp/Audio.hpp @@ -6,7 +6,10 @@ #include #include #include +#include +#include +#include "AudioRules.hpp" #include "Common.hpp" #include "HybridNativeAudioDecoderSpec.hpp" #include "HybridNativeAudioEncoderSpec.hpp" @@ -25,20 +28,25 @@ class AudioCodec { stop(); } - void start(AMediaFormat* format, bool encoder, const std::string& mime) { + // Starts the first of `names` that exists and takes `format`, else the + // platform's default for `mime`. Returns the codec's name ("" when the + // platform does not tell it). + std::string start(AMediaFormat* format, bool encoder, const std::string& mime, + std::initializer_list names = {}) { + for (const char* name : names) { + if ((_codec = AMediaCodec_createCodecByName(name)) && configureAndStart(format, encoder) == AMEDIA_OK) { + return name; + } + } _codec = encoder ? AMediaCodec_createEncoderByType(mime.c_str()) : AMediaCodec_createDecoderByType(mime.c_str()); if (!_codec) { throw domError("NotSupportedError", "no MediaCodec for " + mime); } - media_status_t status = AMediaCodec_configure(_codec, format, nullptr, nullptr, encoder ? AMEDIACODEC_CONFIGURE_FLAG_ENCODE : 0); - if (status == AMEDIA_OK) { - status = AMediaCodec_start(_codec); - } + media_status_t status = configureAndStart(format, encoder); if (status != AMEDIA_OK) { - AMediaCodec_delete(_codec); - _codec = nullptr; throw domError("NotSupportedError", "MediaCodec " + mime + " failed to start (" + std::to_string(status) + ")"); } + return codecName(_codec).value_or(""); } void stop() { @@ -93,9 +101,26 @@ class AudioCodec { } private: + // Configures and starts _codec; on failure, deletes it. + media_status_t configureAndStart(AMediaFormat* format, bool encoder) { + media_status_t status = AMediaCodec_configure(_codec, format, nullptr, nullptr, encoder ? AMEDIACODEC_CONFIGURE_FLAG_ENCODE : 0); + if (status == AMEDIA_OK) { + status = AMediaCodec_start(_codec); + } + if (status != AMEDIA_OK) { + AMediaCodec_delete(_codec); + _codec = nullptr; + } + return status; + } + AMediaCodec* _codec = nullptr; }; +// flush() pads with kAacPaddingFrames frames of silence, enough to push out +// the encoder's delay (aacEncoderDelay) and a partial last frame. +constexpr int64_t kAacPaddingFrames = 3; + // AAC-LC from f32 interleaved PCM. class HybridNativeAudioEncoder : public HybridNativeAudioEncoderSpec { public: @@ -138,6 +163,10 @@ class HybridNativeAudioEncoder : public HybridNativeAudioEncoderSpec { _codec.stop(); start(); } + if (!_firstPts.has_value()) { + _firstPts = ts; + } + _framesIn += static_cast(s16.size()) / _channels; const auto* bytes = reinterpret_cast(s16.data()); size_t size = s16.size() * sizeof(int16_t); // pts of a byte offset: offset / (2 * channels) / sampleRate seconds. @@ -159,9 +188,23 @@ class HybridNativeAudioEncoder : public HybridNativeAudioEncoderSpec { return promise; } _queue.post([this, promise] { - if (!_failed && !_ended) { - media_status_t status = _codec.feed(nullptr, 0, _lastPts, 0, 0, kBufferFlagEndOfStream, - [this](int64_t timeout) { return drain(timeout); }); + // Nothing fed since start() (or since the last flush): nothing to + // output, so no padding and no end of stream; the codec stays as is. + if (!_failed && !_ended && _framesIn > 0) { + // What the encoder still holds (its delay, and the last partial + // frame) must come out before the end of stream: Codec2's AAC + // encoder flushes it at EOS, but MediaCodec then discards those + // late outputs. Silence pushes them out as ordinary frames; drain() + // keeps only the frames that carry input. + std::vector silence(static_cast(kAacPaddingFrames) * 1024 * _channels, 0); + int64_t end = inputEndPts(); + media_status_t status = + _codec.feed(reinterpret_cast(silence.data()), silence.size() * sizeof(int16_t), end, 1000000, + int64_t(2) * _channels * _sampleRate, 0, [this](int64_t timeout) { return drain(timeout); }); + if (status == AMEDIA_OK) { + status = _codec.feed(nullptr, 0, end + kAacPaddingFrames * 1024 * 1000000LL / _sampleRate, 0, 0, + kBufferFlagEndOfStream, [this](int64_t timeout) { return drain(timeout); }); + } for (int i = 0; status == AMEDIA_OK && !_eos && i < 2000; i++) { status = drain(5000); } @@ -193,18 +236,35 @@ class HybridNativeAudioEncoder : public HybridNativeAudioEncoderSpec { AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, _sampleRate); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, _channels); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_AAC_PROFILE, 2); // LC + // The same, for encoders that read only "profile" (AACObjectLC). The + // literal: AMEDIAFORMAT_KEY_PROFILE is API 28, above our minimum (26). + AMediaFormat_setInt32(format, "profile", 2); double bitrate = _config.bitrate.value_or(0); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_BIT_RATE, bitrate > 0 ? static_cast(bitrate) : 128000); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, 64 * 1024); + std::string name; try { - _codec.start(format, true, "audio/mp4a-latm"); + // FDK by name when there, whose delay is known; then the default. + name = _codec.start(format, true, "audio/mp4a-latm", {kAacEncoderNames[0], kAacEncoderNames[1]}); } catch (...) { AMediaFormat_delete(format); throw; } AMediaFormat_delete(format); + _delay = aacEncoderDelay(name); + WC_LOG("audio encoder: %s (delay %lld)", name.empty() ? "?" : name.c_str(), + static_cast(_delay.value_or(-1))); _ended = false; _eos = false; + // A new stream: timed from its own first input. + _firstPts.reset(); + _framesIn = 0; + _framesOut = 0; + } + + // The end of the input fed since start(), in µs. + int64_t inputEndPts() const { + return _firstPts.value_or(0) + _framesIn * 1000000LL / _sampleRate; } void sync() { @@ -237,16 +297,21 @@ class HybridNativeAudioEncoder : public HybridNativeAudioEncoderSpec { const uint8_t* bytes = data + info.offset; if (info.flags & kBufferFlagCodecConfig) { _config_bytes.assign(bytes, bytes + info.size); - } else if (!_closed) { + } else if (!_closed && aacKeepFrame(_framesOut, _framesIn, _delay)) { + // (Past that, a frame holds only the silence flush() added.) std::optional> description; if (!_config_bytes.empty() && _config_bytes != _sentDescription) { _sentDescription = _config_bytes; description = ArrayBuffer::copy(_config_bytes); } double duration = 1024.0 * 1e6 / _sampleRate; - _lastPts = info.presentationTimeUs; - _output(NativeEncodedChunk(ArrayBuffer::copy(bytes, info.size), static_cast(info.presentationTimeUs), - duration, true, description)); + // Timed by frame count from the first input, as on iOS: the + // codec's own timestamps follow the input buffers' boundaries + // and jump at the end of stream. + double pts = static_cast(_firstPts.value_or(0)) + + std::round(static_cast(_framesOut) * 1024.0 * 1e6 / _sampleRate); + _framesOut++; + _output(NativeEncodedChunk(ArrayBuffer::copy(bytes, info.size), pts, duration, true, description)); } } AMediaCodec_releaseOutputBuffer(_codec.get(), index, false); @@ -280,7 +345,13 @@ class HybridNativeAudioEncoder : public HybridNativeAudioEncoderSpec { AudioCodec _codec; std::vector _config_bytes; std::vector _sentDescription; - int64_t _lastPts = 0; + // Timing of the current stream: the first input's timestamp, the sample + // frames fed, and the AAC frames output. + std::optional _firstPts; + int64_t _framesIn = 0; + int64_t _framesOut = 0; + // The encoder's delay in sample frames, when known (FDK's). + std::optional _delay; bool _ended = false; bool _eos = false; @@ -294,34 +365,21 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { std::function output, std::function error) : HybridObject(TAG), _output(std::move(output)), _error(std::move(error)) { - _sampleRate = static_cast(config.sampleRate); - _channels = static_cast(config.numberOfChannels); - std::string mime; + _sampleRate = _configSampleRate = static_cast(config.sampleRate); + _channels = _configChannels = static_cast(config.numberOfChannels); if (config.codec == "aac") { - mime = "audio/mp4a-latm"; + _mime = "audio/mp4a-latm"; } else if (config.codec == "mp3") { - mime = "audio/mpeg"; + _mime = "audio/mpeg"; } else { throw domError("NotSupportedError", "codec " + config.codec); } - AMediaFormat* format = AMediaFormat_new(); - AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, mime.c_str()); - AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, _sampleRate); - AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, _channels); - if (config.codec == "aac") { - AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_IS_ADTS, 0); - if (config.description.has_value() && config.description.value()) { - auto& d = config.description.value(); - AMediaFormat_setBuffer(format, "csd-0", d->data(), d->size()); - } - } - try { - _codec.start(format, false, mime); - } catch (...) { - AMediaFormat_delete(format); - throw; + // Copied: a new codec may be started on the worker thread (flush()). + if (_mime == "audio/mp4a-latm" && config.description.has_value() && config.description.value()) { + auto& d = config.description.value(); + _csd.assign(d->data(), d->data() + d->size()); } - AMediaFormat_delete(format); + startCodec(); } ~HybridNativeAudioDecoder() override { @@ -347,6 +405,7 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { } media_status_t status = _codec.feed(bytes.data(), bytes.size(), ts, 0, 0, 0, [this](int64_t t) { return drain(t); }); if (status == AMEDIA_OK) { + _fedSinceFlush++; status = drain(0); } if (status != AMEDIA_OK) { @@ -362,7 +421,8 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { return promise; } _queue.post([this, promise] { - if (!_failed) { + DecoderFlush action = decoderFlushAction(_fedSinceFlush, _formatSeen); + if (!_failed && action != DecoderFlush::Skip) { _eos = false; media_status_t status = _codec.feed(nullptr, 0, 0, 0, 0, kBufferFlagEndOfStream, [this](int64_t t) { return drain(t); }); for (int i = 0; status == AMEDIA_OK && !_eos && i < 2000; i++) { @@ -370,9 +430,18 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { } if (status != AMEDIA_OK) { fail(describeCodecStatus(status, "decoder", "decoder")); - } else { + } else if (action == DecoderFlush::Flush) { AMediaCodec_flush(_codec.get()); + } else { + WC_LOG("audio decoder: no output format before flush, starting a new codec"); + _codec.stop(); + try { + startCodec(); + } catch (const std::exception& e) { + fail(e.what()); + } } + _fedSinceFlush = 0; } if (_failed) { promise->reject(std::make_exception_ptr(std::runtime_error(_failure))); @@ -390,6 +459,31 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { } private: + // A codec for the config, timed and sized from it again. + void startCodec() { + AMediaFormat* format = AMediaFormat_new(); + AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, _mime.c_str()); + AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, _configSampleRate); + AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, _configChannels); + if (_mime == "audio/mp4a-latm") { + AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_IS_ADTS, 0); + if (!_csd.empty()) { + AMediaFormat_setBuffer(format, "csd-0", _csd.data(), _csd.size()); + } + } + try { + _codec.start(format, false, _mime); + } catch (...) { + AMediaFormat_delete(format); + throw; + } + AMediaFormat_delete(format); + _sampleRate = _configSampleRate; + _channels = _configChannels; + _fedSinceFlush = 0; + _formatSeen = false; + } + media_status_t drain(int64_t timeoutUs) { while (true) { AMediaCodecBufferInfo info{}; @@ -401,6 +495,7 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { continue; } if (index == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { + _formatSeen = true; AMediaFormat* format = AMediaCodec_getOutputFormat(_codec.get()); int32_t value = 0; if (AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, &value) && value > 0) { @@ -418,6 +513,9 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { timeoutUs = 0; size_t capacity = 0; uint8_t* data = AMediaCodec_getOutputBuffer(_codec.get(), index, &capacity); + if (data && info.size > 0) { + _formatSeen = true; + } if (data && info.size > 0 && !_closed) { // s16 interleaved → f32 interleaved. size_t samples = info.size / sizeof(int16_t); @@ -454,11 +552,21 @@ class HybridNativeAudioDecoder : public HybridNativeAudioDecoderSpec { std::atomic _closed{false}; std::string _failure; - // Worker thread only. + // The config, for a new codec. + std::string _mime; + int32_t _configSampleRate = 44100; + int32_t _configChannels = 2; + std::vector _csd; + + // Worker thread only (and the constructor). AudioCodec _codec; int32_t _sampleRate = 44100; int32_t _channels = 2; bool _eos = false; + // Inputs fed since the codec started or was last flushed, and whether it + // has given an output format (or output) since it started. + int64_t _fedSinceFlush = 0; + bool _formatSeen = false; SerialQueue _queue{"wc-adec"}; }; diff --git a/android/src/main/cpp/AudioRules.hpp b/android/src/main/cpp/AudioRules.hpp new file mode 100644 index 0000000..78fafd7 --- /dev/null +++ b/android/src/main/cpp/AudioRules.hpp @@ -0,0 +1,58 @@ +#pragma once + +// The audio codecs' rules that need no NDK, so that a host test +// (android/src/test/cpp, `yarn test:cpp`) can check them. + +#include +#include +#include + +namespace margelo::nitro::webcodecs { + +// The AAC encoders asked for by name, in order, before any other: FDK, whose +// delay is known (c2.android.aac.encoder from API 29, OMX.google.aac.encoder +// before). Whatever "audio/mp4a-latm" gives comes after them. +inline constexpr const char* kAacEncoderNames[] = {"c2.android.aac.encoder", "OMX.google.aac.encoder"}; + +// The AAC-LC encoder's delay in sample frames, when known: FDK's, +// 1024 + 576. Unknown for any other encoder. +inline std::optional aacEncoderDelay(std::string_view name) { + for (std::string_view fdk : kAacEncoderNames) { + if (name == fdk) { + return 1600; + } + } + return std::nullopt; +} + +// Whether the AAC frame numbered `framesOut` (from 0) carries input, of +// `framesIn` sample frames, given the encoder's delay: frames past the input +// plus the delay hold only the silence flush() pads with. With the delay +// unknown, every frame is kept (at worst a few frames of that silence). +inline bool aacKeepFrame(int64_t framesOut, int64_t framesIn, std::optional delay) { + return !delay.has_value() || framesOut * 1024 < framesIn + *delay; +} + +// What a decoder's flush() does with its codec. +enum class DecoderFlush { + // Nothing fed since the last flush: nothing to drain. No end of stream is + // queued (as a first input it can lose the AAC config on API 29's + // c2.android.aac.decoder) and the codec is left as it is. + Skip, + // An end of stream, drained, then AMediaCodec_flush. + Flush, + // An end of stream, drained, then a new codec: flushed before its first + // output format, a codec forgets its config (csd) (b/141097367, API 29's + // c2.android.aac.decoder; Media3 releases the codec then too). Done for + // every decoder, so no name or API level is checked. + Recreate, +}; + +inline DecoderFlush decoderFlushAction(int64_t fedSinceFlush, bool formatSeen) { + if (fedSinceFlush == 0) { + return DecoderFlush::Skip; + } + return formatSeen ? DecoderFlush::Flush : DecoderFlush::Recreate; +} + +} // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/Capabilities.hpp b/android/src/main/cpp/Capabilities.hpp index 0dc74ef..5c27515 100644 --- a/android/src/main/cpp/Capabilities.hpp +++ b/android/src/main/cpp/Capabilities.hpp @@ -3,7 +3,9 @@ #include #include +#include #include +#include namespace margelo::nitro::webcodecs { @@ -18,22 +20,112 @@ struct JCapabilities : facebook::jni::JavaClass { javaClassStatic(); } - // The name of the first encoder for `mime` that takes this config, or none. - // frameRate, bitrate and profile are ignored when 0 or less. - static std::optional findVideoEncoder(const std::string& mime, int width, int height, double frameRate, int bitrate, - int profile, int colorFormat) { + // The name of the encoder for `mime` that takes this size, profile + // (ignored when 0 or less; dropped when `profileOptional` and no encoder + // takes it) and input color format, or none: see Capabilities.java. The + // frame rate and bitrate are hints, which refuse no encoder. + static std::optional findVideoEncoder(const std::string& mime, int width, int height, int profile, bool profileOptional, + int colorFormat) { std::optional name; facebook::jni::ThreadScope::WithClassLoader([&] { static const auto method = - javaClassStatic()->getStaticMethod(facebook::jni::alias_ref, jint, jint, jdouble, jint, jint, jint)>( + javaClassStatic()->getStaticMethod(facebook::jni::alias_ref, jint, jint, jint, jboolean, jint)>( "findVideoEncoder"); - auto result = method(javaClassStatic(), facebook::jni::make_jstring(mime), width, height, frameRate, bitrate, profile, colorFormat); + auto result = method(javaClassStatic(), facebook::jni::make_jstring(mime), width, height, profile, profileOptional ? JNI_TRUE : JNI_FALSE, colorFormat); if (result) { name = result->toStdString(); } }); return name; } + + // Every encoder that may take the config, best first (findVideoEncoder's + // answer first): see Capabilities.findVideoEncoders. + static std::vector findVideoEncoders(const std::string& mime, int width, int height, int profile, bool profileOptional, + int colorFormat) { + std::vector names; + facebook::jni::ThreadScope::WithClassLoader([&] { + static const auto method = + javaClassStatic()->getStaticMethod(facebook::jni::alias_ref, jint, jint, jint, jboolean, jint)>( + "findVideoEncoders"); + auto result = method(javaClassStatic(), facebook::jni::make_jstring(mime), width, height, profile, profileOptional ? JNI_TRUE : JNI_FALSE, colorFormat); + if (result) { + std::istringstream lines(result->toStdString()); + std::string line; + while (std::getline(lines, line)) { + if (!line.empty()) { + names.push_back(line); + } + } + } + }); + return names; + } + + // The bitrate to configure the encoder `name` with: `requested`, or when 0 + // or less width * height * fps * 0.1, clamped into the encoder's range. + static int32_t videoBitrate(const std::string& name, const std::string& mime, double requested, int width, int height, + double frameRate) { + int32_t bitrate = 0; + facebook::jni::ThreadScope::WithClassLoader([&] { + static const auto method = + javaClassStatic() + ->getStaticMethod, facebook::jni::alias_ref, jdouble, + jint, jint, jdouble)>("videoBitrate"); + bitrate = method(javaClassStatic(), facebook::jni::make_jstring(name), facebook::jni::make_jstring(mime), requested, width, height, + frameRate); + }); + return bitrate; + } + + // The H.264 profile and level (MediaCodecInfo.CodecProfileLevel) to give + // the encoder `name`: `profile`, or the next one down it lists (High, + // Main, Baseline); the codec string's level (`levelIdc`), raised to what + // the size and frame rate need, capped at the encoder's highest for the + // profile. None when it lists no profile that will do: it then gets + // neither. See EncoderRules.avcProfile and avcLevel. + struct AvcProfileLevel { + int32_t profile = 0; + int32_t level = 0; + }; + static AvcProfileLevel avcProfileLevel(const std::string& name, const std::string& mime, int profile, int levelIdc, int width, + int height, double frameRate) { + jlong packed = 0; + facebook::jni::ThreadScope::WithClassLoader([&] { + static const auto method = + javaClassStatic() + ->getStaticMethod, facebook::jni::alias_ref, jint, + jint, jint, jint, jdouble)>("avcProfileLevel"); + packed = method(javaClassStatic(), facebook::jni::make_jstring(name), facebook::jni::make_jstring(mime), profile, levelIdc, width, + height, frameRate); + }); + return {static_cast(packed >> 32), static_cast(packed & 0xFFFFFFFF)}; + } + + // The decoders for `mime` that take this size, in the platform's order: + // with "prefer-software" only software ones, with "prefer-hardware" none + // of those. + static std::vector findVideoDecoders(const std::string& mime, int width, int height, const std::string& preference) { + std::vector names; + facebook::jni::ThreadScope::WithClassLoader([&] { + static const auto method = + javaClassStatic() + ->getStaticMethod(facebook::jni::alias_ref, jint, + jint, facebook::jni::alias_ref)>( + "findVideoDecoders"); + auto result = method(javaClassStatic(), facebook::jni::make_jstring(mime), width, height, facebook::jni::make_jstring(preference)); + if (result) { + std::istringstream lines(result->toStdString()); + std::string line; + while (std::getline(lines, line)) { + if (!line.empty()) { + names.push_back(line); + } + } + } + }); + return names; + } }; } // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/Common.hpp b/android/src/main/cpp/Common.hpp index f009897..be9f73c 100644 --- a/android/src/main/cpp/Common.hpp +++ b/android/src/main/cpp/Common.hpp @@ -1,12 +1,15 @@ #pragma once #include +#include +#include #include #include #include #include #include +#include #include #include #include @@ -27,6 +30,22 @@ inline std::string errorMessage(const std::string& name, const std::string& code return name + ": " + code + ": " + message; } +// A codec's name, when the platform tells it: AMediaCodec_getName is +// API 28, above this library's minimum (26). +inline std::optional codecName(AMediaCodec* codec) { + using GetName = media_status_t (*)(AMediaCodec*, char**); + using ReleaseName = void (*)(AMediaCodec*, char*); + static auto getName = reinterpret_cast(dlsym(RTLD_DEFAULT, "AMediaCodec_getName")); + static auto releaseName = reinterpret_cast(dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName")); + char* name = nullptr; + if (!codec || !getName || !releaseName || getName(codec, &name) != AMEDIA_OK || !name) { + return std::nullopt; + } + std::string result(name); + releaseName(codec, name); + return result; +} + // One worker thread running tasks in order. Declare it as the last member of // its owner: it is then destroyed first, after running what is left. class SerialQueue { diff --git a/android/src/main/cpp/EncoderAttempts.hpp b/android/src/main/cpp/EncoderAttempts.hpp new file mode 100644 index 0000000..dafe348 --- /dev/null +++ b/android/src/main/cpp/EncoderAttempts.hpp @@ -0,0 +1,122 @@ +#pragma once + +// The video encoder's configure attempts, with no NDK in them, so that a +// host test (android/src/test/cpp, `yarn test:cpp`) can check them. + +#include +#include +#include +#include + +namespace margelo::nitro::webcodecs { + +// The operating rate to ask for: as fast as the encoder goes (INT32_MAX), +// 1000 (some chipsets throw on INT32_MAX: Media3's +// deviceNeedsLowerOperatingRateAvoidingOverflowWorkaround), or none. +constexpr int32_t kOperatingRateMax = INT32_MAX; +constexpr int32_t kOperatingRateLow = 1000; +constexpr int32_t kOperatingRateNone = -1; + +// One configure() of the encoder: with or without H.264's profile and level, +// an operating rate (offline only), and the frame rate as asked or capped at +// 30 (KEY_FRAME_RATE only budgets the bitrate; some encoders refuse a high +// one even when they list it). +struct EncoderAttempt { + bool profile; + int32_t operatingRate; + bool capFrameRate; +}; + +// From the most to the least demanding, each attempt relaxing one setting +// some encoders refuse at configure time (as #641's writer, after Media3 and +// react-native-skia-video). The rate settings are relaxed with the profile +// kept first, then again without it: dropping the profile and level does not +// also cap the frame rate and drop the operating rate. `profile`: whether +// there is a profile (and level) that may be dropped. `realtime`: no +// operating rate is set. +inline std::vector videoEncoderAttempts(bool profile, bool realtime) { + std::vector rates; + if (realtime) { + rates = {{true, kOperatingRateNone, false}, {true, kOperatingRateNone, true}}; + } else { + rates = {{true, kOperatingRateMax, false}, {true, kOperatingRateLow, false}, {true, kOperatingRateNone, true}}; + } + std::vector attempts; + if (profile) { + attempts = rates; + } + for (EncoderAttempt attempt : rates) { + attempt.profile = false; + attempts.push_back(attempt); + } + return attempts; +} + +// For the log and the error message. +inline std::string describeAttempt(const EncoderAttempt& attempt) { + std::string text = attempt.profile ? "profile and level" : "no profile"; + if (attempt.operatingRate == kOperatingRateMax) { + text += ", operating rate max"; + } else if (attempt.operatingRate == kOperatingRateNone) { + text += ", no operating rate"; + } else { + text += ", operating rate " + std::to_string(attempt.operatingRate); + } + if (attempt.capFrameRate) { + text += ", at most 30 fps"; + } + return text; +} + +// The name of a media_status_t (NdkMediaError.h), or of a status_t that +// MediaCodec passes through (utils/Errors.h, -errno): "" when unknown. +inline const char* mediaStatusName(int32_t status) { + switch (status) { + case 1100: + return "ERROR_INSUFFICIENT_RESOURCE"; + case 1101: + return "ERROR_RECLAIMED"; + case -10000: + return "AMEDIA_ERROR_UNKNOWN"; + case -10001: + return "AMEDIA_ERROR_MALFORMED"; + case -10002: + return "AMEDIA_ERROR_UNSUPPORTED"; + case -10003: + return "AMEDIA_ERROR_INVALID_OBJECT"; + case -10004: + return "AMEDIA_ERROR_INVALID_PARAMETER"; + case -10005: + return "AMEDIA_ERROR_INVALID_OPERATION"; + case -10006: + return "AMEDIA_ERROR_END_OF_STREAM"; + case -10007: + return "AMEDIA_ERROR_IO"; + case -10008: + return "AMEDIA_ERROR_WOULD_BLOCK"; + case -12: + return "NO_MEMORY"; + case -19: + return "NO_INIT"; + case -22: + return "BAD_VALUE"; + case -32: + return "DEAD_OBJECT"; + case -38: + return "INVALID_OPERATION"; + case -110: + return "TIMED_OUT"; + case INT32_MIN: + return "UNKNOWN_ERROR"; + default: + return ""; + } +} + +// A status for a message: "-12 NO_MEMORY", or the number alone. +inline std::string describeMediaStatus(int32_t status) { + std::string name = mediaStatusName(status); + return name.empty() ? std::to_string(status) : std::to_string(status) + " " + name; +} + +} // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/Fence.hpp b/android/src/main/cpp/Fence.hpp new file mode 100644 index 0000000..8531aab --- /dev/null +++ b/android/src/main/cpp/Fence.hpp @@ -0,0 +1,80 @@ +#pragma once + +// Bounded CPU waits on a frame's GPU fence (a sync fd), with no NDK in them, +// so that a host test (android/src/test/cpp, `yarn test:cpp`) can check them +// with pipes standing in for fences. +// +// A fence that never signals (a hung GPU: MediaTek Mali drivers block in +// their sync wait for ever) must fail the frame, not block the GL thread, +// and with it flush(), close() and shutdown(), which queue behind it. Media3 +// waits 500 ms; heavy WebGPU frames can take longer, so 5 s, well inside the +// encoder's 20 s stall timeout. + +#include +#include + +#include +#include +#include +#include + +namespace margelo::nitro::webcodecs { + +constexpr int kFenceTimeoutMs = 5000; + +enum class FenceWait { Signaled, TimedOut, Failed }; + +// Waits up to `timeoutMs` for `fd` to signal (readable). Does not close it. +// No fence (fd < 0) has nothing to wait for. +inline FenceWait waitSyncFd(int fd, int timeoutMs) { + if (fd < 0) { + return FenceWait::Signaled; + } + using Clock = std::chrono::steady_clock; + const auto deadline = Clock::now() + std::chrono::milliseconds(timeoutMs); + for (;;) { + auto left = std::chrono::duration_cast(deadline - Clock::now()).count(); + pollfd p{fd, POLLIN, 0}; + int ready = ::poll(&p, 1, left > 0 ? static_cast(left) : 0); + if (ready < 0) { + if (errno == EINTR) { + // A signal: wait again, for what is left. + continue; + } + return FenceWait::Failed; + } + if (ready == 0) { + return FenceWait::TimedOut; + } + if (p.revents & (POLLERR | POLLNVAL)) { + return FenceWait::Failed; + } + if (p.revents & POLLIN) { + return FenceWait::Signaled; + } + // POLLHUP alone: nothing will ever signal it. + return FenceWait::Failed; + } +} + +inline std::string describeFenceWait(FenceWait wait, int timeoutMs) { + if (wait == FenceWait::TimedOut) { + return "the frame's GPU fence did not signal within " + std::to_string(timeoutMs) + " ms"; + } + return "waiting for the frame's GPU fence failed"; +} + +// Waits for a fence taken over (closed either way); throws when it does not +// signal within `timeoutMs`. +inline void awaitFence(int fd, int timeoutMs = kFenceTimeoutMs) { + if (fd < 0) { + return; + } + FenceWait wait = waitSyncFd(fd, timeoutMs); + ::close(fd); + if (wait != FenceWait::Signaled) { + throw std::runtime_error(describeFenceWait(wait, timeoutMs)); + } +} + +} // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/Files.hpp b/android/src/main/cpp/Files.hpp index bbe9668..95c6e3a 100644 --- a/android/src/main/cpp/Files.hpp +++ b/android/src/main/cpp/Files.hpp @@ -11,7 +11,9 @@ namespace margelo::nitro::webcodecs { -// The app's cache directory, from its package name. +// The app's cache directory, from its package name and Android user: +// /data/data is user 0's only, a work profile or secondary user has its +// files under /data/user/. inline std::string cacheDirectory() { static std::string directory = [] { std::ifstream cmdline("/proc/self/cmdline"); @@ -21,16 +23,49 @@ inline std::string cacheDirectory() { if (colon != std::string::npos) { name = name.substr(0, colon); } - return "/data/data/" + name + "/cache"; + // AID_USER_OFFSET: each Android user has 100000 uids. + unsigned user = static_cast(::getuid()) / 100000; + return "/data/user/" + std::to_string(user) + "/" + name + "/cache"; }(); return directory; } +// "%20" and the like in a file:// URL. +inline std::string percentDecode(const std::string& in) { + std::string out; + out.reserve(in.size()); + auto hex = [](char c) -> int { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; + }; + for (size_t i = 0; i < in.size(); i++) { + if (in[i] == '%' && i + 2 < in.size()) { + int high = hex(in[i + 1]); + int low = hex(in[i + 2]); + if (high >= 0 && low >= 0) { + out.push_back(static_cast(high * 16 + low)); + i += 2; + continue; + } + } + out.push_back(in[i]); + } + return out; +} + // Relative paths are in the cache directory; "file://" URLs are paths. inline std::string resolveFilePath(const std::string& path) { std::string p = path; if (p.rfind("file://", 0) == 0) { - p = p.substr(7); + p = percentDecode(p.substr(7)); } if (!p.empty() && p[0] == '/') { return p; @@ -38,9 +73,19 @@ inline std::string resolveFilePath(const std::string& path) { return cacheDirectory() + "/" + p; } +// mkdir -p of the directory a file goes in. +inline void makeParentDirectories(const std::string& file) { + for (size_t slash = file.find('/', 1); slash != std::string::npos; slash = file.find('/', slash + 1)) { + ::mkdir(file.substr(0, slash).c_str(), 0755); + } +} + class HybridNativeFile : public HybridNativeFileSpec { public: HybridNativeFile(std::string path, bool write) : HybridObject(TAG), _path(std::move(path)) { + if (write) { + makeParentDirectories(_path); + } _fd = ::open(_path.c_str(), write ? (O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC) : (O_RDONLY | O_CLOEXEC), 0644); if (_fd < 0) { if (errno == ENOENT) { diff --git a/android/src/main/cpp/Gl.hpp b/android/src/main/cpp/Gl.hpp index 1b63e5a..94d25b3 100644 --- a/android/src/main/cpp/Gl.hpp +++ b/android/src/main/cpp/Gl.hpp @@ -10,7 +10,10 @@ #include #include +#include + #include "Common.hpp" +#include "Fence.hpp" namespace margelo::nitro::webcodecs { @@ -31,32 +34,51 @@ class GlBlitter { if (_display == EGL_NO_DISPLAY || !eglInitialize(_display, nullptr, nullptr)) { throw std::runtime_error("eglInitialize failed"); } - const EGLint attributes[] = {EGL_RED_SIZE, - 8, - EGL_GREEN_SIZE, - 8, - EGL_BLUE_SIZE, - 8, - EGL_ALPHA_SIZE, - 8, - EGL_RENDERABLE_TYPE, - EGL_OPENGL_ES3_BIT, - EGL_SURFACE_TYPE, - EGL_WINDOW_BIT | EGL_PBUFFER_BIT, - EGL_RECORDABLE_ANDROID, - 1, - EGL_NONE}; + // A recordable window (the encoder's input surface) and a 1x1 pbuffer + // to be current on between windows. Some devices have no config that + // is both: then a window-only one, with no surface between windows + // (EGL_KHR_surfaceless_context). EGLint count = 0; - if (!eglChooseConfig(_display, attributes, &_config, 1, &count) || count == 0) { - throw std::runtime_error("eglChooseConfig failed"); + for (EGLint surfaceType : {EGL_WINDOW_BIT | EGL_PBUFFER_BIT, EGL_WINDOW_BIT}) { + const EGLint attributes[] = {EGL_RED_SIZE, + 8, + EGL_GREEN_SIZE, + 8, + EGL_BLUE_SIZE, + 8, + EGL_ALPHA_SIZE, + 8, + EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES3_BIT, + EGL_SURFACE_TYPE, + surfaceType, + EGL_RECORDABLE_ANDROID, + 1, + EGL_NONE}; + if (eglChooseConfig(_display, attributes, &_config, 1, &count) && count > 0) { + break; + } + } + if (count == 0) { + throw std::runtime_error("eglChooseConfig found no recordable ES 3 config (" + std::to_string(eglGetError()) + ")"); } const EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE}; _context = eglCreateContext(_display, _config, EGL_NO_CONTEXT, contextAttributes); if (_context == EGL_NO_CONTEXT) { - throw std::runtime_error("eglCreateContext failed"); + throw std::runtime_error("eglCreateContext failed (" + std::to_string(eglGetError()) + ")"); } const EGLint pbufferAttributes[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE}; _pbuffer = eglCreatePbufferSurface(_display, _config, pbufferAttributes); + if (_pbuffer == EGL_NO_SURFACE) { + EGLint error = eglGetError(); + const char* extensions = eglQueryString(_display, EGL_EXTENSIONS); + if (!extensions || !std::strstr(extensions, "EGL_KHR_surfaceless_context")) { + throw std::runtime_error("eglCreatePbufferSurface failed (" + std::to_string(error) + + "), and EGL has no surfaceless contexts"); + } + // Current with no surface (makeCurrent(EGL_NO_SURFACE)) instead. + WC_LOG("eglCreatePbufferSurface failed (%d): surfaceless context", error); + } makeCurrent(_pbuffer); buildProgram(); } @@ -80,36 +102,58 @@ class GlBlitter { void makeCurrent(EGLSurface surface) { if (!eglMakeCurrent(_display, surface, surface, _context)) { - throw std::runtime_error("eglMakeCurrent failed"); + throw std::runtime_error("eglMakeCurrent failed (" + std::to_string(eglGetError()) + ")"); } } - // GPU-side wait on a sync_fd (taken over, closed either way). + // Waits for a frame's sync_fd (taken over, closed either way): on the CPU + // first, bounded, so that a fence that never signals (a hung GPU) fails + // the frame (throws) instead of blocking this thread in the driver; then + // on the GPU, where EGL takes the fence, for drivers that order our reads + // through it. That one can no longer block: the fence has signalled. void waitFence(int fd) { if (fd < 0) { return; } + FenceWait wait = waitSyncFd(fd, kFenceTimeoutMs); + if (wait != FenceWait::Signaled) { + ::close(fd); + throw std::runtime_error(describeFenceWait(wait, kFenceTimeoutMs)); + } const EGLint attributes[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fd, EGL_NONE}; EGLSyncKHR sync = eglCreateSyncKHR(_display, EGL_SYNC_NATIVE_FENCE_ANDROID, attributes); if (sync == EGL_NO_SYNC_KHR) { - // Not taken over: wait on the CPU instead. + // Not taken over; the CPU wait above was enough. ::close(fd); - glFinish(); return; } - eglWaitSyncKHR(_display, sync, 0); + if (eglWaitSyncKHR(_display, sync, 0) != EGL_TRUE) { + WC_LOG("eglWaitSyncKHR failed (%d) on a signalled fence", eglGetError()); + } eglDestroySyncKHR(_display, sync); } - // Draws `source` over the whole of `target` (current: window surface). - void drawToWindow(EGLSurface target, AHardwareBuffer* source, int width, int height, int64_t presentationNs) { + // Draws the top-left `visibleWidth` x `visibleHeight` of `source` (its + // crop; 0: all of it) over the whole of `target` (current: window surface). + // `read`: called once `source` has been read, before the frame is sent + // (which can wait for the encoder to take an earlier one). + void drawToWindow(EGLSurface target, AHardwareBuffer* source, uint32_t visibleWidth, uint32_t visibleHeight, int width, int height, + int64_t presentationNs, const std::function& read = nullptr) { makeCurrent(target); glBindFramebuffer(GL_FRAMEBUFFER, 0); + // Cleared first, though the quad covers it all: some drivers keep (and + // tile-based GPUs load) the window buffer's old contents otherwise, and + // the encoder can be given a stale or partly drawn picture (webrtc:5147). + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); // Window: GL's first row is the bottom of the picture. - draw(source, width, height, true); + draw(source, visibleWidth, visibleHeight, width, height, true); eglPresentationTimeANDROID(_display, target, presentationNs); // Done reading `source` before it goes back to the pool. glFinish(); + if (read) { + read(); + } if (!eglSwapBuffers(_display, target)) { throw std::runtime_error("eglSwapBuffers failed (" + std::to_string(eglGetError()) + ")"); } @@ -133,6 +177,24 @@ class GlBlitter { } private: + struct CropUv { + float scale; + float max; + }; + + // The texture coordinates of the first `visible` of `size` texels. A + // cropped edge stops one texel short of the crop, as SurfaceTexture's + // transform does, so filtering (and 4:2:0 chroma, at half the size) + // reads none of the padding. + static CropUv cropUv(uint32_t visible, uint32_t size) { + if (visible == 0 || size == 0 || visible >= size) { + return {1.0f, 1.0f}; + } + float scale = static_cast(visible) / static_cast(size); + float max = static_cast(visible > 1 ? visible - 1 : visible) / static_cast(size); + return {scale, max}; + } + EGLImageKHR createImage(AHardwareBuffer* buffer) { EGLClientBuffer client = eglGetNativeClientBufferANDROID(buffer); const EGLint attributes[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; @@ -143,7 +205,11 @@ class GlBlitter { return image; } - void draw(AHardwareBuffer* source, int width, int height, bool flipY) { + void draw(AHardwareBuffer* source, uint32_t visibleWidth, uint32_t visibleHeight, int width, int height, bool flipY) { + AHardwareBuffer_Desc desc{}; + AHardwareBuffer_describe(source, &desc); + CropUv x = cropUv(visibleWidth, desc.width); + CropUv y = cropUv(visibleHeight, desc.height); EGLImageKHR image = createImage(source); GLuint texture = 0; glGenTextures(1, &texture); @@ -161,6 +227,8 @@ class GlBlitter { glUseProgram(_program); glUniform1i(_samplerLocation, 0); glUniform1f(_flipLocation, flipY ? 1.0f : 0.0f); + glUniform2f(_scaleLocation, x.scale, y.scale); + glUniform2f(_maxLocation, x.max, y.max); glBindVertexArray(_vertexArray); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); @@ -189,21 +257,25 @@ class GlBlitter { const char* vertex = R"(#version 300 es in vec2 aPosition; uniform float uFlip; +// The visible part of the buffer (its crop, at the top left). +uniform vec2 uScale; out vec2 vUv; void main() { // Texture row 0 is the top of the picture. float v = uFlip > 0.5 ? (1.0 - aPosition.y) * 0.5 : (1.0 + aPosition.y) * 0.5; - vUv = vec2((aPosition.x + 1.0) * 0.5, v); + vUv = vec2((aPosition.x + 1.0) * 0.5, v) * uScale; gl_Position = vec4(aPosition, 0.0, 1.0); })"; const char* fragment = R"(#version 300 es #extension GL_OES_EGL_image_external_essl3 : require precision mediump float; uniform samplerExternalOES uTexture; +// Where sampling stops: short of the padding past a crop. +uniform vec2 uMax; in vec2 vUv; out vec4 color; void main() { - color = texture(uTexture, vUv); + color = texture(uTexture, min(vUv, uMax)); })"; GLuint vs = compile(GL_VERTEX_SHADER, vertex); GLuint fs = compile(GL_FRAGMENT_SHADER, fragment); @@ -221,6 +293,8 @@ void main() { } _samplerLocation = glGetUniformLocation(_program, "uTexture"); _flipLocation = glGetUniformLocation(_program, "uFlip"); + _scaleLocation = glGetUniformLocation(_program, "uScale"); + _maxLocation = glGetUniformLocation(_program, "uMax"); const GLfloat quad[] = {-1, -1, 1, -1, -1, 1, 1, 1}; glGenVertexArrays(1, &_vertexArray); @@ -242,6 +316,8 @@ void main() { GLuint _vertexBuffer = 0; GLint _samplerLocation = -1; GLint _flipLocation = -1; + GLint _scaleLocation = -1; + GLint _maxLocation = -1; }; } // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/HybridWebCodecs.hpp b/android/src/main/cpp/HybridWebCodecs.hpp index b3b1deb..5ce7e52 100644 --- a/android/src/main/cpp/HybridWebCodecs.hpp +++ b/android/src/main/cpp/HybridWebCodecs.hpp @@ -30,20 +30,31 @@ class HybridWebCodecs : public HybridWebCodecsSpec { if (width <= 0 || height <= 0) { throw domError("TypeError", "invalid size"); } - return std::make_shared( - static_cast(width), static_cast(height), - format == "RGBA16F" ? AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT : AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM); + uint32_t w = static_cast(width); + uint32_t h = static_cast(height); + uint32_t native = format == "RGBA16F" ? AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT : AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM; + // Half floats are read on the CPU (HDR, to P010): some GPUs cannot make + // such buffers. Said here, not at the first frame. + if (native == AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT && !poolFormatSupported(w, h, native)) { + throw domError("NotSupportedError", "this device cannot make RGBA16F surfaces the CPU can read"); + } + return std::make_shared(w, h, native); } bool isVideoEncoderConfigSupported(const NativeVideoEncoderConfig& config) override { if (config.width <= 0 || config.height <= 0 || !videoEncodingAvailable()) { return false; } - // MediaCodecList: an encoder that takes this size, frame rate, bitrate - // and profile, from a surface (8-bit) or P010 buffers (Main 10, which - // HDR export uses), as the encoder will be created. + // MediaCodecList: an encoder that takes this size and profile, from a + // surface (8-bit) or P010 buffers (Main 10, which HDR export uses), as + // the encoder will be created. The frame rate and bitrate are hints. if (config.codec == "avc" || config.codec == "av1") { bool tenBit = config.profile.value_or("") == "main10"; + // Main 10 is fed from an RGBA16F pool, read on the CPU. + if (tenBit && !poolFormatSupported(static_cast(config.width), static_cast(config.height), + AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT)) { + return false; + } return findVideoEncoder(config, tenBit).has_value(); } return false; @@ -107,6 +118,7 @@ class HybridWebCodecs : public HybridWebCodecsSpec { std::string writeFile(const std::string& path, const std::shared_ptr& data) override { std::string resolved = resolveFilePath(path); + makeParentDirectories(resolved); int fd = ::open(resolved.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd < 0) { throw domError("NotFoundError", "cannot write " + resolved + " (" + std::to_string(errno) + ")"); diff --git a/android/src/main/cpp/P010.hpp b/android/src/main/cpp/P010.hpp new file mode 100644 index 0000000..1cfc11e --- /dev/null +++ b/android/src/main/cpp/P010.hpp @@ -0,0 +1,90 @@ +#pragma once + +// The HDR path's RGBA half-float to P010 conversion, with no NDK in it, so +// that a host test (android/src/test/cpp, `yarn test:cpp`) can check it. + +#include +#include +#include +#include +#include + +namespace margelo::nitro::webcodecs { + +// The chroma pairs (or rows) of `n` luma samples (or rows): an odd last one +// has its own. +inline int p010Chroma(int n) { + return (n + 1) / 2; +} + +// The bytes between rows of the codec's P010 input: what it reports +// (`reported`, 0 for nothing), else the luma row; at least a chroma row +// (4 bytes a pair), which is 2 bytes more than the luma for an odd width. +inline size_t p010Stride(int width, int32_t reported) { + size_t stride = reported > 0 ? static_cast(reported) : static_cast(width) * 2; + // A stride in pixels (some codecs) rather than bytes. + if (stride < static_cast(width) * 2) { + stride *= 2; + } + return std::max(stride, static_cast(p010Chroma(width)) * 4); +} + +// The bytes of a P010 picture: `sliceHeight` rows of luma, then a chroma +// row for every two (an odd last one included). +inline size_t p010Size(size_t stride, size_t sliceHeight) { + return stride * (sliceHeight + (sliceHeight + 1) / 2); +} + +// One half float (IEEE 754 binary16) to a float. +inline float halfToFloat(uint16_t h) { + __fp16 value; + std::memcpy(&value, &h, sizeof(value)); + return static_cast(value); +} + +// Converts an RGBA half-float picture holding BT.2020 R'G'B' (already +// encoded with the transfer function, 0 to 1) to P010: 10-bit BT.2020 +// non-constant-luminance YCbCr, limited range, 4:2:0, each sample in the top +// 10 bits of 16, then Cb and Cr interleaved. `srcStride` is in half floats, +// `dstStride` in bytes. +inline void rgba16fToP010(const uint16_t* src, size_t srcStride, int width, int height, uint8_t* dst, size_t dstStride, + size_t sliceHeight) { + auto code = [](float v, float offset, float range) { + float c = offset + range * v + 0.5f; + c = c < 0.0f ? 0.0f : (c > 1023.0f ? 1023.0f : c); + return static_cast(static_cast(c) << 6); + }; + uint8_t* uv = dst + dstStride * sliceHeight; + // Each chroma sample averages the luma samples it covers: four, or two or + // one at an odd last column or row. + const int chromaWidth = p010Chroma(width); + std::vector cb(chromaWidth); + std::vector cr(chromaWidth); + std::vector count(chromaWidth); + for (int y = 0; y < height; y += 2) { + std::fill(cb.begin(), cb.end(), 0.0f); + std::fill(cr.begin(), cr.end(), 0.0f); + std::fill(count.begin(), count.end(), 0); + for (int dy = 0; dy < 2 && y + dy < height; dy++) { + const uint16_t* row = src + (y + dy) * srcStride; + auto* out = reinterpret_cast(dst + (y + dy) * dstStride); + for (int x = 0; x < width; x++) { + float r = halfToFloat(row[x * 4]); + float g = halfToFloat(row[x * 4 + 1]); + float b = halfToFloat(row[x * 4 + 2]); + float l = 0.2627f * r + 0.6780f * g + 0.0593f * b; + out[x] = code(l, 64.0f, 876.0f); + cb[x / 2] += (b - l) / 1.8814f; + cr[x / 2] += (r - l) / 1.4746f; + count[x / 2]++; + } + } + auto* out = reinterpret_cast(uv + (y / 2) * dstStride); + for (int i = 0; i < chromaWidth; i++) { + out[i * 2] = code(cb[i] / count[i], 512.0f, 896.0f); + out[i * 2 + 1] = code(cr[i] / count[i], 512.0f, 896.0f); + } + } +} + +} // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/Surface.hpp b/android/src/main/cpp/Surface.hpp index e445254..a6ca40c 100644 --- a/android/src/main/cpp/Surface.hpp +++ b/android/src/main/cpp/Surface.hpp @@ -19,6 +19,12 @@ struct HardwareBufferRef { HardwareBufferRef(AHardwareBuffer* buffer, std::function recycle) : buffer(buffer), recycle(std::move(recycle)) {} HardwareBufferRef(const HardwareBufferRef&) = delete; + // Someone else's buffer (wrapSurface), only referenced here: its + // producer may reuse it whenever it likes. A pool's or a decoder's is + // not reused while referenced. + bool foreign() const { + return !recycle; + } HardwareBufferRef& operator=(const HardwareBufferRef&) = delete; ~HardwareBufferRef() { if (recycle) { @@ -45,9 +51,16 @@ inline std::string formatName(uint32_t format) { class HybridNativeSurface : public HybridNativeSurfaceSpec { public: - explicit HybridNativeSurface(std::shared_ptr ref, int fence = -1) - : HybridObject(TAG), _ref(std::move(ref)), _fence(fence) { + // `visibleWidth` x `visibleHeight`: the picture in the buffer's top left + // when the buffer is larger (a decoder's crop; 0: all of it). + // `formatFallback`: the format to report when the buffer's has no name + // here (a decoder's YV12 or vendor-private 4:2:0 layout is its "NV12"). + explicit HybridNativeSurface(std::shared_ptr ref, int fence = -1, uint32_t visibleWidth = 0, + uint32_t visibleHeight = 0, std::string formatFallback = "") + : HybridObject(TAG), _ref(std::move(ref)), _formatFallback(std::move(formatFallback)), _fence(fence) { AHardwareBuffer_describe(_ref->buffer, &_desc); + _visibleWidth = visibleWidth > 0 && visibleWidth < _desc.width ? visibleWidth : _desc.width; + _visibleHeight = visibleHeight > 0 && visibleHeight < _desc.height ? visibleHeight : _desc.height; } ~HybridNativeSurface() override { @@ -62,14 +75,16 @@ class HybridNativeSurface : public HybridNativeSurfaceSpec { uint64_t getPixelBuffer() override { return getHandle(); } + // The picture's size: the buffer may be larger (padding past the crop). double getWidth() override { - return _desc.width; + return _visibleWidth; } double getHeight() override { - return _desc.height; + return _visibleHeight; } std::string getFormat() override { - return formatName(_desc.format); + std::string name = formatName(_desc.format); + return name == "unknown" && !_formatFallback.empty() ? _formatFallback : name; } // `handle` is a sync_fd the surface now owns (react-native-webgpu's @@ -83,7 +98,7 @@ class HybridNativeSurface : public HybridNativeSurfaceSpec { } std::shared_ptr clone() override { - return std::make_shared(ref(), dupFence()); + return std::make_shared(ref(), dupFence(), _visibleWidth, _visibleHeight, _formatFallback); } void release() override { @@ -111,6 +126,13 @@ class HybridNativeSurface : public HybridNativeSurfaceSpec { return ref()->buffer; } + uint32_t visibleWidth() const { + return _visibleWidth; + } + uint32_t visibleHeight() const { + return _visibleHeight; + } + // A copy of the fence for a consumer to wait on and close (-1: none). int dupFence() { std::lock_guard lock(_mutex); @@ -128,6 +150,9 @@ class HybridNativeSurface : public HybridNativeSurfaceSpec { std::mutex _mutex; std::shared_ptr _ref; AHardwareBuffer_Desc _desc{}; + uint32_t _visibleWidth = 0; + uint32_t _visibleHeight = 0; + std::string _formatFallback; int _fence; }; @@ -197,6 +222,30 @@ class SurfacePoolState : public std::enable_shared_from_this { inline constexpr uint64_t kSurfaceUsage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT; +// The usage a pool's buffers of `format` are allocated with. +inline uint64_t poolUsage(uint32_t format) { + return format == AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT ? kSurfaceUsage | AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN : kSurfaceUsage; +} + +// Whether this device can make `width` x `height` buffers of `format` for a +// pool (half floats: ones the CPU can also read, as the HDR encoder does). +// AHardwareBuffer_isSupported is API 29, above this library's minimum (26): +// without it, the first acquire() is what tells. +inline bool poolFormatSupported(uint32_t width, uint32_t height, uint32_t format) { + using IsSupported = int (*)(const AHardwareBuffer_Desc*); + static auto isSupported = reinterpret_cast(dlsym(RTLD_DEFAULT, "AHardwareBuffer_isSupported")); + if (!isSupported) { + return true; + } + AHardwareBuffer_Desc desc{}; + desc.width = width; + desc.height = height; + desc.layers = 1; + desc.format = format; + desc.usage = poolUsage(format); + return isSupported(&desc) == 1; +} + class HybridNativeSurfacePool : public HybridNativeSurfacePoolSpec { public: // RGBA 8-bit, or half floats (AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT) @@ -204,10 +253,7 @@ class HybridNativeSurfacePool : public HybridNativeSurfacePoolSpec { // encoder reads on the CPU (it converts them to P010). HybridNativeSurfacePool(uint32_t width, uint32_t height, uint32_t format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM) : HybridObject(TAG), - _state(std::make_shared( - width, height, format, - format == AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT ? kSurfaceUsage | AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN - : kSurfaceUsage)) {} + _state(std::make_shared(width, height, format, poolUsage(format))) {} double getWidth() override { return _state->width(); diff --git a/android/src/main/cpp/Timestamps.hpp b/android/src/main/cpp/Timestamps.hpp new file mode 100644 index 0000000..7ff8b24 --- /dev/null +++ b/android/src/main/cpp/Timestamps.hpp @@ -0,0 +1,85 @@ +#pragma once + +// The video encoder's frames between the draw and the output, with no NDK in +// them, so that a host test (android/src/test/cpp, `yarn test:cpp`) can check +// them. +// +// MediaCodec's input surface drops a frame whose timestamp does not move +// forward, and some encoders output the second-to-last frame with a pts of 0 +// (b/235045165). So the codec gets a timestamp nudged 1 us past the last one +// when it does not increase, and each output gets back the real timestamp +// and duration of its frame: the codec outputs frames in input order (no +// B-frames), so the frame is the oldest one waiting, or a later one when the +// codec dropped some. +// +// Not done (issue #1 leaves this open): Chromium and WebRTC also respace the +// timestamps evenly before the codec, because some rate control (WebRTC's +// frame-rate bitrate adjuster for Exynos) assumes a fixed frame rate. Here +// the codec still gets the real timestamps, nudged only when they do not +// increase, so uneven input can still throw such rate control off. The +// emulator's c2/goldfish encoders don't show it, so nothing here tests it. + +#include +#include +#include +#include + +namespace margelo::nitro::webcodecs { + +struct PendingFrame { + int64_t codecPts; // what the codec was given (us) + int64_t realTs; // the frame's timestamp (us) + double duration; +}; + +// Not thread-safe: the encoder's mutex guards it. +class TimestampQueue { +public: + // Records a drawn frame; returns the pts to give the codec. + int64_t push(int64_t realTs, double duration) { + int64_t pts = realTs; + if (_last.has_value() && pts <= *_last) { + pts = *_last + 1; + } + _last = pts; + _frames.push_back({pts, realTs, duration}); + return pts; + } + + // The frame an output with this pts is: the one given that pts, the frames + // before it dropped (counted in `skipped`); when none was (a pts of 0, or + // garbage), the oldest one. None when no frame is waiting. + std::optional take(int64_t outPts, size_t& skipped) { + skipped = 0; + if (_frames.empty()) { + return std::nullopt; + } + for (size_t i = 0; i < _frames.size(); i++) { + if (_frames[i].codecPts == outPts) { + PendingFrame frame = _frames[i]; + _frames.erase(_frames.begin(), _frames.begin() + static_cast(i) + 1); + skipped = i; + return frame; + } + } + PendingFrame frame = _frames.front(); + _frames.pop_front(); + return frame; + } + + bool empty() const { + return _frames.empty(); + } + + // A new codec: the timeline starts over. + void clear() { + _frames.clear(); + _last.reset(); + } + +private: + std::deque _frames; + std::optional _last; +}; + +} // namespace margelo::nitro::webcodecs diff --git a/android/src/main/cpp/VideoDecoder.hpp b/android/src/main/cpp/VideoDecoder.hpp index f1dfe7e..f81df04 100644 --- a/android/src/main/cpp/VideoDecoder.hpp +++ b/android/src/main/cpp/VideoDecoder.hpp @@ -12,6 +12,7 @@ #include "HybridNativeVideoDecoderSpec.hpp" #include "NativeDecodedFrame.hpp" +#include "Capabilities.hpp" #include "NativeVideoDecoderConfig.hpp" #include "Surface.hpp" #include "VideoEncoder.hpp" @@ -66,15 +67,18 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { ANativeWindow* window = nullptr; AImageReader_getWindow(_reader, &window); - _codec = AMediaCodec_createDecoderByType(mime.c_str()); - if (!_codec) { - _readerOwner.reset(); - throw domError("NotSupportedError", "no decoder for " + config.codec); - } AMediaFormat* format = AMediaFormat_new(); AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, mime.c_str()); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_WIDTH, width); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_HEIGHT, height); + // Room for a key frame of the size (Media3's: 3/4 of a byte per pixel + // of the 16-aligned picture); Codec2 takes the larger of this and its + // own, others may default to less. + AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, maxInputSize(width, height)); + // No picture dropped by the surface when the reader is behind (the + // default from Android 10). Our drain renders one picture at a time + // and waits for it, so none should be; older releases ignore the key. + AMediaFormat_setInt32(format, "allow-frame-drop", 0); auto csd = [](const std::vector& unit) { std::vector out = {0, 0, 0, 1}; out.insert(out.end(), unit.begin(), unit.end()); @@ -84,17 +88,56 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { auto csd1 = csd(_sets.pps[0]); AMediaFormat_setBuffer(format, "csd-0", csd0.data(), csd0.size()); AMediaFormat_setBuffer(format, "csd-1", csd1.data(), csd1.size()); - status = AMediaCodec_configure(_codec, format, window, nullptr, 0); - AMediaFormat_delete(format); - if (status == AMEDIA_OK) { - status = AMediaCodec_start(_codec); + + // The decoders to try, by name: those hardwareAcceleration prefers + // first, then the others, each in the platform's order. One that fails + // to configure or start (out of instances, a level it refuses) gives way + // to the next; with no list, the platform's choice. + std::vector names; + std::string preference = config.hardwareAcceleration.value_or(""); + try { + names = JCapabilities::findVideoDecoders(mime, width, height, preference); + if (!preference.empty()) { + for (auto& name : JCapabilities::findVideoDecoders(mime, width, height, "")) { + if (std::find(names.begin(), names.end(), name) == names.end()) { + names.push_back(name); + } + } + } + } catch (const std::exception& e) { + WC_ERR("video decoder: MediaCodecList failed (%s); using the platform's decoder", e.what()); + names.clear(); + } + if (names.empty()) { + names.push_back(""); + } + status = AMEDIA_ERROR_UNKNOWN; + std::string tried; + for (auto& name : names) { + AMediaCodec* codec = name.empty() ? AMediaCodec_createDecoderByType(mime.c_str()) : AMediaCodec_createCodecByName(name.c_str()); + std::string label = name.empty() ? "the default decoder" : name; + tried += (tried.empty() ? "" : ", ") + label; + if (!codec) { + WC_ERR("video decoder: could not create %s", label.c_str()); + continue; + } + status = AMediaCodec_configure(codec, format, window, nullptr, 0); + if (status == AMEDIA_OK) { + status = AMediaCodec_start(codec); + } + if (status == AMEDIA_OK) { + _codec = codec; + WC_LOG("video decoder: %s", label.c_str()); + break; + } + WC_ERR("video decoder: %s failed to start (%d)", label.c_str(), status); + AMediaCodec_delete(codec); } - if (status != AMEDIA_OK) { - AMediaCodec_delete(_codec); - _codec = nullptr; + AMediaFormat_delete(format); + if (!_codec) { _readerOwner.reset(); _reader = nullptr; - throw domError("NotSupportedError", "MediaCodec decoder failed to start (" + std::to_string(status) + ")"); + throw domError("NotSupportedError", "no decoder for " + config.codec + " started (" + std::to_string(status) + "; tried " + tried + ")"); } startDrain(); @@ -145,6 +188,22 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { return promise; } _input.post([this, promise] { + // Nothing since configure() or the last flush: nothing to wait for, + // and no end of stream (some decoders mishandle one as the first + // input) or codec flush. + if (_queuedSinceFlush == 0) { + if (_failed) { + std::string failure; + { + std::lock_guard lock(_mutex); + failure = _failure; + } + promise->reject(std::make_exception_ptr(std::runtime_error(failure))); + } else { + promise->resolve(); + } + return; + } if (!_failed) { queueInput(nullptr, 0, 0, kBufferFlagEndOfStream); } @@ -160,6 +219,10 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { ended = true; break; } + if (_heldByJs) { + // Not stuck: waiting for JS to close a frame. + flushStart = now; + } if (now - std::max(flushStart, _lastImage) > std::chrono::seconds(10)) { break; } @@ -191,6 +254,7 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { _acquired = 0; _durations.clear(); } + _queuedSinceFlush = 0; startDrain(); promise->resolve(); }); @@ -202,6 +266,11 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { } private: + static int32_t maxInputSize(int32_t width, int32_t height) { + int64_t pixels = static_cast((width + 15) / 16) * ((height + 15) / 16) * 256; + return static_cast(std::min(pixels * 3 / 4, INT32_MAX)); + } + void startDrain() { { std::lock_guard lock(_mutex); @@ -220,6 +289,11 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { if (index >= 0 || index != AMEDIACODEC_INFO_TRY_AGAIN_LATER) { break; } + // Stalled by JS holding every picture: wait for it as long as it + // takes, as the drain does. + if (_heldByJs) { + tries = 0; + } } if (index < 0 || index == kErrorInsufficientResource || index == kErrorReclaimed) { fail(index == AMEDIACODEC_INFO_TRY_AGAIN_LATER @@ -230,7 +304,9 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { size_t capacity = 0; uint8_t* buffer = AMediaCodec_getInputBuffer(_codec, index, &capacity); if (!buffer || size > capacity) { - fail(errorMessage("EncodingError", "decoder-failed", "chunk larger than the input buffer")); + fail(errorMessage("EncodingError", "decoder-failed", + "chunk larger than the input buffer (" + std::to_string(size) + " > " + std::to_string(capacity) + + " bytes)")); return; } if (size > 0) { @@ -239,6 +315,8 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { media_status_t status = AMediaCodec_queueInputBuffer(_codec, index, 0, size, ts, flags); if (status != AMEDIA_OK) { fail(describeCodecStatus(status, "decoder", "decoder")); + } else if ((flags & kBufferFlagEndOfStream) == 0) { + _queuedSinceFlush++; } } @@ -313,8 +391,16 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { // On the drain thread. void waitAcquired() { auto start = std::chrono::steady_clock::now(); + struct Held { + std::atomic& flag; + ~Held() { + flag = false; + } + } held{_heldByJs}; while (draining() && !_failed) { - if (tryAcquire() == AMEDIA_IMGREADER_MAX_IMAGES_ACQUIRED) { + bool full = tryAcquire() == AMEDIA_IMGREADER_MAX_IMAGES_ACQUIRED; + _heldByJs = full; + if (full) { // JS holds every picture: wait for it to close one, as a web // decoder stalls until frames are closed. start = std::chrono::steady_clock::now(); @@ -352,13 +438,24 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { return; } AImage_getTimestamp(image, ×tampNs); + // The picture's size: the buffer can be larger (c2.android's decoders + // pad the width to 128), the image is its crop. + int32_t visibleWidth = 0; + int32_t visibleHeight = 0; + AImage_getWidth(image, &visibleWidth); + AImage_getHeight(image, &visibleHeight); int64_t pts = (timestampNs + 500) / 1000; double duration = takeDuration(pts); // The image goes back to the reader (kept alive meanwhile) when the last // reference dies. auto owner = _readerOwner; auto ref = std::make_shared(source, [owner, image](AHardwareBuffer*) { AImage_delete(image); }); - _output(NativeDecodedFrame(std::make_shared(ref), static_cast(pts), duration)); + // The format is the decoder's 4:2:0 layout: YCbCr_420_888 (NV12 here), + // YV12 (c2.android) or a vendor's private one, all "NV12" to JS. The + // picture is sampled through the buffer's own YCbCr conversion. + auto surface = std::make_shared(ref, -1, static_cast(std::max(visibleWidth, 0)), + static_cast(std::max(visibleHeight, 0)), "NV12"); + _output(NativeDecodedFrame(surface, static_cast(pts), duration)); countDelivered(); } @@ -460,7 +557,11 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { std::atomic _closed{false}; std::atomic _reported{false}; std::atomic _shutdown{false}; + // The drain waits for JS to close a frame (every picture is taken). + std::atomic _heldByJs{false}; std::thread _drain; + // Chunks queued since configure() or the last flush (the input thread's). + int64_t _queuedSinceFlush = 0; SerialQueue _input{"wc-vdec-input"}; SerialQueue _deliver{"wc-vdec-out"}; diff --git a/android/src/main/cpp/VideoEncoder.hpp b/android/src/main/cpp/VideoEncoder.hpp index 4976093..4285def 100644 --- a/android/src/main/cpp/VideoEncoder.hpp +++ b/android/src/main/cpp/VideoEncoder.hpp @@ -7,22 +7,27 @@ #include #include #include +#include #include #include #include #include +#include +#include #include #include -#include #include #include "Capabilities.hpp" +#include "EncoderAttempts.hpp" #include "Gl.hpp" #include "HybridNativeVideoEncoderSpec.hpp" #include "NativeEncodedChunk.hpp" #include "NativeVideoEncoderConfig.hpp" +#include "P010.hpp" #include "Surface.hpp" +#include "Timestamps.hpp" namespace margelo::nitro::webcodecs { @@ -44,6 +49,117 @@ inline bool isCodecError(ssize_t index) { // Frames in the encoder with no output for this long: it is stuck. constexpr auto kStallTimeout = std::chrono::seconds(20); +// How long a key frame request waits for the frames before it to come out. +constexpr auto kKeyFrameDrainTimeout = std::chrono::milliseconds(200); + +// After the end of stream is asked for, with every frame drawn out: this long +// with no output is the end, for encoders that never say so. +constexpr auto kEndOfStreamQuietTimeout = std::chrono::seconds(1); + +// How long shutdown() waits for the GL thread to stop the codec, before it +// stops it from its own thread (then as long again). +constexpr auto kShutdownTimeout = std::chrono::milliseconds(2000); + +// How long flush() waits for the frames drawn to come out before it ends the +// stream (Media3 waits 100 ms). +constexpr auto kEndOfStreamDrainTimeout = std::chrono::milliseconds(200); + +// How long encode() waits for a frame from a foreign buffer to be read +// (see FrameRead): behind the frames queued before it, and its fence. +constexpr auto kForeignReadTimeout = std::chrono::milliseconds(10000); + +// Set once a frame's buffer has been read (or never will be): when the GL +// thread signals it, when the task's body exits without reading it (see +// FrameReadGuard), or at the latest when the task holding it is destroyed +// unrun. The waiter keeps only the future: the task holds the only +// FrameRead, so its destructor does run when the task is gone. +class FrameRead { +public: + ~FrameRead() { + signal(); + } + std::future future() { + return _promise.get_future(); + } + void signal() { + if (!_signaled.exchange(true)) { + _promise.set_value(); + } + } + +private: + std::promise _promise; + std::atomic _signaled{false}; +}; + +// Signals a FrameRead when the scope exits, by any path: a frame that is +// not drawn (the encoder has failed, the draw throws) is never read. +class FrameReadGuard { +public: + explicit FrameReadGuard(FrameRead* read) : _read(read) {} + ~FrameReadGuard() { + if (_read) { + _read->signal(); + } + } + FrameReadGuard(const FrameReadGuard&) = delete; + FrameReadGuard& operator=(const FrameReadGuard&) = delete; + +private: + FrameRead* _read; +}; + +// Debug builds only: a fault the e2e tests make the encoder act out, from +// `adb shell setprop debug.webcodecs.fault `, read when a codec starts: +// venc-no-eos the end of stream never comes out +// venc-stall-output: no output is taken, and s without it is a stall +// venc-slow-stop: stopping the codec takes ms longer +// venc-fence-hang every frame's GPU fence is one that never signals +// venc-slow-draw: each frame waits ms on the GL thread before +// it is read (a busy encoder's backlog) +// Release builds (NDEBUG) never read it. +struct EncoderFault { + bool noEndOfStream = false; + int stallOutputSeconds = 0; + int slowStopMs = 0; + // The draw of this frame (1-based) fails on the GL thread. + int drawFailAt = 0; + // Each frame's fence is replaced by the read end of a pipe nothing is + // written to: a fence that never signals (a hung GPU). + bool fenceHang = false; + // Each frame waits this long on the GL thread before it is read. + int slowDrawMs = 0; + + static EncoderFault read() { + EncoderFault fault; +#ifndef NDEBUG + char value[PROP_VALUE_MAX] = {0}; + __system_property_get("debug.webcodecs.fault", value); + const std::string text(value); + auto argument = [&](const std::string& name) { + return std::atoi(text.c_str() + name.size()); + }; + if (text == "venc-no-eos") { + fault.noEndOfStream = true; + } else if (text == "venc-fence-hang") { + fault.fenceHang = true; + } else if (text.rfind("venc-stall-output:", 0) == 0) { + fault.stallOutputSeconds = std::max(1, argument("venc-stall-output:")); + } else if (text.rfind("venc-slow-stop:", 0) == 0) { + fault.slowStopMs = std::max(0, argument("venc-slow-stop:")); + } else if (text.rfind("venc-slow-draw:", 0) == 0) { + fault.slowDrawMs = std::max(0, argument("venc-slow-draw:")); + } else if (text.rfind("venc-draw-fail:", 0) == 0) { + fault.drawFailAt = std::max(1, argument("venc-draw-fail:")); + } + if (!text.empty()) { + WC_LOG("video encoder: fault %s", value); + } +#endif + return fault; + } +}; + inline std::string describeCodecStatus(media_status_t status, const std::string& what, const std::string& prefix) { // The system takes a codec back from an app in the background when another // needs it (MediaCodec.CodecException.ERROR_RECLAIMED). @@ -102,82 +218,28 @@ struct ColorAspects { constexpr int32_t kColorFormatYuvP010 = 0x36; -// The encoder MediaCodecList says takes this config (size, frame rate, -// bitrate, profile, and the input: a surface, or P010 buffers for 10-bit -// HDR), the first in the platform's order; none when no encoder does. +// The encoder MediaCodecList says takes this config (size, profile, and the +// input: a surface, or P010 buffers for 10-bit HDR); none when no encoder +// does. Encoders that take the size as they say come first (start() +// configures the size asked for and falls back on no other encoder), then +// those the lenient reading lets through; in each, a hardware one before a +// software one (Capabilities.java). The frame rate and bitrate are hints, as +// in Media3: start() clamps the bitrate into the range of the encoder it made. // // An H.264 profile is a preference, as configure() treats it: when no encoder // lists it (the emulator's software encoder has no High), any encoder that // takes the rest will do, in its default profile, which the avcC description // of the output says. AV1's Main 10 is required: HDR depends on it. inline std::optional findVideoEncoder(const NativeVideoEncoderConfig& config, bool hdr) { - auto find = [&](int32_t profile) { - return JCapabilities::findVideoEncoder(videoMime(config.codec), static_cast(config.width), static_cast(config.height), - config.framerate.value_or(0), static_cast(std::min(config.bitrate.value_or(0), 2e9)), - profile, hdr ? kColorFormatYuvP010 : kColorFormatSurface); - }; - int32_t profile = mediaCodecProfile(config); - auto name = find(profile); - if (!name.has_value() && config.codec == "avc" && profile > 0) { - name = find(0); - } - return name; + return JCapabilities::findVideoEncoder(videoMime(config.codec), static_cast(config.width), static_cast(config.height), + mediaCodecProfile(config), config.codec == "avc", hdr ? kColorFormatYuvP010 : kColorFormatSurface); } -// Waits on the CPU for a sync fd (taken over, closed either way). -inline void waitFenceCpu(int fd) { - if (fd < 0) { - return; - } - pollfd p{fd, POLLIN, 0}; - ::poll(&p, 1, 1000); - ::close(fd); -} - -// One half float (IEEE 754 binary16) to a float. -inline float halfToFloat(uint16_t h) { - __fp16 value; - std::memcpy(&value, &h, sizeof(value)); - return static_cast(value); -} - -// Converts an RGBA half-float picture holding BT.2020 R'G'B' (already -// encoded with the transfer function, 0 to 1) to P010: 10-bit BT.2020 -// non-constant-luminance YCbCr, limited range, 4:2:0, each sample in the top -// 10 bits of 16, then Cb and Cr interleaved. `srcStride` is in half floats, -// `dstStride` in bytes. -inline void rgba16fToP010(const uint16_t* src, size_t srcStride, int width, int height, uint8_t* dst, size_t dstStride, - size_t sliceHeight) { - auto code = [](float v, float offset, float range) { - float c = offset + range * v + 0.5f; - c = c < 0.0f ? 0.0f : (c > 1023.0f ? 1023.0f : c); - return static_cast(static_cast(c) << 6); - }; - uint8_t* uv = dst + dstStride * sliceHeight; - std::vector cb(width / 2); - std::vector cr(width / 2); - for (int y = 0; y < height; y += 2) { - std::fill(cb.begin(), cb.end(), 0.0f); - std::fill(cr.begin(), cr.end(), 0.0f); - for (int dy = 0; dy < 2 && y + dy < height; dy++) { - const uint16_t* row = src + (y + dy) * srcStride; - auto* out = reinterpret_cast(dst + (y + dy) * dstStride); - for (int x = 0; x < width; x++) { - float r = halfToFloat(row[x * 4]); - float g = halfToFloat(row[x * 4 + 1]); - float b = halfToFloat(row[x * 4 + 2]); - float l = 0.2627f * r + 0.6780f * g + 0.0593f * b; - out[x] = code(l, 64.0f, 876.0f); - cb[x / 2] += (b - l) / 1.8814f; - cr[x / 2] += (r - l) / 1.4746f; - } - } - auto* out = reinterpret_cast(uv + (y / 2) * dstStride); - for (int i = 0; i < width / 2; i++) { - out[i * 2] = code(cb[i] / 4.0f, 512.0f, 896.0f); - out[i * 2 + 1] = code(cr[i] / 4.0f, 512.0f, 896.0f); - } - } +// Every encoder that may take this config, best first (findVideoEncoder's +// answer first): start() tries the next when one does not start. +inline std::vector findVideoEncoders(const NativeVideoEncoderConfig& config, bool hdr) { + return JCapabilities::findVideoEncoders(videoMime(config.codec), static_cast(config.width), static_cast(config.height), + mediaCodecProfile(config), config.codec == "avc", hdr ? kColorFormatYuvP010 : kColorFormatSurface); } // H.264, or AV1, through MediaCodec. Frames are copied (GPU, EGL) into the @@ -207,7 +269,15 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { start(); started->set_value(""); } catch (const std::exception& e) { - started->set_value(e.what()); + std::string message = e.what(); + // The destructor will not run: let go of the codec and the EGL + // context here, on the thread that made them. + try { + stop(); + _blitter.destroy(); + } catch (...) { + } + started->set_value(message); } }); std::string message = result.get(); @@ -240,12 +310,19 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { // Taken now: JS may close the frame right after encode(). auto ref = native->ref(); int fence = native->dupFence(); + uint32_t visibleWidth = native->visibleWidth(); + uint32_t visibleHeight = native->visibleHeight(); int64_t ts = static_cast(timestamp); - { - std::lock_guard lock(_mutex); - _durations[ts] = duration; - } - _gl.post([this, ref, fence, ts, keyFrame] { + // A foreign buffer (wrapSurface: a camera's, say) is only referenced: + // its producer may write the next picture into it once encode() + // returns. So encode() returns once it has been read. Pool and decoder + // buffers are not reused while the encoder holds them. + std::shared_ptr read = ref->foreign() ? std::make_shared() : nullptr; + // encode() keeps only the future; the task owns the FrameRead. + std::future readDone = read ? read->future() : std::future(); + _gl.post([this, ref, fence, visibleWidth, visibleHeight, ts, duration, keyFrame, read = std::move(read)]() mutable { + // Signalled after the read, or on whatever path leaves it unread. + FrameReadGuard readGuard(read.get()); if (_failed) { if (fence >= 0) { ::close(fence); @@ -256,27 +333,83 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { if (_ended) { // After flush() (end of stream), a new codec for what comes next. stop(); - start(); + try { + start(); + } catch (...) { + if (fence >= 0) { + ::close(fence); + } + throw; + } } if (keyFrame && _framesIn > 0) { + // request-sync applies to the next frame the encoder takes, which + // may be one already drawn and still queued: first let every frame + // drawn come out. Bounded, for encoders that hold frames until + // more come (the request then is best effort, as before). + { + std::unique_lock lock(_mutex); + bool drained = _cv.wait_for(lock, kKeyFrameDrainTimeout, + [this] { return _framesOut + _framesSkipped >= _framesIn || _failed; }); + if (!drained) { + WC_LOG("video encoder: %lld frame(s) still in the encoder at a key frame request", + static_cast(_framesIn - _framesOut - _framesSkipped)); + } + } AMediaFormat* params = AMediaFormat_new(); AMediaFormat_setInt32(params, "request-sync", 0); AMediaCodec_setParameters(_codec, params); AMediaFormat_delete(params); } + // Recorded in draw order for this codec; the codec gets a pts that + // moves forward (see Timestamps.hpp), the chunk the real one. + int64_t pts = 0; + { + std::lock_guard lock(_mutex); + pts = _timestamps.push(ts, duration); + } + if (_fault.drawFailAt > 0 && _framesIn + 1 == _fault.drawFailAt) { + if (fence >= 0) { + ::close(fence); + } + throw std::runtime_error("fault: the draw failed"); + } + if (_fault.fenceHang) { + int ends[2]; + if (::pipe(ends) == 0) { + if (fence >= 0) { + ::close(fence); + } + fence = ends[0]; + _faultPipes.push_back(ends[1]); + } + } + if (_fault.slowDrawMs > 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(_fault.slowDrawMs)); + } if (_aspects.hdr()) { - waitFenceCpu(fence); - queueP010(ref->buffer, ts); + // Read on the CPU: a fence that does not signal in time fails the + // frame (throws) rather than letting it be read half written. + awaitFence(fence); + queueP010(ref->buffer, pts, read.get()); } else { _blitter.waitFence(fence); - _blitter.drawToWindow(_window, ref->buffer, static_cast(_config.width), static_cast(_config.height), - ts * 1000); + _blitter.drawToWindow(_window, ref->buffer, visibleWidth, visibleHeight, static_cast(_config.width), + static_cast(_config.height), pts * 1000, [&read] { + if (read) { + read->signal(); + } + }); } _framesIn++; } catch (const std::exception& e) { fail(errorMessage("EncodingError", "encoder-failed", e.what())); } }); + if (readDone.valid() && readDone.wait_for(kForeignReadTimeout) != std::future_status::ready) { + throw domError("EncodingError", "the frame was not read within " + std::to_string(kForeignReadTimeout.count()) + + " ms; its buffer may be written over before it is"); + } } std::shared_ptr> flush() override { @@ -294,6 +427,16 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { promise->resolve(); return; } + if (!_aspects.hdr()) { + // Some encoders lose the last frame when the end of stream follows + // it at once (b/301603935): a short encode would then come out with + // no frame. As Media3 does, first let what was drawn come out, for a + // bounded time (encoders that hold frames until more come or the + // stream ends wait it out). + std::unique_lock lock(_mutex); + _cv.wait_for(lock, kEndOfStreamDrainTimeout, + [this] { return _framesOut + _framesSkipped >= _framesIn || _failed || _closed; }); + } // MediaCodec has no flush for a surface input: end the stream (the // next encode() starts a new one). media_status_t status = _aspects.hdr() ? queueEndOfStream() : AMediaCodec_signalEndOfInputStream(_codec); @@ -302,13 +445,42 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { promise->reject(std::make_exception_ptr(std::runtime_error(_failure))); return; } + // Done when the end of stream comes out. Some encoders never output + // it (b/365484741): every frame drawn having come out, and nothing + // more for a while, is the end too. Only an encoder that outputs + // nothing for kStallTimeout with frames still in it has timed out: + // a slow one still making progress has not. + const auto signalled = std::chrono::steady_clock::now(); + bool quiet = false; + bool stalled = false; std::unique_lock lock(_mutex); - bool done = _cv.wait_for(lock, std::chrono::seconds(10), [this] { return _eos || _failed; }); + while (!_cv.wait_for(lock, std::chrono::milliseconds(250), [this] { return _eos || _failed || _closed; })) { + const auto now = std::chrono::steady_clock::now(); + const auto since = now - std::max(_lastOutputAt, signalled); + if (_framesOut + _framesSkipped >= _framesIn && since >= kEndOfStreamQuietTimeout) { + quiet = true; + break; + } + if (since > kStallTimeout) { + stalled = true; + break; + } + } lock.unlock(); + if (quiet) { + // No end of stream to end the drain thread: stop the codec, so no + // output comes after the flush resolves. The next encode() starts a + // new one. + WC_LOG("video encoder: no end of stream after every frame came out; stopping the codec"); + stop(); + for (int64_t n = _framesIn - _framesOut; n > 0 && !_failed; n--) { + _output(NativeEncodedChunk(ArrayBuffer::allocate(0), 0, 0, false, std::nullopt)); + } + } _ended = true; if (_failed) { promise->reject(std::make_exception_ptr(std::runtime_error(_failure))); - } else if (!done) { + } else if (stalled) { promise->reject(std::make_exception_ptr(std::runtime_error(errorMessage("EncodingError", "encoder-failed", "flush timed out")))); } else { promise->resolve(); @@ -342,17 +514,15 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { } stop(); _aspects = aspects; - _encoderName.reset(); // HDR takes P010 buffers: maybe another encoder + _candidates.reset(); // HDR takes P010 buffers: maybe other encoders + _firstAttempt = 0; start(); restarted->set_value(""); } catch (const std::exception& e) { - // No codec now (an encoder without Main 10 or P010): later frames - // are dropped, and the caller gets the error. - { - std::lock_guard lock(_mutex); - _failure = errorMessage("NotSupportedError", "encoder-failed", e.what()); - _failed = true; - } + // No codec now (an encoder without Main 10 or P010): the encoder + // has failed, and says so through the error callback too, so that + // JS closes it rather than queue frames that are dropped. + fail(errorMessage("NotSupportedError", "encoder-failed", e.what())); restarted->set_value(e.what()); } }); @@ -362,47 +532,94 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { } } + // Synchronous, as the decoder's: the codec is let go before close() + // returns, so that a configure() after it (a new native encoder) does not + // make a second codec while this one is still there (devices with few + // codec instances refuse it). Bounded: see shutdown(). void close() override { - _closed = true; - _failed = true; - _gl.post([this] { stop(); }); + shutdown(); } private: - // The encoder MediaCodecList says takes the config, as isConfigSupported - // answered; the platform's default for the type when none says so. - AMediaCodec* createCodec() { - if (!_encoderName.has_value()) { - _encoderName = findVideoEncoder(_config, _aspects.hdr()).value_or(""); - } - if (!_encoderName->empty()) { - if (AMediaCodec* codec = AMediaCodec_createCodecByName(_encoderName->c_str())) { - return codec; + // The encoders MediaCodecList says may take the config, best first + // (isConfigSupported's answer first), looked up once; "" (the platform's + // default for the type) when none says so. + const std::vector& candidates() { + if (!_candidates.has_value()) { + _candidates = findVideoEncoders(_config, _aspects.hdr()); + if (_candidates->empty()) { + _candidates->push_back(""); } } - return AMediaCodec_createEncoderByType(videoMime(_config.codec).c_str()); + return *_candidates; } - void start() { - _codec = createCodec(); + // The encoder `name`, or the type's default for "". + AMediaCodec* createCodec(const std::string& name) { + if (name.empty()) { + return AMediaCodec_createEncoderByType(videoMime(_config.codec).c_str()); + } + return AMediaCodec_createCodecByName(name.c_str()); + } + + // The codec's name ("" when unknown). AMediaCodec_getName is API 28, + // above this library's minimum (26). + static std::string codecName(AMediaCodec* codec) { + using GetName = media_status_t (*)(AMediaCodec*, char**); + using ReleaseName = void (*)(AMediaCodec*, char*); + static auto getName = reinterpret_cast(dlsym(RTLD_DEFAULT, "AMediaCodec_getName")); + static auto releaseName = reinterpret_cast(dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName")); + std::string result; + char* name = nullptr; + if (getName && releaseName && getName(codec, &name) == AMEDIA_OK && name) { + result = name; + releaseName(codec, name); + } + return result; + } + + // Makes, configures and starts the encoder `name` ("" for the type's + // default), from the configure attempt `firstAttempt` on. False, with the + // codec let go and `failure` saying why (each attempt's status), when it + // does not start. + bool startEncoder(const std::string& name, size_t firstAttempt, std::string& failure) { + const std::string label = name.empty() ? "the " + _config.codec + " default" : name; + _codec = createCodec(name); if (!_codec) { - throw std::runtime_error("no encoder for " + _config.codec); + failure = label + ": could not be made"; + return false; } int32_t width = static_cast(_config.width); int32_t height = static_cast(_config.height); - double framerate = _config.framerate.value_or(30); - if (framerate <= 0) { + // Hints: the frame rate floored, and below 1 the default; the bitrate + // (or the default one) clamped into the range of the encoder made. + double framerate = std::floor(_config.framerate.value_or(0)); + if (!(framerate >= 1)) { framerate = 30; } - double bitrate = _config.bitrate.value_or(0); - if (bitrate <= 0) { - bitrate = width * height * framerate * 0.1; + std::string encoderName = codecName(_codec); + if (encoderName.empty()) { + encoderName = name; + } + double bitrate = JCapabilities::videoBitrate(encoderName, videoMime(_config.codec), _config.bitrate.value_or(0), width, height, + _config.framerate.value_or(0)); + // H.264's profile goes with a level (OMX encoders refuse a profile + // alone): the next profile down when the encoder does not list the one + // asked for, and neither when it lists none that will do. AV1's profile + // is always set: without it the encoder makes 8-bit streams. + int32_t profile = mediaCodecProfile(_config); + int32_t level = 0; + if (_config.codec == "avc" && profile > 0) { + auto chosen = JCapabilities::avcProfileLevel(encoderName, videoMime(_config.codec), profile, + static_cast(_config.level.value_or(0)), width, height, + _config.framerate.value_or(0)); + profile = chosen.profile; + level = chosen.level; } - // From the most to the least demanding: each attempt drops a setting some - // encoders refuse at configure time (as #641's writer, after Media3 and - // react-native-skia-video). A codec a configure failed on is in an error + // See videoEncoderAttempts. A codec a configure failed on is in an error // state: each attempt makes a new one. - auto configure = [&](int attempt) { + const auto attempts = videoEncoderAttempts(level > 0, _config.realtime); + auto configure = [&](const EncoderAttempt& attempt) { AMediaFormat* format = AMediaFormat_new(); AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, videoMime(_config.codec).c_str()); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_WIDTH, width); @@ -412,7 +629,7 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { // KEY_FRAME_RATE only budgets the bitrate (the timestamps time the // frames); some encoders refuse a high one even when they list it. AMediaFormat_setFloat(format, AMEDIAFORMAT_KEY_FRAME_RATE, - static_cast(attempt >= 2 ? std::min(framerate, 30.0) : framerate)); + static_cast(attempt.capFrameRate ? std::min(framerate, 30.0) : framerate)); // Key frames come from encode({ keyFrame: true }), as on the web. AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, 3600); // WebCodecs outputs chunks in decode order: no B-frames. @@ -425,64 +642,60 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { AMediaFormat_setInt32(format, "priority", 0); } else { // Best effort, as fast as the encoder goes: without an operating rate - // some encoders pace an offline export in real time. INT32_MAX throws - // on some chipsets (Media3's - // deviceNeedsLowerOperatingRateAvoidingOverflowWorkaround), which take - // 1000; the last attempt asks for none. + // some encoders pace an offline export in real time. AMediaFormat_setInt32(format, "priority", 1); - if (attempt == 0) { - AMediaFormat_setInt32(format, "operating-rate", INT32_MAX); - } else if (attempt == 1) { - AMediaFormat_setInt32(format, "operating-rate", 1000); + if (attempt.operatingRate != kOperatingRateNone) { + AMediaFormat_setInt32(format, "operating-rate", attempt.operatingRate); } } if (_config.codec == "av1") { // AV1ProfileMain8, or AV1ProfileMain10 (HDR: AV1ProfileMain10HDR10 - // is for PQ with static metadata, which HLG does not use). Always - // set: without it the encoder makes 8-bit streams. - AMediaFormat_setInt32(format, "profile", mediaCodecProfile(_config)); - } else if (attempt < 2 && _config.profile.has_value()) { - AMediaFormat_setInt32(format, "profile", mediaCodecProfile(_config)); + // is for PQ with static metadata, which HLG does not use). + AMediaFormat_setInt32(format, "profile", profile); + } else if (attempt.profile && level > 0) { + AMediaFormat_setInt32(format, "profile", profile); + AMediaFormat_setInt32(format, "level", level); } media_status_t status = AMediaCodec_configure(_codec, format, nullptr, nullptr, AMEDIACODEC_CONFIGURE_FLAG_ENCODE); AMediaFormat_delete(format); return status; }; media_status_t configured = AMEDIA_ERROR_UNKNOWN; - for (int attempt = 0; attempt < 3; attempt++) { - if (attempt > 0) { + std::string statuses; + size_t attempt = std::min(firstAttempt, attempts.size() - 1); + for (size_t first = attempt; attempt < attempts.size(); attempt++) { + if (attempt > first) { AMediaCodec_delete(_codec); - _codec = createCodec(); + _codec = createCodec(name); if (!_codec) { + statuses += ", then could not be made again"; break; } } - configured = configure(attempt); + configured = configure(attempts[attempt]); if (configured == AMEDIA_OK) { break; } + WC_LOG("video encoder: %s refused attempt %zu (%s): %d", encoderName.c_str(), attempt, + describeAttempt(attempts[attempt]).c_str(), configured); + statuses += (statuses.empty() ? "" : ", ") + describeMediaStatus(configured) + " (" + describeAttempt(attempts[attempt]) + ")"; } if (configured != AMEDIA_OK) { if (_codec) { AMediaCodec_delete(_codec); _codec = nullptr; } - throw std::runtime_error("the " + _config.codec + " encoder does not take " + std::to_string(width) + "x" + std::to_string(height) + - " at " + std::to_string(static_cast(bitrate)) + " bps (" + - std::to_string(configured) + ")"); + failure = (encoderName.empty() ? label : encoderName) + " at " + std::to_string(static_cast(bitrate)) + + " bps: configure " + statuses; + return false; } + _firstAttempt = attempt; + _codecLabel = encoderName.empty() ? label : encoderName; // Software codecs are Codec2's c2.android.* (and OMX.google.*). - // AMediaCodec_getName is API 28, above this library's minimum (26). - using GetName = media_status_t (*)(AMediaCodec*, char**); - using ReleaseName = void (*)(AMediaCodec*, char*); - static auto getName = reinterpret_cast(dlsym(RTLD_DEFAULT, "AMediaCodec_getName")); - static auto releaseName = reinterpret_cast(dlsym(RTLD_DEFAULT, "AMediaCodec_releaseName")); - char* name = nullptr; - if (getName && releaseName && getName(_codec, &name) == AMEDIA_OK && name) { - std::string codecName(name); - _hardware = codecName.rfind("c2.android.", 0) != 0 && codecName.rfind("OMX.google.", 0) != 0; - WC_LOG("video encoder: %s", name); - releaseName(_codec, name); + if (!encoderName.empty()) { + _hardware = encoderName.rfind("c2.android.", 0) != 0 && encoderName.rfind("OMX.google.", 0) != 0; + WC_LOG("video encoder: %s, %dx%d at %lld bps, %g fps, profile %d level %d: attempt %zu (%s)", encoderName.c_str(), width, height, + static_cast(bitrate), framerate, profile, level, attempt, describeAttempt(attempts[attempt]).c_str()); } media_status_t status = AMEDIA_OK; if (!_aspects.hdr()) { @@ -491,19 +704,58 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { if (status != AMEDIA_OK || !window) { AMediaCodec_delete(_codec); _codec = nullptr; - throw std::runtime_error("AMediaCodec_createInputSurface failed (" + std::to_string(status) + ")"); + _firstAttempt = 0; + failure = encoderName + ": createInputSurface " + describeMediaStatus(status); + return false; } _nativeWindow = window; - _window = _blitter.createWindowSurface(window); + try { + _window = _blitter.createWindowSurface(window); + } catch (const std::exception& e) { + stopQuietly(); + _firstAttempt = 0; + failure = encoderName + ": " + e.what(); + return false; + } } status = AMediaCodec_start(_codec); if (status != AMEDIA_OK) { - throw std::runtime_error("AMediaCodec_start failed (" + std::to_string(status) + ")"); + stopQuietly(); + _firstAttempt = 0; + failure = encoderName + ": start " + describeMediaStatus(status); + return false; + } + return true; + } + + // Makes and starts the codec: each candidate encoder in turn (software + // ones included), each through the configure attempts, until one starts. + // The encoder and attempt that did are tried first the next time (after a + // flush, on a new color space). + void start() { + _fault = EncoderFault::read(); + const auto& names = candidates(); + std::string failures; + bool started = false; + for (size_t c = 0; c < names.size() && !started; c++) { + std::string failure; + started = startEncoder(names[c], c == 0 ? _firstAttempt : 0, failure); + if (started && c > 0) { + std::rotate(_candidates->begin(), _candidates->begin() + static_cast(c), _candidates->begin() + static_cast(c) + 1); + } + if (!started) { + WC_LOG("video encoder: %s", failure.c_str()); + failures += (failures.empty() ? "" : "; ") + failure; + } + } + if (!started) { + throw std::runtime_error("no " + _config.codec + " encoder took " + std::to_string(static_cast(_config.width)) + "x" + + std::to_string(static_cast(_config.height)) + " (" + failures + ")"); } if (_aspects.hdr()) { // The layout of the input buffers: rows `stride` bytes apart, the // chroma plane `slice-height` rows after the luma one. - _stride = static_cast(_config.width) * 2; + int32_t stride = 0; _sliceHeight = static_cast(_config.height); // API 28, above this library's minimum (26). using GetInputFormat = AMediaFormat* (*)(AMediaCodec*); @@ -513,25 +765,36 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { if (input) { int32_t value = 0; if (AMediaFormat_getInt32(input, "stride", &value) && value > 0) { - _stride = static_cast(value); + stride = value; } - if (AMediaFormat_getInt32(input, "slice-height", &value) && value > 0) { + // Never fewer rows than the picture has, or its chroma would land on + // its luma. + if (AMediaFormat_getInt32(input, "slice-height", &value) && value >= static_cast(_config.height)) { _sliceHeight = static_cast(value); } AMediaFormat_delete(input); } - // A stride in pixels (some codecs) rather than bytes. - if (_stride < static_cast(_config.width) * 2) { - _stride *= 2; - } + _stride = p010Stride(static_cast(_config.width), stride); WC_LOG("video encoder: P010 input, stride %zu, slice height %zu", _stride, _sliceHeight); } _framesIn = 0; + _framesOut = 0; _ended = false; { std::lock_guard lock(_mutex); _eos = false; _draining = true; + _lastOutputAt = std::chrono::steady_clock::now(); + _timestamps.clear(); + _framesSkipped = 0; + } + { + // Surface input only: that is where the GL thread can block (in + // eglSwapBuffers). HDR takes buffers, with bounded waits that end on + // _failed, and its codec is not stopped under a P010 copy. + std::lock_guard lock(_codecMutex); + _liveCodec = _aspects.hdr() ? nullptr : _codec; + _aborted = false; } _drain = std::thread([this, codec = _codec] { drainLoop(codec); }); } @@ -545,24 +808,64 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { if (_drain.joinable()) { _drain.join(); } + { + std::lock_guard lock(_codecMutex); + _liveCodec = nullptr; + } if (_window != EGL_NO_SURFACE) { _blitter.destroySurface(_window); _window = EGL_NO_SURFACE; } if (_codec) { + if (_fault.slowStopMs > 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(_fault.slowStopMs)); + } AMediaCodec_stop(_codec); AMediaCodec_delete(_codec); _codec = nullptr; + WC_LOG("video encoder: released %s", _codecLabel.c_str()); } if (_nativeWindow) { ANativeWindow_release(_nativeWindow); _nativeWindow = nullptr; } + for (int end : _faultPipes) { + ::close(end); + } + _faultPipes.clear(); + } + + // stop() on a failure path, where the first error is the one to report. + void stopQuietly() { + try { + stop(); + } catch (...) { + } + } + + // Stops the codec from another thread than the GL thread, once: its input + // surface is let go, so a draw blocked waiting for the codec to take a + // buffer (eglSwapBuffers in dequeueBuffer) returns, and the GL thread gets + // to what comes next. The GL thread's stop() still deletes it. Under + // _codecMutex, which the drain thread holds while it reads an output + // buffer: stopping the codec takes its buffers back. + void abortCodec() { + std::lock_guard lock(_codecMutex); + if (!_liveCodec || _aborted) { + return; + } + _aborted = true; + WC_LOG("video encoder: stopping %s from another thread", _codecLabel.c_str()); + AMediaCodec_stop(_liveCodec); } void shutdown() { + if (_shutdown.exchange(true)) { + return; + } _closed = true; _failed = true; + _cv.notify_all(); auto done = std::make_shared>(); auto future = done->get_future(); _gl.post([this, done] { @@ -570,7 +873,18 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { _blitter.destroy(); done->set_value(); }); - future.wait(); + if (future.wait_for(kShutdownTimeout) == std::future_status::ready) { + return; + } + // The GL thread is stuck (in a draw into a codec that takes nothing): + // stopping the codec here lets it go on. + WC_LOG("video encoder: not stopped after %lld ms", static_cast(kShutdownTimeout.count())); + abortCodec(); + if (future.wait_for(kShutdownTimeout) != std::future_status::ready) { + // Left to finish on the GL thread: the destructor's ~SerialQueue + // waits for it, as it must while the task uses this object. + WC_ERR("video encoder: the GL thread is still busy"); + } } bool draining() { @@ -582,6 +896,22 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { pthread_setname_np(pthread_self(), "wc-venc-drain"); auto lastOutput = std::chrono::steady_clock::now(); while (draining()) { + if (_fault.stallOutputSeconds > 0) { + // Fault: the codec's output is never taken, as if it hung. + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + bool waiting = false; + { + std::lock_guard lock(_mutex); + waiting = !_timestamps.empty(); + } + if (!waiting) { + lastOutput = std::chrono::steady_clock::now(); + } else if (std::chrono::steady_clock::now() - lastOutput > std::chrono::seconds(_fault.stallOutputSeconds)) { + fail(errorMessage("EncodingError", "encoder-failed", "timed out waiting for the encoder"), true); + return; + } + continue; + } AMediaCodecBufferInfo info{}; ssize_t index = AMediaCodec_dequeueOutputBuffer(codec, &info, 10000); if (index == AMEDIACODEC_INFO_TRY_AGAIN_LATER) { @@ -589,12 +919,12 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { bool waiting = false; { std::lock_guard lock(_mutex); - waiting = !_durations.empty(); + waiting = !_timestamps.empty(); } if (!waiting) { lastOutput = std::chrono::steady_clock::now(); } else if (std::chrono::steady_clock::now() - lastOutput > kStallTimeout) { - fail(errorMessage("EncodingError", "encoder-failed", "timed out waiting for the encoder")); + fail(errorMessage("EncodingError", "encoder-failed", "timed out waiting for the encoder"), true); return; } continue; @@ -603,6 +933,10 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { continue; } lastOutput = std::chrono::steady_clock::now(); + { + std::lock_guard lock(_mutex); + _lastOutputAt = lastOutput; + } if (index == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { AMediaFormat* format = AMediaCodec_getOutputFormat(codec); void* sps = nullptr; @@ -620,7 +954,15 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { continue; } if (isCodecError(index)) { - fail(describeCodecStatus(static_cast(index), "encoder", "encoder")); + fail(describeCodecStatus(static_cast(index), "encoder", "encoder"), true); + return; + } + // From the buffer to its release, the codec is not stopped from another + // thread (abortCodec), which would take the buffer back mid-copy. No + // fail() in here: abortCodec() takes this mutex. + std::unique_lock codecLock(_codecMutex); + if (_aborted) { + // Stopped meanwhile: the index is no longer the codec's. return; } size_t capacity = 0; @@ -639,7 +981,19 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { } } AMediaCodec_releaseOutputBuffer(codec, index, false); - if (info.flags & kBufferFlagEndOfStream) { + codecLock.unlock(); + if ((info.flags & kBufferFlagEndOfStream) && !_fault.noEndOfStream) { + // Frames the codec took and never output (dropped): an empty chunk + // each, as VideoToolbox reports a dropped frame, so JS stops + // counting them. + // (flush() waits on the GL thread meanwhile: _framesIn is still.) + for (int64_t n = _framesIn - _framesOut; n > 0 && !_failed; n--) { + _output(NativeEncodedChunk(ArrayBuffer::allocate(0), 0, 0, false, std::nullopt)); + } + { + std::lock_guard lock(_mutex); + _timestamps.clear(); + } { std::lock_guard lock(_mutex); _eos = true; @@ -680,7 +1034,7 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { } // HDR: a half-float surface, converted to P010 into an input buffer. - void queueP010(AHardwareBuffer* buffer, int64_t ptsUs) { + void queueP010(AHardwareBuffer* buffer, int64_t ptsUs, FrameRead* read = nullptr) { AHardwareBuffer_Desc desc{}; AHardwareBuffer_describe(buffer, &desc); if (desc.format != AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT) { @@ -694,17 +1048,32 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { ssize_t index = dequeueInput(); size_t capacity = 0; uint8_t* dst = AMediaCodec_getInputBuffer(_codec, static_cast(index), &capacity); - size_t size = _stride * _sliceHeight * 3 / 2; + size_t size = p010Size(_stride, _sliceHeight); if (!dst || capacity < size) { throw std::runtime_error("the input buffer is too small for P010"); } + // No fence (-1): the caller waited for the frame's fence to signal + // (awaitFence). Passing it would hand it to gralloc, whose wait on it can + // be unbounded. void* src = nullptr; int locked = AHardwareBuffer_lock(buffer, AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN, -1, nullptr, &src); if (locked != 0 || !src) { throw std::runtime_error("AHardwareBuffer_lock failed (" + std::to_string(locked) + ")"); } - rgba16fToP010(static_cast(src), desc.stride * 4, width, height, dst, _stride, _sliceHeight); - AHardwareBuffer_unlock(buffer, nullptr); + { + // Unlocked whatever happens while it is read. + struct Unlock { + AHardwareBuffer* buffer; + ~Unlock() { + AHardwareBuffer_unlock(buffer, nullptr); + } + } unlock{buffer}; + rgba16fToP010(static_cast(src), desc.stride * 4, width, height, dst, _stride, _sliceHeight); + } + // Copied out and unlocked: its producer may have it back. + if (read) { + read->signal(); + } media_status_t status = AMediaCodec_queueInputBuffer(_codec, static_cast(index), 0, size, ptsUs, 0); if (status != AMEDIA_OK) { throw std::runtime_error("queueInputBuffer failed (" + std::to_string(status) + ")"); @@ -720,27 +1089,31 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { } } - double takeDuration(int64_t ptsUs) { + // The real timestamp and duration of the frame an output is (the codec's + // pts when no frame is waiting). + PendingFrame takeFrame(int64_t ptsUs) { std::lock_guard lock(_mutex); - auto it = _durations.find(ptsUs); - if (it == _durations.end()) { - return 0; + size_t skipped = 0; + auto frame = _timestamps.take(ptsUs, skipped); + _framesSkipped += static_cast(skipped); + if (!frame.has_value()) { + return {ptsUs, ptsUs, 0}; } - double duration = it->second; - _durations.erase(_durations.begin(), std::next(it)); - return duration; + return *frame; } // AV1 chunks are the OBUs as they come (low-overhead format, with sizes), // as WebCodecs has them. No description: the av1C record is optional, and // the sequence header is in the key frames. void emitAv1(const uint8_t* data, size_t size, int64_t ptsUs, bool key) { - double duration = takeDuration(ptsUs); + PendingFrame frame = takeFrame(ptsUs); if (_failed) { return; } std::vector chunk(data, data + size); - _output(NativeEncodedChunk(ArrayBuffer::move(std::move(chunk)), static_cast(ptsUs), duration, key, std::nullopt)); + frameOut(); + _output(NativeEncodedChunk(ArrayBuffer::move(std::move(chunk)), static_cast(frame.realTs), frame.duration, key, + std::nullopt)); } void emit(const uint8_t* data, size_t size, int64_t ptsUs, bool key) { @@ -762,7 +1135,7 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { avcc.push_back(static_cast(length)); avcc.insert(avcc.end(), unit, unit + length); } - double duration = takeDuration(ptsUs); + PendingFrame frame = takeFrame(ptsUs); std::optional> description; if (key) { auto record = makeAvcC(_sps, _pps); @@ -774,10 +1147,24 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { if (_failed) { return; } - _output(NativeEncodedChunk(ArrayBuffer::move(std::move(avcc)), static_cast(ptsUs), duration, key, description)); + frameOut(); + _output(NativeEncodedChunk(ArrayBuffer::move(std::move(avcc)), static_cast(frame.realTs), frame.duration, key, description)); } - void fail(const std::string& message) { + // Counts an output, and wakes a key frame request waiting for it. + void frameOut() { + { + std::lock_guard lock(_mutex); + _framesOut++; + } + _cv.notify_all(); + } + + // stopCodec: from the drain thread (holding no output buffer), whose + // failure may leave the GL thread blocked drawing into the codec. Not from + // the GL thread, which is not blocked, while the drain thread may be + // copying from an output buffer. + void fail(const std::string& message, bool stopCodec = false) { bool expected = false; if (!_reported.compare_exchange_strong(expected, true)) { return; @@ -788,6 +1175,11 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { _failed = true; } _cv.notify_all(); + // A failed codec takes nothing more: stop it now, so that the GL thread + // is not left blocked drawing into it. + if (stopCodec) { + abortCodec(); + } if (!_closed) { _error(message); } @@ -799,13 +1191,23 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { std::mutex _mutex; std::condition_variable _cv; - std::map _durations; + // Frames drawn and not yet output, in draw order. + TimestampQueue _timestamps; + // Frames the codec dropped (found when a later one came out). + int64_t _framesSkipped = 0; bool _eos = false; bool _draining = false; + // When the codec last output anything (flush() reads it for progress). + std::chrono::steady_clock::time_point _lastOutputAt; std::string _failure; std::atomic _failed{false}; std::atomic _closed{false}; std::atomic _reported{false}; + std::atomic _shutdown{false}; + // The codec between start() and stop(), for abortCodec() from any thread. + std::mutex _codecMutex; + AMediaCodec* _liveCodec = nullptr; + bool _aborted = false; // GL thread only. AMediaCodec* _codec = nullptr; @@ -813,14 +1215,25 @@ class HybridNativeVideoEncoder : public HybridNativeVideoEncoderSpec { EGLSurface _window = EGL_NO_SURFACE; GlBlitter _blitter; ColorAspects _aspects; - // The encoder chosen for the config and color aspects (empty: the type's - // default), looked up once. - std::optional _encoderName; + // The encoders that may take the config and color aspects, best first + // ("": the type's default), looked up once; the one that started first. + std::optional> _candidates; + // The configure attempt the encoder that started took. + size_t _firstAttempt = 0; size_t _stride = 0; size_t _sliceHeight = 0; - int64_t _framesIn = 0; + // Frames drawn into the current codec (GL thread), and output by it + // (drain thread). + std::atomic _framesIn{0}; + std::atomic _framesOut{0}; bool _ended = false; std::atomic _hardware{false}; + // Set in start(), before the drain thread starts (which reads it). + EncoderFault _fault; + // venc-fence-hang: the write ends of the pipes standing in for fences. + std::vector _faultPipes; + // The codec's name, for the log. + std::string _codecLabel; std::thread _drain; // Drain thread only. diff --git a/android/src/main/java/com/margelo/nitro/webcodecs/Capabilities.java b/android/src/main/java/com/margelo/nitro/webcodecs/Capabilities.java index e071558..20b5bf6 100644 --- a/android/src/main/java/com/margelo/nitro/webcodecs/Capabilities.java +++ b/android/src/main/java/com/margelo/nitro/webcodecs/Capabilities.java @@ -1,14 +1,17 @@ package com.margelo.nitro.webcodecs; +import android.media.CamcorderProfile; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.os.Build; -import android.util.Range; import androidx.annotation.Keep; import androidx.annotation.Nullable; -// What the device's encoders can do, from MediaCodecList: the NDK has no +import java.util.ArrayList; +import java.util.List; + +// What the device's codecs can do, from MediaCodecList: the NDK has no // capability queries before API 36. Called from C++ (VideoEncoder.hpp), for // VideoEncoder.isConfigSupported() and to create the encoder that answered, // so the two agree. @@ -17,16 +20,92 @@ public final class Capabilities { private Capabilities() {} /** - * The name of the first encoder for `mime` (in the platform's order, as - * MediaCodec.createEncoderByType picks) that takes frames of this size, at - * this frame rate and bitrate, in this profile and input color format; or - * null when none does. `frameRate`, `bitrate` and `profile` are ignored - * when 0 or less. + * The name of the encoder for `mime` that takes frames of this size, in + * this profile (ignored when 0 or less; when `profileOptional`, dropped + * when no encoder takes it) and input color format; or null when none + * does. Encoders that take the size as they say come before those only + * the lenient reading (as in Media3: see EncoderRules.sizeSupported) lets + * through; in each, the first hardware one in the platform's order (the + * order MediaCodec.createEncoderByType tries), else the first software + * one: see EncoderRules.choose. The frame rate and bitrate are hints, as + * in Media3: they refuse no encoder (see videoBitrate). */ @Keep @Nullable - public static String findVideoEncoder( - String mime, int width, int height, double frameRate, int bitrate, int profile, int colorFormat) { + public static String findVideoEncoder(String mime, int width, int height, int profile, boolean profileOptional, int colorFormat) { + return EncoderRules.choose(videoEncoders(mime), width, height, profile, profileOptional, colorFormat, Capabilities::camcorderHasHeight); + } + + /** + * Every encoder that may take the config, best first (findVideoEncoder's + * answer first), newline-separated: see EncoderRules.candidates. When + * configure() fails on one, the next is tried. + */ + @Keep + public static String findVideoEncoders(String mime, int width, int height, int profile, boolean profileOptional, int colorFormat) { + return String.join("\n", + EncoderRules.candidates(videoEncoders(mime), width, height, profile, profileOptional, colorFormat, Capabilities::camcorderHasHeight)); + } + + // Whether the device records 1080p (1080) or 4K (2160) video, by its + // CamcorderProfile: Media3's cross-check for encoders that list fewer rows + // than they take. False on devices with no camera. + private static boolean camcorderHasHeight(int height) { + int quality; + if (height == 1080) { + quality = CamcorderProfile.QUALITY_1080P; + } else if (height == 2160) { + quality = CamcorderProfile.QUALITY_2160P; + } else { + return false; + } + try { + return CamcorderProfile.hasProfile(quality); + } catch (RuntimeException e) { + return false; + } + } + + /** + * The bitrate to configure the encoder `name` with: `requested`, or when + * 0 or less width * height * fps * 0.1, clamped into the encoder's range + * when it lists one. `frameRate` is floored, and ignored below 1. + */ + @Keep + public static int videoBitrate(String name, String mime, double requested, int width, int height, double frameRate) { + int lower = 1; + int upper = Integer.MAX_VALUE; + for (EncoderRules.Encoder encoder : videoEncoders(mime)) { + if (encoder.name().equals(name)) { + lower = encoder.bitrateLower(); + upper = encoder.bitrateUpper(); + break; + } + } + return EncoderRules.bitrate(requested, width, height, frameRate, lower, upper); + } + + /** + * The H.264 profile and level (MediaCodecInfo.CodecProfileLevel) to give + * the encoder `name`, as (profile << 32) | level: see + * EncoderRules.avcProfile and avcLevel. 0 when the encoder lists no + * profile that will do, or is not found: it then gets neither. + */ + @Keep + public static long avcProfileLevel(String name, String mime, int profile, int levelIdc, int width, int height, double frameRate) { + for (EncoderRules.Encoder encoder : videoEncoders(mime)) { + if (encoder.name().equals(name)) { + int chosen = EncoderRules.avcProfile(encoder, profile); + int level = EncoderRules.avcLevel(encoder, chosen, levelIdc, width, height, frameRate); + return level > 0 ? ((long) chosen << 32) | level : 0; + } + } + return 0; + } + + // The encoders for `mime`, in the platform's order, aliases left out. + private static List videoEncoders(String mime) { + List encoders = new ArrayList<>(); MediaCodecInfo[] infos = new MediaCodecList(MediaCodecList.REGULAR_CODECS).getCodecInfos(); for (MediaCodecInfo info : infos) { if (!info.isEncoder()) { @@ -44,60 +123,141 @@ public static String findVideoEncoder( } catch (IllegalArgumentException e) { continue; } - if (fits(caps, width, height, frameRate, bitrate, profile, colorFormat)) { - return info.getName(); + if (caps.getVideoCapabilities() == null) { + continue; } + encoders.add(new VideoEncoder(info, caps)); } - return null; + return encoders; } - private static boolean supportsType(MediaCodecInfo info, String mime) { - for (String type : info.getSupportedTypes()) { - if (type.equalsIgnoreCase(mime)) { - return true; - } + // MediaCodecInfo's capabilities, as EncoderRules reads them. + private static final class VideoEncoder implements EncoderRules.Encoder { + private final MediaCodecInfo info; + private final MediaCodecInfo.CodecCapabilities caps; + private final MediaCodecInfo.VideoCapabilities video; + + VideoEncoder(MediaCodecInfo info, MediaCodecInfo.CodecCapabilities caps) { + this.info = info; + this.caps = caps; + this.video = caps.getVideoCapabilities(); } - return false; - } - private static boolean fits( - MediaCodecInfo.CodecCapabilities caps, - int width, - int height, - double frameRate, - int bitrate, - int profile, - int colorFormat) { - MediaCodecInfo.VideoCapabilities video = caps.getVideoCapabilities(); - if (video == null) { - return false; + @Override + public String name() { + return info.getName(); } - boolean size = frameRate > 0 - ? video.areSizeAndRateSupported(width, height, frameRate) - : video.isSizeSupported(width, height); - if (!size) { - return false; + + @Override + public boolean isSizeSupported(int width, int height) { + return video.isSizeSupported(width, height); + } + + @Override + public boolean hardware() { + return !isSoftwareOnly(info); + } + + @Override + public int widthAlignment() { + return video.getWidthAlignment(); + } + + @Override + public int heightAlignment() { + return video.getHeightAlignment(); } - if (bitrate > 0) { - Range range = video.getBitrateRange(); - if (!range.contains(bitrate)) { - return false; + + @Override + public int bitrateLower() { + return video.getBitrateRange().getLower(); + } + + @Override + public int bitrateUpper() { + return video.getBitrateRange().getUpper(); + } + + @Override + public int[] profiles() { + int[] profiles = new int[caps.profileLevels.length]; + for (int i = 0; i < profiles.length; i++) { + profiles[i] = caps.profileLevels[i].profile; } + return profiles; } - if (profile > 0) { - boolean found = false; - for (MediaCodecInfo.CodecProfileLevel level : caps.profileLevels) { - if (level.profile == profile) { - found = true; - break; - } + + @Override + public int[] levels() { + int[] levels = new int[caps.profileLevels.length]; + for (int i = 0; i < levels.length; i++) { + levels[i] = caps.profileLevels[i].level; } - if (!found) { - return false; + return levels; + } + + @Override + public int[] colorFormats() { + return caps.colorFormats; + } + } + + /** + * The decoders for `mime` that take pictures of this size (either way + * round), newline-separated, in the platform's order (the order + * MediaCodec.createDecoderByType tries them in), aliases left out. With + * `preference` "prefer-software", software decoders only; with + * "prefer-hardware", all but the software ones; otherwise all. + */ + @Keep + public static String findVideoDecoders(String mime, int width, int height, String preference) { + boolean software = "prefer-software".equals(preference); + boolean hardware = "prefer-hardware".equals(preference); + StringBuilder names = new StringBuilder(); + MediaCodecInfo[] infos = new MediaCodecList(MediaCodecList.REGULAR_CODECS).getCodecInfos(); + for (MediaCodecInfo info : infos) { + if (info.isEncoder()) { + continue; } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && info.isAlias()) { + continue; + } + if (!supportsType(info, mime)) { + continue; + } + boolean isSoftware = isSoftwareOnly(info); + if ((software && !isSoftware) || (hardware && isSoftware)) { + continue; + } + MediaCodecInfo.VideoCapabilities video; + try { + video = info.getCapabilitiesForType(mime).getVideoCapabilities(); + } catch (IllegalArgumentException e) { + continue; + } + if (video != null && width > 0 && height > 0 + && !video.isSizeSupported(width, height) && !video.isSizeSupported(height, width)) { + continue; + } + if (names.length() > 0) { + names.append('\n'); + } + names.append(info.getName()); + } + return names.toString(); + } + + private static boolean isSoftwareOnly(MediaCodecInfo info) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + return info.isSoftwareOnly(); } - for (int format : caps.colorFormats) { - if (format == colorFormat) { + String name = info.getName(); + return name.startsWith("c2.android.") || name.startsWith("OMX.google."); + } + + private static boolean supportsType(MediaCodecInfo info, String mime) { + for (String type : info.getSupportedTypes()) { + if (type.equalsIgnoreCase(mime)) { return true; } } diff --git a/android/src/main/java/com/margelo/nitro/webcodecs/EncoderRules.java b/android/src/main/java/com/margelo/nitro/webcodecs/EncoderRules.java new file mode 100644 index 0000000..a66e602 --- /dev/null +++ b/android/src/main/java/com/margelo/nitro/webcodecs/EncoderRules.java @@ -0,0 +1,297 @@ +package com.margelo.nitro.webcodecs; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntPredicate; +import java.util.function.Predicate; + +// The rules Capabilities applies to MediaCodecList's answers, apart from +// MediaCodecInfo (whose classes are stubs on the JVM): unit-tested in +// android/src/test/java (`yarn test:jvm`). +final class EncoderRules { + private EncoderRules() {} + + /** What an encoder says it takes, as MediaCodecInfo's capabilities say. */ + interface Encoder { + String name(); + + /** False for software-only encoders (c2.android.*, OMX.google.*). */ + boolean hardware(); + + boolean isSizeSupported(int width, int height); + + int widthAlignment(); + + int heightAlignment(); + + int bitrateLower(); + + int bitrateUpper(); + + int[] profiles(); + + /** The level of each of profiles(), as MediaCodecInfo pairs them. */ + int[] levels(); + + int[] colorFormats(); + } + + /** + * Whether the encoder takes frames of this size (see sizeSupported), in + * this profile (ignored when 0 or less) and input color format. The frame + * rate and bitrate are hints, as in Media3: they never refuse an encoder + * (the bitrate is clamped into its range, see bitrate()). + */ + static boolean fits(Encoder encoder, int width, int height, int profile, int colorFormat, IntPredicate camcorderHasHeight) { + return sizeSupported(encoder, width, height, camcorderHasHeight) && takes(encoder, profile, colorFormat); + } + + /** fits(), with no camcorder profile to vouch for a size. */ + static boolean fits(Encoder encoder, int width, int height, int profile, int colorFormat) { + return fits(encoder, width, height, profile, colorFormat, h -> false); + } + + /** fits(), with the size as asked for: as the encoder says, not leniently. */ + static boolean fitsStrictly(Encoder encoder, int width, int height, int profile, int colorFormat) { + return encoder.isSizeSupported(width, height) && takes(encoder, profile, colorFormat); + } + + private static boolean takes(Encoder encoder, int profile, int colorFormat) { + if (profile > 0 && !contains(encoder.profiles(), profile)) { + return false; + } + return contains(encoder.colorFormats(), colorFormat); + } + + /** + * The encoder to make, or null when none fits: the first of candidates(). + */ + static String choose(List encoders, int width, int height, int profile, boolean profileOptional, int colorFormat, + IntPredicate camcorderHasHeight) { + List names = candidates(encoders, width, height, profile, profileOptional, colorFormat, camcorderHasHeight); + return names.isEmpty() ? null : names.get(0); + } + + /** choose(), with the profile required. */ + static String choose( + List encoders, int width, int height, int profile, int colorFormat, IntPredicate camcorderHasHeight) { + return choose(encoders, width, height, profile, false, colorFormat, camcorderHasHeight); + } + + /** + * The encoders that may take the config, best first, each once: the + * encoder is configured with the size asked for, so as in Media3 those + * that take that size as they say come first: + * 1. that take the size strictly, in the profile; + * 2. that take it strictly, in any profile (when `profileOptional`); + * 3. that take it as read leniently (see sizeSupported), in the profile; + * 4. that take it leniently, in any profile (when `profileOptional`). + * In each, the hardware encoders in the platform's order, then the + * software ones. When configure() fails on one, the next is tried. + */ + static List candidates(List encoders, int width, int height, int profile, boolean profileOptional, + int colorFormat, IntPredicate camcorderHasHeight) { + boolean dropProfile = profileOptional && profile > 0; + List names = new ArrayList<>(); + addAll(names, encoders, e -> fitsStrictly(e, width, height, profile, colorFormat)); + if (dropProfile) { + addAll(names, encoders, e -> fitsStrictly(e, width, height, 0, colorFormat)); + } + addAll(names, encoders, e -> fits(e, width, height, profile, colorFormat, camcorderHasHeight)); + if (dropProfile) { + addAll(names, encoders, e -> fits(e, width, height, 0, colorFormat, camcorderHasHeight)); + } + return names; + } + + // Adds the encoders `fit` takes that are not in `names` yet: the hardware + // ones in the platform's order, then the software ones. + private static void addAll(List names, List encoders, Predicate fit) { + for (boolean hardware : new boolean[] {true, false}) { + for (Encoder encoder : encoders) { + if (encoder.hardware() == hardware && !names.contains(encoder.name()) && fit.test(encoder)) { + names.add(encoder.name()); + } + } + } + } + + /** + * Whether the encoder takes frames of this size, read leniently, as Media3 + * and ExoPlayer do (the encoder is still given the size asked for): + * - also aligned up to the encoder's alignment, for even sizes: encoders + * listing 16 often take 1080 rows (ExoPlayer #6551), while odd sizes + * are refused by encoders aligned to 2; + * - also swapped: encoders limit the number of macroblocks rather than + * the orientation; + * - 1920x1080 and 3840x2160 also when `camcorderHasHeight` (the device's + * CamcorderProfile) has 1080 or 2160: some Samsung, Huawei and Pixel 6 + * encoders list 1072 and 2144 rows (b/222095724, b/229825948). + */ + static boolean sizeSupported(Encoder encoder, int width, int height, IntPredicate camcorderHasHeight) { + return landscapeOrPortraitSupported(encoder, width, height, camcorderHasHeight) + || landscapeOrPortraitSupported(encoder, height, width, camcorderHasHeight); + } + + private static boolean landscapeOrPortraitSupported(Encoder encoder, int width, int height, IntPredicate camcorderHasHeight) { + if (encoder.isSizeSupported(width, height)) { + return true; + } + // Even sizes only: the encoder is given the size asked for, and an odd + // one is refused by encoders aligned to 2 (the 1080-rows case is even). + if (width % 2 == 0 && height % 2 == 0) { + int alignedWidth = alignUp(width, encoder.widthAlignment()); + int alignedHeight = alignUp(height, encoder.heightAlignment()); + if ((alignedWidth != width || alignedHeight != height) && encoder.isSizeSupported(alignedWidth, alignedHeight)) { + return true; + } + } + if (width == 1920 && height == 1080) { + return camcorderHasHeight.test(1080); + } + if (width == 3840 && height == 2160) { + return camcorderHasHeight.test(2160); + } + return false; + } + + static int alignUp(int value, int alignment) { + if (alignment <= 1) { + return value; + } + return (value + alignment - 1) / alignment * alignment; + } + + /** + * The frame rate to configure: a hint, floored to whole frames (some + * encoders refuse a fractional one); 0 (none: the default) below 1. + */ + static double frameRate(double frameRate) { + if (!(frameRate >= 1)) { + return 0; + } + return Math.floor(frameRate); + } + + /** + * The bitrate to configure: the one asked for, or when none (0 or less) + * width * height * fps * 0.1 (fps 30 when none); a hint either way, + * clamped into the encoder's range [lower, upper]. + */ + static int bitrate(double requested, int width, int height, double frameRate, int lower, int upper) { + double fps = frameRate(frameRate) > 0 ? frameRate(frameRate) : 30; + double bitrate = requested > 0 ? requested : (double) width * height * fps * 0.1; + return (int) Math.max(lower, Math.min(upper, bitrate)); + } + + static boolean contains(int[] values, int value) { + for (int v : values) { + if (v == value) { + return true; + } + } + return false; + } + + // H.264's levels (Rec. ITU-T H.264 Table A-1): level_idc, the + // MediaCodecInfo.CodecProfileLevel.AVCLevel* constant, the most + // macroblocks a second (MaxMBPS) and in a frame (MaxFS). Level 1b is + // level_idc 9 here (in avc1 codec strings it is 11 with a constraint flag, + // read as 1.1). The constants grow with the level. + private static final int[][] AVC_LEVELS = { + {10, 0x01, 1485, 99}, + {9, 0x02, 1485, 99}, + {11, 0x04, 3000, 396}, + {12, 0x08, 6000, 396}, + {13, 0x10, 11880, 396}, + {20, 0x20, 11880, 396}, + {21, 0x40, 19800, 792}, + {22, 0x80, 20250, 1620}, + {30, 0x100, 40500, 1620}, + {31, 0x200, 108000, 3600}, + {32, 0x400, 216000, 5120}, + {40, 0x800, 245760, 8192}, + {41, 0x1000, 245760, 8192}, + {42, 0x2000, 522240, 8704}, + {50, 0x4000, 589824, 22080}, + {51, 0x8000, 983040, 36864}, + {52, 0x10000, 2073600, 36864}, + {60, 0x20000, 4177920, 139264}, + {61, 0x40000, 8355840, 139264}, + {62, 0x80000, 16711680, 139264}, + }; + + /** The AVCLevel* constant of an H.264 level_idc, or 0 when there is none. */ + static int avcLevelOf(int levelIdc) { + for (int[] level : AVC_LEVELS) { + if (level[0] == levelIdc) { + return level[1]; + } + } + return 0; + } + + // The lowest level whose limits take this size at this frame rate (30 + // when none); the highest when none does. + private static int avcLevelNeeded(int width, int height, double frameRate) { + double fps = frameRate(frameRate) > 0 ? frameRate(frameRate) : 30; + long macroblocks = (long) ((width + 15) / 16) * ((height + 15) / 16); + for (int[] level : AVC_LEVELS) { + if (level[0] != 9 && macroblocks <= level[3] && macroblocks * fps <= level[2]) { + return level[1]; + } + } + return AVC_LEVELS[AVC_LEVELS.length - 1][1]; + } + + // AVCProfileHigh, AVCProfileMain, AVCProfileBaseline: each decodable by a + // decoder of the one before (the encoders' Baseline is the constrained + // one). + private static final int[] AVC_PROFILES_DOWN = {8, 2, 1}; + + /** + * The H.264 profile to configure the encoder with: `profile` when it + * lists it, else the next one down it lists (High, Main, Baseline), so + * that the stream still decodes as the codec string says; 0 (none) when + * it lists none of them, or none is asked for. + */ + static int avcProfile(Encoder encoder, int profile) { + boolean below = false; + for (int candidate : AVC_PROFILES_DOWN) { + below = below || candidate == profile; + if (below && contains(encoder.profiles(), candidate)) { + return candidate; + } + } + return 0; + } + + /** + * The H.264 level (an AVCLevel* constant) to configure along with + * `profile`, as Media3 and Chromium set both (OMX encoders refuse a + * profile without a level): the codec string's level (`levelIdc`; when 0 + * or unknown, the encoder's highest for the profile, as Media3), raised to + * the lowest one that takes the size at the frame rate, and capped at the + * highest the encoder lists for the profile. 0 when the encoder does not + * list the profile (or none is asked for): it is then given neither. + */ + static int avcLevel(Encoder encoder, int profile, int levelIdc, int width, int height, double frameRate) { + if (profile <= 0) { + return 0; + } + int[] profiles = encoder.profiles(); + int[] levels = encoder.levels(); + int highest = 0; + for (int i = 0; i < profiles.length && i < levels.length; i++) { + if (profiles[i] == profile) { + highest = Math.max(highest, levels[i]); + } + } + if (highest == 0) { + return 0; + } + int asked = avcLevelOf(levelIdc); + int level = asked > 0 ? Math.max(asked, avcLevelNeeded(width, height, frameRate)) : highest; + return Math.min(level, highest); + } +} diff --git a/android/src/test/cpp/audio_rules_test.cpp b/android/src/test/cpp/audio_rules_test.cpp new file mode 100644 index 0000000..d67a3a5 --- /dev/null +++ b/android/src/test/cpp/audio_rules_test.cpp @@ -0,0 +1,64 @@ +// Host test of android/src/main/cpp/AudioRules.hpp: `yarn test:cpp`. + +#include "AudioRules.hpp" + +#include +#include + +using namespace margelo::nitro::webcodecs; + +static int failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +static void encoderDelay() { + CHECK(aacEncoderDelay("c2.android.aac.encoder") == 1600); + CHECK(aacEncoderDelay("OMX.google.aac.encoder") == 1600); + CHECK(!aacEncoderDelay("c2.sec.aac.encoder").has_value()); + CHECK(!aacEncoderDelay("OMX.qcom.audio.encoder.aac").has_value()); + CHECK(!aacEncoderDelay("").has_value()); +} + +static void keepFrame() { + // 1 s at 48 kHz with FDK's delay: frames 0 to 48 carry sound (48 * 1024 = + // 49152 < 49600), frame 49 only the padding. + int64_t kept = 0; + for (int64_t n = 0; n < 60; n++) { + kept += aacKeepFrame(n, 48000, 1600) ? 1 : 0; + } + CHECK(kept == 49); + CHECK(aacKeepFrame(48, 48000, 1600)); + CHECK(!aacKeepFrame(49, 48000, 1600)); + // Nothing fed: nothing past the delay. + CHECK(aacKeepFrame(1, 0, 1600)); + CHECK(!aacKeepFrame(2, 0, 1600)); + // An encoder of unknown delay: nothing is trimmed. + CHECK(aacKeepFrame(49, 48000, std::nullopt)); + CHECK(aacKeepFrame(1000, 48000, std::nullopt)); +} + +static void decoderFlush() { + CHECK(decoderFlushAction(0, false) == DecoderFlush::Skip); + CHECK(decoderFlushAction(0, true) == DecoderFlush::Skip); + CHECK(decoderFlushAction(1, true) == DecoderFlush::Flush); + CHECK(decoderFlushAction(376, true) == DecoderFlush::Flush); + CHECK(decoderFlushAction(1, false) == DecoderFlush::Recreate); +} + +int main() { + encoderDelay(); + keepFrame(); + decoderFlush(); + if (failures > 0) { + std::fprintf(stderr, "%d check(s) failed\n", failures); + return EXIT_FAILURE; + } + std::printf("audio rules: all checks passed\n"); + return EXIT_SUCCESS; +} diff --git a/android/src/test/cpp/encoder_attempts_test.cpp b/android/src/test/cpp/encoder_attempts_test.cpp new file mode 100644 index 0000000..aca6819 --- /dev/null +++ b/android/src/test/cpp/encoder_attempts_test.cpp @@ -0,0 +1,97 @@ +// Host test of android/src/main/cpp/EncoderAttempts.hpp: `yarn test:cpp`. + +#include "EncoderAttempts.hpp" + +#include +#include +#include + +using namespace margelo::nitro::webcodecs; + +static int failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +static bool same(const EncoderAttempt& a, bool profile, int32_t operatingRate, bool capFrameRate) { + return a.profile == profile && a.operatingRate == operatingRate && a.capFrameRate == capFrameRate; +} + +// With a profile, the rate settings are relaxed one at a time with the +// profile kept; dropping the profile starts the rates over (it no longer +// also caps the frame rate and drops the operating rate). +static void withProfile() { + auto attempts = videoEncoderAttempts(true, false); + CHECK(attempts.size() == 6); + if (attempts.size() == 6) { + CHECK(same(attempts[0], true, kOperatingRateMax, false)); + CHECK(same(attempts[1], true, kOperatingRateLow, false)); + CHECK(same(attempts[2], true, kOperatingRateNone, true)); + CHECK(same(attempts[3], false, kOperatingRateMax, false)); + CHECK(same(attempts[4], false, kOperatingRateLow, false)); + CHECK(same(attempts[5], false, kOperatingRateNone, true)); + } +} + +// No profile to drop (none asked for, the encoder lists none, or AV1's, +// which is required): the rate steps only. +static void withoutProfile() { + auto attempts = videoEncoderAttempts(false, false); + CHECK(attempts.size() == 3); + if (attempts.size() == 3) { + CHECK(same(attempts[0], false, kOperatingRateMax, false)); + CHECK(same(attempts[1], false, kOperatingRateLow, false)); + CHECK(same(attempts[2], false, kOperatingRateNone, true)); + } +} + +// Realtime sets no operating rate: no two attempts are the same. +static void realtime() { + auto attempts = videoEncoderAttempts(true, true); + CHECK(attempts.size() == 4); + if (attempts.size() == 4) { + CHECK(same(attempts[0], true, kOperatingRateNone, false)); + CHECK(same(attempts[1], true, kOperatingRateNone, true)); + CHECK(same(attempts[2], false, kOperatingRateNone, false)); + CHECK(same(attempts[3], false, kOperatingRateNone, true)); + } + CHECK(videoEncoderAttempts(false, true).size() == 2); +} + +static void describe() { + CHECK(describeAttempt(EncoderAttempt{true, kOperatingRateMax, false}) == "profile and level, operating rate max"); + CHECK(describeAttempt(EncoderAttempt{false, kOperatingRateLow, false}) == "no profile, operating rate 1000"); + CHECK(describeAttempt(EncoderAttempt{false, kOperatingRateNone, true}) == "no profile, no operating rate, at most 30 fps"); +} + +// media_status_t values by name, for the error message. +static void statusNames() { + CHECK(std::string(mediaStatusName(-10000)) == "AMEDIA_ERROR_UNKNOWN"); + // A status_t MediaCodec passes through: -ENOMEM. + CHECK(std::string(mediaStatusName(-12)) == "NO_MEMORY"); + CHECK(std::string(mediaStatusName(-10004)) == "AMEDIA_ERROR_INVALID_PARAMETER"); + CHECK(std::string(mediaStatusName(1100)) == "ERROR_INSUFFICIENT_RESOURCE"); + CHECK(std::string(mediaStatusName(1101)) == "ERROR_RECLAIMED"); + CHECK(std::string(mediaStatusName(42)) == ""); + CHECK(describeMediaStatus(-12) == "-12 NO_MEMORY"); + CHECK(describeMediaStatus(7) == "7"); +} + +int main() { + withProfile(); + withoutProfile(); + realtime(); + describe(); + statusNames(); + if (failures > 0) { + std::fprintf(stderr, "%d failed\n", failures); + return EXIT_FAILURE; + } + std::printf("encoder_attempts: ok\n"); + return EXIT_SUCCESS; +} diff --git a/android/src/test/cpp/fence_test.cpp b/android/src/test/cpp/fence_test.cpp new file mode 100644 index 0000000..7f5f3db --- /dev/null +++ b/android/src/test/cpp/fence_test.cpp @@ -0,0 +1,160 @@ +// Host test of android/src/main/cpp/Fence.hpp: `yarn test:cpp`. A pipe's +// read end stands in for a sync fd: unsignalled while nothing is written to +// it, signalled once a byte is. + +#include "Fence.hpp" + +#include +#include +#include + +#include +#include +#include + +using namespace margelo::nitro::webcodecs; + +static int failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +using Clock = std::chrono::steady_clock; + +static long long msSince(Clock::time_point start) { + return std::chrono::duration_cast(Clock::now() - start).count(); +} + +static bool isOpen(int fd) { + return ::fcntl(fd, F_GETFD) != -1; +} + +static void noFence() { + CHECK(waitSyncFd(-1, 10) == FenceWait::Signaled); + awaitFence(-1, 10); +} + +static void signaled() { + int ends[2]; + CHECK(::pipe(ends) == 0); + CHECK(::write(ends[1], "x", 1) == 1); + auto start = Clock::now(); + CHECK(waitSyncFd(ends[0], 1000) == FenceWait::Signaled); + CHECK(msSince(start) < 100); + // Not closed by the wait. + CHECK(isOpen(ends[0])); + ::close(ends[0]); + ::close(ends[1]); +} + +// Signalled while waiting: the wait ends then, not at the timeout. +static void signaledLater() { + int ends[2]; + CHECK(::pipe(ends) == 0); + std::thread writer([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + CHECK(::write(ends[1], "x", 1) == 1); + }); + auto start = Clock::now(); + CHECK(waitSyncFd(ends[0], 2000) == FenceWait::Signaled); + long long ms = msSince(start); + CHECK(ms >= 40 && ms < 1000); + writer.join(); + ::close(ends[0]); + ::close(ends[1]); +} + +// Never signalled: the wait ends at the timeout. +static void timedOut() { + int ends[2]; + CHECK(::pipe(ends) == 0); + auto start = Clock::now(); + CHECK(waitSyncFd(ends[0], 100) == FenceWait::TimedOut); + long long ms = msSince(start); + CHECK(ms >= 95 && ms < 1000); + ::close(ends[0]); + ::close(ends[1]); +} + +static void onAlarm(int) {} + +// A signal in the middle (EINTR) neither ends the wait early nor makes it +// longer than its timeout. +static void interrupted() { + struct sigaction action {}; + action.sa_handler = onAlarm; + sigemptyset(&action.sa_mask); + action.sa_flags = 0; // no SA_RESTART: poll() returns EINTR + struct sigaction previous {}; + sigaction(SIGALRM, &action, &previous); + itimerval timer{}; + timer.it_value.tv_usec = 20 * 1000; + timer.it_interval.tv_usec = 20 * 1000; + setitimer(ITIMER_REAL, &timer, nullptr); + + int ends[2]; + CHECK(::pipe(ends) == 0); + auto start = Clock::now(); + CHECK(waitSyncFd(ends[0], 200) == FenceWait::TimedOut); + long long ms = msSince(start); + CHECK(ms >= 190 && ms < 1000); + + itimerval off{}; + setitimer(ITIMER_REAL, &off, nullptr); + sigaction(SIGALRM, &previous, nullptr); + ::close(ends[0]); + ::close(ends[1]); +} + +// Not a file descriptor (POLLNVAL): failed, at once. +static void invalid() { + int ends[2]; + CHECK(::pipe(ends) == 0); + ::close(ends[0]); + ::close(ends[1]); + auto start = Clock::now(); + CHECK(waitSyncFd(ends[0], 1000) == FenceWait::Failed); + CHECK(msSince(start) < 100); +} + +// awaitFence closes the fence either way, and throws unless it signalled. +static void await() { + int ends[2]; + CHECK(::pipe(ends) == 0); + CHECK(::write(ends[1], "x", 1) == 1); + awaitFence(ends[0], 100); + CHECK(!isOpen(ends[0])); + ::close(ends[1]); + + CHECK(::pipe(ends) == 0); + bool threw = false; + try { + awaitFence(ends[0], 50); + } catch (const std::runtime_error& e) { + threw = std::string(e.what()).find("did not signal within 50 ms") != std::string::npos; + } + CHECK(threw); + CHECK(!isOpen(ends[0])); + ::close(ends[1]); +} + +int main() { + noFence(); + signaled(); + signaledLater(); + timedOut(); + interrupted(); + invalid(); + await(); + if (failures > 0) { + std::fprintf(stderr, "fence: %d check(s) failed\n", failures); + return 1; + } + std::printf("fence: ok\n"); + return 0; +} diff --git a/android/src/test/cpp/p010_test.cpp b/android/src/test/cpp/p010_test.cpp new file mode 100644 index 0000000..3618456 --- /dev/null +++ b/android/src/test/cpp/p010_test.cpp @@ -0,0 +1,163 @@ +// Host test of android/src/main/cpp/P010.hpp: `yarn test:cpp` (ASan finds +// writes past the buffers). + +#include "P010.hpp" + +#include +#include +#include + +using namespace margelo::nitro::webcodecs; + +static int failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +#define CHECK_EQ(a, b) \ + do { \ + long long va = static_cast(a), vb = static_cast(b); \ + if (va != vb) { \ + std::fprintf(stderr, "%s:%d: %s == %s (%lld != %lld)\n", __FILE__, __LINE__, #a, #b, va, vb); \ + failures++; \ + } \ + } while (0) + +struct Rgb { + float r, g, b; +}; + +static uint16_t toHalf(float v) { + __fp16 h = static_cast<__fp16>(v); + uint16_t bits; + std::memcpy(&bits, &h, sizeof(bits)); + return bits; +} + +// A picture converted as queueP010 does with a codec that reports no layout: +// the stride and size it computes, the buffer exactly that large. +struct P010 { + int width, height; + size_t stride, sliceHeight; + std::vector bytes; + + uint16_t y(int x, int row) const { + uint16_t v; + std::memcpy(&v, bytes.data() + row * stride + x * 2, 2); + return v; + } + // Chroma pair `i` of chroma row `row`: Cb, then Cr. + uint16_t cb(int i, int row) const { + uint16_t v; + std::memcpy(&v, bytes.data() + (sliceHeight + row) * stride + i * 4, 2); + return v; + } + uint16_t cr(int i, int row) const { + uint16_t v; + std::memcpy(&v, bytes.data() + (sliceHeight + row) * stride + i * 4 + 2, 2); + return v; + } +}; + +static P010 convert(int width, int height, const std::function& pixel) { + // Rows of the source padded, as an AHardwareBuffer's may be. + size_t srcStride = static_cast(width + 3) * 4; + std::vector src(srcStride * height, toHalf(0.5f)); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + Rgb c = pixel(x, y); + uint16_t* p = &src[y * srcStride + x * 4]; + p[0] = toHalf(c.r); + p[1] = toHalf(c.g); + p[2] = toHalf(c.b); + p[3] = toHalf(1.0f); + } + } + P010 out{width, height, p010Stride(width, 0), static_cast(height), {}}; + out.bytes.assign(p010Size(out.stride, out.sliceHeight), 0); + rgba16fToP010(src.data(), srcStride, width, height, out.bytes.data(), out.stride, out.sliceHeight); + return out; +} + +static const Rgb kRed{1, 0, 0}; +static const Rgb kBlack{0, 0, 0}; +static const Rgb kWhite{1, 1, 1}; + +// White and black land on the limited-range codes, in the top 10 bits. +static void whiteAndBlack() { + P010 white = convert(4, 2, [](int, int) { return kWhite; }); + CHECK_EQ(white.y(0, 0), 940 << 6); + CHECK_EQ(white.y(3, 1), 940 << 6); + CHECK_EQ(white.cb(0, 0), 512 << 6); + CHECK_EQ(white.cr(1, 0), 512 << 6); + P010 black = convert(4, 2, [](int, int) { return kBlack; }); + CHECK_EQ(black.y(2, 1), 64 << 6); + CHECK_EQ(black.cb(1, 0), 512 << 6); +} + +// An odd width: the last column has a chroma pair of its own, written. +static void oddWidth() { + P010 even = convert(2, 2, [](int, int) { return kRed; }); + P010 odd = convert(3, 2, [](int x, int) { return x == 2 ? kRed : kBlack; }); + CHECK_EQ(odd.y(2, 0), even.y(0, 0)); + CHECK_EQ(odd.cb(0, 0), 512 << 6); + CHECK_EQ(odd.cb(1, 0), even.cb(0, 0)); + CHECK_EQ(odd.cr(1, 0), even.cr(0, 0)); +} + +// An odd height: the last row has a chroma row of its own, as saturated as +// the others (an average of the samples there are, not of four). +static void oddHeight() { + P010 even = convert(2, 2, [](int, int) { return kRed; }); + P010 odd = convert(2, 3, [](int, int) { return kRed; }); + CHECK_EQ(odd.cb(0, 0), even.cb(0, 0)); + CHECK_EQ(odd.cr(0, 0), even.cr(0, 0)); + CHECK_EQ(odd.cb(0, 1), even.cb(0, 0)); + CHECK_EQ(odd.cr(0, 1), even.cr(0, 0)); +} + +// Both odd, and a size where each odd dimension is larger. +static void oddBoth() { + P010 even = convert(2, 2, [](int, int) { return kRed; }); + P010 odd = convert(5, 5, [](int, int) { return kRed; }); + for (int row = 0; row < 3; row++) { + for (int i = 0; i < 3; i++) { + CHECK_EQ(odd.cb(i, row), even.cb(0, 0)); + CHECK_EQ(odd.cr(i, row), even.cr(0, 0)); + } + } + CHECK_EQ(odd.y(4, 4), even.y(0, 0)); +} + +// The codec's stride wins, in bytes or in pixels; the chroma rows always fit. +static void strides() { + CHECK_EQ(p010Stride(1920, 0), 3840); + CHECK_EQ(p010Stride(1920, 4096), 4096); + CHECK_EQ(p010Stride(1920, 1920), 3840); + CHECK_EQ(p010Stride(1920, 2048), 4096); + CHECK(p010Stride(3, 0) >= 8); + CHECK(p010Stride(3, 3) >= 8); + // The size covers the chroma rows of every luma row. + CHECK_EQ(p010Size(3840, 1080), 3840 * 1620); + CHECK_EQ(p010Size(3840, 1088), 3840 * 1632); + CHECK_EQ(p010Size(8, 3), 8 * 5); +} + +int main() { + whiteAndBlack(); + oddWidth(); + oddHeight(); + oddBoth(); + strides(); + if (failures > 0) { + std::fprintf(stderr, "p010: %d check(s) failed\n", failures); + return 1; + } + std::printf("p010: ok\n"); + return 0; +} diff --git a/android/src/test/cpp/timestamps_test.cpp b/android/src/test/cpp/timestamps_test.cpp new file mode 100644 index 0000000..e1af885 --- /dev/null +++ b/android/src/test/cpp/timestamps_test.cpp @@ -0,0 +1,141 @@ +// Host test of android/src/main/cpp/Timestamps.hpp: `yarn test:cpp`. + +#include "Timestamps.hpp" + +#include +#include + +using namespace margelo::nitro::webcodecs; + +static int failures = 0; + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +static bool is(const std::optional& f, int64_t realTs, double duration) { + return f.has_value() && f->realTs == realTs && f->duration == duration; +} + +// Increasing timestamps go to the codec as they are, and come back with +// their durations. +static void inOrder() { + TimestampQueue q; + CHECK(q.push(0, 10) == 0); + CHECK(q.push(33333, 11) == 33333); + CHECK(q.push(66666, 12) == 66666); + size_t skipped = 9; + CHECK(is(q.take(0, skipped), 0, 10)); + CHECK(skipped == 0); + CHECK(is(q.take(33333, skipped), 33333, 11)); + CHECK(is(q.take(66666, skipped), 66666, 12)); + CHECK(q.empty()); +} + +// A first frame at 0 is not moved: there is nothing before it. +static void firstAtZero() { + TimestampQueue q; + CHECK(q.push(0, 1) == 0); + q.clear(); + CHECK(q.empty()); + // After clear() (a new codec) the timeline starts over. + CHECK(q.push(0, 1) == 0); +} + +// A repeated timestamp goes to the codec 1 us later; the chunk has the real +// one. +static void repeated() { + TimestampQueue q; + CHECK(q.push(0, 10) == 0); + CHECK(q.push(0, 11) == 1); + CHECK(q.push(33333, 12) == 33333); + size_t skipped = 0; + CHECK(is(q.take(0, skipped), 0, 10)); + CHECK(is(q.take(1, skipped), 0, 11)); + CHECK(is(q.take(33333, skipped), 33333, 12)); + CHECK(skipped == 0); +} + +// A timestamp going backwards goes to the codec 1 us after the last one, +// and so does the next one if still not past it. +static void backwards() { + TimestampQueue q; + CHECK(q.push(0, 10) == 0); + CHECK(q.push(33333, 11) == 33333); + CHECK(q.push(20000, 12) == 33334); + CHECK(q.push(33334, 13) == 33335); + CHECK(q.push(66666, 14) == 66666); + size_t skipped = 0; + q.take(0, skipped); + q.take(33333, skipped); + CHECK(is(q.take(33334, skipped), 20000, 12)); + CHECK(is(q.take(33335, skipped), 33334, 13)); + CHECK(is(q.take(66666, skipped), 66666, 14)); +} + +// A frame the codec dropped is skipped (and counted); the later ones keep +// their own timestamps. +static void droppedMiddle() { + TimestampQueue q; + q.push(0, 10); + q.push(33333, 11); + q.push(66666, 12); + q.push(99999, 13); + size_t skipped = 0; + CHECK(is(q.take(0, skipped), 0, 10)); + CHECK(skipped == 0); + CHECK(is(q.take(66666, skipped), 66666, 12)); + CHECK(skipped == 1); + CHECK(is(q.take(99999, skipped), 99999, 13)); + CHECK(skipped == 0); + CHECK(q.empty()); +} + +// b/235045165: some encoders output the second-to-last frame with a pts of +// 0. It takes the oldest frame's timestamp, and the last one still matches. +static void zeroPtsSecondToLast() { + TimestampQueue q; + q.push(100000, 10); + q.push(133333, 11); + q.push(166666, 12); + q.push(199999, 13); + size_t skipped = 0; + CHECK(is(q.take(100000, skipped), 100000, 10)); + CHECK(is(q.take(133333, skipped), 133333, 11)); + CHECK(is(q.take(0, skipped), 166666, 12)); + CHECK(skipped == 0); + CHECK(is(q.take(199999, skipped), 199999, 13)); + CHECK(q.empty()); +} + +// A pts matching no frame (garbage) takes the oldest one. +static void garbagePts() { + TimestampQueue q; + q.push(0, 10); + q.push(33333, 11); + size_t skipped = 0; + CHECK(is(q.take(0, skipped), 0, 10)); + CHECK(is(q.take(123456789, skipped), 33333, 11)); + CHECK(skipped == 0); + CHECK(!q.take(5, skipped).has_value()); +} + +int main() { + inOrder(); + firstAtZero(); + repeated(); + backwards(); + droppedMiddle(); + zeroPtsSecondToLast(); + garbagePts(); + if (failures > 0) { + std::fprintf(stderr, "timestamps: %d failure(s)\n", failures); + return EXIT_FAILURE; + } + std::printf("timestamps: ok\n"); + return EXIT_SUCCESS; +} diff --git a/android/src/test/java/com/margelo/nitro/webcodecs/EncoderRulesTest.java b/android/src/test/java/com/margelo/nitro/webcodecs/EncoderRulesTest.java new file mode 100644 index 0000000..353a1de --- /dev/null +++ b/android/src/test/java/com/margelo/nitro/webcodecs/EncoderRulesTest.java @@ -0,0 +1,391 @@ +package com.margelo.nitro.webcodecs; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.function.IntPredicate; + +import org.junit.Test; + +// `yarn test:jvm`: EncoderRules, with encoders made up here. +public class EncoderRulesTest { + static final int SURFACE = 0x7f000789; + static final int P010 = 0x36; + static final int AVC_BASELINE = 1; + static final int AVC_MAIN = 2; + static final int AVC_HIGH = 8; + // MediaCodecInfo.CodecProfileLevel.AVCLevel*. + static final int AVC_LEVEL_3 = 0x100; + static final int AVC_LEVEL_31 = 0x200; + static final int AVC_LEVEL_4 = 0x800; + static final int AVC_LEVEL_41 = 0x1000; + static final int AVC_LEVEL_42 = 0x2000; + static final int AVC_LEVEL_5 = 0x4000; + static final int AVC_LEVEL_51 = 0x8000; + static final int AVC_LEVEL_52 = 0x10000; + + // An encoder taking sizes up to maxWidth x maxHeight, each a multiple of + // its alignment, and bitrates in [1, maxBitrate]. + static class Fake implements EncoderRules.Encoder { + final String name; + boolean hardware = true; + int maxWidth = 4096; + int maxHeight = 4096; + int widthAlignment = 2; + int heightAlignment = 2; + int maxBitrate = 12_000_000; + int[] profiles = {AVC_BASELINE}; + // The level of each of `profiles`. + int[] levels = {AVC_LEVEL_41}; + int[] colorFormats = {SURFACE}; + + Fake(String name) { + this.name = name; + } + + Fake software() { + hardware = false; + return this; + } + + Fake size(int w, int h) { + maxWidth = w; + maxHeight = h; + return this; + } + + Fake align(int w, int h) { + widthAlignment = w; + heightAlignment = h; + return this; + } + + @Override + public String name() { + return name; + } + + @Override + public boolean isSizeSupported(int width, int height) { + return width > 0 && height > 0 && width <= maxWidth && height <= maxHeight + && width % widthAlignment == 0 && height % heightAlignment == 0; + } + + @Override + public boolean hardware() { + return hardware; + } + + @Override + public int widthAlignment() { + return widthAlignment; + } + + @Override + public int heightAlignment() { + return heightAlignment; + } + + @Override + public int bitrateLower() { + return 1; + } + + @Override + public int bitrateUpper() { + return maxBitrate; + } + + @Override + public int[] profiles() { + return profiles; + } + + @Override + public int[] levels() { + return levels; + } + + @Override + public int[] colorFormats() { + return colorFormats; + } + + Fake profileLevels(int[] profiles, int[] levels) { + this.profiles = profiles; + this.levels = levels; + return this; + } + } + + @Test + public void fitsSizeProfileAndColorFormat() { + Fake encoder = new Fake("c2.android.avc.encoder").size(2048, 2048); + assertTrue(EncoderRules.fits(encoder, 1280, 720, 0, SURFACE)); + assertTrue(EncoderRules.fits(encoder, 1280, 720, AVC_BASELINE, SURFACE)); + assertFalse(EncoderRules.fits(encoder, 1280, 720, AVC_HIGH, SURFACE)); + assertFalse(EncoderRules.fits(encoder, 1280, 720, 0, P010)); + assertFalse(EncoderRules.fits(encoder, 16384, 16384, 0, SURFACE)); + } + + @Test + public void choosesTheFirstThatFitsInPlatformOrder() { + Fake small = new Fake("small").size(640, 480); + Fake a = new Fake("a"); + Fake b = new Fake("b"); + assertEquals("a", EncoderRules.choose(Arrays.asList(small, a, b), 1280, 720, 0, SURFACE, h -> false)); + assertNull(EncoderRules.choose(Arrays.asList(small), 1280, 720, 0, SURFACE, h -> false)); + } + + // The frame rate and bitrate are hints (as in Media3): an encoder is not + // refused for them, the bitrate is clamped into its range. + @Test + public void frameRateAndBitrateDoNotRefuseAnEncoder() { + Fake encoder = new Fake("c2.android.avc.encoder").size(2048, 2048); + // The check knows neither: c2.android.avc.encoder lists at most + // 12 Mbps, and about 30 fps at 1080x1920, yet takes more once configured. + assertTrue(EncoderRules.fits(encoder, 1080, 1920, 0, SURFACE)); + assertTrue(EncoderRules.fits(encoder, 1280, 720, 0, SURFACE)); + } + + @Test + public void frameRateIsFlooredAndIgnoredBelowOne() { + assertEquals(29, EncoderRules.frameRate(29.97), 0); + assertEquals(60, EncoderRules.frameRate(60), 0); + assertEquals(0, EncoderRules.frameRate(0.5), 0); + assertEquals(0, EncoderRules.frameRate(-1), 0); + assertEquals(0, EncoderRules.frameRate(Double.NaN), 0); + } + + @Test + public void aGivenBitrateIsClampedIntoTheRange() { + assertEquals(12_000_000, EncoderRules.bitrate(100e6, 1280, 720, 30, 1, 12_000_000)); + assertEquals(5_000_000, EncoderRules.bitrate(5e6, 1280, 720, 30, 1, 12_000_000)); + assertEquals(64_000, EncoderRules.bitrate(1000, 1280, 720, 30, 64_000, 12_000_000)); + assertEquals(Integer.MAX_VALUE, EncoderRules.bitrate(5e12, 1280, 720, 30, 1, Integer.MAX_VALUE)); + } + + // With no bitrate, width * height * fps * 0.1, in the encoder's range: + // vision-camera's 100 Mbps default failed on an 80 Mbps encoder (#2208). + @Test + public void theDefaultBitrateIsClampedIntoTheRange() { + assertEquals(2_764_800, EncoderRules.bitrate(0, 1280, 720, 30, 1, 80_000_000)); + assertEquals(80_000_000, EncoderRules.bitrate(0, 3840, 2160, 120, 1, 80_000_000)); + assertEquals(12_000_000, EncoderRules.bitrate(0, 1080, 1920, 120, 1, 12_000_000)); + // No frame rate (or below 1): 30. + assertEquals(2_764_800, EncoderRules.bitrate(0, 1280, 720, 0.5, 1, 80_000_000)); + assertEquals(500_000, EncoderRules.bitrate(0, 64, 64, 30, 500_000, 80_000_000)); + } + + // Encoders listing a 16-pixel alignment often take 1080 rows (ExoPlayer + // #6551): the size is checked aligned up too (the encoder is still given + // the size asked for). + @Test + public void sizesAreCheckedAlignedUp() { + Fake encoder = new Fake("hw").size(1920, 1088).align(16, 16); + assertTrue(EncoderRules.fits(encoder, 1920, 1080, 0, SURFACE)); + assertTrue(EncoderRules.fits(encoder, 1278, 718, 0, SURFACE)); + assertFalse(EncoderRules.fits(encoder, 1930, 1080, 0, SURFACE)); + } + + // Only even sizes are aligned up: the encoder is given the size asked + // for, and an odd one is refused by encoders aligned to 2 or more. + @Test + public void oddSizesAreNotAlignedUp() { + Fake two = new Fake("c2.android.avc.encoder"); + assertFalse(EncoderRules.fits(two, 1279, 720, 0, SURFACE)); + assertFalse(EncoderRules.fits(two, 641, 481, 0, SURFACE)); + assertFalse(EncoderRules.fits(two, 720, 1279, 0, SURFACE)); + Fake sixteen = new Fake("hw").size(1920, 1088).align(16, 16); + assertFalse(EncoderRules.fits(sixteen, 1279, 720, 0, SURFACE)); + assertFalse(EncoderRules.fits(sixteen, 1920, 1079, 0, SURFACE)); + assertTrue(EncoderRules.fits(sixteen, 1920, 1080, 0, SURFACE)); + } + + // Encoders limit the number of macroblocks rather than the orientation + // (as Media3 assumes): a portrait size is retried swapped. + @Test + public void portraitSizesAreRetriedSwapped() { + Fake encoder = new Fake("hw").size(1920, 1088); + assertTrue(EncoderRules.fits(encoder, 1080, 1920, 0, SURFACE)); + assertTrue(EncoderRules.fits(encoder, 720, 1280, 0, SURFACE)); + assertFalse(EncoderRules.fits(encoder, 1088, 2000, 0, SURFACE)); + } + + // Some Samsung, Huawei and Pixel 6 encoders list 1072 rows for H.264 + // 1920x1080 and 2144 for HEVC 3840x2160 (b/222095724, b/229825948): + // CamcorderProfile vouches for those two sizes, as in Media3. + @Test + public void camcorderProfilesVouchFor1080pAnd2160p() { + Fake avc = new Fake("hw").size(1920, 1072).align(16, 16); + Fake hevc = new Fake("hw").size(3840, 2144).align(16, 16); + IntPredicate both = height -> height == 1080 || height == 2160; + IntPredicate none = height -> false; + assertTrue(EncoderRules.fits(avc, 1920, 1080, 0, SURFACE, both)); + assertTrue(EncoderRules.fits(avc, 1080, 1920, 0, SURFACE, both)); + assertTrue(EncoderRules.fits(hevc, 3840, 2160, 0, SURFACE, both)); + assertFalse(EncoderRules.fits(avc, 1920, 1080, 0, SURFACE, none)); + assertFalse(EncoderRules.fits(hevc, 3840, 2160, 0, SURFACE, none)); + assertFalse(EncoderRules.fits(avc, 1280, 1080, 0, SURFACE, both)); + assertFalse(EncoderRules.fits(hevc, 3840, 2160, 0, SURFACE, height -> height == 1080)); + } + + // A hardware encoder that takes the config as it is asked for is chosen + // over a software one, wherever the platform lists it; software when no + // hardware one does. + @Test + public void prefersHardwareThatFitsOverSoftware() { + Fake software = new Fake("c2.android.avc.encoder").software().size(2048, 2048); + Fake hardware = new Fake("c2.qti.avc.encoder").size(1920, 1088).align(16, 16); + Fake small = new Fake("c2.small.avc.encoder").size(640, 480); + assertEquals("c2.qti.avc.encoder", + EncoderRules.choose(Arrays.asList(software, small, hardware), 1920, 1088, 0, SURFACE, h -> false)); + assertEquals("c2.android.avc.encoder", + EncoderRules.choose(Arrays.asList(small, software, hardware), 2048, 2048, 0, SURFACE, h -> false)); + assertNull(EncoderRules.choose(Arrays.asList(small, software, hardware), 4096, 4096, 0, SURFACE, h -> false)); + } + + // The encoder is configured with the size asked for, and configure() has + // no other encoder to fall back on: one that takes the size as asked for + // (software or not) beats a hardware one only the lenient reading lets + // through (as Media3 orders them). + @Test + public void anEncoderThatTakesTheSizeBeatsHardwareReadLeniently() { + Fake software = new Fake("c2.android.avc.encoder").software().size(2048, 2048); + Fake hardware = new Fake("c2.qti.avc.encoder").size(1920, 1088).align(16, 16); + // 1080x1920: the hardware one only swapped and aligned up. + assertEquals("c2.android.avc.encoder", + EncoderRules.choose(Arrays.asList(hardware, software), 1080, 1920, 0, SURFACE, h -> false)); + // 1920x1080 by CamcorderProfile only. + Fake hardware1072 = new Fake("c2.exynos.avc.encoder").size(1920, 1072).align(16, 16); + assertEquals("c2.android.avc.encoder", + EncoderRules.choose(Arrays.asList(hardware1072, software), 1920, 1080, 0, SURFACE, h -> h == 1080)); + // No encoder takes it as asked for: the lenient reading, hardware first. + Fake smallSoftware = new Fake("c2.android.small").software().size(1088, 1088); + assertEquals("c2.qti.avc.encoder", + EncoderRules.choose(Arrays.asList(smallSoftware, hardware), 1080, 1920, 0, SURFACE, h -> false)); + assertEquals("c2.exynos.avc.encoder", + EncoderRules.choose(Arrays.asList(smallSoftware, hardware1072), 1920, 1080, 0, SURFACE, h -> h == 1080)); + } + + // An optional profile (H.264's) is dropped before the size is read + // leniently: a size the encoder may refuse at configure time is worse than + // the encoder's default profile. + @Test + public void anOptionalProfileIsDroppedBeforeTheLenientReading() { + Fake software = new Fake("c2.android.avc.encoder").software().size(2048, 2048); + Fake hardware = new Fake("c2.qti.avc.encoder").size(1920, 1088).align(16, 16); + hardware.profiles = new int[] {AVC_BASELINE, AVC_HIGH}; + assertEquals("c2.android.avc.encoder", + EncoderRules.choose(Arrays.asList(hardware, software), 1080, 1920, AVC_HIGH, true, SURFACE, h -> false)); + // A required profile is not dropped. + assertEquals("c2.qti.avc.encoder", + EncoderRules.choose(Arrays.asList(hardware, software), 1080, 1920, AVC_HIGH, false, SURFACE, h -> false)); + // Taken as asked for, in the profile: the hardware one. + assertEquals("c2.qti.avc.encoder", + EncoderRules.choose(Arrays.asList(software, hardware), 1920, 1088, AVC_HIGH, true, SURFACE, h -> false)); + // No encoder lists the profile: any that takes the size. + assertEquals("c2.android.avc.encoder", + EncoderRules.choose(Arrays.asList(software), 1280, 720, AVC_HIGH, true, SURFACE, h -> false)); + assertNull(EncoderRules.choose(Arrays.asList(software), 1280, 720, AVC_HIGH, false, SURFACE, h -> false)); + } + + // H.264's level goes with its profile (OMX encoders refuse a profile + // alone): the codec string's, raised to what the size and frame rate need, + // and capped at the highest the encoder lists for the profile. + @Test + public void theLevelIsTheCodecStringsWithinTheEncodersRange() { + Fake encoder = new Fake("c2.android.avc.encoder") + .profileLevels(new int[] {AVC_BASELINE, AVC_MAIN, AVC_BASELINE}, new int[] {AVC_LEVEL_31, AVC_LEVEL_41, AVC_LEVEL_41}); + // 4.0 at 1280x720, as asked for (not the encoder's 4.1). + assertEquals(AVC_LEVEL_4, EncoderRules.avcLevel(encoder, AVC_BASELINE, 40, 1280, 720, 30)); + assertEquals(AVC_LEVEL_31, EncoderRules.avcLevel(encoder, AVC_BASELINE, 31, 640, 480, 30)); + // Higher than the encoder lists for the profile: its highest. + assertEquals(AVC_LEVEL_41, EncoderRules.avcLevel(encoder, AVC_MAIN, 51, 1280, 720, 30)); + // None in the codec string (0): the encoder's highest for the profile, as Media3. + assertEquals(AVC_LEVEL_41, EncoderRules.avcLevel(encoder, AVC_BASELINE, 0, 1280, 720, 30)); + } + + @Test + public void theLevelIsRaisedToWhatTheSizeAndFrameRateNeed() { + Fake encoder = new Fake("hw").profileLevels(new int[] {AVC_HIGH}, new int[] {AVC_LEVEL_52}); + // avc1.42001f (3.1) at 1920x1080: 8160 macroblocks need 4.0. + assertEquals(AVC_LEVEL_4, EncoderRules.avcLevel(encoder, AVC_HIGH, 31, 1920, 1080, 30)); + assertEquals(AVC_LEVEL_4, EncoderRules.avcLevel(encoder, AVC_HIGH, 31, 1080, 1920, 30)); + // At 60 fps: 489600 macroblocks a second, 4.2. + assertEquals(AVC_LEVEL_42, EncoderRules.avcLevel(encoder, AVC_HIGH, 31, 1920, 1080, 60)); + // 4K at 30 fps: 5.1. No frame rate: 30. + assertEquals(AVC_LEVEL_51, EncoderRules.avcLevel(encoder, AVC_HIGH, 40, 3840, 2160, 0)); + // 1280x720 at 30 fps fits in 3.1: a lower level asked for is raised. + assertEquals(AVC_LEVEL_31, EncoderRules.avcLevel(encoder, AVC_HIGH, 30, 1280, 720, 30)); + // Never past the encoder's highest. + Fake small = new Fake("small").profileLevels(new int[] {AVC_HIGH}, new int[] {AVC_LEVEL_41}); + assertEquals(AVC_LEVEL_41, EncoderRules.avcLevel(small, AVC_HIGH, 31, 3840, 2160, 30)); + } + + // An encoder that does not list the profile is given the next one down + // that it lists (High, Main, Baseline: a High decoder decodes Main), so + // that the level still goes with a profile: the emulator's + // c2.android.avc.encoder has no High. 0 when it lists none of them. + @Test + public void aProfileTheEncoderDoesNotListFallsToTheNextOneDown() { + Fake encoder = new Fake("c2.android.avc.encoder") + .profileLevels(new int[] {AVC_BASELINE, AVC_MAIN}, new int[] {AVC_LEVEL_41, AVC_LEVEL_41}); + assertEquals(AVC_HIGH, EncoderRules.avcProfile(new Fake("hw").profileLevels(new int[] {AVC_HIGH}, new int[] {AVC_LEVEL_52}), AVC_HIGH)); + assertEquals(AVC_MAIN, EncoderRules.avcProfile(encoder, AVC_HIGH)); + assertEquals(AVC_MAIN, EncoderRules.avcProfile(encoder, AVC_MAIN)); + assertEquals(AVC_BASELINE, EncoderRules.avcProfile(encoder, AVC_BASELINE)); + Fake baselineOnly = new Fake("baseline").profileLevels(new int[] {AVC_BASELINE}, new int[] {AVC_LEVEL_41}); + assertEquals(AVC_BASELINE, EncoderRules.avcProfile(baselineOnly, AVC_HIGH)); + Fake highOnly = new Fake("high").profileLevels(new int[] {AVC_HIGH}, new int[] {AVC_LEVEL_41}); + assertEquals(0, EncoderRules.avcProfile(highOnly, AVC_BASELINE)); + assertEquals(0, EncoderRules.avcProfile(encoder, 0)); + // avcLevel() reads the levels of the profile it is given. + assertEquals(0, EncoderRules.avcLevel(encoder, AVC_HIGH, 40, 1280, 720, 30)); + assertEquals(AVC_LEVEL_4, EncoderRules.avcLevel(encoder, EncoderRules.avcProfile(encoder, AVC_HIGH), 40, 1280, 720, 30)); + } + + @Test + public void levelIdcsMapToMediaCodecLevels() { + assertEquals(0x01, EncoderRules.avcLevelOf(10)); + assertEquals(0x02, EncoderRules.avcLevelOf(9)); + assertEquals(AVC_LEVEL_3, EncoderRules.avcLevelOf(30)); + assertEquals(AVC_LEVEL_52, EncoderRules.avcLevelOf(52)); + assertEquals(0x80000, EncoderRules.avcLevelOf(62)); + assertEquals(0, EncoderRules.avcLevelOf(0)); + assertEquals(0, EncoderRules.avcLevelOf(33)); + } + + // Every encoder that may take the config, in the order choose() ranks them + // (its answer first): when configure() fails on one, the next is tried, + // software ones included. + @Test + public void candidatesAreEveryFittingEncoderInChoosesOrder() { + Fake hwA = new Fake("c2.qti.avc.encoder").size(1920, 1088).align(16, 16); + Fake small = new Fake("c2.small.avc.encoder").size(640, 480); + Fake hwB = new Fake("c2.exynos.avc.encoder"); + Fake software = new Fake("c2.android.avc.encoder").software().size(2048, 2048); + assertEquals(Arrays.asList("c2.qti.avc.encoder", "c2.exynos.avc.encoder", "c2.android.avc.encoder"), + EncoderRules.candidates(Arrays.asList(software, hwA, small, hwB), 1280, 720, 0, false, SURFACE, h -> false)); + // Taken strictly before leniently: 1080x1920 only swapped and aligned up + // on hwA, as asked for on the others. + assertEquals(Arrays.asList("c2.exynos.avc.encoder", "c2.android.avc.encoder", "c2.qti.avc.encoder"), + EncoderRules.candidates(Arrays.asList(hwA, software, hwB), 1080, 1920, 0, false, SURFACE, h -> false)); + // In the profile first, then (optional) in any, each once. + hwB.profiles = new int[] {AVC_BASELINE, AVC_HIGH}; + assertEquals(Arrays.asList("c2.exynos.avc.encoder", "c2.qti.avc.encoder", "c2.android.avc.encoder"), + EncoderRules.candidates(Arrays.asList(software, hwA, hwB), 1280, 720, AVC_HIGH, true, SURFACE, h -> false)); + assertEquals(Arrays.asList("c2.exynos.avc.encoder"), + EncoderRules.candidates(Arrays.asList(software, hwA, hwB), 1280, 720, AVC_HIGH, false, SURFACE, h -> false)); + assertEquals(Arrays.asList(), + EncoderRules.candidates(Arrays.asList(software, small), 4096, 4096, 0, false, SURFACE, h -> false)); + // choose() is the first of them. + for (int[] size : new int[][] {{1280, 720}, {1080, 1920}, {640, 480}}) { + java.util.List all = EncoderRules.candidates(Arrays.asList(software, hwA, small, hwB), size[0], size[1], AVC_HIGH, true, SURFACE, h -> false); + assertEquals(all.get(0), EncoderRules.choose(Arrays.asList(software, hwA, small, hwB), size[0], size[1], AVC_HIGH, true, SURFACE, h -> false)); + } + } +} diff --git a/docs/api.md b/docs/api.md index b5395dd..3040521 100644 --- a/docs/api.md +++ b/docs/api.md @@ -46,9 +46,15 @@ How each platform answers: prepares it to encode (which allocates what it needs), and closes it. Sizes above the codec's highest level are refused before that, since VideoToolbox would only fail at the first frame. -- **Android** asks `MediaCodecList` for an encoder that takes the size, - frame rate, bitrate and profile, with the input the encoder will use (a - surface, or P010 buffers for Main 10, which HDR needs). The encoder that +- **Android** asks `MediaCodecList` for an encoder that takes the size and + profile, with the input the encoder will use (a surface, or P010 buffers + for Main 10, which HDR needs), a hardware one before a software one. As in + Media3, sizes are read leniently (even sizes also aligned up to the encoder's + alignment, swapped, and 1920x1080 or 3840x2160 when the device's camera records + them), though an encoder that takes the size as it says, hardware or + software, comes before one only that reading lets through; the frame rate and bitrate are hints: the bitrate, or the + default of width × height × fps × 0.1, is clamped into the encoder's + range, and the frame rate is floored, and ignored below 1. The encoder that answered is the one `configure` creates. An H.264 profile no encoder lists is a preference rather than a requirement: the encoder's default is used, and the output's `description` says which. Android 10 (API 29) or later. @@ -63,7 +69,7 @@ do. | :-- | :-- | :-- | | `VideoEncoder` | `configure`, `encode` (with `keyFrame`), `flush`, `reset`, `close`, `state`, `encodeQueueSize`, `dequeue` and `ondequeue`, `isConfigSupported`. Config: `codec`, `width`, `height`, `bitrate`, `framerate`, `latencyMode`. Output metadata: `decoderConfig` with `description` and `colorSpace`. | `hardwareAcceleration`, `bitrateMode`, `scalabilityMode` (SVC), `alpha`, `contentHint`, `displayWidth`/`displayHeight`; per-frame encode options other than `keyFrame`; Annex B output (`avc.format`/`hevc.format: "annexb"` is reported unsupported). | | `VideoDecoder` | `configure`, `decode`, `flush`, `reset`, `close`, `state`, `decodeQueueSize`, `dequeue`, `isConfigSupported`. Config: `codec`, `description`, `codedWidth`, `codedHeight`, `colorSpace`. | Streams without a `description` (Annex B), `hardwareAcceleration`, `optimizeForLatency`, `rotation`, `flip`, `displayAspectWidth`/`Height`. | -| `AudioEncoder` | The same members as `VideoEncoder`. Config: `codec`, `sampleRate`, `numberOfChannels`, `bitrate`. | Codec-specific options (`aac.format`, Opus, FLAC). Android takes 1 or 2 channels. | +| `AudioEncoder` | The same members as `VideoEncoder`. Config: `codec`, `sampleRate`, `numberOfChannels`, `bitrate`. | Codec-specific options (`aac.format`, Opus, FLAC). AAC-LC only, in 1 or 2 channels; iOS also only at the standard AAC sample rates (8 to 96 kHz). | | `AudioDecoder` | The same members as `VideoDecoder`. Output: `f32` interleaved. | Other output formats (convert with `AudioData.copyTo`). | | `VideoFrame` | From another `VideoFrame` or a native surface; `format`, `codedWidth`/`Height`, `codedRect`, `visibleRect`, `displayWidth`/`Height`, `timestamp`, `duration`, `colorSpace`, `clone`, `close`. | Frames from pixels in memory (`BufferSource`), `ImageBitmap`, a canvas or an image; `copyTo`, `allocationSize`, `metadata()`; cropping (`visibleRect` is the whole frame); `rotation` is always 0 and `flip` false. | | `AudioData` | From samples in memory; `u8`, `s16`, `s32`, `f32`, interleaved and planar; `copyTo` (with format conversion), `allocationSize`, `clone`, `close`. | `transfer`. | @@ -77,17 +83,19 @@ do. | --- | --- | | `VideoFrame` | `new VideoFrame(surface, init)` from a pool surface or `{ handle }` (any native surface, such as a camera frame). `init.fence`: a React Native WebGPU `endAccess()` fence, or `{ handle, value }`. `pixelBuffer` and `nativeHandle` give the native buffer back. | | `VideoDecoder` | `outputFormat: "BGRA" \| "NV12"` in the config (iOS: both, default BGRA; Android: NV12). | -| `createSurfacePool(width, height, format?)` | Recycled GPU surfaces to draw frames into: `"BGRA"` (default), `"NV12"`, or `"RGBA16F"` (half float, for HDR). | +| `createSurfacePool(width, height, format?)` | Recycled GPU surfaces to draw frames into: `"BGRA"` (default), `"NV12"`, or `"RGBA16F"` (half float, for HDR). On Android, `"BGRA"` gives RGBA surfaces (the frames' `format` says `"RGBA"`), and `"NV12"` is not supported. | | `createFileWritable(path)` | `{ writable, path, remove() }`: a `WritableStream` for Mediabunny's `StreamTarget`, written natively at the positions it asks for. | | `fileSourceOptions(path)` | Options for Mediabunny's `CustomSource`, read natively. | | `withBackgroundTask(fn)` | Runs `fn` with the app kept alive in the background (an iOS background task). | -| `writeFile`, `removeFile`, `resolvePath` | A relative path is in the app's cache directory; `file://` URLs are paths. | +| `writeFile`, `removeFile`, `resolvePath` | A relative path is in the app's cache directory; `file://` URLs are paths. Writing creates the missing directories. | | `installWebCodecs()` | Installs the classes, `DOMException` and `WritableStream` on `globalThis` where missing. | ## Errors Errors are `DOMException`s with the WebCodecs names (`NotSupportedError`, -`InvalidStateError`, `EncodingError`, `NotFoundError`, `DataError`), and a +`InvalidStateError`, `EncodingError`, `NotFoundError`, `NotReadableError`, +`DataError`, `AbortError` for a `flush()` that `reset()` or `close()` cut +short), and a string `code` where there is more to say: - `interrupted`: the app went to the background while a codec was in use @@ -98,10 +106,11 @@ string `code` where there is more to say: ## Backgrounding iOS takes the hardware codecs away from an app in the background -(VideoToolbox then fails with `kVTInvalidSessionErr`). A codec in use when -the app goes to the background therefore fails with `interrupted` right -away, rather than on a later frame, unless a `withBackgroundTask()` is -running. In that case, the app keeps running for as long as iOS grants, and +(VideoToolbox then fails with `kVTInvalidSessionErr`). A configured video +encoder or decoder therefore fails with `interrupted` as soon as the app +goes to the background, rather than on a later frame, unless a +`withBackgroundTask()` is running. Configure codecs when you need them, +and close them when done. In that case, the app keeps running for as long as iOS grants, and the codecs keep going. Wrap `finalize()` in it so that an export the user leaves near the end still completes. diff --git a/docs/guides.md b/docs/guides.md index 8055dc9..1c1fc1f 100644 --- a/docs/guides.md +++ b/docs/guides.md @@ -74,7 +74,8 @@ for (let i = 0; i < frames; i++) { duration: frameDuration, fence: fences[0], }); - const sample = new VideoSample(frame); + // Mediabunny is typed for the DOM's VideoFrame; this one stands in for it. + const sample = new VideoSample(frame as unknown as globalThis.VideoFrame); try { await video.add(sample); } finally { @@ -125,7 +126,11 @@ Mediabunny demuxes the file and drives `VideoDecoder`. The decoded without a copy. ```ts -import { fileSourceOptions, installWebCodecs } from "react-native-webcodecs"; +import { + fileSourceOptions, + installWebCodecs, + type VideoFrame, +} from "react-native-webcodecs"; import { ALL_FORMATS, CustomSource, Input, VideoSampleSink } from "mediabunny"; installWebCodecs(); @@ -135,7 +140,8 @@ const input = new Input({ }); const track = await input.getPrimaryVideoTrack(); const sample = await new VideoSampleSink(track).getSample(1.5); -const frame = sample.toVideoFrame(); +// This package's VideoFrame, typed as the DOM's by Mediabunny. +const frame = sample.toVideoFrame() as unknown as VideoFrame; sample.close(); const buffer = RNWebGPU.createNativeBufferFromPointer(frame.pixelBuffer, { @@ -153,7 +159,7 @@ frame.close(); | Platform | Decoded frame | | :-- | :-- | | iOS | A BGRA `CVPixelBuffer` by default; NV12 with `outputFormat: "NV12"` in the decoder config. | -| Android | The decoder's own YUV (NV12) `AHardwareBuffer`. | +| Android | The decoder's own YUV (NV12) `AHardwareBuffer`. It can be wider or taller than the frame (software decoders pad the width to a multiple of 128): the picture is its top-left `codedWidth` x `codedHeight`, so sample only that. | The frame's `colorSpace` comes from the stream (Mediabunny passes the track's to `configure`). Android's buffers carry no color information of @@ -192,6 +198,8 @@ const input = new Input({ source: new CustomSource(fileSourceOptions(path)), formats: ALL_FORMATS, }); +const videoTrack = await input.getPrimaryVideoTrack(); +const rotation = videoTrack ? await videoTrack.getRotation() : 0; const file = createFileWritable("compressed.mp4"); const output = new Output({ // The index first, so the file plays while it downloads. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 9ebe62c..f7a5c13 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -29,10 +29,15 @@ Every holder (JavaScript's `VideoFrame`, the encoder, a clone) takes its own reference. A pool's surface returns to the pool once the last reference is gone, so a long export reuses a handful of surfaces instead of allocating one per frame. Pools come in three formats: `BGRA` (8 bits), `NV12` (YUV) -and `RGBA16F` (half float, for HDR). +and `RGBA16F` (half float, for HDR). Android has no `NV12` pools, and its +8-bit ones are RGBA. `new VideoFrame({ handle }, init)` wraps any surface the app already has, -such as a camera frame, by its handle. +such as a camera frame, by its handle. The frame only references that +surface, and its producer may write into it again. On Android, `encode()` +returns once the frame has been read (after the frames queued before it), +so the producer can reuse the buffer from then on; pool and decoder +surfaces are not reused while a frame holds them, so they never wait. ## Fences @@ -41,14 +46,17 @@ signals once the surface is drawn. The fence is waited on natively, where the surface is read: - **iOS**: an `MTLSharedEvent` and the value to wait for, which - react-native-webgpu's `endAccess()` returns. The encoder waits for the - event (with a one-second guard) before handing the surface to - VideoToolbox. + react-native-webgpu's `endAccess()` returns. The encoder's queue waits + for the event before handing the surface to VideoToolbox. After a second + it gives up and encodes the surface as it is, so a draw that is never + submitted shows up as a stall and a wrong frame, not an error. - **Android**: a sync file descriptor. The encoder turns it into an EGL sync - and waits on the GPU (`eglWaitSyncKHR`), so even the CPU does not block. + and waits on the GPU (`eglWaitSyncKHR`), then copies the surface into the + codec's input and waits for that copy on its own thread. HDR frames are + read on the CPU, after waiting for the fence there. -This is why the export loop has no `await` for the GPU: drawing frame *n+1* -overlaps with encoding frame *n*. +Either way the JavaScript thread never waits for the GPU: drawing frame +*n+1* overlaps with encoding frame *n*. ## Encoding @@ -61,8 +69,16 @@ overlaps with encoding frame *n*. - **Android**: a `MediaCodec` encoder in surface-input mode. An EGL context samples each `AHardwareBuffer` as an external texture and draws it into the codec's input surface (one GPU copy per frame). `max-bframes` is 0. - When an encoder refuses a setting (operating rate, profile, frame rate), - `configure` retries without it, as Media3 does. Each codec runs on its own + H.264's profile is set with a level, as Media3 and Chromium do: the codec + string's level, raised to what the size and frame rate need and capped at + the encoder's highest; an encoder without the profile gets the next one + down it lists (High, Main, Baseline). When an encoder refuses a setting, + `configure` retries: first with a lower operating rate, then none and at + most 30 fps, keeping the profile; then the same again without the profile + and level, as Media3 does. When an encoder takes none of them (or does + not start), the next one that may take the config is tried, software + ones included; the error names each encoder and the status of each + attempt. Each codec runs on its own worker thread. HDR is different: the encoder runs in buffer mode, and each half-float surface is read on the CPU and converted to P010 (10-bit BT.2020 YCbCr) into an input buffer, as an EGL window has no 10-bit format @@ -96,7 +112,12 @@ numbers. - **Android**: an H.264 `MediaCodec` decoder writing into an `AImageReader`. Each output image's `AHardwareBuffer` becomes the frame's surface, with no copy, and stays with the decoder until JavaScript closes the frame. The reader has - 16 images, so a decoder stalls if JavaScript keeps all of them. + 16 images, so a decoder stalls if JavaScript keeps all of them. The + frame's size is the image's crop, which can be smaller than the buffer + (padding on the right or bottom); the encoder samples only that part. + `hardwareAcceleration` picks the decoder: `"prefer-software"` a + software one, `"prefer-hardware"` another, falling back to the rest when + the preferred ones fail to start. A config needs a `description`. The output frames carry the config's `colorSpace` (BT.709 for what it leaves out). @@ -143,7 +164,14 @@ moves the codec to `closed` and calls its `error` callback, as on the web. **Android encoding** copies each frame once on the GPU (EGL) into MediaCodec's input surface. `flush()` on Android's encoder ends the stream; -encoding after it starts a new stream, from a key frame. +encoding after it starts a new stream, from a key frame. Frame timestamps +must grow: MediaCodec drops a frame whose timestamp does not move forward +(it then counts as dropped, with no output). + +**AAC priming.** AAC encoders put about 1600 (Android) to 2112 (iOS) +samples of silence ahead of the sound, and nothing in the output says so +yet: the sound of an export starts that much (33 to 44 ms at 48 kHz) after +the video. **Android decoding** stalls while JavaScript holds all 16 output frames, as a web decoder does until frames are closed. diff --git a/example/src/Tests.tsx b/example/src/Tests.tsx index c23fcf0..3cfca91 100644 --- a/example/src/Tests.tsx +++ b/example/src/Tests.tsx @@ -3,8 +3,26 @@ import { AppState, Text, View } from "react-native"; // Installs navigator.gpu. import "react-native-webgpu"; +import { supportedCodecs } from "./Compress/codecs"; +import { compress, openSource } from "./Compress/compress"; +import * as settings from "./Compress/settings"; import { serve } from "./serve"; import { useClient } from "./useClient"; +import { loadCardAssets, loadSound, makeCard } from "./VideoExport/lottieCard"; +import { exportVideo } from "./VideoExport/export"; + +// The example's own code, for the e2e tests of its screens: they run what +// the app runs, not copies of it. +const example = { + exportVideo, + loadCardAssets, + makeCard, + loadSound, + openSource, + compress, + supportedCodecs, + settings, +}; // The app's side of the e2e tests (src/__tests__): the // host sends functions as source, run here with a WebGPU device and the @@ -64,6 +82,7 @@ export const Tests = () => { mediabunny: require("mediabunny"), webcodecs: require("react-native-webcodecs"), AppState, + example, ...params.ctx, }, }), diff --git a/example/src/VideoExport/VideoExport.tsx b/example/src/VideoExport/VideoExport.tsx index 1e912c0..8e73f27 100644 --- a/example/src/VideoExport/VideoExport.tsx +++ b/example/src/VideoExport/VideoExport.tsx @@ -1,25 +1,24 @@ -import React, { useCallback, useMemo, useRef, useState } from "react"; +import React, { + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import { Platform, StatusBar, StyleSheet, Text, View } from "react-native"; import type { RouteProp } from "@react-navigation/native"; import { useNavigation, useRoute } from "@react-navigation/native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useDerivedValue } from "react-native-reanimated"; import type { SkSkottieAnimation } from "react-native-skia"; -import { - Canvas, - Group, - Skia, - Skottie, - useClock, - useData, -} from "react-native-skia"; +import { Canvas, Group, Skottie, useClock } from "react-native-skia"; import type { Routes } from "../Route"; -import card from "./card.json"; +import type { CardAssets } from "./lottieCard"; +import { loadCardAssets, loadSound, makeCard } from "./lottieCard"; import type { Result } from "./export"; -import { assetBytes, exportVideo, HEIGHT, shareVideo, WIDTH } from "./export"; -import { boostLights } from "./hdr"; +import { exportVideo, HEIGHT, shareVideo, WIDTH } from "./export"; import { HdrPreview } from "./HdrPreview"; import { colors, PillButton, RoundButton, Segmented } from "./ui"; @@ -27,10 +26,6 @@ import { colors, PillButton, RoundButton, Segmented } from "./ui"; // with react-native-webcodecs (export.ts), or with the browser's WebCodecs on // the web (export.web.ts). -const json = JSON.stringify(card); -// For HDR, the lights go above SDR white, up to the HLG peak. -const hdrJson = JSON.stringify(boostLights(card)); - type Status = | { state: "idle" } | { state: "exporting"; frames: number; totalFrames: number } @@ -87,9 +82,17 @@ export const VideoExportView = ({ onClose?: () => void; }) => { const insets = useSafeAreaInsets(); - const photo = useData(require("./assets/photo.jpg")); - const logo = useData(require("./assets/logo.png")); - const font = useData(require("./assets/Roboto-Bold.ttf")); + const [assets, setAssets] = useState(null); + useEffect(() => { + let mounted = true; + loadCardAssets().then( + (loaded) => mounted && setAssets(loaded), + (e) => console.warn(e), + ); + return () => { + mounted = false; + }; + }, []); const [sound, setSound] = useState("sound"); const [status, setStatus] = useState({ state: "idle" }); const abort = useRef(null); @@ -101,17 +104,8 @@ export const VideoExportView = ({ // One instance for the preview, another for the export: seeking one does // not move the other. const make = useCallback( - () => - photo && logo && font - ? Skia.Skottie.Make(hdr ? hdrJson : json, { - "photo.jpg": photo, - "logo.png": logo, - // The animation asks for SF Pro, which can't be redistributed: - // Roboto stands in. - SFProBold: font, - }) - : null, - [photo, logo, font, hdr], + () => (assets ? makeCard(assets, hdr) : null), + [assets, hdr], ); const preview = useMemo(make, [make]); @@ -124,10 +118,7 @@ export const VideoExportView = ({ abort.current = controller; setStatus({ state: "exporting", frames: 0, totalFrames: 0 }); try { - const bytes = - sound === "sound" - ? await assetBytes(require("./assets/sound.m4a")) - : null; + const bytes = sound === "sound" ? await loadSound() : null; const result = await exportVideo( animation, bytes, diff --git a/example/src/VideoExport/lottieCard.ts b/example/src/VideoExport/lottieCard.ts new file mode 100644 index 0000000..36c839c --- /dev/null +++ b/example/src/VideoExport/lottieCard.ts @@ -0,0 +1,50 @@ +import type { SkData } from "react-native-skia"; +import { loadData, Skia } from "react-native-skia"; + +import card from "./card.json"; +import { assetBytes } from "./export"; +import { boostLights } from "./hdr"; + +// The share card of react-native-skia's Skottie export example: its images +// and font, the animation built from them, and the sound that goes with it. +// The export screen and the e2e tests (Tests.tsx) both use these. + +const json = JSON.stringify(card); +// For HDR, the lights go above SDR white, up to the HLG peak. +const hdrJson = JSON.stringify(boostLights(card)); + +export interface CardAssets { + photo: SkData; + logo: SkData; + font: SkData; +} + +const data = async (asset: number) => { + const loaded = await loadData(asset, (d) => d); + if (!loaded) { + throw new Error("Could not load an asset of the card"); + } + return loaded; +}; + +export const loadCardAssets = async (): Promise => { + const [photo, logo, font] = await Promise.all([ + data(require("./assets/photo.jpg")), + data(require("./assets/logo.png")), + data(require("./assets/Roboto-Bold.ttf")), + ]); + return { photo, logo, font }; +}; + +// A new instance each time: seeking one does not move another. +export const makeCard = (assets: CardAssets, hdr: boolean) => + Skia.Skottie.Make(hdr ? hdrJson : json, { + "photo.jpg": assets.photo, + "logo.png": assets.logo, + // The animation asks for SF Pro, which can't be redistributed: Roboto + // stands in. + SFProBold: assets.font, + }); + +// The M4A the export copies as its sound track. +export const loadSound = () => assetBytes(require("./assets/sound.m4a")); diff --git a/example/src/useClient.ts b/example/src/useClient.ts index ecbf4f5..18ecbb4 100644 --- a/example/src/useClient.ts +++ b/example/src/useClient.ts @@ -6,7 +6,13 @@ import { Platform } from "react-native"; // "adb reverse tcp: tcp:" (as the RN CLI does for Metro on 8081), // which covers the emulator and a physical device alike. Only a device that // cannot be reached over adb needs this machine's LAN IP here instead. -const HOST = "localhost"; +// E2E_ANDROID_HOST (inlined like E2E_PORT) replaces it on Android when adb +// reverse is not available: 10.0.2.2 is the emulator's address for this +// machine. +const HOST = + Platform.OS === "android" && process.env.E2E_ANDROID_HOST + ? process.env.E2E_ANDROID_HOST + : "localhost"; // E2E_PORT is inlined at bundle time (transform-inline-environment-variables), // so CI can run the test server on another port than other projects sharing // the machine. Kept in sync with TEST_SERVER_PORT in the jest config, which diff --git a/ios/Audio.swift b/ios/Audio.swift index b4adfff..ff9e62a 100644 --- a/ios/Audio.swift +++ b/ios/Audio.swift @@ -182,13 +182,19 @@ final class HybridNativeAudioEncoder: HybridNativeAudioEncoderSpec { func flush() throws -> Promise { guard converter != nil else { return Promise.rejected(withError: WebCodecsError.invalidState("the encoder is closed")) } return Promise.parallel(queue) { - if self.failed { return } + // Nothing encoded since the last flush (start is set by the first + // encode()): nothing to output. An end of stream now would still give + // the converter's priming, as frames of silence. + if self.failed || self.start == nil { return } self.endOfStream = true self.pull() // The converter is done after an end of stream: start a new stream for // later encode() calls, as WebCodecs allows encoding after a flush. if let converter = self.converter { AudioConverterReset(converter) } self.endOfStream = false + // Which starts at its own first timestamp, as Android's does. + self.start = nil + self.framesOut = 0 } } diff --git a/ios/VideoDecoder.swift b/ios/VideoDecoder.swift index 8a8600e..0d9a611 100644 --- a/ios/VideoDecoder.swift +++ b/ios/VideoDecoder.swift @@ -20,6 +20,245 @@ private func withParameterSetPointers( } } +// Reads a NAL unit's RBSP (emulation prevention bytes removed) bit by bit. +// Reading past the end throws, so a truncated parameter set gives no answer +// rather than a wrong one. +struct BitReader { + private let bytes: [UInt8] + private var bit = 0 + + struct End: Error {} + + init(nal: [UInt8]) { + var out: [UInt8] = [] + out.reserveCapacity(nal.count) + var zeros = 0 + for b in nal { + if zeros >= 2 && b == 3 { + zeros = 0 + continue + } + zeros = b == 0 ? zeros + 1 : 0 + out.append(b) + } + bytes = out + } + + mutating func u(_ n: Int) throws -> Int { + var v = 0 + for _ in 0..> (7 - UInt8(bit % 8))) & 1) + bit += 1 + } + return v + } + + mutating func skip(_ n: Int) throws { _ = try u(n) } + + mutating func ue() throws -> Int { + var zeros = 0 + while try u(1) == 0 { + zeros += 1 + if zeros > 31 { throw End() } + } + let rest = try u(zeros) + return (1 << zeros) - 1 + rest + } + + mutating func se() throws -> Int { + let k = try ue() + return k % 2 == 1 ? (k + 1) / 2 : -(k / 2) + } +} + +// How many frames a stream may decode ahead of the one it shows next: its +// SPS's max_num_reorder_frames (H.264, in the VUI) or +// sps_max_num_reorder_pics (HEVC). nil when the SPS does not say. +enum ReorderDepth { + static func h264(sps nal: [UInt8]) -> Int? { + var r = BitReader(nal: nal) + do { + try r.skip(8) // NAL header + let profile = try r.u(8) + try r.skip(16) // constraint flags, level + _ = try r.ue() // seq_parameter_set_id + if [100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135].contains(profile) { + let chroma = try r.ue() + if chroma == 3 { try r.skip(1) } + _ = try r.ue() // bit depths + _ = try r.ue() + try r.skip(1) + if try r.u(1) == 1 { // seq_scaling_matrix_present_flag + for i in 0..<(chroma == 3 ? 12 : 8) { + guard try r.u(1) == 1 else { continue } + var last = 8 + var next = 8 + for _ in 0..<(i < 6 ? 16 : 64) { + if next != 0 { + let delta = try r.se() + next = (last + delta + 256) % 256 + } + last = next == 0 ? last : next + } + } + } + } + _ = try r.ue() // log2_max_frame_num_minus4 + let pocType = try r.ue() + if pocType == 0 { + _ = try r.ue() + } else if pocType == 1 { + try r.skip(1) + _ = try r.se() + _ = try r.se() + let cycle = try r.ue() + for _ in 0.. Int? { + var r = BitReader(nal: nal) + do { + try r.skip(16) // NAL header + try r.skip(4) // sps_video_parameter_set_id + let subLayers = try r.u(3) // sps_max_sub_layers_minus1 + try r.skip(1) + // profile_tier_level + try r.skip(2 + 1 + 5 + 32 + 48 + 8) + var profilePresent: [Bool] = [] + var levelPresent: [Bool] = [] + for _ in 0.. 0 { + for _ in subLayers..<8 { try r.skip(2) } + } + for i in 0.. [[UInt8]] { + let b = [UInt8](hvcC) + guard b.count > 23 else { return [] } + var sets: [[UInt8]] = [] + var i = 23 + for _ in 0.. Int { + guard let description = config.description else { return fallback } + let record = description.toData(copyIfNeeded: true) + let depth: Int? + if config.codec.hasPrefix("avc") { + if let sps = HybridNativeVideoDecoder.parameterSets(avcC: record)?.first { + depth = h264(sps: [UInt8](sps)) + } else { + depth = nil + } + } else { + depth = hevcParameterSets(hvcC: record, type: 33).first.flatMap { hevc(sps: $0) } + } + return min(depth ?? fallback, most) + } +} + final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { private var session: VTDecompressionSession? private let format: CMVideoFormatDescription @@ -28,6 +267,15 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { private let queue = DispatchQueue(label: "webcodecs.video-decoder") private var failed = false private var background: BackgroundWatch? + // VideoToolbox may output frames in decoding order (the Simulator's + // decoder does, temporal processing or not), and WebCodecs outputs them in + // presentation order: decoded frames wait here, sorted by timestamp, until + // more than the stream's reorder depth are held, then the earliest goes + // out. Frames that already come in order only wait, they are not moved. + private let reorder = NSLock() + private var held: [NativeDecodedFrame] = [] + private var depth: Int + private var lastOut = -Double.infinity init( config: NativeVideoDecoderConfig, @@ -37,6 +285,7 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { self.output = output self.error = error format = try HybridNativeVideoDecoder.formatDescription(config) + depth = ReorderDepth.of(config) super.init() let attributes: [CFString: Any] = [ @@ -44,6 +293,8 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { kCVPixelBufferIOSurfacePropertiesKey: [:] as [CFString: Any], kCVPixelBufferMetalCompatibilityKey: true, ] + // config.hardwareAcceleration is left to VideoToolbox, which picks the + // decoder (no decoder specification). var session: VTDecompressionSession? let status = VTDecompressionSessionCreate( allocator: kCFAllocatorDefault, formatDescription: format, decoderSpecification: nil, @@ -118,10 +369,47 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { queue.async { if self.failed { return } self.failed = true + self.discardHeld() self.error(message) } } + // From VideoToolbox's output callback. + private func hold(_ frame: NativeDecodedFrame) { + reorder.lock() + defer { reorder.unlock() } + if failed { return } + // Later than its turn: the stream reorders more than it said. It goes + // out next (out of order, which cannot be helped now), and later + // frames wait for one more. + if frame.timestamp < lastOut && depth < ReorderDepth.most { + depth += 1 + } + let at = held.firstIndex { $0.timestamp > frame.timestamp } ?? held.count + held.insert(frame, at: at) + while held.count > depth { + emit(held.removeFirst()) + } + } + + private func emit(_ frame: NativeDecodedFrame) { + lastOut = max(lastOut, frame.timestamp) + output(frame) + } + + private func drainHeld() { + reorder.lock() + defer { reorder.unlock() } + while !held.isEmpty { emit(held.removeFirst()) } + } + + // Their surfaces go back to the decoder's pool unseen. + private func discardHeld() { + reorder.lock() + held.removeAll() + reorder.unlock() + } + func decode(data: ArrayBuffer, timestamp: Double, duration: Double, key: Bool) throws { guard let session else { throw WebCodecsError.invalidState("the decoder is closed") } let bytes = data.toData(copyIfNeeded: true) @@ -169,7 +457,7 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { guard let imageBuffer else { return } // dropped let ts = pts.isValid ? Double(CMTimeConvertScale(pts, timescale: 1_000_000, method: .roundHalfAwayFromZero).value) : timestamp let d = dur.isValid ? Double(CMTimeConvertScale(dur, timescale: 1_000_000, method: .roundHalfAwayFromZero).value) : duration - self.output(NativeDecodedFrame(surface: HybridNativeSurface(pixelBuffer: imageBuffer), timestamp: ts, duration: d)) + self.hold(NativeDecodedFrame(surface: HybridNativeSurface(pixelBuffer: imageBuffer), timestamp: ts, duration: d)) } if status != noErr { self.fail(HybridNativeVideoEncoder.describe(status).replacingOccurrences(of: "encoder", with: "decoder")) @@ -182,6 +470,11 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { return Promise.parallel(queue) { VTDecompressionSessionFinishDelayedFrames(session) VTDecompressionSessionWaitForAsynchronousFrames(session) + if !self.failed { self.drainHeld() } + // A flush ends the stream: what follows starts from a key frame. + self.reorder.lock() + self.lastOut = -Double.infinity + self.reorder.unlock() } } @@ -191,6 +484,7 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { queue.async { self.failed = true VTDecompressionSessionInvalidate(session) + self.discardHeld() } } session = nil diff --git a/nitrogen/generated/ios/swift/NativeVideoDecoderConfig.swift b/nitrogen/generated/ios/swift/NativeVideoDecoderConfig.swift index 985b25e..93663c5 100644 --- a/nitrogen/generated/ios/swift/NativeVideoDecoderConfig.swift +++ b/nitrogen/generated/ios/swift/NativeVideoDecoderConfig.swift @@ -18,7 +18,7 @@ public extension NativeVideoDecoderConfig { /** * Create a new instance of `NativeVideoDecoderConfig`. */ - init(codec: String, description: ArrayBuffer?, codedWidth: Double?, codedHeight: Double?, pixelFormat: String?) { + init(codec: String, description: ArrayBuffer?, codedWidth: Double?, codedHeight: Double?, pixelFormat: String?, hardwareAcceleration: String?) { self.init(std.string(codec), { () -> bridge.std__optional_std__shared_ptr_ArrayBuffer__ in if let __unwrappedValue = description { return bridge.create_std__optional_std__shared_ptr_ArrayBuffer__(__unwrappedValue.getArrayBuffer()) @@ -43,6 +43,12 @@ public extension NativeVideoDecoderConfig { } else { return .init() } + }(), { () -> bridge.std__optional_std__string_ in + if let __unwrappedValue = hardwareAcceleration { + return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) + } else { + return .init() + } }()) } @@ -98,4 +104,16 @@ public extension NativeVideoDecoderConfig { } }() } + + @inline(__always) + var hardwareAcceleration: String? { + return { () -> String? in + if bridge.has_value_std__optional_std__string_(self.__hardwareAcceleration) { + let __unwrapped = bridge.get_std__optional_std__string_(self.__hardwareAcceleration) + return String(__unwrapped) + } else { + return nil + } + }() + } } diff --git a/nitrogen/generated/ios/swift/NativeVideoEncoderConfig.swift b/nitrogen/generated/ios/swift/NativeVideoEncoderConfig.swift index e7aff38..b0f5b72 100644 --- a/nitrogen/generated/ios/swift/NativeVideoEncoderConfig.swift +++ b/nitrogen/generated/ios/swift/NativeVideoEncoderConfig.swift @@ -18,7 +18,7 @@ public extension NativeVideoEncoderConfig { /** * Create a new instance of `NativeVideoEncoderConfig`. */ - init(codec: String, width: Double, height: Double, bitrate: Double?, framerate: Double?, realtime: Bool, profile: String?) { + init(codec: String, width: Double, height: Double, bitrate: Double?, framerate: Double?, realtime: Bool, profile: String?, level: Double?) { self.init(std.string(codec), width, height, { () -> bridge.std__optional_double_ in if let __unwrappedValue = bitrate { return bridge.create_std__optional_double_(__unwrappedValue) @@ -37,6 +37,12 @@ public extension NativeVideoEncoderConfig { } else { return .init() } + }(), { () -> bridge.std__optional_double_ in + if let __unwrappedValue = level { + return bridge.create_std__optional_double_(__unwrappedValue) + } else { + return .init() + } }()) } @@ -95,4 +101,16 @@ public extension NativeVideoEncoderConfig { } }() } + + @inline(__always) + var level: Double? { + return { () -> Double? in + if bridge.has_value_std__optional_double_(self.__level) { + let __unwrapped = bridge.get_std__optional_double_(self.__level) + return __unwrapped + } else { + return nil + } + }() + } } diff --git a/nitrogen/generated/shared/c++/NativeVideoDecoderConfig.hpp b/nitrogen/generated/shared/c++/NativeVideoDecoderConfig.hpp index 5178ed0..a3ef44a 100644 --- a/nitrogen/generated/shared/c++/NativeVideoDecoderConfig.hpp +++ b/nitrogen/generated/shared/c++/NativeVideoDecoderConfig.hpp @@ -46,10 +46,11 @@ namespace margelo::nitro::webcodecs { std::optional codedWidth SWIFT_PRIVATE; std::optional codedHeight SWIFT_PRIVATE; std::optional pixelFormat SWIFT_PRIVATE; + std::optional hardwareAcceleration SWIFT_PRIVATE; public: NativeVideoDecoderConfig() = default; - explicit NativeVideoDecoderConfig(std::string codec, std::optional> description, std::optional codedWidth, std::optional codedHeight, std::optional pixelFormat): codec(codec), description(description), codedWidth(codedWidth), codedHeight(codedHeight), pixelFormat(pixelFormat) {} + explicit NativeVideoDecoderConfig(std::string codec, std::optional> description, std::optional codedWidth, std::optional codedHeight, std::optional pixelFormat, std::optional hardwareAcceleration): codec(codec), description(description), codedWidth(codedWidth), codedHeight(codedHeight), pixelFormat(pixelFormat), hardwareAcceleration(hardwareAcceleration) {} public: friend bool operator==(const NativeVideoDecoderConfig& lhs, const NativeVideoDecoderConfig& rhs) = default; @@ -69,7 +70,8 @@ namespace margelo::nitro { JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "description"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "codedWidth"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "codedHeight"))), - JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "pixelFormat"))) + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "pixelFormat"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "hardwareAcceleration"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::webcodecs::NativeVideoDecoderConfig& arg) { @@ -79,6 +81,7 @@ namespace margelo::nitro { obj.setProperty(runtime, PropNameIDCache::get(runtime, "codedWidth"), JSIConverter>::toJSI(runtime, arg.codedWidth)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "codedHeight"), JSIConverter>::toJSI(runtime, arg.codedHeight)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "pixelFormat"), JSIConverter>::toJSI(runtime, arg.pixelFormat)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "hardwareAcceleration"), JSIConverter>::toJSI(runtime, arg.hardwareAcceleration)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -94,6 +97,7 @@ namespace margelo::nitro { if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "codedWidth")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "codedHeight")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "pixelFormat")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "hardwareAcceleration")))) return false; return true; } }; diff --git a/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp b/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp index 1b6e2e9..4f12a01 100644 --- a/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp +++ b/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp @@ -47,10 +47,11 @@ namespace margelo::nitro::webcodecs { std::optional framerate SWIFT_PRIVATE; bool realtime SWIFT_PRIVATE; std::optional profile SWIFT_PRIVATE; + std::optional level SWIFT_PRIVATE; public: NativeVideoEncoderConfig() = default; - explicit NativeVideoEncoderConfig(std::string codec, double width, double height, std::optional bitrate, std::optional framerate, bool realtime, std::optional profile): codec(codec), width(width), height(height), bitrate(bitrate), framerate(framerate), realtime(realtime), profile(profile) {} + explicit NativeVideoEncoderConfig(std::string codec, double width, double height, std::optional bitrate, std::optional framerate, bool realtime, std::optional profile, std::optional level): codec(codec), width(width), height(height), bitrate(bitrate), framerate(framerate), realtime(realtime), profile(profile), level(level) {} public: friend bool operator==(const NativeVideoEncoderConfig& lhs, const NativeVideoEncoderConfig& rhs) = default; @@ -72,7 +73,8 @@ namespace margelo::nitro { JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bitrate"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "framerate"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "realtime"))), - JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "profile"))) + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "profile"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "level"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::webcodecs::NativeVideoEncoderConfig& arg) { @@ -84,6 +86,7 @@ namespace margelo::nitro { obj.setProperty(runtime, PropNameIDCache::get(runtime, "framerate"), JSIConverter>::toJSI(runtime, arg.framerate)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "realtime"), JSIConverter::toJSI(runtime, arg.realtime)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "profile"), JSIConverter>::toJSI(runtime, arg.profile)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "level"), JSIConverter>::toJSI(runtime, arg.level)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -101,6 +104,7 @@ namespace margelo::nitro { if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "framerate")))) return false; if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "realtime")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "profile")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "level")))) return false; return true; } }; diff --git a/package.json b/package.json index 603cf80..9417715 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,8 @@ "scripts": { "test": "NODE_OPTIONS='--experimental-require-module' jest -i", "test:unit": "jest -c jest.unit.config.js", + "test:cpp": "scripts/test-cpp.sh", + "test:jvm": "cd example/android && ./gradlew :react-native-webcodecs:testDebugUnitTest -PreactNativeArchitectures=arm64-v8a", "lint": "eslint . --ext .ts,.tsx --max-warnings 0 --cache --fix && yarn example lint", "tsc": "tsc --noEmit && yarn example tsc", "build": "bob build", diff --git a/scripts/test-cpp.sh b/scripts/test-cpp.sh new file mode 100755 index 0000000..e199762 --- /dev/null +++ b/scripts/test-cpp.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Host tests of the Android C++ helpers that need no NDK +# (android/src/test/cpp/*_test.cpp), each built with clang and run under +# AddressSanitizer and UndefinedBehaviorSanitizer: `yarn test:cpp`. +# clang, not g++: P010.hpp uses __fp16, which clang has on every target. +set -euo pipefail + +cd "$(dirname "$0")/.." +CXX="${CXX:-clang++}" +OUT=android/build/test-cpp +mkdir -p "$OUT" + +failed=0 +for test in android/src/test/cpp/*_test.cpp; do + name="$(basename "$test" .cpp)" + echo "== $name" + "$CXX" -std=c++20 -Wall -Wextra -Werror -g -O1 -fno-omit-frame-pointer \ + -fsanitize=address,undefined -fno-sanitize-recover=all \ + -I android/src/main/cpp -o "$OUT/$name" "$test" + if ! ASAN_OPTIONS=detect_leaks=0 "$OUT/$name"; then + failed=1 + fi +done +exit "$failed" diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index cd660db..f2389da 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -169,10 +169,26 @@ const adb = (args: string[], input?: Buffer) => { input, maxBuffer: 256 * 1024 * 1024 }, ); +// Android debug builds: a fault the video encoder acts out from its next +// codec on (see EncoderFault in VideoEncoder.hpp); "" for none. The property +// outlives the app: reset it in a finally. +const setFault = (value: string) => + adb([ + "shell", + "setprop", + "debug.webcodecs.fault", + value === "" ? '""' : value, + ]); + const pushAsset = (name: string) => + pushFile(path.join(__dirname, "assets", name)); + +// Copies a file of this machine into the app's cache directory, as +// e2e-. +const pushFile = (source: string) => appCache().then((dir) => { + const name = path.basename(source); const destination = `${dir}/e2e-${name}`; - const source = path.join(__dirname, "assets", name); if (client.OS === "android") { // Written aside, then renamed: the app never sees a partial file. The // rename is its own command: `adb exec-in` can end the shell as soon @@ -496,6 +512,396 @@ const expectOk = (result: Export) => { return result as Required; }; +// Runs `fn` on the device with the eval context, for longer than one call +// to the app may take: started in one call, then polled until it settles. +const runOnDevice = async ( + fn: (context: { + example: any; + mediabunny: any; + webcodecs: any; + ctx: any; + }) => Promise, + ctx: object, + limitMs: number, +): Promise => { + const key = `__e2e_${Math.random().toString(36).slice(2)}`; + await client.eval( + ({ example, mediabunny, webcodecs, ctx: c }) => { + const g = globalThis as any; + const run = eval(`(${c.fn})`); + g[c.key] = null; + Promise.resolve() + .then(() => run({ example, mediabunny, webcodecs, ctx: c.args })) + .then( + (value: any) => (g[c.key] = { value }), + (e: any) => (g[c.key] = { error: String((e && e.stack) || e) }), + ); + return true; + }, + { ctx: { fn: fn.toString(), key, args: ctx } }, + ); + const deadline = Date.now() + limitMs; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 2000)); + const settled = (await client.eval( + ({ ctx: c }) => { + const g = globalThis as any; + const r = g[c.key]; + if (r) { + delete g[c.key]; + } + return r; + }, + { ctx: { key } }, + )) as { value?: R; error?: string } | null; + if (settled) { + if (settled.error !== undefined) { + throw new Error(settled.error); + } + return settled.value as R; + } + } + throw new Error(`timed out after ${limitMs} ms`); +}; + +interface CardExport { + path: string; + frames: number; + duration: number; + ms: number; +} + +// The Video Export screen's export (example/src/VideoExport), on the device. +const exportCard = async (o: { hdr: boolean; sound: boolean }) => { + const result = await runOnDevice( + ({ example, ctx }) => + example.loadCardAssets().then((assets: any) => { + const animation = example.makeCard(assets, ctx.hdr); + const done = () => animation.dispose && animation.dispose(); + return (ctx.sound ? example.loadSound() : Promise.resolve(null)) + .then((sound: any) => + example.exportVideo( + animation, + sound, + ctx.hdr, + new AbortController().signal, + () => {}, + ), + ) + .then( + (r: any) => { + done(); + return r; + }, + (e: any) => { + done(); + throw e; + }, + ); + }), + o, + // AV1 in software on the Android emulator is slow. + o.hdr && client.OS === "android" ? 1440000 : 540000, + ); + if (!result) { + throw new Error("the export was cancelled"); + } + console.log( + `card ${o.hdr ? "HDR" : "SDR"}${o.sound ? " + sound" : ""}: ${result.frames} frames in ${Math.round(result.ms)} ms`, + ); + return result; +}; + +interface Compressed { + skipped?: boolean; + supported?: string[]; + source: { width: number; height: number; rotation: number }; + target: { width: number; height: number }; + result: { + path: string; + size: number; + width: number; + height: number; + ms: number; + }; +} + +// The Compress screen's compression (example/src/Compress) of a file in +// the app's cache, at 480p and medium quality unless told otherwise; with +// a `codec` the device's supportedCodecs does not list, `skipped`. +const compressOnDevice = ( + file: string, + options: { codec?: string; audio?: boolean; frameRate?: number }, +) => + runOnDevice( + ({ example, ctx }) => + example + .openSource({ name: "source.mp4", path: ctx.file, size: 0 }) + .then((source: any) => + example + .supportedCodecs(source.width, source.height) + .then((supported: string[]) => { + if (supported.indexOf(ctx.codec) < 0) { + return { skipped: true, supported }; + } + const s = example.settings; + const settings = { + resolution: "480", + quality: "medium", + codec: ctx.codec, + frameRate: ctx.frameRate, + audio: ctx.audio, + videoBitrate: s.videoBitrate( + source, + "480", + "medium", + ctx.codec, + ctx.frameRate, + ), + }; + return example + .compress( + source, + settings, + new AbortController().signal, + () => {}, + ) + .then((result: any) => ({ + source, + target: s.targetSize(source, "480"), + result, + })); + }), + ), + { + file, + codec: options.codec ?? "avc", + audio: options.audio ?? true, + frameRate: options.frameRate ?? null, + }, + 540000, + ); + +// The clips to compress, made with ffmpeg once (kept in the temporary +// directory) and pushed to the app's cache once per run. +const clipDirectory = path.join(os.tmpdir(), "rnwc-e2e-clips"); +const clips = new Map>(); +const sourceClip = (rotated: boolean) => { + let clip = clips.get(rotated); + if (!clip) { + const plain = path.join(clipDirectory, "clip.mp4"); + fs.mkdirSync(clipDirectory, { recursive: true }); + if (!fs.existsSync(plain)) { + execFileSync("ffmpeg", [ + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + "testsrc2=size=1280x720:rate=30:duration=3", + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=3", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-profile:v", + "high", + "-c:a", + "aac", + "-b:a", + "128k", + "-movflags", + "+faststart", + plain, + ]); + } + let file = plain; + if (rotated) { + file = path.join(clipDirectory, "clip-portrait.mp4"); + // ffmpeg counts counterclockwise: -90 is 90° clockwise, the tag of + // a phone held upright, which stores its frames landscape. + execFileSync("ffmpeg", [ + "-loglevel", + "error", + "-y", + "-display_rotation:v:0", + "-90", + "-i", + plain, + "-c", + "copy", + file, + ]); + } + clip = pushFile(file); + clips.set(rotated, clip); + } + return clip; +}; + +interface Probed extends Stream { + profile?: string; + pix_fmt?: string; + color_transfer?: string; + nb_read_packets?: string; + side_data_list?: { rotation?: number }[]; +} + +const probe = (file: string): { streams: Probed[] } => + JSON.parse( + execFileSync( + "ffprobe", + ["-v", "error", "-count_packets", "-show_streams", "-of", "json", file], + { encoding: "utf8" }, + ), + ); + +const rotationOf = (stream: Probed) => + Math.abs( + stream.side_data_list?.find((d) => d.rotation !== undefined)?.rotation ?? 0, + ); + +// The video packets' presentation times, in the order they are stored. +const videoPacketTimes = (file: string) => + execFileSync( + "ffprobe", + [ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "packet=pts_time", + "-of", + "csv=p=0", + file, + ], + { encoding: "utf8" }, + ) + .trim() + .split("\n") + .map(Number); + +// The MP4's top-level boxes, in order. +const topLevelBoxes = (file: string) => { + const bytes = fs.readFileSync(file); + const boxes: string[] = []; + let at = 0; + while (at + 8 <= bytes.length) { + let size = bytes.readUInt32BE(at); + boxes.push(bytes.toString("latin1", at + 4, at + 8)); + if (size === 1) { + size = Number(bytes.readBigUInt64BE(at + 8)); + } else if (size === 0) { + size = bytes.length - at; + } + if (size < 8) { + break; + } + at += size; + } + return boxes; +}; + +interface Decoded { + frames: number; + errors: string[]; + // The first frame's. + first: { + codedWidth: number; + codedHeight: number; + visibleRect: { x: number; y: number; width: number; height: number }; + displayWidth: number; + displayHeight: number; + format: string | null; + } | null; +} + +// Decodes a file of the app's on the device with the track's decoder config +// and `ctx.config` on top (e.g. hardwareAcceleration), without the members +// named in `drop`. +const decodeOnDevice = (file: string, config: object, drop: string[] = []) => + runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((trackConfig: any) => { + const result: Decoded = { frames: 0, errors: [], first: null }; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + if (!result.first) { + const r = frame.visibleRect; + result.first = { + codedWidth: frame.codedWidth, + codedHeight: frame.codedHeight, + visibleRect: { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + }, + displayWidth: frame.displayWidth, + displayHeight: frame.displayHeight, + format: frame.format, + }; + } + result.frames++; + frame.close(); + }, + error: (e: any) => result.errors.push(String(e)), + }); + const merged = Object.assign({}, trackConfig, ctx.config); + for (const name of ctx.drop) { + delete merged[name]; + } + decoder.configure(merged); + const packets = new mb.EncodedPacketSink(track).packets(); + // Stops at an error: the decoder is closed then. + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done || decoder.state === "closed") { + return undefined; + } + decoder.decode(r.value.toEncodedVideoChunk()); + return step(); + }); + return step() + .then(() => + decoder.state === "closed" ? undefined : decoder.flush(), + ) + .catch((e: any) => { + result.errors.push(`flush: ${e}`); + }) + .then(() => { + if (decoder.state !== "closed") { + decoder.close(); + } + input.dispose(); + return result; + }); + }), + ); + }, + { file, config, drop }, + 120000, + ); + +// The codecs the app allocated since `logcatClear()` (Android). +const logcatClear = () => adb(["logcat", "-c"]); +const allocatedCodecs = () => + adb(["logcat", "-d", "-s", "CCodec:D"]) + .toString() + .split("\n") + .map((line) => /allocate\(([^)]+)\)/.exec(line)?.[1]) + .filter((name): name is string => !!name); + const ios = () => client.OS === "ios"; const supported = () => client.OS === "ios" || client.OS === "android"; @@ -614,6 +1020,10 @@ describe("react-native-webcodecs + Mediabunny", () => { const local = copyLocal(result.path); const audio = streamOf(local, "audio"); expect(audio.codec_name).toBe("aac"); + // AAC-LC, as configured ("mp4a.40.2"). + expect( + probe(local).streams.find((s) => s.codec_type === "audio")?.profile, + ).toBe("LC"); expect(Math.abs(Number(audio.duration) - 2)).toBeLessThan(0.1); // The sine survives the round trip at its level (silence would be // below -90 dB). @@ -884,6 +1294,2225 @@ describe("react-native-webcodecs + Mediabunny", () => { expect(result.huge).toBe(false); }, 60000); + // Android: an odd size is not read aligned up (the encoder would be given + // the odd size, which encoders aligned to 2 refuse at configure time). + it("answers isConfigSupported false for odd sizes on Android", async () => { + if (client.OS !== "android") { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => + Promise.all( + [ + [1279, 720], + [641, 481], + [1280, 720], + ].map(([width, height]) => + wc.VideoEncoder.isConfigSupported({ + codec: "avc1.42001f", + width, + height, + }).then((support: any) => support.supported), + ), + ), + )) as any; + expect(result).toEqual([false, false, true]); + }, 60000); + + // Android: createSurfacePool asks AHardwareBuffer_isSupported whether + // RGBA16F buffers the CPU can read (the HDR encoder converts them to P010) + // can be made, and refuses the pool up front when not. The emulator can: + // its pool is made, and its buffers allocated. + it("creates an RGBA16F surface pool where the device can read one (Android)", async () => { + if (client.OS !== "android") { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + try { + const pool = wc.createSurfacePool(64, 32, "RGBA16F"); + const surface = pool.acquire(); + const out = { + format: surface.format, + width: surface.width, + height: surface.height, + }; + surface.release(); + return out; + } catch (e: any) { + return { error: `${e.name}: ${e.message}` }; + } + })) as any; + expect(result).toEqual({ format: "RGBA16F", width: 64, height: 32 }); + }, 60000); + + // The frame rate and bitrate are hints, as in Media3: an encoder is not + // refused for them (the emulator's c2.android.avc.encoder lists at most + // 12 Mbps, and about 30 fps at 1080x1920). The bitrate is clamped into the + // encoder's range, the frame rate floored, and below 1 ignored. + it("treats framerate and bitrate as hints", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + const configs = [ + { codec: "avc1.42001f", width: 1280, height: 720, bitrate: 100e6 }, + { codec: "avc1.42001f", width: 1080, height: 1920, framerate: 120 }, + { codec: "avc1.42001f", width: 640, height: 480, framerate: 0.5 }, + ]; + const run = (config: any) => + wc.VideoEncoder.isConfigSupported(config).then((support: any) => { + const chunks: number[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => chunks.push(chunk.byteLength), + error: (e: any) => errors.push(`${e.name}: ${e.message}`), + }); + encoder.configure(config); + const pool = wc.createSurfacePool(config.width, config.height); + [0, 33333, 66666].forEach((timestamp) => { + const frame = new wc.VideoFrame(pool.acquire(), { timestamp }); + encoder.encode(frame, { keyFrame: timestamp === 0 }); + frame.close(); + }); + return encoder + .flush() + .catch((e: any) => errors.push(`flush: ${e.name}: ${e.message}`)) + .then(() => { + if (encoder.state !== "closed") { + encoder.close(); + } + return { + supported: support.supported, + chunks: chunks.filter((n) => n > 0).length, + errors, + }; + }); + }); + // One at a time: a 1080x1920 software encode next to another one is + // slow on the emulator. + return configs.reduce( + (done: Promise, config) => + done.then((all) => run(config).then((r: any) => [...all, r])), + Promise.resolve([]), + ); + })) as any[]; + expect(result).toEqual([ + { supported: true, chunks: 3, errors: [] }, + { supported: true, chunks: 3, errors: [] }, + { supported: true, chunks: 3, errors: [] }, + ]); + }, 120000); + + // The SPS (avcC) of the output: the codec string's profile, and a level no + // higher than its own when the size fits in it (raised when it does not). + // Android configures the encoder with the level along with the profile + // (OMX encoders refuse a profile alone), the codec string's rather than + // the encoder's highest; iOS picks the lowest that fits. An encoder + // without the profile gets the next one down that it lists: the emulator's + // c2.android.avc.encoder (libavc) has no High, and gives Main for + // avc1.640028 (it gave its default, Baseline, before). + it("encodes H.264 in the codec string's profile and level", async () => { + if (!supported()) { + return; + } + if (client.OS === "android") { + logcatClear(); + } + const result = (await client.eval(({ webcodecs: wc }) => { + const configs = [ + { codec: "avc1.640028", width: 1280, height: 720 }, + { codec: "avc1.4d0028", width: 1280, height: 720 }, + { codec: "avc1.42001f", width: 640, height: 480 }, + { codec: "avc1.42001f", width: 1920, height: 1080 }, + ]; + const run = (config: any) => { + let avcC: number[] = []; + const errors: string[] = []; + let chunks = 0; + const encoder = new wc.VideoEncoder({ + output: (chunk: any, meta: any) => { + chunks += chunk.byteLength > 0 ? 1 : 0; + const d = meta?.decoderConfig?.description; + if (d && avcC.length === 0) { + const bytes = ArrayBuffer.isView(d) + ? new Uint8Array(d.buffer, d.byteOffset, d.byteLength) + : new Uint8Array(d); + avcC = [bytes[1], bytes[3]]; + } + }, + error: (e: any) => errors.push(`${e.name}: ${e.message}`), + }); + encoder.configure(config); + const pool = wc.createSurfacePool(config.width, config.height); + [0, 33333, 66666, 100000, 133333].forEach((timestamp) => { + const frame = new wc.VideoFrame(pool.acquire(), { timestamp }); + encoder.encode(frame, { keyFrame: timestamp === 0 }); + frame.close(); + }); + return encoder + .flush() + .catch((e: any) => errors.push(`flush: ${e.name}: ${e.message}`)) + .then(() => { + if (encoder.state !== "closed") { + encoder.close(); + } + return { codec: config.codec, avcC, chunks, errors }; + }); + }; + return configs.reduce( + (done: Promise, config) => + done.then((all) => run(config).then((r: any) => [...all, r])), + Promise.resolve([]), + ); + })) as any[]; + for (const run of result) { + expect(run.errors).toEqual([]); + expect(run.chunks).toBe(5); + } + const [high, main, baseline, baseline1080] = result.map((r) => r.avcC); + if (ios()) { + expect(high[0]).toBe(100); + } else { + expect([100, 77]).toContain(high[0]); + } + expect(main[0]).toBe(77); + expect(baseline[0]).toBe(66); + expect(baseline1080[0]).toBe(66); + // Within the codec string's level, or raised to 4.0 for 1080p. + expect(high[1]).toBeLessThanOrEqual(40); + expect(main[1]).toBeLessThanOrEqual(40); + expect(baseline[1]).toBeLessThanOrEqual(31); + expect(baseline1080[1]).toBeGreaterThanOrEqual(40); + if (client.OS === "android") { + expect([high[1], main[1], baseline[1], baseline1080[1]]).toEqual([ + 40, 40, 31, 40, + ]); + // The first attempt took each config. + const attempts = adb(["logcat", "-d", "-s", "WebCodecs:I"]) + .toString() + .split("\n") + .map((line) => /video encoder: .*: attempt (\d+)/.exec(line)?.[1]) + .filter((n): n is string => !!n); + expect(attempts).toEqual(["0", "0", "0", "0"]); + } + }, 120000); + + // A config no encoder takes: NotSupportedError, and on Android a message + // naming each encoder tried and the status of each configure attempt + // (MediaCodec's own, e.g. NO_MEMORY -12 on a device out of codec memory). + it("says which encoders refused a config and why", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: () => undefined, + error: (e: any) => errors.push(`${e.name}: ${e.message}`), + }); + encoder.configure({ codec: "avc1.42001f", width: 16384, height: 16384 }); + return new Promise((resolve) => setTimeout(resolve, 100)).then(() => ({ + errors, + state: encoder.state, + })); + })) as any; + expect(result.state).toBe("closed"); + expect(result.errors.length).toBe(1); + expect(result.errors[0]).toMatch(/^NotSupportedError: /); + if (client.OS === "android") { + const [message] = result.errors as string[]; + expect(message).toContain("c2.android.avc.encoder"); + // Every attempt, with the status by name: three with Baseline and its + // level, three without. + expect(message.match(/-10000 AMEDIA_ERROR_UNKNOWN/g)?.length).toBe(6); + } + }, 60000); + + // AudioEncoder alone, fed a 440 Hz sine in 1000-frame AudioData (not + // multiples of an AAC frame): `segments` runs, each from its own start + // time and followed by a flush. Returns each chunk's timestamp and + // duration, in µs, per run. + const encodeAac = (segments: { start: number; seconds: number }[]) => + client.eval( + ({ webcodecs: wc, ctx }) => { + const rate = 48000; + const runs: (number | string)[][][] = []; + let run: (number | string)[][] = []; + const encoder = new wc.AudioEncoder({ + output: (chunk: any) => run.push([chunk.timestamp, chunk.duration]), + error: (e: any) => run.push([-1, String(e)]), + }); + encoder.configure({ + codec: "mp4a.40.2", + sampleRate: rate, + numberOfChannels: 1, + bitrate: 128000, + }); + const segment = (i: number): Promise => { + if (i >= ctx.segments.length) { + return Promise.resolve(); + } + const { start, seconds } = ctx.segments[i]; + const total = Math.round(seconds * rate); + for (let at = 0; at < total; at += 1000) { + const frames = Math.min(1000, total - at); + const data = new Float32Array(frames); + for (let f = 0; f < frames; f++) { + data[f] = 0.5 * Math.sin((2 * Math.PI * 440 * (at + f)) / rate); + } + const audio = new wc.AudioData({ + format: "f32", + sampleRate: rate, + numberOfFrames: frames, + numberOfChannels: 1, + timestamp: start + Math.round((at * 1e6) / rate), + data, + }); + encoder.encode(audio); + audio.close(); + } + return encoder.flush().then(() => { + runs.push(run); + run = []; + return segment(i + 1); + }); + }; + return segment(0).then(() => { + encoder.close(); + return runs; + }); + }, + { ctx: { segments } }, + ) as Promise; + + const FRAME_US = (1024 * 1e6) / 48000; + + it("encodes 1 s of sound to 1 s of AAC, in steps of one frame", async () => { + if (!supported()) { + return; + } + const [chunks] = await encodeAac([{ start: 0, seconds: 1 }]); + expect(chunks.filter(([t]) => t < 0)).toEqual([]); + const [first] = chunks; + const last = chunks[chunks.length - 1]; + // Every sample is in (the last frame padded), plus the encoder's + // priming, which is not trimmed. + expect(last[0] + last[1] - first[0]).toBeGreaterThanOrEqual(1e6); + expect(first[0]).toBe(0); + for (let i = 1; i < chunks.length; i++) { + expect( + Math.abs(chunks[i][0] - chunks[i - 1][0] - FRAME_US), + ).toBeLessThanOrEqual(1); + } + }, 60000); + + it("starts the AAC timeline over after a flush", async () => { + if (!supported()) { + return; + } + const [, second] = await encodeAac([ + { start: 0, seconds: 0.5 }, + { start: 5e6, seconds: 0.5 }, + ]); + expect(second.length).toBeGreaterThan(0); + expect(second[0][0]).toBe(5e6); + }, 60000); + + // WebCodecs: flush() outputs what was encoded, so nothing when nothing was + // (no padding of silence), before the first encode() or right after + // another flush(). + it("outputs no AAC from a flush with nothing encoded", async () => { + if (!supported()) { + return; + } + const [before, sound, after] = await encodeAac([ + { start: 0, seconds: 0 }, + { start: 0, seconds: 0.5 }, + { start: 1e6, seconds: 0 }, + ]); + expect(before).toEqual([]); + expect(sound.filter(([t]) => t < 0)).toEqual([]); + expect(sound.length).toBeGreaterThan(0); + expect(sound[0][0]).toBe(0); + expect(after).toEqual([]); + }, 60000); + + // AudioDecoder.flush() with nothing queued (first thing after configure, + // and right after another flush) settles at once and outputs nothing; the + // decoder then decodes the whole sound, twice over, with flushes between. + // (On Android an end of stream queued as the first input, or a codec + // flushed before any output format, can lose the AAC config: b/141097367.) + it("flushes an AudioDecoder with nothing queued, then decodes after flushes", async () => { + if (!supported()) { + return; + } + const sound = await pushAsset("sine-8s.m4a"); + const result = await runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + return input.getPrimaryAudioTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => { + const errors: string[] = []; + let frames = 0; + let sum = 0; + let count = 0; + const decoder = new wc.AudioDecoder({ + output: (data: any) => { + frames += data.numberOfFrames; + const samples = new Float32Array( + data.numberOfFrames * data.numberOfChannels, + ); + data.copyTo(samples, { planeIndex: 0, format: "f32" }); + for (let i = 0; i < samples.length; i++) { + sum += samples[i] * samples[i]; + } + count += samples.length; + data.close(); + }, + error: (e: any) => errors.push(String(e)), + }); + decoder.configure(config); + const timedFlush = () => { + const before = frames; + const t0 = Date.now(); + return decoder + .flush() + .then(() => ({ ms: Date.now() - t0, frames: frames - before })); + }; + const pass = () => { + const before = frames; + let packetCount = 0; + const packets = new mb.EncodedPacketSink(track).packets(); + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done) { + return undefined; + } + packetCount++; + decoder.decode(r.value.toEncodedAudioChunk()); + return step(); + }); + sum = 0; + count = 0; + return step() + .then(() => decoder.flush()) + .then(() => ({ + packets: packetCount, + frames: frames - before, + rms: Math.sqrt(sum / Math.max(1, count)), + })); + }; + const out: any = { errors }; + return timedFlush() + .then((first: any) => { + out.first = first; + return pass(); + }) + .then((one: any) => { + out.one = one; + return timedFlush(); + }) + .then((again: any) => { + out.again = again; + return pass(); + }) + .then((two: any) => { + out.two = two; + decoder.close(); + input.dispose(); + return out; + }); + }), + ); + }, + { file: sound }, + 120000, + ); + expect(result.errors).toEqual([]); + expect(result.first.frames).toBe(0); + expect(result.first.ms).toBeLessThan(1000); + expect(result.again.frames).toBe(0); + expect(result.again.ms).toBeLessThan(1000); + for (const run of [result.one, result.two]) { + // One AAC frame per packet, give or take the decoder's priming and + // tail (out of scope here). + expect(run.frames).toBeGreaterThan((run.packets - 4) * 1024); + expect(run.frames).toBeLessThanOrEqual((run.packets + 1) * 1024); + // The sine, not silence. + expect(run.rms).toBeGreaterThan(0.01); + } + expect(Math.abs(result.two.frames - result.one.frames)).toBeLessThanOrEqual( + 2048, + ); + }, 180000); + + it("flushes a VideoEncoder given two frames with one timestamp", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + const chunks: number[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => chunks.push(chunk.timestamp), + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 64, height: 64 }); + const pool = wc.createSurfacePool(64, 64); + [0, 0, 33333, 66666].forEach((timestamp) => { + const frame = new wc.VideoFrame(pool.acquire(), { timestamp }); + encoder.encode(frame, { keyFrame: timestamp === 0 }); + frame.close(); + }); + const timeout = new Promise((resolve) => + setTimeout(() => resolve("timeout"), 15000), + ); + return Promise.race([ + encoder.flush().then( + () => "flushed", + (e: any) => `${e.name}: ${e.message}`, + ), + timeout, + ]).then((flushed: any) => { + const queue = encoder.encodeQueueSize; + encoder.close(); + return { flushed, chunks, errors, queue }; + }); + })) as any; + expect(result.errors).toEqual([]); + expect(result.flushed).toBe("flushed"); + expect(result.queue).toBe(0); + if (client.OS === "android") { + expect(result.chunks.length).toBe(4); + } else { + expect(result.chunks.length).toBeGreaterThanOrEqual(3); + } + }, 60000); + + it("puts key frames exactly where requested", async () => { + if (!supported()) { + return; + } + const keys = [0, 7, 20, 33, 50, 51, 77]; + const sizes = [ + [64, 64], + [1280, 720], + ]; + const result = (await client.eval( + ({ webcodecs: wc, keys: wanted, sizes: all }) => { + const encodeAt = (width: number, height: number) => { + const types: Record = {}; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => { + types[String(chunk.timestamp)] = chunk.type; + }, + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width, height }); + const pool = wc.createSurfacePool(width, height); + // All queued at once, without waiting on the encoder. + for (let i = 0; i < 90; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: wanted.indexOf(i) >= 0 }); + frame.close(); + } + return encoder.flush().then( + () => { + encoder.close(); + return { types, errors }; + }, + (e: any) => { + encoder.close(); + return { types, errors: errors.concat([String(e)]) }; + }, + ); + }; + const runs: any[] = []; + return all + .reduce( + (p: Promise, size: number[]) => + p.then(() => + encodeAt(size[0], size[1]).then((r: any) => { + runs.push(r); + }), + ), + Promise.resolve(), + ) + .then(() => runs); + }, + { keys, sizes }, + )) as any; + result.forEach((run: any) => { + expect(run.errors).toEqual([]); + const keyAt = Array.from({ length: 90 }, (_, i) => + run.types[String(i * 33333)] === "key" ? i : -1, + ).filter((i) => i >= 0); + expect(keyAt).toEqual(keys); + expect(Object.keys(run.types).length).toBe(90); + }); + }, 120000); + + it("encodes every frame when timestamps repeat or go backwards", async () => { + if (!supported()) { + return; + } + const cases = { + repeated: [0, 0, 33333, 66666], + backwards: [0, 33333, 20000, 66666], + }; + const result = (await client.eval( + ({ webcodecs: wc, cases: input }) => { + const encodeAll = (times: number[]) => { + const chunks: { timestamp: number; duration: number }[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => + chunks.push({ + timestamp: chunk.timestamp, + duration: chunk.duration, + }), + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 64, height: 64 }); + const pool = wc.createSurfacePool(64, 64); + times.forEach((timestamp: number, i: number) => { + // A duration per frame: each chunk must keep its own. + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp, + duration: 1000 + i, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + }); + return encoder.flush().then( + () => { + encoder.close(); + return { chunks, errors }; + }, + (e: any) => { + encoder.close(); + return { chunks, errors: errors.concat([String(e)]) }; + }, + ); + }; + return encodeAll(input.repeated).then((repeated: any) => + encodeAll(input.backwards).then((backwards: any) => ({ + repeated, + backwards, + })), + ); + }, + { cases }, + )) as any; + for (const name of ["repeated", "backwards"] as const) { + const run = result[name]; + expect(run.errors).toEqual([]); + if (client.OS === "android") { + // Every frame comes out, in input order, with its own timestamp and + // duration (no B-frames: output order is input order). + expect(run.chunks).toEqual( + cases[name].map((timestamp, i) => ({ + timestamp, + duration: 1000 + i, + })), + ); + } else { + expect(run.chunks.length).toBeGreaterThanOrEqual(3); + } + } + }, 60000); + + it("encodes 1, 2 and 3 frames to one chunk each, again and again", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + const encodeFew = (count: number) => { + const chunks: { timestamp: number; type: string; size: number }[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => + chunks.push({ + timestamp: chunk.timestamp, + type: chunk.type, + size: chunk.byteLength, + }), + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 64, height: 64 }); + const pool = wc.createSurfacePool(64, 64); + // Each round is a short stream of its own: flush() ends it right + // after its last frame. + const round = (r: number): Promise => { + for (let i = 0; i < count; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: (r * count + i) * 33333, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + } + return encoder.flush(); + }; + return [0, 1, 2] + .reduce( + (p: Promise, r: number) => p.then(() => round(r)), + Promise.resolve(), + ) + .then( + () => { + encoder.close(); + return { chunks, errors }; + }, + (e: any) => { + encoder.close(); + return { chunks, errors: errors.concat([String(e)]) }; + }, + ); + }; + const runs: any[] = []; + return [1, 2, 3] + .reduce( + (p: Promise, count: number) => + p.then(() => + encodeFew(count).then((r: any) => { + runs.push(r); + }), + ), + Promise.resolve(), + ) + .then(() => runs); + })) as any; + result.forEach((run: any, n: number) => { + const count = n + 1; + expect(run.errors).toEqual([]); + expect(run.chunks.map((c: any) => c.timestamp)).toEqual( + Array.from({ length: 3 * count }, (_, i) => i * 33333), + ); + run.chunks.forEach((c: any, i: number) => { + expect(c.size).toBeGreaterThan(0); + // The first frame of each round starts a new stream: a key frame. + if (i % count === 0) { + expect(c.type).toBe("key"); + } + }); + }); + }, 120000); + + it("flushes a VideoEncoder whose codec never ends the stream (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + // Debug builds only: the codec's end of stream is never seen. + setFault("venc-no-eos"); + try { + const result = (await client.eval(({ webcodecs: wc }) => { + const chunks: number[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => { + if (chunk.byteLength > 0) { + chunks.push(chunk.timestamp); + } + }, + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 64, height: 64 }); + const pool = wc.createSurfacePool(64, 64); + const flushes: { flushed: string; ms: number }[] = []; + // Two streams: after a flush, the encoder starts a new codec. + const round = (first: number, count: number) => { + for (let i = first; i < first + count; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === first }); + frame.close(); + } + const start = Date.now(); + return Promise.race([ + encoder.flush().then( + () => "flushed", + (e: any) => `${e.name}: ${e.message}`, + ), + new Promise((resolve) => + setTimeout(() => resolve("timeout"), 15000), + ), + ]).then((flushed: any) => { + flushes.push({ flushed, ms: Date.now() - start }); + }); + }; + return round(0, 5) + .then(() => round(5, 3)) + .then(() => { + const queue = encoder.encodeQueueSize; + encoder.close(); + return { chunks, errors, flushes, queue }; + }); + })) as any; + expect(result.errors).toEqual([]); + expect(result.flushes.map((f: any) => f.flushed)).toEqual([ + "flushed", + "flushed", + ]); + result.flushes.forEach((f: any) => expect(f.ms).toBeLessThan(5000)); + expect(result.chunks).toEqual( + Array.from({ length: 8 }, (_, i) => i * 33333), + ); + expect(result.queue).toBe(0); + } finally { + setFault(""); + } + }, 120000); + + it("lets go of a VideoEncoder codec that hangs with frames queued (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + // Debug builds only: the codec's output is never taken, so it stops + // taking input with frames still to draw; 3 s later that is a stall. + setFault("venc-stall-output:3"); + adb(["logcat", "-c"]); + let stuck: any; + try { + stuck = (await client.eval(({ webcodecs: wc }) => { + const errors: string[] = []; + let failed: () => void = () => {}; + const failure = new Promise((resolve) => { + failed = resolve; + }); + const encoder = new wc.VideoEncoder({ + output: () => {}, + error: (e: any) => { + errors.push(`${e.name}: ${e.message}`); + failed(); + }, + }); + encoder.configure({ codec: "avc1.42001f", width: 1280, height: 720 }); + const pool = wc.createSurfacePool(1280, 720); + // All queued at once, without waiting on the encoder. + for (let i = 0; i < 90; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + } + const start = Date.now(); + const flushed = encoder.flush().then( + () => "flushed", + (e: any) => `${e.name}`, + ); + return Promise.race([ + Promise.all([failure, flushed]).then(([, f]) => f), + new Promise((resolve) => setTimeout(() => resolve("timeout"), 30000)), + ]).then((outcome: any) => ({ + outcome, + errors, + ms: Date.now() - start, + state: encoder.state, + })); + })) as any; + } finally { + setFault(""); + } + expect(stuck.outcome).toBe("AbortError"); + expect(stuck.errors.length).toBe(1); + expect(stuck.errors[0]).toMatch(/^EncodingError: /); + expect(stuck.state).toBe("closed"); + // The codec is let go (on the encoder's GL thread, which must not stay + // blocked drawing into a codec that takes nothing). + let released = false; + for (let i = 0; i < 50 && !released; i++) { + released = /video encoder: released/.test( + adb(["logcat", "-d", "-s", "WebCodecs"]).toString(), + ); + if (!released) { + execFileSync("sleep", ["0.2"]); + } + } + expect(released).toBe(true); + // And encoding goes on with a new encoder. + const after = (await client.eval(({ webcodecs: wc }) => { + const chunks: number[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => chunks.push(chunk.timestamp), + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 1280, height: 720 }); + const pool = wc.createSurfacePool(1280, 720); + for (let i = 0; i < 3; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + } + return encoder.flush().then( + () => { + encoder.close(); + return { chunks, errors }; + }, + (e: any) => { + encoder.close(); + return { chunks, errors: errors.concat([String(e)]) }; + }, + ); + })) as any; + expect(after.errors).toEqual([]); + expect(after.chunks.length).toBe(3); + }, 120000); + + it("closes a VideoEncoder whose codec hangs without failing, in bounded time (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + // Debug builds only: the codec's output is never taken, and the stall + // is not reported for 60 s, so nothing has failed when close() comes, + // with the GL thread blocked drawing. + setFault("venc-stall-output:60"); + adb(["logcat", "-c"]); + let closed: any; + try { + closed = (await client.eval(({ webcodecs: wc }) => { + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: () => {}, + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 1280, height: 720 }); + const pool = wc.createSurfacePool(1280, 720); + for (let i = 0; i < 90; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + } + return new Promise((resolve) => setTimeout(resolve, 1500)).then(() => { + const start = Date.now(); + encoder.close(); + return { ms: Date.now() - start, errors }; + }); + })) as any; + } finally { + setFault(""); + } + // Closed by the user: no error. close() waits for the GL thread, then + // stops the codec itself and the draw returns. + expect(closed.errors).toEqual([]); + expect(closed.ms).toBeLessThan(5000); + expect( + /video encoder: released/.test( + adb(["logcat", "-d", "-s", "WebCodecs"]).toString(), + ), + ).toBe(true); + const after = (await client.eval(({ webcodecs: wc }) => { + const chunks: number[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => chunks.push(chunk.timestamp), + error: (e: any) => errors.push(String(e)), + }); + encoder.configure({ codec: "avc1.42001f", width: 64, height: 64 }); + const pool = wc.createSurfacePool(64, 64); + const frame = new wc.VideoFrame(pool.acquire(), { timestamp: 0 }); + encoder.encode(frame, { keyFrame: true }); + frame.close(); + return encoder.flush().then( + () => { + encoder.close(); + return { chunks, errors }; + }, + (e: any) => { + encoder.close(); + return { chunks, errors: errors.concat([String(e)]) }; + }, + ); + })) as any; + expect(after.errors).toEqual([]); + expect(after.chunks).toEqual([0]); + }, 120000); + + it("does not stop a VideoEncoder codec from the GL thread when a draw fails (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + // Debug builds only: the 10th draw fails on the GL thread while the + // drain thread is taking the codec's output. The GL thread is not + // blocked, so the codec must not be stopped under the drain thread + // (which may be copying from one of its buffers): only the GL thread's + // stop(), at close(), lets it go. + setFault("venc-draw-fail:10"); + adb(["logcat", "-c"]); + let failed: any; + try { + failed = (await client.eval(({ webcodecs: wc }) => { + const errors: string[] = []; + let chunks = 0; + let reported: () => void = () => {}; + const failure = new Promise((resolve) => { + reported = resolve; + }); + const encoder = new wc.VideoEncoder({ + output: () => { + chunks++; + }, + error: (e: any) => { + errors.push(`${e.name}: ${e.message}`); + reported(); + }, + }); + encoder.configure({ codec: "avc1.42001f", width: 640, height: 480 }); + const pool = wc.createSurfacePool(640, 480); + for (let i = 0; i < 30; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + } + return Promise.race([ + failure.then(() => "failed"), + new Promise((resolve) => setTimeout(() => resolve("timeout"), 20000)), + ]).then((outcome: any) => { + const { state } = encoder; + if (state !== "closed") { + encoder.close(); + } + return { outcome, errors, chunks, state }; + }); + })) as any; + } finally { + setFault(""); + } + expect(failed.outcome).toBe("failed"); + expect(failed.errors.length).toBe(1); + expect(failed.errors[0]).toMatch(/^EncodingError: .*the draw failed/); + expect(failed.state).toBe("closed"); + let log = ""; + for (let i = 0; i < 50; i++) { + log = adb(["logcat", "-d", "-s", "WebCodecs"]).toString(); + if (/video encoder: released/.test(log)) { + break; + } + execFileSync("sleep", ["0.2"]); + } + expect(log).toMatch(/video encoder: released/); + expect(log).not.toMatch(/stopping .* from another thread/); + }, 120000); + + it("fails a VideoEncoder whose frame's GPU fence never signals (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + // Debug builds only: every frame's fence is a pipe nothing is written + // to, as a hung GPU's would be. The wait is bounded: the frame fails + // with an EncodingError instead of being drawn unfinished or blocking + // the GL thread for ever. + setFault("venc-fence-hang"); + let run: any; + try { + run = (await client.eval(({ webcodecs: wc }) => { + const errors: string[] = []; + let chunks = 0; + const encoder = new wc.VideoEncoder({ + output: () => { + chunks++; + }, + error: (e: any) => { + errors.push(`${e.name}: ${e.message}`); + }, + }); + encoder.configure({ codec: "avc1.42001f", width: 320, height: 240 }); + const pool = wc.createSurfacePool(320, 240); + for (let i = 0; i < 5; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + } + const started = Date.now(); + return Promise.race([ + encoder.flush().then( + () => "flushed", + () => "failed", + ), + new Promise((resolve) => setTimeout(() => resolve("timeout"), 30000)), + ]).then((outcome: any) => { + const { state } = encoder; + if (state !== "closed") { + encoder.close(); + } + return { outcome, errors, chunks, state, ms: Date.now() - started }; + }); + })) as any; + } finally { + setFault(""); + } + console.log(`fence hang: ${JSON.stringify(run)}`); + expect(run.outcome).toBe("failed"); + expect(run.errors.length).toBe(1); + expect(run.errors[0]).toMatch(/^EncodingError: .*fence did not signal/); + expect(run.chunks).toBe(0); + expect(run.state).toBe("closed"); + }, 120000); + + // A VideoFrame made from a foreign handle (a camera's AHardwareBuffer) + // only references the buffer: its producer may write the next picture + // into it as soon as encode() returns. Each frame must be read as it was + // at encode(), even when the encoder is behind. A surface pool stands in + // for the producer: a released buffer is the next one acquire() hands + // out. Debug builds only: every draw waits 300 ms first, as behind a + // backlog. + it("encodes a wrapped surface as it was at encode(), though its producer reuses the buffer (Android fault)", async () => { + if (client.OS !== "android" || !probes()) { + return; + } + setFault("venc-slow-draw:300"); + let run: any; + try { + run = (await client.eval(({ device, mediabunny: mb, webcodecs: wc }) => { + const fill = (surface: any, rgba: number[]) => { + const buffer = RNWebGPU.createNativeBufferFromPointer( + surface.pixelBuffer, + ); + const memory = device.importSharedTextureMemory({ source: buffer }); + const texture = memory.createTexture(); + memory.beginAccess(texture, false); + const encoder = device.createCommandEncoder(); + const pass = encoder.beginRenderPass({ + colorAttachments: [ + { + view: texture.createView(), + clearValue: rgba, + loadOp: "clear", + storeOp: "store", + }, + ], + }); + pass.end(); + device.queue.submit([encoder.finish()]); + (memory as any).endAccess(texture); + texture.destroy(); + memory.destroy(); + buffer.release(); + return device.queue.onSubmittedWorkDone(); + }; + const target = new mb.BufferTarget(); + const output = new mb.Output({ + format: new mb.Mp4OutputFormat(), + target, + }); + const source = new mb.EncodedVideoPacketSource("avc"); + output.addVideoTrack(source, { frameRate: 10 }); + const errors: string[] = []; + const sameBuffer: boolean[] = []; + let written = Promise.resolve(); + const encoder = new wc.VideoEncoder({ + output: (chunk: any, meta: any) => { + const data = new Uint8Array(chunk.byteLength); + chunk.copyTo(data); + const packet = new mb.EncodedPacket( + data, + chunk.type, + chunk.timestamp / 1e6, + (chunk.duration || 0) / 1e6, + ); + written = written.then(() => source.add(packet, meta)); + }, + error: (e: any) => errors.push(`${e.name}: ${e.message}`), + }); + encoder.configure({ codec: "avc1.42001f", width: 128, height: 128 }); + const pool = wc.createSurfacePool(128, 128); + const frameAt = (i: number): Promise => { + const surface = pool.acquire(); + const { handle } = surface; + return fill(surface, [1, 0, 0, 1]).then(() => { + const frame = new wc.VideoFrame( + { handle }, + { timestamp: i * 100000, duration: 100000 }, + ); + // The producer has the buffer back... + surface.release(); + encoder.encode(frame, { keyFrame: i === 0 }); + frame.close(); + // ...and writes its next picture into it. + const next = pool.acquire(); + sameBuffer.push(next.handle === handle); + return fill(next, [0, 1, 0, 1]).then(() => next.release()); + }); + }; + const frames = (i: number): Promise => + i === 3 ? Promise.resolve() : frameAt(i).then(() => frames(i + 1)); + return output + .start() + .then(() => frames(0)) + .then(() => encoder.flush()) + .then(() => written) + .then(() => output.finalize()) + .then(() => { + encoder.close(); + return { + errors, + sameBuffer, + path: wc.writeFile("e2e-wrapped.mp4", target.buffer), + }; + }) + .catch((e: any) => ({ + errors: errors.concat([`${e && e.name}: ${e && e.message}`]), + sameBuffer, + path: "", + })); + })) as any; + } finally { + setFault(""); + } + console.log(`wrapped: ${JSON.stringify(run)}`); + expect(run.errors).toEqual([]); + // Otherwise the producer did not reuse the buffer, and this shows nothing. + expect(run.sameBuffer).toEqual([true, true, true]); + const local = copyLocal(run.path); + const pixels = [0, 0.1, 0.2].map((t) => pixel(local, t)); + console.log(`wrapped pixels: ${JSON.stringify(pixels)}`); + pixels.forEach((p) => { + expect(p[0]).toBeGreaterThan(240); + expect(p[1]).toBeLessThan(15); + expect(p[2]).toBeLessThan(15); + }); + }, 120000); + + // encode() of a wrapped surface waits until its buffer has been read. A + // frame that is never drawn (the draw fails, or the encoder has already + // failed) is never read either: encode() must return at once then, not + // block the JS thread until the read times out. Debug builds only: the + // second draw fails. + it("does not block encode() of a wrapped surface whose frame is not drawn (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + setFault("venc-draw-fail:2"); + let run: any; + try { + run = (await client.eval(({ webcodecs: wc }) => { + const errors: string[] = []; + const thrown: string[] = []; + const ms: number[] = []; + let reported: () => void = () => {}; + const failure = new Promise((resolve) => { + reported = resolve; + }); + const encoder = new wc.VideoEncoder({ + output: () => {}, + error: (e: any) => { + errors.push(`${e.name}: ${e.message}`); + reported(); + }, + }); + encoder.configure({ codec: "avc1.42001f", width: 128, height: 128 }); + const pool = wc.createSurfacePool(128, 128); + const surfaces: any[] = []; + // Frame 0 is drawn, frame 1's draw fails, frame 2 comes to an + // encoder that has failed. + for (let i = 0; i < 3; i++) { + const surface = pool.acquire(); + surfaces.push(surface); + const frame = new wc.VideoFrame( + { handle: surface.handle }, + { timestamp: i * 100000, duration: 100000 }, + ); + const started = Date.now(); + try { + encoder.encode(frame, { keyFrame: i === 0 }); + } catch (e: any) { + thrown.push(`${e && e.name}: ${e && e.message}`); + } + ms.push(Date.now() - started); + frame.close(); + } + return Promise.race([ + failure.then(() => "failed"), + new Promise((resolve) => setTimeout(() => resolve("timeout"), 20000)), + ]).then((outcome: any) => { + const { state } = encoder; + if (state !== "closed") { + encoder.close(); + } + surfaces.forEach((s) => s.release()); + return { outcome, errors, thrown, ms, state }; + }); + })) as any; + } finally { + setFault(""); + } + console.log(`wrapped, not drawn: ${JSON.stringify(run)}`); + expect(run.thrown).toEqual([]); + expect(Math.max(...run.ms)).toBeLessThan(3000); + expect(run.outcome).toBe("failed"); + expect(run.errors.length).toBe(1); + expect(run.errors[0]).toMatch(/^EncodingError: .*the draw failed/); + expect(run.state).toBe("closed"); + }, 120000); + + it("releases the old VideoEncoder codec before configure() makes a new one (Android fault)", async () => { + if (client.OS !== "android") { + return; + } + // Debug builds only: stopping a codec takes 800 ms longer. Devices + // with few codec instances need the old one gone before the new one. + setFault("venc-slow-stop:800"); + adb(["logcat", "-c"]); + let result: any; + try { + result = (await client.eval(({ webcodecs: wc }) => { + const chunks: number[] = []; + const errors: string[] = []; + const encoder = new wc.VideoEncoder({ + output: (chunk: any) => chunks.push(chunk.timestamp), + error: (e: any) => errors.push(String(e)), + }); + const config = { codec: "avc1.42001f", width: 64, height: 64 }; + const pool = wc.createSurfacePool(64, 64); + const encodeSome = (first: number) => { + for (let i = first; i < first + 3; i++) { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: i * 33333, + }); + encoder.encode(frame, { keyFrame: i === first }); + frame.close(); + } + }; + encoder.configure(config); + encodeSome(0); + // A new config: the native codec is replaced. + encoder.configure(config); + encodeSome(3); + return encoder.flush().then( + () => { + encoder.close(); + return { chunks, errors }; + }, + (e: any) => { + encoder.close(); + return { chunks, errors: errors.concat([String(e)]) }; + }, + ); + })) as any; + } finally { + setFault(""); + } + expect(result.errors).toEqual([]); + expect(result.chunks).toEqual([3, 4, 5].map((i) => i * 33333)); + const log = adb(["logcat", "-d", "-s", "WebCodecs"]) + .toString() + .split("\n") + .filter((line) => /video encoder: (c2\.|OMX\.|released)/.test(line)) + .map((line) => (/released/.test(line) ? "released" : "made")); + // Made, released, made: never two at once. + expect(log.slice(0, 3)).toEqual(["made", "released", "made"]); + }, 120000); + + it("writes into missing directories and reads percent-encoded file:// URLs", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + const written = wc.writeFile( + "e2e dir/nested/data.bin", + new Uint8Array([1, 2, 3, 4, 5]), + ) as string; + const url = `file://${written.split("/").map(encodeURIComponent).join("/")}`; + const source = wc.fileSourceOptions(url); + return Promise.resolve(source.read(0, 5)).then((bytes: Uint8Array) => { + const size = source.getSize(); + source.dispose(); + const writable = wc.createFileWritable("e2e dir/other/stream.bin"); + const writer = writable.writable.getWriter(); + return writer + .write({ type: "write", data: new Uint8Array([9, 9]), position: 0 }) + .then(() => writer.close()) + .then(() => { + wc.removeFile(writable.path); + wc.removeFile(written); + return { size, bytes: Array.from(bytes), url }; + }); + }); + })) as any; + expect(result.size).toBe(5); + expect(result.bytes).toEqual([1, 2, 3, 4, 5]); + }, 60000); + + // x264's High profile reorders frames (B-frames): the decoder must still + // output them in presentation order, as WebCodecs does, whatever order + // the platform's decoder returns them in. + it("decodes a video with B-frames into frames in presentation order", async () => { + if (!supported() || !probes()) { + return; + } + const file = await sourceClip(false); + const out = await runOnDevice<(number | string)[]>( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => { + const times: (number | string)[] = []; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + times.push(frame.timestamp); + frame.close(); + }, + error: (e: any) => times.push(String(e)), + }); + decoder.configure(config); + const packets = new mb.EncodedPacketSink(track).packets(); + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done) { + return undefined; + } + decoder.decode(r.value.toEncodedVideoChunk()); + return step(); + }); + return step() + .then(() => decoder.flush()) + .then(() => { + decoder.close(); + input.dispose(); + return times; + }); + }), + ); + }, + { file }, + 120000, + ); + // The source does reorder: its packets are not stored in time order. + const local = path.join(os.tmpdir(), "rnwc-e2e-clips", "clip.mp4"); + const stored = videoPacketTimes(local); + expect(stored.some((t, i) => i > 0 && t < stored[i - 1])).toBe(true); + expect(out.filter((t) => typeof t === "string")).toEqual([]); + expect(out).toHaveLength(90); + const times = out as number[]; + expect(times.filter((t, i) => i > 0 && t <= times[i - 1])).toEqual([]); + }, 180000); + + // A flush with nothing decoded since configure() or the last flush has + // nothing to wait for: it resolves at once, outputs nothing, and the + // decoder decodes the whole clip after it, on either decoder. + it("flushes a VideoDecoder with nothing queued, then decodes after flushes", async () => { + if (!supported() || !probes()) { + return; + } + const file = await sourceClip(false); + const run = (hardwareAcceleration?: string) => + runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => { + const errors: string[] = []; + let times: number[] = []; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + times.push(frame.timestamp); + frame.close(); + }, + error: (e: any) => errors.push(String(e)), + }); + decoder.configure( + ctx.hardwareAcceleration + ? Object.assign({}, config, { + hardwareAcceleration: ctx.hardwareAcceleration, + }) + : config, + ); + const timedFlush = () => { + const before = times.length; + const t0 = Date.now(); + return decoder.flush().then(() => ({ + ms: Date.now() - t0, + frames: times.length - before, + })); + }; + const pass = () => { + times = []; + const packets = new mb.EncodedPacketSink(track).packets(); + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done) { + return undefined; + } + decoder.decode(r.value.toEncodedVideoChunk()); + return step(); + }); + return step() + .then(() => decoder.flush()) + .then(() => ({ + frames: times.length, + unordered: times.filter( + (t, i) => i > 0 && t <= times[i - 1]!, + ).length, + })); + }; + const out: any = { errors }; + return timedFlush() + .then((r: any) => { + out.first = r; + return timedFlush(); + }) + .then((r: any) => { + out.second = r; + return pass(); + }) + .then((r: any) => { + out.one = r; + return timedFlush(); + }) + .then((r: any) => { + out.again = r; + return pass(); + }) + .then((r: any) => { + out.two = r; + decoder.close(); + input.dispose(); + return out; + }); + }), + ); + }, + { file, hardwareAcceleration }, + 180000, + ); + const plain = await run(); + const software = await run("prefer-software"); + console.log(`empty flush: ${JSON.stringify({ plain, software })}`); + for (const result of [plain, software]) { + const empty = { frames: 0, fast: true }; + const flushed = (r: { ms: number; frames: number }) => ({ + frames: r.frames, + fast: r.ms < 200, + }); + expect({ + errors: result.errors, + first: flushed(result.first), + second: flushed(result.second), + again: flushed(result.again), + one: result.one, + two: result.two, + }).toEqual({ + errors: [], + first: empty, + second: empty, + again: empty, + one: { frames: 90, unordered: 0 }, + two: { frames: 90, unordered: 0 }, + }); + } + }, 400000); + + // JS holds every picture the decoder's ImageReader has (Android: 16) for + // longer than the decoder's 5 s waits for a picture or an input buffer: + // the decoder must wait for JS rather than drop, lose or fail any (our + // drain renders one picture at a time, so the surface has nothing to + // drop). iOS has no such limit and does not wait. + it("loses no frame while JS holds every decoded picture for 12 s", async () => { + if (!supported() || !probes()) { + return; + } + const file = await sourceClip(false); + const android = client.OS === "android"; + if (android) { + logcatClear(); + } + const result = await runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => { + const errors: string[] = []; + const times: number[] = []; + let held: any[] | null = []; + let maxHeld = 0; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + times.push(frame.timestamp); + if (held) { + held.push(frame); + maxHeld = Math.max(maxHeld, held.length); + if (held.length === 1) { + setTimeout(() => { + for (const f of held!) { + f.close(); + } + held = null; + }, ctx.holdMs); + } + } else { + frame.close(); + } + }, + error: (e: any) => errors.push(String(e)), + }); + decoder.configure(config); + const packets = new mb.EncodedPacketSink(track).packets(); + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done || decoder.state === "closed") { + return undefined; + } + decoder.decode(r.value.toEncodedVideoChunk()); + return step(); + }); + const t0 = Date.now(); + return step() + .then(() => + decoder.state === "closed" ? undefined : decoder.flush(), + ) + .catch((e: any) => { + errors.push(`flush: ${e}`); + }) + .then(() => { + if (decoder.state !== "closed") { + decoder.close(); + } + input.dispose(); + return { + errors, + frames: times.length, + unordered: times.filter((t, i) => i > 0 && t <= times[i - 1]!) + .length, + maxHeld, + ms: Date.now() - t0, + }; + }); + }), + ); + }, + { file, holdMs: 12000 }, + 180000, + ); + const lost = android + ? adb(["logcat", "-d"]) + .toString() + .split("\n") + .filter((line) => /did not reach the ImageReader/.test(line)) + : []; + console.log(`held: ${JSON.stringify({ result, lost })}`); + expect({ + errors: result.errors, + frames: result.frames, + unordered: result.unordered, + lost, + waited: android ? result.ms > 12000 : true, + }).toEqual({ + errors: [], + frames: 90, + unordered: 0, + lost: [], + waited: true, + }); + }, 300000); + + // close() while JS holds every picture and the decoder waits for it + // (input and drain both blocked on Android) returns at once. + it("closes a VideoDecoder at once while JS holds every decoded picture", async () => { + if (!supported() || !probes()) { + return; + } + const file = await sourceClip(false); + const result = await runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => { + const errors: string[] = []; + const held: any[] = []; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => held.push(frame), + error: (e: any) => errors.push(String(e)), + }); + decoder.configure(config); + const packets = new mb.EncodedPacketSink(track).packets(); + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done) { + return undefined; + } + decoder.decode(r.value.toEncodedVideoChunk()); + return step(); + }); + return step() + .then( + () => new Promise((resolve) => setTimeout(resolve, ctx.holdMs)), + ) + .then(() => { + const t0 = Date.now(); + decoder.close(); + const ms = Date.now() - t0; + const frames = held.length; + for (const f of held) { + f.close(); + } + input.dispose(); + return { errors, frames, ms, state: decoder.state }; + }); + }), + ); + }, + { file, holdMs: 7000 }, + 120000, + ); + console.log(`close held: ${JSON.stringify(result)}`); + expect(result.errors).toEqual([]); + expect(result.state).toBe("closed"); + expect(result.ms).toBeLessThan(1000); + if (client.OS === "android") { + expect(result.frames).toBe(16); + } + }, 180000); + + // hardwareAcceleration picks the decoder: "prefer-software" a software + // one (on the emulator c2.android.avc.decoder rather than goldfish's), + // "prefer-hardware" none of those. iOS takes the preference as a hint. + it("decodes on a software decoder with hardwareAcceleration: prefer-software", async () => { + if (!supported() || !probes()) { + return; + } + const file = await sourceClip(false); + const android = client.OS === "android"; + const run = async (hardwareAcceleration?: string) => { + if (android) { + logcatClear(); + } + const decoded = await decodeOnDevice( + file, + hardwareAcceleration ? { hardwareAcceleration } : {}, + ); + const codecs = android + ? allocatedCodecs().filter((name) => /decoder/.test(name)) + : []; + return { + frames: decoded.frames, + errors: decoded.errors, + format: decoded.first?.format, + codecs, + }; + }; + const software = await run("prefer-software"); + const hardware = await run("prefer-hardware"); + const plain = await run(); + console.log(`decoders: ${JSON.stringify({ software, hardware, plain })}`); + const isSoftware = (name: string) => + /^(c2\.android\.|OMX\.google\.)/.test(name); + expect({ + software: software.frames, + hardware: hardware.frames, + plain: plain.frames, + errors: [...software.errors, ...hardware.errors, ...plain.errors], + softwareDecoders: software.codecs.every(isSoftware), + hardwareDecoders: hardware.codecs.some(isSoftware), + formats: [software.format, hardware.format, plain.format], + }).toEqual({ + software: 90, + hardware: 90, + plain: 90, + errors: [], + softwareDecoders: true, + hardwareDecoders: false, + // The decoder's own picture on Android, whatever its layout. + formats: Array(3).fill(ios() ? "BGRA" : "NV12"), + }); + if (android) { + expect(software.codecs.length).toBeGreaterThan(0); + } + }, 300000); + + // A width that is not a multiple of 128 (360): Android's software decoder + // pads its pictures to 384, and only the crop says where the picture is. + // The frames must have the visible size, and an encoder given them must + // take that region only: the red stripe on the right edge stays there, + // and no padding comes in. + it("decodes a 360x640 video to frames without the decoder's padding", async () => { + if (!supported() || !probes()) { + return; + } + const clip = path.join(clipDirectory, "clip-360x640.mp4"); + fs.mkdirSync(clipDirectory, { recursive: true }); + if (!fs.existsSync(clip)) { + execFileSync("ffmpeg", [ + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + "color=c=blue:s=360x640:r=30:d=1", + "-vf", + "drawbox=x=344:y=0:w=16:h=640:color=red:t=fill,drawbox=x=0:y=624:w=360:h=16:color=yellow:t=fill", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-profile:v", + "high", + clip, + ]); + } + const file = await pushFile(clip); + const decoded = await runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + const target = new mb.BufferTarget(); + const output = new mb.Output({ + format: new mb.Mp4OutputFormat(), + target, + }); + const source = new mb.EncodedVideoPacketSource("avc"); + output.addVideoTrack(source, { frameRate: 30 }); + const result: any = { frames: 0, errors: [], first: null, path: "" }; + let written = Promise.resolve(); + const encoder = new wc.VideoEncoder({ + output: (chunk: any, meta: any) => { + const data = new Uint8Array(chunk.byteLength); + chunk.copyTo(data); + const packet = new mb.EncodedPacket( + data, + chunk.type, + chunk.timestamp / 1e6, + (chunk.duration || 0) / 1e6, + ); + written = written.then(() => source.add(packet, meta)); + }, + error: (e: any) => result.errors.push(`encoder: ${e}`), + }); + encoder.configure({ + codec: "avc1.42001f", + width: 360, + height: 640, + framerate: 30, + }); + return output.start().then(() => + input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((trackConfig: any) => { + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + if (!result.first) { + const r = frame.visibleRect; + result.first = { + codedWidth: frame.codedWidth, + codedHeight: frame.codedHeight, + visibleRect: { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + }, + displayWidth: frame.displayWidth, + displayHeight: frame.displayHeight, + format: frame.format, + }; + } + encoder.encode(frame, { keyFrame: result.frames === 0 }); + result.frames++; + frame.close(); + }, + error: (e: any) => result.errors.push(`decoder: ${e}`), + }); + decoder.configure( + Object.assign({}, trackConfig, { + hardwareAcceleration: "prefer-software", + }), + ); + const packets = new mb.EncodedPacketSink(track).packets(); + const step = (): Promise => + packets.next().then((r: any) => { + if (r.done) { + return undefined; + } + decoder.decode(r.value.toEncodedVideoChunk()); + return step(); + }); + return step() + .then(() => decoder.flush()) + .then(() => encoder.flush()) + .then(() => written) + .then(() => output.finalize()) + .then(() => { + decoder.close(); + encoder.close(); + input.dispose(); + result.path = wc.writeFile("e2e-crop-out.mp4", target.buffer); + return result; + }); + }), + ), + ); + }, + { file }, + 120000, + ); + const local = copyLocal(decoded.path); + const px = { + redEdge: pixel(local, 0, 355, 320), + blue: pixel(local, 0, 300, 320), + yellowBottom: pixel(local, 0, 180, 633), + }; + console.log(`crop: ${JSON.stringify({ ...decoded, px })}`); + const is = (p: number[], rgb: boolean[]) => + p.every((v, i) => (rgb[i] ? v > 170 : v < 90)); + expect({ + frames: decoded.frames, + errors: decoded.errors, + visibleRect: decoded.first?.visibleRect, + codedWidth: decoded.first?.codedWidth, + codedHeight: decoded.first?.codedHeight, + displayWidth: decoded.first?.displayWidth, + displayHeight: decoded.first?.displayHeight, + format: decoded.first?.format, + redEdge: is(px.redEdge, [true, false, false]), + blue: is(px.blue, [false, false, true]), + yellowBottom: is(px.yellowBottom, [true, true, false]), + }).toEqual({ + frames: 30, + errors: [], + visibleRect: { x: 0, y: 0, width: 360, height: 640 }, + codedWidth: 360, + codedHeight: 640, + displayWidth: 360, + displayHeight: 640, + format: ios() ? "BGRA" : "NV12", + redEdge: true, + blue: true, + yellowBottom: true, + }); + }, 300000); + + // A config without codedWidth/codedHeight (allowed: the avcC has the + // size): the decoder must still take a 4K key frame. Sized for 1920x1080, + // Android's software decoder has 2 MiB input buffers, and this key frame + // is about 3.4 MB. + it("decodes 4K key frames from a config without a coded size", async () => { + if (!supported() || !probes()) { + return; + } + const clip = path.join(clipDirectory, "clip-4k-noise.mp4"); + fs.mkdirSync(clipDirectory, { recursive: true }); + if (!fs.existsSync(clip)) { + execFileSync("ffmpeg", [ + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + "nullsrc=s=3840x2160:r=30:d=0.2,geq=lum='random(1)*255':cb=128:cr=128", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-qp", + "38", + "-g", + "1", + clip, + ]); + } + const sizes = execFileSync( + "ffprobe", + [ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "packet=size", + "-of", + "csv=p=0", + clip, + ], + { encoding: "utf8" }, + ) + .trim() + .split("\n") + .map(Number); + // Larger than 2 MiB, smaller than 4K's own 0.75 byte per pixel. + expect(sizes[0]).toBeGreaterThan(2.2e6); + expect(sizes[0]).toBeLessThan(5.5e6); + const file = await pushFile(clip); + const android = client.OS === "android"; + const run = async (config: object) => { + if (android) { + logcatClear(); + } + const decoded = await decodeOnDevice(file, config, [ + "codedWidth", + "codedHeight", + "displayAspectWidth", + "displayAspectHeight", + ]); + const codecs = android + ? allocatedCodecs().filter((name) => /decoder/.test(name)) + : []; + return { + frames: decoded.frames, + errors: decoded.errors, + width: decoded.first?.visibleRect.width, + height: decoded.first?.visibleRect.height, + codecs, + }; + }; + const software = await run({ hardwareAcceleration: "prefer-software" }); + const plain = await run({}); + console.log(`4k: ${JSON.stringify({ sizes, software, plain })}`); + const frames = { + frames: sizes.length, + errors: [], + width: 3840, + height: 2160, + }; + expect({ + software: { ...software, codecs: undefined }, + plain: { ...plain, codecs: undefined }, + }).toEqual({ + software: { ...frames, codecs: undefined }, + plain: { ...frames, codecs: undefined }, + }); + if (android) { + expect(software.codecs.length).toBeGreaterThan(0); + expect( + software.codecs.every((name) => + /^(c2\.android\.|OMX\.google\.)/.test(name), + ), + ).toBe(true); + } + }, 300000); + + // The example app's screens, through its own code (example/src/Tests.tsx + // hands it over): the Lottie share card exported as the Video Export + // screens do, and videos compressed as the Compress screen does. + describe("the example app", () => { + // The card: 7 s at 30 fps, 1080x1920. + const CARD_FRAMES = 210; + const CARD_SECONDS = 7; + + it("exports the Lottie card to H.264, silent", async () => { + if (!supported()) { + return; + } + const result = await exportCard({ hdr: false, sound: false }); + const local = copyLocal(result.path); + if (!probes()) { + return; + } + const { streams } = probe(local); + expectCardVideo(streams, "h264"); + expect(streams.some((s) => s.codec_type === "audio")).toBe(false); + }, 600000); + + it("exports the Lottie card to H.264 with its sound", async () => { + if (!supported()) { + return; + } + const result = await exportCard({ hdr: false, sound: true }); + if (!probes()) { + return; + } + const { streams } = probe(copyLocal(result.path)); + const video = expectCardVideo(streams, "h264"); + const audio = streams.find((s) => s.codec_type === "audio")!; + expect(audio.codec_name).toBe("aac"); + // Cut where the video ends: the last AAC frame (21 ms at 48 kHz) + // starts before it. + expect( + Math.abs(Number(audio.duration) - Number(video.duration)), + ).toBeLessThan(0.05); + }, 600000); + + // HEVC Main 10 on iOS, AV1 Main 10 on Android, where a device without + // a 10-bit AV1 encoder (the emulator) skips it. + it("exports the Lottie card to 10-bit HLG", async () => { + if (!supported()) { + return; + } + let result: CardExport; + try { + result = await exportCard({ hdr: true, sound: false }); + } catch (e) { + // The app's own check (isConfigSupported): the Android emulator's + // software AV1 encoder has no 10-bit profile. + if (/has no .* Main 10 encoder/.test(String(e))) { + console.log(`HDR skipped: ${String(e)}`); + return; + } + throw e; + } + if (!probes()) { + return; + } + const { streams } = probe(copyLocal(result.path)); + const video = expectCardVideo(streams, ios() ? "hevc" : "av1"); + expect(video.profile).toBe(ios() ? "Main 10" : "Main"); + expect(video.pix_fmt).toBe("yuv420p10le"); + expect(video.color_transfer).toBe("arib-std-b67"); + expect(video.color_primaries).toBe("bt2020"); + expect(video.color_space).toBe("bt2020nc"); + }, 1500000); + + // 3 s of 1280x720 H.264 at 30 fps with an AAC sine, made here with + // ffmpeg (no video files in the repository); the second is tagged to + // play turned 90° clockwise, as a phone's portrait recording is. + const SOURCE_SECONDS = 3; + + it.each(["avc", "hevc", "av1"])( + "compresses a video to %s, if the device encodes it", + async (codec) => { + if (!supported() || !probes()) { + return; + } + const run = await compressOnDevice(await sourceClip(false), { + codec, + }); + if (run.skipped) { + console.log(`${codec}: not in supportedCodecs (${run.supported})`); + return; + } + expectCompressed(run, { + codec: { avc: "h264", hevc: "hevc", av1: "av1" }[codec]!, + width: 854, + height: 480, + frameRate: 30, + audio: true, + }); + }, + 600000, + ); + + it("compresses a video without its sound", async () => { + if (!supported() || !probes()) { + return; + } + const run = await compressOnDevice(await sourceClip(false), { + audio: false, + }); + expectCompressed(run, { + codec: "h264", + width: 854, + height: 480, + frameRate: 30, + audio: false, + }); + }, 600000); + + it("compresses a video to another frame rate", async () => { + if (!supported() || !probes()) { + return; + } + const run = await compressOnDevice(await sourceClip(false), { + frameRate: 15, + }); + expectCompressed(run, { + codec: "h264", + width: 854, + height: 480, + frameRate: 15, + audio: true, + }); + }, 600000); + + it("compresses a phone's portrait video upright", async () => { + if (!supported() || !probes()) { + return; + } + const run = await compressOnDevice(await sourceClip(true), {}); + expect(run.source.rotation).toBe(90); + expect([run.source.width, run.source.height]).toEqual([720, 1280]); + expectCompressed(run, { + codec: "h264", + width: 480, + height: 854, + frameRate: 30, + audio: true, + }); + }, 600000); + + const expectCardVideo = (streams: Probed[], codec: string) => { + const video = streams.find((s) => s.codec_type === "video")!; + expect(video.codec_name).toBe(codec); + expect(video.width).toBe(1080); + expect(video.height).toBe(1920); + expect(Number(video.nb_read_packets)).toBe(CARD_FRAMES); + expect(Number(video.duration)).toBeCloseTo(CARD_SECONDS, 2); + return video; + }; + + const expectCompressed = ( + run: Compressed, + want: { + codec: string; + width: number; + height: number; + frameRate: number; + audio: boolean; + }, + ) => { + expect([run.result.width, run.result.height]).toEqual([ + want.width, + want.height, + ]); + expect([run.target.width, run.target.height]).toEqual([ + want.width, + want.height, + ]); + const local = copyLocal(run.result.path); + const { streams } = probe(local); + const video = streams.find((s) => s.codec_type === "video")!; + expect(video.codec_name).toBe(want.codec); + expect([video.width, video.height]).toEqual([want.width, want.height]); + // No rotation tag left: the frames are upright. + expect(rotationOf(video)).toBe(0); + expect( + Math.abs(Number(video.duration) - SOURCE_SECONDS), + ).toBeLessThanOrEqual(1 / want.frameRate + 1e-3); + expect(Number(video.nb_read_packets)).toBe( + SOURCE_SECONDS * want.frameRate, + ); + expect(streams.some((s) => s.codec_type === "audio")).toBe(want.audio); + // In order: the encoders make no B-frames, so each frame is later than + // the one before it (frames decoded out of order would not be). + const times = videoPacketTimes(local); + expect(times.filter((t, i) => i > 0 && t <= times[i - 1]).length).toBe(0); + // Fast start: the index ahead of the media. + const boxes = topLevelBoxes(local); + expect(boxes.indexOf("moov")).toBeGreaterThanOrEqual(0); + expect(boxes.indexOf("moov")).toBeLessThan(boxes.indexOf("mdat")); + console.log( + `compressed to ${want.codec} ${want.width}x${want.height}@${want.frameRate}${want.audio ? " + AAC" : ""}: ${run.result.size} bytes in ${Math.round(run.result.ms)} ms`, + ); + }; + }); + // iOS takes the hardware codecs away from a backgrounded app. Two exports, // one after the other, each sent to the background by opening Settings on // the Simulator and then brought back: diff --git a/src/__tests__/setup.ts b/src/__tests__/setup.ts index 3cfb52d..897992a 100644 --- a/src/__tests__/setup.ts +++ b/src/__tests__/setup.ts @@ -30,6 +30,8 @@ interface TestingContext { mediabunny: any; webcodecs: any; AppState: any; + // The example app's own export and compression code (Tests.tsx). + example: any; } type Ctx = Record; diff --git a/src/__tests__/unit/avc.test.ts b/src/__tests__/unit/avc.test.ts new file mode 100644 index 0000000..a776e7e --- /dev/null +++ b/src/__tests__/unit/avc.test.ts @@ -0,0 +1,111 @@ +import { avcCodedSize } from "../../lib/avc"; + +const hex = (s: string) => Uint8Array.from(Buffer.from(s, "hex")); + +// avcC records from libx264 (ffmpeg 8.1, testsrc2), with the size ffprobe +// reports for each file. +const X264: [string, string, number, number][] = [ + [ + "High 1920x1080 (cropped from 1088)", + "01640028ffe1001b67640028acd940780227e5c044000003000400000300f03c60c65801000668ebe3cb22c0fdf8f800", + 1920, + 1080, + ], + [ + "High 360x640 (cropped from 368)", + "0164001effe1001a6764001eacd9417051e5f0110000030001000003003c0f162d9601000668ebe3cb22c0fdf8f800", + 360, + 640, + ], + [ + "High 3840x2160", + "01640033ffe1001a67640033acd9403c0043ec0440000003004000000f03c60c658001000668ebe3cb22c0fdf8f800", + 3840, + 2160, + ], + [ + "Constrained Baseline 1278x718", + "0142c01fffe1001a6742c01fd9005005beab0110000003001000000303c0f183248001000568cb83cb20", + 1278, + 718, + ], + [ + "High 4:4:4 642x358", + "01f4001effe1001b67f4001e919b281485fc7c5e0220000003002000000781e2c5b2c001000668ebe3c44844fff8f800", + 642, + 358, + ], + [ + "High 4:2:2 642x358", + "017a001effe1001b677a001ebcd940a42fe222f0110000030001000003003c0f162d9601000668ebe3cb22c0fef8f800", + 642, + 358, + ], + [ + "High interlaced 720x576", + "0164001fffe100186764001facd940b424d80880000003008000001e0f8b16cb01000668fba3cb22c0fdf8f800", + 720, + 576, + ], + [ + "High monochrome 322x240", + "0164000dffe100196764000df3650547f8ff016c80000003008000001e078a14cb01000668ebe3cb22c0fcf8f800", + 322, + 240, + ], +]; + +describe("avcCodedSize", () => { + it.each(X264)("reads %s", (_, record, width, height) => { + expect(avcCodedSize(hex(record))).toEqual({ width, height }); + }); + + // Written by hand (fields checked with ffmpeg's trace_headers): scaling + // lists (one ending early, one default, one full 8x8), pic_order_cnt_type + // 1 with a cycle, fields (frame_mbs_only_flag 0), crop on every side but + // the top, and emulation prevention bytes. 1440x1088 coded, crop 4+12 + // horizontally, 8 at the bottom (2 units of 2 rows, twice for fields). + it("reads scaling lists, POC type 1, fields and emulation prevention", () => { + const record = + "01640028ffe1003767640028ad88c32422534d34d34d34d34d34d34d34d34d34d34d34d34d34d34d34d4000003010000030072118000080000280b4089d9ed01000468ee3c80"; + expect(avcCodedSize(hex(record))).toEqual({ width: 1424, height: 1080 }); + }); + + it("takes an ArrayBuffer or a view into a larger buffer", () => { + const record = hex(X264[0]![1]); + const padded = new Uint8Array(record.length + 4); + padded.set(record, 4); + expect(avcCodedSize(record.slice().buffer)).toEqual({ + width: 1920, + height: 1080, + }); + expect(avcCodedSize(padded.subarray(4))).toEqual({ + width: 1920, + height: 1080, + }); + }); + + it("returns undefined, never throws, for what it cannot read", () => { + const full = hex(X264[0]![1]); + expect(avcCodedSize(undefined)).toBeUndefined(); + expect(avcCodedSize(new Uint8Array(0))).toBeUndefined(); + // The records other tests use: a header without parameter sets. + expect( + avcCodedSize(new Uint8Array([1, 0x64, 0, 0x28, 0xff, 0xe1])), + ).toBeUndefined(); + // Not version 1. + expect(avcCodedSize(Uint8Array.from([2, ...full.subarray(1)]))).toBe( + undefined, + ); + // Truncated at every length. + for (let n = 0; n < full.length - 10; n++) { + expect(() => avcCodedSize(full.subarray(0, n))).not.toThrow(); + } + // The SPS cut short inside the record: a length past its end. + const cut = full.slice(0, 14); + expect(avcCodedSize(cut)).toBeUndefined(); + // A PPS where the SPS should be. + const pps = hex("01640028ffe100046868ebe3cb"); + expect(avcCodedSize(pps)).toBeUndefined(); + }); +}); diff --git a/src/__tests__/unit/codecs.test.ts b/src/__tests__/unit/codecs.test.ts new file mode 100644 index 0000000..c6083da --- /dev/null +++ b/src/__tests__/unit/codecs.test.ts @@ -0,0 +1,467 @@ +// The WebCodecs state machine of the TypeScript classes, against a fake +// native module: what happens on reconfigure, reset, close, native errors +// and frames the codec never returns. +import { AudioData, AudioDecoder, AudioEncoder } from "../../lib/audio"; +import { + EncodedVideoChunk, + VideoDecoder, + VideoEncoder, + VideoFrame, +} from "../../lib/video"; +import type { NativeEncodedChunk } from "../../specs/WebCodecs.nitro"; + +type Output = (value: T) => void; + +interface FakeCodec { + output: Output; + error: (message: string) => void; + close: jest.Mock; + flush: jest.Mock; + encode: jest.Mock; + decode: jest.Mock; + setColorSpace: jest.Mock; + maxFrameDelay: number; + hardwareAccelerated: boolean; + // The native config it was created with. + config: unknown; +} + +const made: FakeCodec[] = []; +let createError: Error | null = null; + +const fakeCodec = ( + output: Output, + error: (m: string) => void, + config?: unknown, +) => { + if (createError) { + throw createError; + } + const codec: FakeCodec = { + output, + error, + close: jest.fn(), + flush: jest.fn(() => Promise.resolve()), + encode: jest.fn(), + decode: jest.fn(), + setColorSpace: jest.fn(), + maxFrameDelay: 3, + hardwareAccelerated: false, + config, + }; + made.push(codec as FakeCodec); + return codec; +}; + +// Read lazily, when the classes first create a native object. +const mockNative = { + createVideoEncoder: ( + c: unknown, + o: Output, + e: (m: string) => void, + ) => fakeCodec(o, e, c), + createVideoDecoder: ( + c: unknown, + o: Output, + e: (m: string) => void, + ) => fakeCodec(o, e, c), + createAudioEncoder: ( + _c: unknown, + o: Output, + e: (m: string) => void, + ) => fakeCodec(o, e), + createAudioDecoder: ( + _c: unknown, + o: Output, + e: (m: string) => void, + ) => fakeCodec(o, e), +}; + +jest.mock("react-native-nitro-modules", () => ({ + NitroModules: { createHybridObject: () => mockNative }, +})); + +const last = () => made[made.length - 1]; + +interface FakeSurface { + handle: bigint; + pixelBuffer: bigint; + width: number; + height: number; + format: string; + setFence: jest.Mock; + clone: jest.Mock; + release: jest.Mock; +} + +const fakeSurface = (): FakeSurface => { + const surface: FakeSurface = { + handle: 1n, + pixelBuffer: 1n, + width: 16, + height: 16, + format: "BGRA", + setFence: jest.fn(), + clone: jest.fn(() => fakeSurface()), + release: jest.fn(), + }; + return surface; +}; + +const frame = (timestamp: number) => + // eslint-disable-next-line @typescript-eslint/no-explicit-any + new VideoFrame(fakeSurface() as any, { timestamp, duration: 33_333 }); + +const chunk = (timestamp: number): NativeEncodedChunk => ({ + data: new Uint8Array([1, 2, 3]).buffer, + timestamp, + duration: 33_333, + key: true, +}); + +const CONFIG = { codec: "avc1.640028", width: 16, height: 16 }; + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +/** Resolves to "timeout" when `promise` has not settled after `ms`. */ +const settles = (promise: Promise, ms = 200) => + Promise.race([ + promise.then( + () => "resolved", + (e: Error) => e.name, + ), + new Promise((resolve) => setTimeout(() => resolve("timeout"), ms)), + ]); + +beforeEach(() => { + made.length = 0; + createError = null; +}); + +const newEncoder = () => { + const output = jest.fn(); + const error = jest.fn(); + const encoder = new VideoEncoder({ output, error }); + return { encoder, output, error }; +}; + +describe("VideoEncoder", () => { + it("flushes after a reconfigure with frames still in the old encoder", async () => { + const { encoder } = newEncoder(); + encoder.configure(CONFIG); + encoder.encode(frame(0)); + encoder.encode(frame(33_333)); + encoder.configure({ ...CONFIG, bitrate: 1_000_000 }); + encoder.encode(frame(66_666)); + last().output(chunk(66_666)); + expect(await settles(encoder.flush())).toBe("resolved"); + }); + + it("flushes when the codec returned fewer frames than it took", async () => { + const { encoder, output } = newEncoder(); + encoder.configure(CONFIG); + encoder.encode(frame(0)); + encoder.encode(frame(0)); // dropped by the codec: no output for it + last().output(chunk(0)); + expect(await settles(encoder.flush())).toBe("resolved"); + expect(output).toHaveBeenCalledTimes(1); + // And the queue is open again. + encoder.encode(frame(33_333)); + await tick(); + expect(encoder.encodeQueueSize).toBe(0); + }); + + it("drops outputs of the native encoder a reset replaced", () => { + const { encoder, output } = newEncoder(); + encoder.configure(CONFIG); + encoder.encode(frame(0)); + const old = last(); + encoder.reset(); + encoder.configure(CONFIG); + old.output(chunk(0)); + expect(output).not.toHaveBeenCalled(); + last().output(chunk(0)); + expect(output).toHaveBeenCalledTimes(1); + }); + + it("reports a native NotSupportedError thrown by configure() as such", () => { + const { encoder, error } = newEncoder(); + createError = new Error( + "WebCodecs.createVideoEncoder(...): NotSupportedError: 8192x8192 is above the codec's highest level", + ); + encoder.configure(CONFIG); + expect(error).toHaveBeenCalledTimes(1); + expect(error.mock.calls[0][0].name).toBe("NotSupportedError"); + expect(error.mock.calls[0][0].message).toBe( + "8192x8192 is above the codec's highest level", + ); + expect(encoder.state).toBe("closed"); + }); + + it("keeps the code of a native error", () => { + const { encoder, error } = newEncoder(); + encoder.configure(CONFIG); + last().error("EncodingError: interrupted: the app went to the background"); + expect(error.mock.calls[0][0].name).toBe("EncodingError"); + expect(error.mock.calls[0][0].code).toBe("interrupted"); + }); + + it("closes the native encoder on a native error", () => { + const { encoder } = newEncoder(); + encoder.configure(CONFIG); + const codec = last(); + codec.error("EncodingError: encoder-failed: VideoToolbox failed (-12902)"); + expect(encoder.state).toBe("closed"); + expect(codec.close).toHaveBeenCalled(); + }); + + it("closes the native encoder when the output callback throws", () => { + const encoder = new VideoEncoder({ + output: () => { + throw new Error("app bug"); + }, + error: jest.fn(), + }); + encoder.configure(CONFIG); + encoder.encode(frame(0)); + const codec = last(); + codec.output(chunk(0)); + expect(encoder.state).toBe("closed"); + expect(codec.close).toHaveBeenCalled(); + }); + + it("closes the configured native encoder when a new config is unsupported", () => { + const { encoder } = newEncoder(); + encoder.configure(CONFIG); + const codec = last(); + encoder.configure({ ...CONFIG, codec: "vp8" }); + expect(encoder.state).toBe("closed"); + expect(codec.close).toHaveBeenCalled(); + }); + + it("rejects a flush with AbortError when reset() and configure() follow at once", async () => { + const { encoder } = newEncoder(); + encoder.configure(CONFIG); + encoder.encode(frame(0)); + const flushed = encoder.flush(); + encoder.reset(); + encoder.configure(CONFIG); + expect(await settles(flushed)).toBe("AbortError"); + }); + + it("throws InvalidStateError on reset() once closed", () => { + const { encoder } = newEncoder(); + encoder.close(); + expect(() => encoder.reset()).toThrow( + expect.objectContaining({ name: "InvalidStateError" }), + ); + expect(encoder.state).toBe("closed"); + }); + + it("passes the H.264 level of the codec string to the native encoder", () => { + const { encoder } = newEncoder(); + const passed = ["avc1.640028", "avc1.42001f", "avc1.4d0033"].map( + (codec) => { + encoder.configure({ ...CONFIG, codec }); + const config = last().config as { profile?: string; level?: number }; + return [config.profile, config.level]; + }, + ); + encoder.configure({ ...CONFIG, codec: "av01.0.04M.08" }); + const av1 = (last().config as { level?: number }).level; + encoder.close(); + expect(passed).toEqual([ + ["high", 40], + ["baseline", 31], + ["main", 51], + ]); + expect(av1).toBeUndefined(); + }); + + it("throws TypeError when encoding a closed frame", () => { + const { encoder } = newEncoder(); + encoder.configure(CONFIG); + const f = frame(0); + f.close(); + expect(() => encoder.encode(f)).toThrow(TypeError); + }); +}); + +describe("VideoDecoder", () => { + const DECODER_CONFIG = { + codec: "avc1.640028", + description: new Uint8Array([1, 0x64, 0, 0x28, 0xff, 0xe1]), + }; + const key = () => + new EncodedVideoChunk({ + type: "key", + timestamp: 0, + data: new Uint8Array([0, 0, 0, 1, 0x65]), + }); + + it("releases frames from a decoder a reset replaced, without outputting them", () => { + const output = jest.fn(); + const decoder = new VideoDecoder({ output, error: jest.fn() }); + decoder.configure(DECODER_CONFIG); + decoder.decode(key()); + const old = last(); + decoder.reset(); + decoder.configure(DECODER_CONFIG); + const surface = fakeSurface(); + old.output({ surface, timestamp: 0, duration: 0 }); + expect(output).not.toHaveBeenCalled(); + expect(surface.release).toHaveBeenCalled(); + }); + + it("rejects a pending flush with AbortError on reset()", async () => { + const decoder = new VideoDecoder({ output: jest.fn(), error: jest.fn() }); + decoder.configure(DECODER_CONFIG); + decoder.decode(key()); + last().flush.mockReturnValue(new Promise(() => undefined)); + const flushed = decoder.flush(); + decoder.reset(); + expect(await settles(flushed)).toBe("AbortError"); + }); + + it("rejects a pending flush with AbortError on close()", async () => { + const decoder = new VideoDecoder({ output: jest.fn(), error: jest.fn() }); + decoder.configure(DECODER_CONFIG); + decoder.decode(key()); + last().flush.mockReturnValue(new Promise(() => undefined)); + const flushed = decoder.flush(); + decoder.close(); + expect(await settles(flushed)).toBe("AbortError"); + }); + + it("passes hardwareAcceleration's preference to the native decoder", () => { + const decoder = new VideoDecoder({ output: jest.fn(), error: jest.fn() }); + const preferences = [ + "prefer-software", + "prefer-hardware", + "no-preference", + ] as const; + const passed = preferences.map((hardwareAcceleration) => { + decoder.configure({ ...DECODER_CONFIG, hardwareAcceleration }); + return (last().config as { hardwareAcceleration?: string }) + .hardwareAcceleration; + }); + decoder.close(); + expect(passed).toEqual(["prefer-software", "prefer-hardware", undefined]); + }); + + it("passes the SPS's size to the native decoder when the config has none", () => { + // libx264, 3840x2160. + const description = Uint8Array.from( + Buffer.from( + "01640033ffe1001a67640033acd9403c0043ec0440000003004000000f03c60c658001000668ebe3cb22c0fdf8f800", + "hex", + ), + ); + const decoder = new VideoDecoder({ output: jest.fn(), error: jest.fn() }); + const sizes = [ + { codec: "avc1.640033", description }, + { codec: "avc1.640033", description, codedWidth: 64, codedHeight: 48 }, + DECODER_CONFIG, + ].map((config) => { + decoder.configure(config); + const { codedWidth, codedHeight } = last().config as { + codedWidth?: number; + codedHeight?: number; + }; + return [codedWidth, codedHeight]; + }); + decoder.close(); + expect(sizes).toEqual([ + [3840, 2160], + [64, 48], + // Unreadable: native picks one. + [undefined, undefined], + ]); + }); + + it("closes the native decoder on a native error", () => { + const decoder = new VideoDecoder({ output: jest.fn(), error: jest.fn() }); + decoder.configure(DECODER_CONFIG); + const codec = last(); + codec.error("EncodingError: decoder-failed: boom"); + expect(codec.close).toHaveBeenCalled(); + }); +}); + +describe("AudioEncoder", () => { + const AUDIO = { codec: "mp4a.40.2", sampleRate: 48_000, numberOfChannels: 1 }; + const audio = () => + new AudioData({ + format: "f32", + sampleRate: 48_000, + numberOfFrames: 1024, + numberOfChannels: 1, + timestamp: 0, + data: new Float32Array(1024), + }); + + it("drops outputs of the native encoder a reset replaced", () => { + const output = jest.fn(); + const encoder = new AudioEncoder({ output, error: jest.fn() }); + encoder.configure(AUDIO); + const old = last(); + encoder.reset(); + encoder.configure(AUDIO); + old.output(chunk(0)); + expect(output).not.toHaveBeenCalled(); + }); + + it("rejects a pending flush with AbortError on reset()", async () => { + const encoder = new AudioEncoder({ output: jest.fn(), error: jest.fn() }); + encoder.configure(AUDIO); + encoder.encode(audio()); + last().flush.mockReturnValue(new Promise(() => undefined)); + const flushed = encoder.flush(); + encoder.reset(); + expect(await settles(flushed)).toBe("AbortError"); + }); + + it("throws TypeError when encoding a closed AudioData", () => { + const encoder = new AudioEncoder({ output: jest.fn(), error: jest.fn() }); + encoder.configure(AUDIO); + const data = audio(); + data.close(); + expect(() => encoder.encode(data)).toThrow(TypeError); + }); + + it("closes the native encoder on a native error", () => { + const encoder = new AudioEncoder({ output: jest.fn(), error: jest.fn() }); + encoder.configure(AUDIO); + const codec = last(); + codec.error("EncodingError: audio-failed: boom"); + expect(codec.close).toHaveBeenCalled(); + }); + + it("throws InvalidStateError on reset() once closed", () => { + const encoder = new AudioEncoder({ output: jest.fn(), error: jest.fn() }); + encoder.close(); + expect(() => encoder.reset()).toThrow( + expect.objectContaining({ name: "InvalidStateError" }), + ); + }); +}); + +describe("AudioDecoder", () => { + it("drops data of the native decoder a reset replaced", () => { + const output = jest.fn(); + const decoder = new AudioDecoder({ output, error: jest.fn() }); + const config = { codec: "mp3", sampleRate: 44_100, numberOfChannels: 2 }; + decoder.configure(config); + const old = last(); + decoder.reset(); + decoder.configure(config); + old.output({ + data: new Float32Array(2).buffer, + frames: 1, + sampleRate: 44_100, + numberOfChannels: 2, + timestamp: 0, + }); + expect(output).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/audio.ts b/src/lib/audio.ts index b721647..3ca6bbe 100644 --- a/src/lib/audio.ts +++ b/src/lib/audio.ts @@ -13,6 +13,7 @@ import { domError, native, nativeError, + nextMacrotask, rethrow, toArrayBuffer, toBytes, @@ -267,7 +268,7 @@ export class AudioEncoder extends CodecBase { ); return; } - this._encoder?.close(); + this._replaceNative(); this._config = config; try { this._encoder = native().createAudioEncoder( @@ -277,8 +278,8 @@ export class AudioEncoder extends CodecBase { numberOfChannels: config.numberOfChannels, bitrate: config.bitrate, }, - (chunk) => this._onChunk(chunk), - (message) => this._fail(nativeError(message)), + this._bind((chunk: NativeEncodedChunk) => this._onChunk(chunk)), + this._bind((message: string) => this._fail(nativeError(message))), ); } catch (e) { this._fail(nativeError((e as Error).message)); @@ -292,6 +293,9 @@ export class AudioEncoder extends CodecBase { if (!(data instanceof AudioData)) { throw new TypeError("data must be an AudioData"); } + if (!data._data) { + throw new TypeError("the AudioData is closed"); + } if ( data.sampleRate !== this._config!.sampleRate || data.numberOfChannels !== this._config!.numberOfChannels @@ -314,29 +318,31 @@ export class AudioEncoder extends CodecBase { setTimeout(() => this._drain(), 0); } - async flush() { - this._assertConfigured(); - try { + flush() { + return this._flush(async () => { await this._encoder!.flush(); - } catch (e) { - rethrow(e); - } - await new Promise((resolve) => setTimeout(() => resolve(), 0)); + await nextMacrotask(); + }); } reset() { - this._encoder?.close(); - this._encoder = null; - this._state = "unconfigured"; - this._reset(); + this._resetCodec(); } close() { - this._encoder?.close(); - this._encoder = null; this._close(); } + _releaseNative() { + const encoder = this._encoder; + this._encoder = null; + try { + encoder?.close(); + } catch { + // Already closed natively. + } + } + _onChunk(chunk: NativeEncodedChunk) { if (this._state !== "configured") { return; @@ -420,7 +426,7 @@ export class AudioDecoder extends CodecBase { ); return; } - this._decoder?.close(); + this._replaceNative(); try { this._decoder = native().createAudioDecoder( { @@ -431,8 +437,8 @@ export class AudioDecoder extends CodecBase { ? toArrayBuffer(config.description) : undefined, }, - (data) => this._onData(data), - (message) => this._fail(nativeError(message)), + this._bind((data: NativeDecodedAudio) => this._onData(data)), + this._bind((message: string) => this._fail(nativeError(message))), ); } catch (e) { this._fail(nativeError((e as Error).message)); @@ -456,29 +462,31 @@ export class AudioDecoder extends CodecBase { setTimeout(() => this._drain(), 0); } - async flush() { - this._assertConfigured(); - try { + flush() { + return this._flush(async () => { await this._decoder!.flush(); - } catch (e) { - rethrow(e); - } - await new Promise((resolve) => setTimeout(() => resolve(), 0)); + await nextMacrotask(); + }); } reset() { - this._decoder?.close(); - this._decoder = null; - this._state = "unconfigured"; - this._reset(); + this._resetCodec(); } close() { - this._decoder?.close(); - this._decoder = null; this._close(); } + _releaseNative() { + const decoder = this._decoder; + this._decoder = null; + try { + decoder?.close(); + } catch { + // Already closed natively. + } + } + _onData(data: NativeDecodedAudio) { if (this._state !== "configured") { return; diff --git a/src/lib/avc.ts b/src/lib/avc.ts new file mode 100644 index 0000000..2c34026 --- /dev/null +++ b/src/lib/avc.ts @@ -0,0 +1,166 @@ +// The picture size an H.264 stream declares in its sequence parameter set, +// read from an avcC record (ISO/IEC 14496-15) — what a VideoDecoderConfig +// without codedWidth/codedHeight still carries. + +class BitReader { + private bit = 0; + constructor(private readonly bytes: Uint8Array) {} + + u(n: number) { + let value = 0; + for (let i = 0; i < n; i++) { + const byte = this.bytes[this.bit >> 3]; + if (byte === undefined) { + throw new RangeError("past the end of the SPS"); + } + value = value * 2 + ((byte >> (7 - (this.bit & 7))) & 1); + this.bit++; + } + return value; + } + + ue() { + let zeros = 0; + while (this.u(1) === 0) { + if (++zeros > 31) { + throw new RangeError("exp-Golomb code too long"); + } + } + return 2 ** zeros - 1 + this.u(zeros); + } + + se() { + const k = this.ue(); + return k % 2 === 1 ? (k + 1) / 2 : -(k / 2); + } +} + +// The NAL unit's payload without its emulation prevention bytes +// (00 00 03 → 00 00). +const unescape = (nal: Uint8Array) => { + const out: number[] = []; + let zeros = 0; + for (const byte of nal) { + if (zeros >= 2 && byte === 3) { + zeros = 0; + continue; + } + out.push(byte); + zeros = byte === 0 ? zeros + 1 : 0; + } + return new Uint8Array(out); +}; + +const skipScalingList = (r: BitReader, size: number) => { + let last = 8; + let next = 8; + for (let j = 0; j < size; j++) { + if (next !== 0) { + next = (last + r.se() + 256) % 256; + } + last = next === 0 ? last : next; + } +}; + +// Profiles whose SPS carries chroma_format_idc, bit depths and scaling lists. +const HIGH_PROFILES = new Set([ + 100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135, +]); + +/** The size (after cropping) of an SPS NAL unit, header byte included. */ +export const spsSize = (nal: Uint8Array) => { + const r = new BitReader(unescape(nal)); + if ((r.u(8) & 0x1f) !== 7) { + return undefined; + } + const profile = r.u(8); + r.u(16); // constraint flags, level + r.ue(); // seq_parameter_set_id + let chromaFormat = 1; + let separateColourPlane = false; + if (HIGH_PROFILES.has(profile)) { + chromaFormat = r.ue(); + if (chromaFormat === 3) { + separateColourPlane = r.u(1) === 1; + } + r.ue(); // bit_depth_luma_minus8 + r.ue(); // bit_depth_chroma_minus8 + r.u(1); // qpprime_y_zero_transform_bypass_flag + if (r.u(1) === 1) { + const lists = chromaFormat === 3 ? 12 : 8; + for (let i = 0; i < lists; i++) { + if (r.u(1) === 1) { + skipScalingList(r, i < 6 ? 16 : 64); + } + } + } + } + r.ue(); // log2_max_frame_num_minus4 + const pocType = r.ue(); + if (pocType === 0) { + r.ue(); // log2_max_pic_order_cnt_lsb_minus4 + } else if (pocType === 1) { + r.u(1); // delta_pic_order_always_zero_flag + r.se(); // offset_for_non_ref_pic + r.se(); // offset_for_top_to_bottom_field + const cycle = r.ue(); + for (let i = 0; i < cycle; i++) { + r.se(); + } + } + r.ue(); // max_num_ref_frames + r.u(1); // gaps_in_frame_num_value_allowed_flag + const widthInMbs = r.ue() + 1; + const heightInMapUnits = r.ue() + 1; + const frameMbsOnly = r.u(1); + if (frameMbsOnly === 0) { + r.u(1); // mb_adaptive_frame_field_flag + } + r.u(1); // direct_8x8_inference_flag + let width = widthInMbs * 16; + let height = (2 - frameMbsOnly) * heightInMapUnits * 16; + if (r.u(1) === 1) { + const left = r.ue(); + const right = r.ue(); + const top = r.ue(); + const bottom = r.ue(); + // Crop units: one sample without chroma (monochrome or separate + // planes), else the chroma subsampling; twice as tall for fields. + const arrayType = separateColourPlane ? 0 : chromaFormat; + const subWidth = arrayType === 1 || arrayType === 2 ? 2 : 1; + const subHeight = arrayType === 1 ? 2 : 1; + width -= subWidth * (left + right); + height -= subHeight * (2 - frameMbsOnly) * (top + bottom); + } + if (width <= 0 || height <= 0) { + return undefined; + } + return { width, height }; +}; + +/** + * The size of the stream an avcC record describes, from its first SPS; + * undefined when the record or the SPS cannot be read. + */ +export const avcCodedSize = ( + avcC: ArrayBuffer | ArrayBufferView | undefined, +): { width: number; height: number } | undefined => { + if (!avcC) { + return undefined; + } + const bytes = ArrayBuffer.isView(avcC) + ? new Uint8Array(avcC.buffer, avcC.byteOffset, avcC.byteLength) + : new Uint8Array(avcC); + if (bytes.length < 8 || bytes[0] !== 1 || (bytes[5]! & 0x1f) === 0) { + return undefined; + } + const length = (bytes[6]! << 8) | bytes[7]!; + if (8 + length > bytes.length) { + return undefined; + } + try { + return spsSize(bytes.subarray(8, 8 + length)); + } catch { + return undefined; + } +}; diff --git a/src/lib/native.ts b/src/lib/native.ts index 8212dfb..60e7dd0 100644 --- a/src/lib/native.ts +++ b/src/lib/native.ts @@ -40,19 +40,28 @@ export const domError = (name: string, message: string, code?: string) => { return e; }; -// Native messages are "Name: code: message" (or "Name: message"). +// Native messages are "Name: code: message" (or "Name: message"). Nitro +// prefixes what a native method throws with the method's name +// ("WebCodecs.createVideoEncoder(...): Name: message"), hence no anchor. +const NATIVE_ERROR = /(\w+Error): (?:([a-z-]+): )?([\s\S]*)$/; + export const nativeError = (message: string) => { - const m = /^(\w+Error): (?:([a-z-]+): )?([\s\S]*)$/.exec(message); + const m = NATIVE_ERROR.exec(message); return m ? domError(m[1], m[3], m[2]) : domError("EncodingError", message); }; // A native call that throws "Name: message": rethrow as that DOMException. export const rethrow = (e: unknown): never => { const message = e instanceof Error ? e.message : String(e); - const m = /(\w+Error): (?:([a-z-]+): )?([\s\S]*)$/.exec(message); + const m = NATIVE_ERROR.exec(message); throw m ? domError(m[1], m[3], m[2]) : e; }; +// After a native flush resolved: the outputs it sent come back through the +// JS thread's queue first. +export const nextMacrotask = () => + new Promise((resolve) => setTimeout(() => resolve(), 0)); + export const toArrayBuffer = ( data: ArrayBuffer | ArrayBufferView, ): ArrayBuffer => { @@ -77,8 +86,8 @@ export const toBytes = (data: ArrayBuffer | ArrayBufferView) => type Listener = (event: { type: string }) => void; -// The control queue of a WebCodecs codec: state, the "dequeue" event, and -// flush() waiting for the outputs of what was submitted. +// The control queue of a WebCodecs codec: state, the "dequeue" event, +// flush(), and which native codec's callbacks still count. export class CodecBase { _state: "unconfigured" | "configured" | "closed" = "unconfigured"; // Submitted calls the codec has not taken yet. @@ -88,6 +97,11 @@ export class CodecBase { _listeners = new Map>(); ondequeue: Listener | null = null; _errorCallback: (error: Error) => void; + // Bumped whenever the native codec is replaced or let go: callbacks of an + // older one are ignored (reset() discards pending outputs). + _generation = 0; + // flush() calls not settled yet: reset() and close() reject them. + _flushes = new Set<(error: Error) => void>(); constructor(error: (error: Error) => void) { this._errorCallback = error; @@ -144,16 +158,58 @@ export class CodecBase { } } - // Waits until every frame taken has come back. - async _waitPending() { - while (this._pending > 0 && this._state === "configured") { - await new Promise((resolve) => - this.addEventListener("output", resolve, { once: true }), - ); - } - if (this._state !== "configured") { - throw domError("AbortError", "the codec was closed during flush"); + /** + * Wraps a callback of the native codec created now (after + * _replaceNative()): once that codec is replaced or let go, its late + * callbacks go to `stale` instead. + */ + _bind(fn: (value: T) => void, stale?: (value: T) => void) { + const generation = this._generation; + return (value: T) => { + if (generation === this._generation) { + fn(value); + } else { + stale?.(value); + } + }; + } + + /** + * flush(): runs `flushNative` (the native flush, then whatever waits for + * its outputs), and rejects with AbortError if reset() or close() comes + * first, as the specification does. + */ + _flush(flushNative: () => Promise): Promise { + try { + this._assertConfigured(); + } catch (e) { + return Promise.reject(e); } + const generation = this._generation; + return new Promise((resolve, reject) => { + this._flushes.add(reject); + flushNative().then( + () => { + this._flushes.delete(reject); + resolve(); + }, + (e: unknown) => { + this._flushes.delete(reject); + // A configure() since let the codec go, with what it held: there + // is nothing left to flush. (reset() and close() already + // rejected this flush with AbortError.) + if (generation !== this._generation) { + resolve(); + return; + } + try { + rethrow(e); + } catch (error) { + reject(error); + } + }, + ); + }); } _outputSeen() { @@ -161,15 +217,39 @@ export class CodecBase { this._dispatch("output"); } - _reset() { + /** Lets go of the native codec. Each codec implements it. */ + _releaseNative() {} + + /** + * Forgets what the native codec held (it was let go, so it will not come + * back), and wakes whoever waits on the queue: Mediabunny waits for + * "dequeue" while encodeQueueSize >= 4. + */ + _discardPending() { this._queue = 0; this._pending = 0; - // Wake whoever waits on the queue (Mediabunny waits for "dequeue" when - // encodeQueueSize >= 4) or on outputs (flush()). this._dispatch("dequeue"); this._dispatch("output"); } + /** A new config: the old native codec goes, with what it held. */ + _replaceNative() { + this._releaseNative(); + this._generation++; + this._discardPending(); + } + + _reset() { + this._replaceNative(); + const flushes = [...this._flushes]; + this._flushes.clear(); + for (const reject of flushes) { + reject( + domError("AbortError", "the codec was reset or closed during flush"), + ); + } + } + _fail(error: Error) { if (this._state === "closed") { return; @@ -178,6 +258,15 @@ export class CodecBase { this._errorCallback(error); } + /** reset() of the specification: back to unconfigured. */ + _resetCodec() { + if (this._state === "closed") { + throw domError("InvalidStateError", "the codec is closed"); + } + this._state = "unconfigured"; + this._reset(); + } + _close() { this._state = "closed"; this._reset(); diff --git a/src/lib/video.ts b/src/lib/video.ts index 306e1e6..1d5e920 100644 --- a/src/lib/video.ts +++ b/src/lib/video.ts @@ -7,12 +7,14 @@ import type { NativeVideoEncoderConfig, } from "../specs/WebCodecs.nitro"; +import { avcCodedSize } from "./avc"; import { cloneConfig, CodecBase, domError, native, nativeError, + nextMacrotask, rethrow, toArrayBuffer, toBytes, @@ -175,7 +177,10 @@ export class VideoFrame { * a decoder. The frame takes it over: close the frame, not the surface. * - `new VideoFrame({ handle }, init)`: any native surface handle, such as * a react-native-webgpu NativeBuffer. The frame takes its own reference, - * so the source can be released right after. + * so the source can be released right after. On Android, encode() + * returns once such a frame has been read, so its producer may then + * write into the buffer again (encode() waits for the frames queued + * before it). */ constructor( source: VideoFrame | NativeSurface | NativeSurfaceSource, @@ -422,9 +427,12 @@ const toNativeEncoderConfig = ( return null; } let profile: string | undefined; + let level: number | undefined; if (codec === "avc") { const profileIdc = parseInt(config.codec.slice(5, 7), 16); profile = avcProfile(profileIdc); + const levelIdc = parseInt(config.codec.slice(9, 11), 16); + level = levelIdc > 0 ? levelIdc : undefined; } else if (codec === "av1") { // av01...: Main (profile 0), 8 or 10 // bits. @@ -449,6 +457,7 @@ const toNativeEncoderConfig = ( framerate: config.framerate, realtime: config.latencyMode === "realtime", profile, + level, }; }; @@ -519,7 +528,8 @@ export class VideoEncoder extends CodecBase { ); return; } - this._encoder?.close(); + // The frames the old encoder holds go with it. + this._replaceNative(); this._config = config; this._nativeConfig = nativeConfig; this._colorSpace = { ...BT709 }; @@ -527,8 +537,8 @@ export class VideoEncoder extends CodecBase { try { this._encoder = native().createVideoEncoder( nativeConfig, - (chunk) => this._onChunk(chunk), - (message) => this._fail(nativeError(message)), + this._bind((chunk: NativeEncodedChunk) => this._onChunk(chunk)), + this._bind((message: string) => this._fail(nativeError(message))), ); } catch (e) { this._fail(nativeError((e as Error).message)); @@ -544,6 +554,9 @@ export class VideoEncoder extends CodecBase { if (!(frame instanceof VideoFrame)) { throw new TypeError("frame must be a VideoFrame"); } + if (!frame._surface) { + throw new TypeError("the VideoFrame is closed"); + } // The encoder takes its own reference (and the frame's fence), so the // caller may close the frame right away, as on the web. try { @@ -570,29 +583,41 @@ export class VideoEncoder extends CodecBase { _stats.maxPending = Math.max(_stats.maxPending, this._pending); } - async flush() { - this._assertConfigured(); - try { + flush() { + return this._flush(async () => { + const generation = this._generation; await this._encoder!.flush(); - } catch (e) { - rethrow(e); - } - await this._waitPending(); + await nextMacrotask(); + if (generation !== this._generation) { + return; + } + // Every output the codec had came back before its flush resolved. A + // frame still counted is one it dropped without saying so (MediaCodec + // does for a timestamp that does not move forward): forget it, or + // the queue would stay blocked. + this._pending = this._queue; + this._drain(this._limit()); + }); } reset() { - this._encoder?.close(); - this._encoder = null; - this._state = "unconfigured"; - this._reset(); + this._resetCodec(); } close() { - this._encoder?.close(); - this._encoder = null; this._close(); } + _releaseNative() { + const encoder = this._encoder; + this._encoder = null; + try { + encoder?.close(); + } catch { + // Already closed natively. + } + } + _onChunk(chunk: NativeEncodedChunk) { if (this._state !== "configured") { return; @@ -666,6 +691,10 @@ export interface VideoDecoderConfig { // importExternalTexture or copyExternalImageToTexture. By default, "BGRA" // on iOS and "NV12" on Android. outputFormat?: "BGRA" | "NV12"; + // On Android, "prefer-software" decodes on a software decoder and + // "prefer-hardware" never does; iOS leaves the choice to VideoToolbox. + hardwareAcceleration?: + "no-preference" | "prefer-hardware" | "prefer-software"; [key: string]: unknown; } @@ -674,12 +703,23 @@ const toNativeDecoderConfig = (config: VideoDecoderConfig) => { if (!codec || !config.description) { return null; } + // Without a size, the SPS's: Android sizes the decoder's input buffers + // (and its pictures) from it. + const sized = + config.codedWidth !== undefined && config.codedHeight !== undefined; + const size = + !sized && codec === "avc" ? avcCodedSize(config.description) : undefined; return { codec, description: toArrayBuffer(config.description), - codedWidth: config.codedWidth, - codedHeight: config.codedHeight, + codedWidth: config.codedWidth ?? size?.width, + codedHeight: config.codedHeight ?? size?.height, pixelFormat: config.outputFormat, + hardwareAcceleration: + config.hardwareAcceleration === "prefer-software" || + config.hardwareAcceleration === "prefer-hardware" + ? config.hardwareAcceleration + : undefined, }; }; @@ -726,12 +766,17 @@ export class VideoDecoder extends CodecBase { ); return; } - this._decoder?.close(); + this._replaceNative(); try { this._decoder = native().createVideoDecoder( nativeConfig, - (frame) => this._onFrame(frame), - (message) => this._fail(nativeError(message)), + // A frame of a decoder since reset or closed is not output, but + // goes back to its decoder. + this._bind( + (frame: NativeDecodedFrame) => this._onFrame(frame), + (frame) => frame.surface.release(), + ), + this._bind((message: string) => this._fail(nativeError(message))), ); } catch (e) { this._fail(nativeError((e as Error).message)); @@ -762,31 +807,32 @@ export class VideoDecoder extends CodecBase { setTimeout(() => this._drain(), 0); } - async flush() { - this._assertConfigured(); - try { + flush() { + return this._flush(async () => { await this._decoder!.flush(); - } catch (e) { - rethrow(e); - } - // Frames come back through the JS thread's queue after the flush. - await new Promise((resolve) => setTimeout(() => resolve(), 0)); - this._key = false; + await nextMacrotask(); + this._key = false; + }); } reset() { - this._decoder?.close(); - this._decoder = null; - this._state = "unconfigured"; - this._reset(); + this._resetCodec(); } close() { - this._decoder?.close(); - this._decoder = null; this._close(); } + _releaseNative() { + const decoder = this._decoder; + this._decoder = null; + try { + decoder?.close(); + } catch { + // Already closed natively. + } + } + _onFrame(frame: NativeDecodedFrame) { if (this._state !== "configured") { frame.surface.release(); diff --git a/src/specs/WebCodecs.nitro.ts b/src/specs/WebCodecs.nitro.ts index f037454..5bf4b2f 100644 --- a/src/specs/WebCodecs.nitro.ts +++ b/src/specs/WebCodecs.nitro.ts @@ -75,6 +75,9 @@ export interface NativeVideoEncoderConfig { realtime: boolean; // "baseline" | "main" | "high" (avc1.PPCCLL), "main" | "main10" (hvc1.P.*) profile?: string; + // H.264's level_idc, from avc1.PPCCLL (e.g. 40 for 4.0): the highest the + // stream may need. Android sets it with the profile; iOS picks the level. + level?: number; } export interface NativeVideoEncoder extends HybridObject { @@ -107,6 +110,9 @@ export interface NativeVideoDecoderConfig { codedHeight?: number; // "BGRA" (default) or "NV12" pixelFormat?: string; + // WebCodecs' "prefer-software" or "prefer-hardware"; none: the platform's + // choice. Android picks the decoder by it; iOS ignores it. + hardwareAcceleration?: string; } export interface NativeDecodedFrame {