From 6b5807b9697c073394f131f98aed28fd2d6a2f46 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:48:01 +0200 Subject: [PATCH 01/10] test(ios): decode from an open-GOP CRA after a flush, and a GOP that goes back in time --- src/__tests__/WebCodecs.spec.ts | 238 ++++++++++++++++++++++++++++++++ 1 file changed, 238 insertions(+) diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index f2389da..14aeb28 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -3309,6 +3309,244 @@ describe("react-native-webcodecs + Mediabunny", () => { } }, 300000); + // Decoding from a key frame that is not the first: after a seek + // (flush() then a later key frame), or a GOP that goes back in time. + describe("decoding from a later key frame", () => { + interface Runs { + supported: boolean; + // Every packet, in decoding order (microseconds). + packets: { timestamp: number; key: boolean }[]; + // Each run's output timestamps, in output order. + runs: number[][]; + errors: string[]; + } + + const hasLibx265 = () => { + try { + return /libx265/.test( + execFileSync("ffmpeg", ["-hide_banner", "-encoders"], { + encoding: "utf8", + }), + ); + } catch { + return false; + } + }; + + // Two GOPs of 30 frames at 30 fps, made with ffmpeg once. + const gopClip = (name: string, codec: string[]) => { + const clip = path.join(clipDirectory, name); + fs.mkdirSync(clipDirectory, { recursive: true }); + if (!fs.existsSync(clip)) { + execFileSync( + "ffmpeg", + [ + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + "testsrc2=size=640x360:rate=30:duration=2", + "-pix_fmt", + "yuv420p", + ].concat(codec, [clip]), + ); + } + return pushFile(clip); + }; + + // Decodes `runs` of GOPs (each a list of [first, end) GOP ranges, in + // that order, without a flush between them), each run followed by a + // flush, with one decoder. + const decodeRuns = (file: string, runs: number[][][]) => + runOnDevice( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + const result: any = { + supported: false, + packets: [], + runs: [], + errors: [], + }; + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => + wc.VideoDecoder.isConfigSupported(config).then((s: any) => { + result.supported = s.supported; + if (!s.supported) { + input.dispose(); + return result; + } + const chunks: any[] = []; + const keys: number[] = []; + const iterator = new mb.EncodedPacketSink(track).packets(); + const read = (): Promise => + iterator.next().then((r: any) => { + if (r.done) { + return undefined; + } + const chunk = r.value.toEncodedVideoChunk(); + if (chunk.type === "key") { + keys.push(chunks.length); + } + chunks.push(chunk); + result.packets.push({ + timestamp: chunk.timestamp, + key: chunk.type === "key", + }); + return read(); + }); + let current: number[] = []; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + current.push(frame.timestamp); + frame.close(); + }, + error: (e: any) => result.errors.push(String(e)), + }); + decoder.configure(config); + const order: number[][] = []; + const decodeFrom = (i: number): Promise => { + if (i >= order.length || decoder.state === "closed") { + return Promise.resolve(); + } + decoder.decode(chunks[order[i][0]]); + return new Promise((resolve) => setTimeout(resolve, 0)).then( + () => decodeFrom(i + 1), + ); + }; + const run = (n: number): Promise => { + if (n >= ctx.runs.length || decoder.state === "closed") { + return Promise.resolve(); + } + current = []; + result.runs.push(current); + order.length = 0; + ctx.runs[n].forEach((range: number[]) => { + const end = + range[1] < keys.length ? keys[range[1]] : chunks.length; + for (let p = keys[range[0]]; p < end; p++) { + order.push([p]); + } + }); + return decodeFrom(0) + .then(() => + decoder.state === "closed" ? undefined : decoder.flush(), + ) + .catch((e: any) => { + result.errors.push(`flush: ${e}`); + }) + .then(() => run(n + 1)); + }; + return read() + .then(() => run(0)) + .then(() => { + if (decoder.state !== "closed") { + decoder.close(); + } + input.dispose(); + return result; + }); + }), + ), + ); + }, + { file, runs }, + 120000, + ); + + const sorted = (values: number[]) => values.slice().sort((a, b) => a - b); + // The packets of GOP `gop` (0-based), in decoding order. + const gopOf = (packets: Runs["packets"], gop: number) => { + const keys = packets + .map((p, i) => (p.key ? i : -1)) + .filter((i) => i >= 0); + return packets.slice(keys[gop], keys[gop + 1] ?? packets.length); + }; + + // x265's open GOPs: the second key frame is a CRA, and the 4 frames + // after it in decoding order (RASL, shown before it) reference the + // first GOP. Decoded from that CRA after a flush, as a seek does, they + // cannot be decoded: VideoToolbox fails them with + // kVTVideoDecoderReferenceMissingErr (-17694) or bad data, which closed + // the decoder. They are left out, as Chromium does (Android's decoders + // may output them). + it("decodes HEVC from an open-GOP key frame (CRA) after a flush", async () => { + if (!supported() || !probes() || !hasLibx265()) { + return; + } + const file = await gopClip("clip-hevc-open-gop.mp4", [ + "-c:v", + "libx265", + "-tag:v", + "hvc1", + "-x265-params", + "open-gop=1:keyint=30:min-keyint=30:scenecut=0:log-level=error", + ]); + const decoded = await decodeRuns(file, [[[0, 2]], [[1, 2]]]); + console.log(`open GOP: ${JSON.stringify(decoded)}`); + if (!decoded.supported) { + return; + } + const all = decoded.packets.map((p) => p.timestamp); + const second = gopOf(decoded.packets, 1).map((p) => p.timestamp); + const cra = second[0]!; + const fromCra = sorted(second.filter((t) => t >= cra)); + expect(second.length - fromCra.length).toBe(4); + expect({ + errors: decoded.errors, + first: decoded.runs[0], + }).toEqual({ errors: [], first: sorted(all) }); + if (ios()) { + expect(decoded.runs[1]).toEqual(fromCra); + } else { + expect([fromCra, sorted(second)]).toContainEqual(decoded.runs[1]); + } + }, 300000); + + // A key frame earlier than the frames before it, without a flush: the + // second GOP, then the first. Each GOP's frames come out in order, all + // of the second's before the first's: frames held for reordering go + // out at that key frame instead of being sorted in with the first + // GOP's. + it("outputs a GOP that goes back in time after the one before it", async () => { + if (!supported() || !probes()) { + return; + } + const file = await gopClip("clip-h264-two-gops.mp4", [ + "-c:v", + "libx264", + "-profile:v", + "high", + "-g", + "30", + "-keyint_min", + "30", + "-sc_threshold", + "0", + ]); + const decoded = await decodeRuns(file, [ + [ + [1, 2], + [0, 1], + ], + ]); + console.log(`back in time: ${JSON.stringify(decoded)}`); + if (!decoded.supported) { + return; + } + const times = (gop: number) => + sorted(gopOf(decoded.packets, gop).map((p) => p.timestamp)); + expect({ errors: decoded.errors, frames: decoded.runs[0] }).toEqual({ + errors: [], + frames: times(1).concat(times(0)), + }); + }, 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. From 05e9063dc91bddbaf5f5418b3419225cd30c9090 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:52:55 +0200 Subject: [PATCH 02/10] fix(ios): forward bitrateMode, refuse quantizer, and tag the range the encoder writes VideoToolbox gets bitrateMode: "quantizer" is refused (no per-frame QP outside the low-latency H.264 mode), so Mediabunny's Quality presets fall back to a bitrate instead of VT's default rate; "constant" uses ConstantBitRate on iOS 16+ when the encoder has it; "variable" caps each second at 1.5x the bitrate with DataRateLimits. The decoder config's colorSpace says limited range, as the encoders write, instead of copying the frames' fullRange (Mediabunny wrote a full-range colr over a video-range SPS). Decoded RGB frames are tagged full range. --- ios/VideoEncoder.swift | 25 +- .../ios/swift/NativeVideoEncoderConfig.swift | 20 +- .../shared/c++/NativeVideoEncoderConfig.hpp | 8 +- src/__tests__/WebCodecs.spec.ts | 259 ++++++++++++++++++ src/lib/video.ts | 26 +- src/specs/WebCodecs.nitro.ts | 3 + 6 files changed, 334 insertions(+), 7 deletions(-) diff --git a/ios/VideoEncoder.swift b/ios/VideoEncoder.swift index a0188f0..33fe936 100644 --- a/ios/VideoEncoder.swift +++ b/ios/VideoEncoder.swift @@ -97,6 +97,12 @@ final class HybridNativeVideoEncoder: HybridNativeVideoEncoderSpec { if tooLarge { throw WebCodecsError.notSupported("\(config.width)x\(config.height) is above the codec's highest level") } + // A per-frame quantizer needs BaseFrameQP, which only VideoToolbox's + // low-latency H.264 mode takes: refused, so that Mediabunny falls back to + // a bitrate instead of encoding at the default rate. + if config.bitrateMode == "quantizer" { + throw WebCodecsError.notSupported("bitrateMode quantizer") + } super.init() var session: VTCompressionSession? @@ -148,7 +154,24 @@ final class HybridNativeVideoEncoder: HybridNativeVideoEncoderSpec { maxFrameDelay = 3 } if let bitrate = config.bitrate, bitrate > 0 { - set(kVTCompressionPropertyKey_AverageBitRate, Int(bitrate) as CFNumber) + var constant = false + if #available(iOS 16.0, *), config.bitrateMode == "constant" { + // Not every encoder has CBR (kVTPropertyNotSupportedErr): the + // average bitrate then. It excludes AverageBitRate and DataRateLimits. + constant = + VTSessionSetProperty( + session, key: kVTCompressionPropertyKey_ConstantBitRate, value: Int(bitrate) as CFNumber) == noErr + } + if !constant { + set(kVTCompressionPropertyKey_AverageBitRate, Int(bitrate) as CFNumber) + } + if config.bitrateMode != "constant" { + // "variable" (WebCodecs' default): AverageBitRate alone overshoots + // freely, so cap each second at 1.5x the bitrate, as WebRTC does. + // Some encoders have no data rate limits; the average still holds. + let limits = [bitrate * 1.5 / 8, 1] as CFArray + set(kVTCompressionPropertyKey_DataRateLimits, limits) + } } if let framerate = config.framerate, framerate > 0 { set(kVTCompressionPropertyKey_ExpectedFrameRate, framerate as CFNumber) diff --git a/nitrogen/generated/ios/swift/NativeVideoEncoderConfig.swift b/nitrogen/generated/ios/swift/NativeVideoEncoderConfig.swift index b0f5b72..e8fd6dd 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?, level: Double?) { + init(codec: String, width: Double, height: Double, bitrate: Double?, framerate: Double?, realtime: Bool, profile: String?, level: Double?, bitrateMode: String?) { self.init(std.string(codec), width, height, { () -> bridge.std__optional_double_ in if let __unwrappedValue = bitrate { return bridge.create_std__optional_double_(__unwrappedValue) @@ -43,6 +43,12 @@ public extension NativeVideoEncoderConfig { } else { return .init() } + }(), { () -> bridge.std__optional_std__string_ in + if let __unwrappedValue = bitrateMode { + return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) + } else { + return .init() + } }()) } @@ -113,4 +119,16 @@ public extension NativeVideoEncoderConfig { } }() } + + @inline(__always) + var bitrateMode: String? { + return { () -> String? in + if bridge.has_value_std__optional_std__string_(self.__bitrateMode) { + let __unwrapped = bridge.get_std__optional_std__string_(self.__bitrateMode) + return String(__unwrapped) + } else { + return nil + } + }() + } } diff --git a/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp b/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp index 4f12a01..b41ea15 100644 --- a/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp +++ b/nitrogen/generated/shared/c++/NativeVideoEncoderConfig.hpp @@ -48,10 +48,11 @@ namespace margelo::nitro::webcodecs { bool realtime SWIFT_PRIVATE; std::optional profile SWIFT_PRIVATE; std::optional level SWIFT_PRIVATE; + std::optional bitrateMode 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, std::optional level): codec(codec), width(width), height(height), bitrate(bitrate), framerate(framerate), realtime(realtime), profile(profile), level(level) {} + explicit NativeVideoEncoderConfig(std::string codec, double width, double height, std::optional bitrate, std::optional framerate, bool realtime, std::optional profile, std::optional level, std::optional bitrateMode): codec(codec), width(width), height(height), bitrate(bitrate), framerate(framerate), realtime(realtime), profile(profile), level(level), bitrateMode(bitrateMode) {} public: friend bool operator==(const NativeVideoEncoderConfig& lhs, const NativeVideoEncoderConfig& rhs) = default; @@ -74,7 +75,8 @@ namespace margelo::nitro { 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, "level"))) + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "level"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bitrateMode"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::webcodecs::NativeVideoEncoderConfig& arg) { @@ -87,6 +89,7 @@ namespace margelo::nitro { 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)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "bitrateMode"), JSIConverter>::toJSI(runtime, arg.bitrateMode)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -105,6 +108,7 @@ namespace margelo::nitro { 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; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "bitrateMode")))) return false; return true; } }; diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index f2389da..8509bae 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -1527,6 +1527,265 @@ describe("react-native-webcodecs + Mediabunny", () => { } }, 60000); + // bitrateMode: VideoToolbox takes no per-frame quantizer outside its + // low-latency H.264 mode, so iOS refuses "quantizer" (Android takes the + // config and encodes at its default bitrate). "constant" (CBR where the + // encoder has it, else the average bitrate) and "variable" (the average + // bitrate, capped at 1.5x over each second on iOS) encode on both. + it("refuses bitrateMode quantizer on iOS, and encodes constant and variable", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ webcodecs: wc }) => { + const base = { codec: "avc1.42001f", width: 640, height: 480 }; + const run = (bitrateMode: string) => { + const config = Object.assign({}, base, { + bitrateMode, + bitrate: bitrateMode === "quantizer" ? undefined : 1_000_000, + }); + return wc.VideoEncoder.isConfigSupported(config).then( + (support: any) => { + if (bitrateMode === "quantizer") { + return { bitrateMode, supported: support.supported }; + } + 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(base.width, base.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 { + bitrateMode, + supported: support.supported, + chunks: chunks.filter((n) => n > 0).length, + errors, + }; + }); + }, + ); + }; + return ["quantizer", "constant", "variable"].reduce( + (done: Promise, mode) => + done.then((all) => run(mode).then((r: any) => all.concat([r]))), + Promise.resolve([]), + ); + })) as any[]; + expect(result).toEqual([ + { bitrateMode: "quantizer", supported: !ios() }, + { bitrateMode: "constant", supported: true, chunks: 3, errors: [] }, + { bitrateMode: "variable", supported: true, chunks: 3, errors: [] }, + ]); + }, 120000); + + // A Mediabunny Quality without a bitrate (QUALITY_HIGH) tries a quantizer + // config first, then a bitrate one. iOS refuses the quantizer, so the + // encoder gets a bitrate rather than running at VideoToolbox's default + // rate; Android takes the quantizer config, as before. + it("configures a bitrate for a Mediabunny Quality preset on iOS", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ mediabunny: mb, webcodecs: wc }) => { + wc.installWebCodecs(); + const configs: any[] = []; + const proto = wc.VideoEncoder.prototype; + const { configure } = proto; + proto.configure = function (this: any, config: any) { + configs.push({ + bitrate: config.bitrate, + bitrateMode: config.bitrateMode, + }); + return configure.call(this, config); + }; + const output = new mb.Output({ + format: new mb.Mp4OutputFormat({ fastStart: "in-memory" }), + target: new mb.BufferTarget(), + }); + const video = new mb.VideoSampleSource({ + codec: "avc", + quality: mb.QUALITY_HIGH, + }); + output.addVideoTrack(video, { frameRate: 30 }); + const pool = wc.createSurfacePool(128, 128); + const add = (i: number): Promise => { + if (i === 10) { + return Promise.resolve(); + } + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp: Math.round((i * 1e6) / 30), + duration: Math.round(1e6 / 30), + }); + const sample = new mb.VideoSample(frame); + return video.add(sample).then( + () => { + sample.close(); + return add(i + 1); + }, + (e: unknown) => { + sample.close(); + throw e; + }, + ); + }; + return output + .start() + .then(() => add(0)) + .then(() => { + video.close(); + return output.finalize(); + }) + .then( + () => ({ configs, bytes: output.target.buffer.byteLength }), + (e: any) => ({ configs, error: `${e && e.name}: ${e && e.message}` }), + ) + .then((r: any) => { + // The app outlives this test. + proto.configure = configure; + return r; + }); + })) as any; + expect(result.error).toBeUndefined(); + expect(result.bytes).toBeGreaterThan(0); + expect(result.configs.length).toBe(1); + if (ios()) { + expect(result.configs[0].bitrateMode).not.toBe("quantizer"); + expect(result.configs[0].bitrate).toBeGreaterThan(0); + } + }, 120000); + + // The encoders write limited range whatever the frames say (VideoToolbox + // converts to video range, MediaCodec is set to color-range 2), so the + // decoder config says so too: a full-range frame must not make Mediabunny + // write a colr box with full_range_flag over a video-range SPS. And a + // decoder's RGB (BGRA) frames are full range, whatever the stream's range. + it("tags the stream's range, not the frames', in the decoder config and colr box", async () => { + if (!supported()) { + return; + } + const result = (await client.eval(({ mediabunny: mb, webcodecs: wc }) => { + const errors: string[] = []; + const chunks: any[] = []; + let decoderConfig: any = null; + const target = new mb.BufferTarget(); + const output = new mb.Output({ + format: new mb.Mp4OutputFormat({ fastStart: "in-memory" }), + target, + }); + const source = new mb.EncodedVideoPacketSource("avc"); + output.addVideoTrack(source, { frameRate: 30 }); + let written = Promise.resolve(); + const encoder = new wc.VideoEncoder({ + output: (chunk: any, meta: any) => { + chunks.push(chunk); + if (meta && meta.decoderConfig && !decoderConfig) { + ({ decoderConfig } = meta); + } + 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(`encoder: ${e}`), + }); + encoder.configure({ codec: "avc1.42001f", width: 128, height: 128 }); + const pool = wc.createSurfacePool(128, 128); + [0, 33333, 66666].forEach((timestamp) => { + const frame = new wc.VideoFrame(pool.acquire(), { + timestamp, + duration: 33333, + colorSpace: { + primaries: "bt709", + transfer: "bt709", + matrix: "bt709", + fullRange: true, + }, + }); + encoder.encode(frame, { keyFrame: timestamp === 0 }); + frame.close(); + }); + let decoded: any = null; + return output + .start() + .then(() => encoder.flush()) + .then(() => written) + .then(() => output.finalize()) + .then(() => { + encoder.close(); + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + if (!decoded) { + decoded = { + format: frame.format, + fullRange: frame.colorSpace.fullRange, + }; + } + frame.close(); + }, + error: (e: any) => errors.push(`decoder: ${e}`), + }); + decoder.configure(decoderConfig); + chunks.forEach((chunk) => decoder.decode(chunk)); + return decoder.flush().then(() => decoder.close()); + }) + .then(() => ({ + errors, + configRange: decoderConfig && decoderConfig.colorSpace.fullRange, + decoded, + path: wc.writeFile("e2e-range.mp4", target.buffer), + })); + })) as any; + expect(result.errors).toEqual([]); + expect(result.configRange).toBe(false); + // NV12 keeps the stream's tags; RGB is full range. + expect(result.decoded.fullRange).toBe(result.decoded.format !== "NV12"); + if (!probes()) { + return; + } + const local = copyLocal(result.path); + const bytes = fs.readFileSync(local); + const colr = bytes.indexOf("colr"); + expect(colr).toBeGreaterThan(0); + expect(bytes.toString("latin1", colr + 4, colr + 8)).toBe("nclx"); + // nclx: primaries, transfer and matrix (2 bytes each), then the flag. + const colrFullRange = bytes[colr + 14] >> 7; + // The SPS's VUI video_full_range_flag (0 when the VUI does not say). + const trace = execFileSync( + "sh", + [ + "-c", + 'ffmpeg -hide_banner -i "$0" -c:v copy -bsf:v trace_headers -f null - 2>&1', + local, + ], + { encoding: "utf8" }, + ); + const spsFullRange = Number( + /video_full_range_flag\s+[01]+\s*=\s*(\d+)/.exec(trace)?.[1] ?? 0, + ); + expect({ colr: colrFullRange, sps: spsFullRange }).toEqual({ + colr: 0, + sps: 0, + }); + }, 120000); + // 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 diff --git a/src/lib/video.ts b/src/lib/video.ts index 1d5e920..bb934c7 100644 --- a/src/lib/video.ts +++ b/src/lib/video.ts @@ -382,6 +382,7 @@ export interface VideoEncoderConfig { bitrate?: number; framerate?: number; latencyMode?: "quality" | "realtime"; + bitrateMode?: "constant" | "variable" | "quantizer"; hardwareAcceleration?: string; avc?: { format?: "avc" | "annexb" }; hevc?: { format?: "hevc" | "annexb" }; @@ -458,6 +459,7 @@ const toNativeEncoderConfig = ( realtime: config.latencyMode === "realtime", profile, level, + bitrateMode: config.bitrateMode, }; }; @@ -618,6 +620,18 @@ export class VideoEncoder extends CodecBase { } } + // The color space the stream says, for the decoder config: the frames' + // own, but limited range whatever they say, since that is what the + // encoders write (VideoToolbox converts to video range, Android sets + // color-range 2). A full-range tag there makes muxers write a colr box + // that disagrees with the stream. + _streamColorSpace() { + return new VideoColorSpace({ + ...this._colorSpace, + fullRange: false, + }).toJSON(); + } + _onChunk(chunk: NativeEncodedChunk) { if (this._state !== "configured") { return; @@ -639,7 +653,7 @@ export class VideoEncoder extends CodecBase { codec: this._config!.codec, codedWidth: this._config!.width, codedHeight: this._config!.height, - colorSpace: new VideoColorSpace(this._colorSpace).toJSON(), + colorSpace: this._streamColorSpace(), }, }; } @@ -655,7 +669,7 @@ export class VideoEncoder extends CodecBase { description: chunk.description, codedWidth: this._config!.width, codedHeight: this._config!.height, - colorSpace: new VideoColorSpace(this._colorSpace).toJSON(), + colorSpace: this._streamColorSpace(), }, }; } @@ -838,10 +852,16 @@ export class VideoDecoder extends CodecBase { frame.surface.release(); return; } + // RGB pictures were converted from the stream's YCbCr to full range, + // whatever range the stream has; NV12 ones keep the stream's tags. + const rgb = + frame.surface.format === "BGRA" || frame.surface.format === "RGBA"; const videoFrame = new VideoFrame(frame.surface, { timestamp: frame.timestamp, duration: frame.duration || undefined, - colorSpace: this._colorSpace, + colorSpace: rgb + ? { ...this._colorSpace, fullRange: true } + : this._colorSpace, }); try { this._output(videoFrame); diff --git a/src/specs/WebCodecs.nitro.ts b/src/specs/WebCodecs.nitro.ts index 5bf4b2f..72360c4 100644 --- a/src/specs/WebCodecs.nitro.ts +++ b/src/specs/WebCodecs.nitro.ts @@ -78,6 +78,9 @@ export interface NativeVideoEncoderConfig { // 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; + // WebCodecs' bitrateMode: "constant", "variable" or "quantizer". Android + // ignores it. + bitrateMode?: string; } export interface NativeVideoEncoder extends HybridObject { From 99d3aa68a85169a96d091ff51240a8f965615ab5 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:52:55 +0200 Subject: [PATCH 03/10] fix(ios): pin a wrapped surface's use count until the frame is closed A CVPixelBufferPool reuses an IOSurface once its use count is zero, whatever its retain count, so a producer (camera, AVAssetWriter) could write a newer image into a wrapped frame held before encode(). --- ios/Surface.swift | 17 +++++++++++++++++ src/lib/video.ts | 4 +++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/ios/Surface.swift b/ios/Surface.swift index c9cdea4..7f75020 100644 --- a/ios/Surface.swift +++ b/ios/Surface.swift @@ -90,11 +90,18 @@ final class HybridNativeSurface: HybridNativeSurfaceSpec { let height: Double let format: String + // Whether `surface` holds a use count, released with it. + private var inUse = false + init(surface: IOSurfaceRef) { self.surface = surface width = Double(IOSurfaceGetWidth(surface)) height = Double(IOSurfaceGetHeight(surface)) format = webCodecsFormat(IOSurfaceGetPixelFormat(surface)) + // A producer's CVPixelBufferPool reuses a surface once its use count is + // zero, whatever its retain count: pin it until the frame is closed. + IOSurfaceIncrementUseCount(surface) + inUse = true super.init() } @@ -148,11 +155,21 @@ final class HybridNativeSurface: HybridNativeSurfaceSpec { return copy } + private func unpin() { + if inUse, let surface { IOSurfaceDecrementUseCount(surface) } + inUse = false + } + func release() throws { + unpin() surface = nil buffer = nil fence = nil } + + deinit { + unpin() + } } final class HybridNativeSurfacePool: HybridNativeSurfacePoolSpec { diff --git a/src/lib/video.ts b/src/lib/video.ts index bb934c7..c1c86e8 100644 --- a/src/lib/video.ts +++ b/src/lib/video.ts @@ -177,7 +177,9 @@ 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. On Android, encode() + * so the source can be released right after. On iOS it also keeps the + * producer's pool from reusing the surface until the frame is closed: + * frames held open can starve a camera's pool. 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). From 5c3e02a1b5d586e8a3260075d0a1c47cc90dac45 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:49:55 +0200 Subject: [PATCH 04/10] fix(ios): decode from a CRA or recovery point, drain the reorder buffer when a key frame goes back in time Drop kVTVideoDecoderReferenceMissingErr frames instead of failing, set ResetDecoderBeforeDecoding on a stream's first key frame, and skip HEVC RASL pictures after a CRA/BLA entry until the next IRAP. A key frame earlier than what was decoded since the last flush drains the held frames first; flush() and that drain restore the stream's reorder depth. failed is written under the reorder lock. --- ios/VideoDecoder.swift | 113 +++++++++++++++++++++++++++++++++++------ 1 file changed, 97 insertions(+), 16 deletions(-) diff --git a/ios/VideoDecoder.swift b/ios/VideoDecoder.swift index 0d9a611..e03e792 100644 --- a/ios/VideoDecoder.swift +++ b/ios/VideoDecoder.swift @@ -274,8 +274,17 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { // out. Frames that already come in order only wait, they are not moved. private let reorder = NSLock() private var held: [NativeDecodedFrame] = [] + private let baseDepth: Int private var depth: Int private var lastOut = -Double.infinity + // On `queue`: the latest timestamp decoded since the stream started, and + // whether the next key frame starts one (after configure or flush). + private var lastIn = -Double.infinity + private var start = true + // HEVC: the NAL unit length size, and whether the stream started at a + // CRA or BLA whose leading RASL pictures are still to be skipped. + private let hevcNalLength: Int? + private var skipRASL = false init( config: NativeVideoDecoderConfig, @@ -285,7 +294,15 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { self.output = output self.error = error format = try HybridNativeVideoDecoder.formatDescription(config) - depth = ReorderDepth.of(config) + let base = ReorderDepth.of(config) + baseDepth = base + depth = base + if config.codec == "hevc", let description = config.description { + let record = [UInt8](description.toData(copyIfNeeded: true)) + hevcNalLength = record.count > 22 ? Int(record[21] & 0x3) + 1 : nil + } else { + hevcNalLength = nil + } super.init() let attributes: [CFString: Any] = [ @@ -368,12 +385,47 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { private func fail(_ message: String) { queue.async { if self.failed { return } - self.failed = true - self.discardHeld() + self.stop() self.error(message) } } + // On `queue`. `failed` is written under `reorder` too, as hold() reads it + // there; held surfaces go back to the decoder's pool unseen. + private func stop() { + reorder.lock() + failed = true + held.removeAll() + reorder.unlock() + } + + // On `queue`: what follows starts from a key frame, with the stream's own + // reorder depth again. + private func restart() { + lastIn = -Double.infinity + start = true + reorder.lock() + lastOut = -Double.infinity + depth = baseDepth + reorder.unlock() + } + + // The type of an HEVC sample's first picture (VCL) NAL unit, nil when it + // cannot be read. + static func hevcPictureType(_ bytes: Data, nalLength: Int) -> Int? { + var i = bytes.startIndex + while i + nalLength < bytes.endIndex { + var length = 0 + for k in 0.. 0, i + length <= bytes.endIndex else { return nil } + let type = Int(bytes[i] >> 1) & 0x3f + if type < 32 { return type } + i += length + } + return nil + } + // From VideoToolbox's output callback. private func hold(_ frame: NativeDecodedFrame) { reorder.lock() @@ -403,19 +455,38 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { 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) let format = format + let hevcNalLength = hevcNalLength queue.async { if self.failed { return } + // A key frame earlier than what came before it, without a flush: a + // new stream. The frames held for reordering go out first, rather + // than being sorted in with the new stream's. + if key && timestamp < self.lastIn { + VTDecompressionSessionFinishDelayedFrames(session) + VTDecompressionSessionWaitForAsynchronousFrames(session) + if !self.failed { self.drainHeld() } + self.restart() + } + self.lastIn = max(self.lastIn, timestamp) + let first = key && self.start + if key { self.start = false } + // Started at a CRA or BLA (a seek in an open-GOP stream): the RASL + // pictures after it reference frames before it, which the decoder + // never had. VideoToolbox fails them, so they are skipped until the + // next IRAP picture, as Chromium does. + if let hevcNalLength, let type = HybridNativeVideoDecoder.hevcPictureType(bytes, nalLength: hevcNalLength) { + if first { + self.skipRASL = type == 21 || (16...18).contains(type) + } else if (16...23).contains(type) { + self.skipRASL = false + } else if self.skipRASL && (type == 8 || type == 9) { + return + } + } var block: CMBlockBuffer? var status = CMBlockBufferCreateWithMemoryBlock( allocator: kCFAllocatorDefault, memoryBlock: nil, blockLength: bytes.count, @@ -443,6 +514,15 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { self.fail(errorMessage("EncodingError", "decoder-failed", "CMSampleBufferCreate failed (\(status))")) return } + // The first key frame of a stream may be a recovery point or CRA + // rather than an IDR: without a reset, VideoToolbox may decode it + // against stale state, silently corrupted (Apple's advice to + // Chromium, crbug 451536366). + if first { + CMSetAttachment( + sample, key: kCMSampleBufferAttachmentKey_ResetDecoderBeforeDecoding, value: kCFBooleanTrue, + attachmentMode: CMAttachmentMode(kCMAttachmentMode_ShouldNotPropagate)) + } // Temporal processing: frames come out in presentation order, as // WebCodecs outputs them. let flags: VTDecodeFrameFlags = [._EnableAsynchronousDecompression, ._EnableTemporalProcessing] @@ -450,6 +530,10 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { session, sampleBuffer: sample, flags: flags, infoFlagsOut: nil ) { [weak self] status, _, imageBuffer, pts, dur in guard let self else { return } + // A frame referencing one from before the stream's start (it + // started at a recovery point or open-GOP key frame): dropped, as + // Chromium, WebKit and FFmpeg do. + if status == kVTVideoDecoderReferenceMissingErr { return } if status != noErr { self.fail(HybridNativeVideoEncoder.describe(status).replacingOccurrences(of: "encoder", with: "decoder")) return @@ -459,7 +543,7 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { let d = dur.isValid ? Double(CMTimeConvertScale(dur, timescale: 1_000_000, method: .roundHalfAwayFromZero).value) : duration self.hold(NativeDecodedFrame(surface: HybridNativeSurface(pixelBuffer: imageBuffer), timestamp: ts, duration: d)) } - if status != noErr { + if status != noErr && status != kVTVideoDecoderReferenceMissingErr { self.fail(HybridNativeVideoEncoder.describe(status).replacingOccurrences(of: "encoder", with: "decoder")) } } @@ -472,9 +556,7 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { 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() + self.restart() } } @@ -482,9 +564,8 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { background = nil if let session { queue.async { - self.failed = true + self.stop() VTDecompressionSessionInvalidate(session) - self.discardHeld() } } session = nil From b78c8636d3a98a79ca2cd298872e8a89dd30649f Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:55:08 +0200 Subject: [PATCH 05/10] fix(ios): decode AAC from its AudioSpecificConfig, ADTS, and restart the AudioDecoder on flush - AudioDecoder wraps config.description in an esds magic cookie, takes the format from it (kAudioFormatProperty_FormatList: HE-AAC and HE-AAC v2 at their full rate and channels, 2048 frames a packet) and reports the converter's output rate and channels (#3). - AAC without a description is ADTS: JS builds the AudioSpecificConfig and strips each chunk's header, on both platforms; mp4a.40.5/29 decode (#2). - flush() ends the converter's stream and resets it, so what is decoded after it does not overlap what came before (#10). Refs #2 --- ios/Audio.swift | 158 ++++++++++++++--- src/__tests__/WebCodecs.spec.ts | 281 ++++++++++++++++++++++++++++++ src/__tests__/unit/codecs.test.ts | 63 ++++++- src/lib/audio.ts | 71 +++++++- 4 files changed, 540 insertions(+), 33 deletions(-) diff --git a/ios/Audio.swift b/ios/Audio.swift index ff9e62a..35f73b5 100644 --- a/ios/Audio.swift +++ b/ios/Audio.swift @@ -47,6 +47,62 @@ private func compressedFormat(codec: String, sampleRate: Double, channels: Int) mBitsPerChannel: 0, mReserved: 0) } +// An AudioSpecificConfig in an ES descriptor (esds): the magic cookie +// AudioToolbox takes for AAC, laid out as FFmpeg's ffat_get_magic_cookie does. +private func esdsCookie(_ asc: Data) -> Data { + func descriptor(_ tag: UInt8, _ size: Int) -> [UInt8] { + [ + tag, UInt8((size >> 21) & 0x7f) | 0x80, UInt8((size >> 14) & 0x7f) | 0x80, + UInt8((size >> 7) & 0x7f) | 0x80, UInt8(size & 0x7f), + ] + } + var cookie = descriptor(0x03, 3 + 5 + 13 + 5 + asc.count) + cookie += [0, 0, 0] // ES_ID, flags + cookie += descriptor(0x04, 13 + 5 + asc.count) + // MPEG-4 audio, an audio stream, buffer size, max and average bitrate. + cookie += [0x40, 0x15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + cookie += descriptor(0x05, asc.count) + return Data(cookie) + asc +} + +// The stream's format as its cookie describes it, which the config's rate and +// channels may not: the richest layer the system plays (HE-AAC v2, HE-AAC, +// then AAC-LC), so SBR and PS are decoded, at their rate and channels, with +// 2048 frames a packet. +private func aacFormat(cookie: Data) throws -> AudioStreamBasicDescription { + try cookie.withUnsafeBytes { raw -> AudioStreamBasicDescription in + var base = AudioStreamBasicDescription() + base.mFormatID = kAudioFormatMPEG4AAC + var size = UInt32(MemoryLayout.size) + let status = AudioFormatGetProperty( + kAudioFormatProperty_FormatInfo, UInt32(raw.count), raw.baseAddress, &size, &base) + guard status == noErr else { + throw WebCodecsError.notSupported("an AudioSpecificConfig AudioToolbox rejects (\(status))") + } + var info = AudioFormatInfo(mASBD: base, mMagicCookie: raw.baseAddress!, mMagicCookieSize: UInt32(raw.count)) + let infoSize = UInt32(MemoryLayout.size) + let itemSize = MemoryLayout.size + var listSize = UInt32(0) + guard AudioFormatGetPropertyInfo(kAudioFormatProperty_FormatList, infoSize, &info, &listSize) == noErr, + Int(listSize) >= itemSize + else { return base } + var items = [AudioFormatListItem](repeating: AudioFormatListItem(), count: Int(listSize) / itemSize) + guard AudioFormatGetProperty(kAudioFormatProperty_FormatList, infoSize, &info, &listSize, &items) == noErr + else { return base } + let count = min(items.count, Int(listSize) / itemSize) + guard count > 0 else { return base } + var index = UInt32(0) + var indexSize = UInt32(MemoryLayout.size) + if AudioFormatGetProperty( + kAudioFormatProperty_FirstPlayableFormatFromList, UInt32(count * itemSize), &items, &indexSize, &index) + != noErr || Int(index) >= count + { + index = 0 + } + return items[Int(index)].mASBD + } +} + // MARK: - AudioEncoder (PCM → AAC) final class HybridNativeAudioEncoder: HybridNativeAudioEncoderSpec { @@ -223,24 +279,58 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { private var start: Double? private var framesOut: Int64 = 0 private var failed = false + // flush(): the input procedure ends the stream when it has nothing more. + private var endOfStream = false init( config: NativeAudioDecoderConfig, output: @escaping (NativeDecodedAudio) -> Void, error: @escaping (String) -> Void ) throws { - channels = Int(config.numberOfChannels) - sampleRate = config.sampleRate self.output = output self.error = error - var source = try compressedFormat(codec: config.codec, sampleRate: sampleRate, channels: channels) - framesPerPacket = Int(source.mFramesPerPacket) - var destination = floatFormat(sampleRate: sampleRate, channels: channels) + // The AudioSpecificConfig is authoritative (WebCodecs AAC registration): + // the format and cookie come from it, the config's values only without one. + var source: AudioStreamBasicDescription + var cookie: Data? + if config.codec == "aac", let description = config.description, description.size > 0 { + let esds = esdsCookie(description.toData(copyIfNeeded: true)) + source = try aacFormat(cookie: esds) + cookie = esds + } else { + source = try compressedFormat( + codec: config.codec, sampleRate: config.sampleRate, channels: Int(config.numberOfChannels)) + } + if source.mSampleRate <= 0 { source.mSampleRate = config.sampleRate } + if source.mChannelsPerFrame == 0 { source.mChannelsPerFrame = UInt32(config.numberOfChannels) } + framesPerPacket = max(Int(source.mFramesPerPacket), 1024) + var destination = floatFormat(sampleRate: source.mSampleRate, channels: Int(source.mChannelsPerFrame)) var converter: AudioConverterRef? let status = AudioConverterNew(&source, &destination, &converter) guard status == noErr, let converter else { throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))") } + if let cookie { + let status = cookie.withUnsafeBytes { + AudioConverterSetProperty( + converter, kAudioConverterDecompressionMagicCookie, UInt32($0.count), $0.baseAddress!) + } + guard status == noErr else { + AudioConverterDispose(converter) + throw WebCodecsError.notSupported("the AAC magic cookie (\(status))") + } + } + // What the converter outputs, which the AudioData say. + var current = destination + var currentSize = UInt32(MemoryLayout.size) + if AudioConverterGetProperty( + converter, kAudioConverterCurrentOutputStreamDescription, ¤tSize, ¤t) != noErr + || current.mSampleRate <= 0 || current.mChannelsPerFrame != destination.mChannelsPerFrame + { + current = destination + } + sampleRate = current.mSampleRate + channels = Int(current.mChannelsPerFrame) self.converter = converter super.init() } @@ -255,7 +345,7 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { ) -> OSStatus { guard let packet else { packets.pointee = 0 - return noMoreInputNow + return endOfStream ? noErr : noMoreInputNow } held = packet // valid until the next call self.packet = nil @@ -276,21 +366,30 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { guard converter != nil else { throw WebCodecsError.invalidState("the decoder is closed") } let bytes = data.toData(copyIfNeeded: true) queue.async { - guard !self.failed, let converter = self.converter else { return } + guard !self.failed, self.converter != nil else { return } if self.start == nil { self.start = timestamp } self.packet = bytes - let capacity = self.framesPerPacket * 2 - var samples = [Float](repeating: 0, count: capacity * self.channels) + self.pull() + } + } + + // Outputs what the converter has decoded, until it wants more input (or, + // at the end of the stream, has no more). + private func pull() { + guard let converter else { return } + let capacity = framesPerPacket * 2 + var done = false + while !done { + var samples = [Float](repeating: 0, count: capacity * channels) var total = 0 - while true { + while total < capacity { var frames = UInt32(capacity - total) - if frames == 0 { break } let status = samples.withUnsafeMutableBytes { raw -> OSStatus in var list = AudioBufferList( mNumberBuffers: 1, mBuffers: AudioBuffer( - mNumberChannels: UInt32(self.channels), mDataByteSize: UInt32(Int(frames) * 4 * self.channels), - mData: raw.baseAddress!.advanced(by: total * 4 * self.channels))) + mNumberChannels: UInt32(channels), mDataByteSize: UInt32(Int(frames) * 4 * channels), + mData: raw.baseAddress!.advanced(by: total * 4 * channels))) return AudioConverterFillComplexBuffer( converter, { _, packets, data, descriptions, user in @@ -300,21 +399,24 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { Unmanaged.passUnretained(self).toOpaque(), &frames, &list, nil) } total += Int(frames) - if status == noMoreInputNow || frames == 0 { break } + if status == noMoreInputNow || frames == 0 { + done = true + break + } if status != noErr { - self.failed = true - self.error(errorMessage("EncodingError", "audio-failed", "AudioConverter failed (\(status))")) + failed = true + error(errorMessage("EncodingError", "audio-failed", "AudioConverter failed (\(status))")) return } } if total > 0 { - let buffer = ArrayBuffer.allocate(size: total * 4 * self.channels) - samples.withUnsafeBytes { memcpy(buffer.data, $0.baseAddress!, total * 4 * self.channels) } - let ts = (self.start ?? 0) + Double(self.framesOut) * 1_000_000 / self.sampleRate - self.framesOut += Int64(total) - self.output(NativeDecodedAudio( - data: buffer, frames: Double(total), sampleRate: self.sampleRate, - numberOfChannels: Double(self.channels), timestamp: ts.rounded())) + let buffer = ArrayBuffer.allocate(size: total * 4 * channels) + samples.withUnsafeBytes { memcpy(buffer.data, $0.baseAddress!, total * 4 * channels) } + let ts = (start ?? 0) + Double(framesOut) * 1_000_000 / sampleRate + framesOut += Int64(total) + output(NativeDecodedAudio( + data: buffer, frames: Double(total), sampleRate: sampleRate, + numberOfChannels: Double(channels), timestamp: ts.rounded())) } } } @@ -322,6 +424,16 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { func flush() throws -> Promise { guard converter != nil else { return Promise.rejected(withError: WebCodecsError.invalidState("the decoder is closed")) } return Promise.parallel(queue) { + // Nothing decoded since the last flush: nothing to end. + if self.failed || self.start == nil { return } + // End the stream, for the frames the converter still holds, then start + // a new one: without a reset, the next chunk would overlap the last + // (MDCT and SBR state), as after a seek. + self.endOfStream = true + self.pull() + if let converter = self.converter { AudioConverterReset(converter) } + self.endOfStream = false + self.packet = nil // A later decode() may jump: start timing from its timestamp again. self.start = nil self.framesOut = 0 diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index f2389da..a24ba4d 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -1748,6 +1748,287 @@ describe("react-native-webcodecs + Mediabunny", () => { ); }, 180000); + // A sound made with ffmpeg here (a 440 Hz sine, at ffmpeg's level of 1/8), + // pushed to the app once. + const soundClip = (name: string, args: string[]) => { + const clip = path.join(clipDirectory, name); + fs.mkdirSync(clipDirectory, { recursive: true }); + if (!fs.existsSync(clip)) { + execFileSync("ffmpeg", ["-loglevel", "error", "-y"].concat(args, [clip])); + } + return pushFile(clip); + }; + const hasEncoder = (name: string) => + execFileSync("ffmpeg", ["-hide_banner", "-encoders"], { + encoding: "utf8", + }) + .split("\n") + .some((line) => line.trim().split(/\s+/)[1] === name); + + // Decodes a file's sound track with AudioDecoder (Mediabunny demuxes), and + // measures it: frames, format, level and pitch (from channel 0's upward + // zero crossings). + const decodeSoundOnDevice = (file: 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.getPrimaryAudioTrack().then((track: any) => + track.getDecoderConfig().then((config: any) => + wc.AudioDecoder.isConfigSupported(config).then((support: any) => { + const out: any = { + errors: [], + supported: support.supported, + config: { + codec: config.codec, + sampleRate: config.sampleRate, + numberOfChannels: config.numberOfChannels, + description: !!config.description, + }, + packets: 0, + frames: 0, + sampleRates: [], + channels: [], + }; + let sum = 0; + let count = 0; + let crossings = 0; + let previous = 0; + const decoder = new wc.AudioDecoder({ + output: (data: any) => { + out.frames += data.numberOfFrames; + if (out.sampleRates.indexOf(data.sampleRate) < 0) { + out.sampleRates.push(data.sampleRate); + } + if (out.channels.indexOf(data.numberOfChannels) < 0) { + out.channels.push(data.numberOfChannels); + } + const n = data.numberOfChannels; + const samples = new Float32Array(data.numberOfFrames * n); + data.copyTo(samples, { planeIndex: 0, format: "f32" }); + for (let i = 0; i < samples.length; i++) { + sum += samples[i] * samples[i]; + } + for (let i = 0; i < samples.length; i += n) { + if (previous <= 0 && samples[i] > 0) { + crossings++; + } + previous = samples[i]; + } + count += samples.length; + data.close(); + }, + error: (e: any) => out.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; + } + out.packets++; + decoder.decode(r.value.toEncodedAudioChunk()); + return step(); + }); + return step() + .then(() => decoder.flush()) + .then( + () => undefined, + (e: any) => out.errors.push(String(e)), + ) + .then(() => { + const rate = out.sampleRates[0] || 1; + out.rms = Math.sqrt(sum / Math.max(1, count)); + out.seconds = out.frames / rate; + out.hz = crossings / Math.max(1e-6, out.seconds); + if (decoder.state !== "closed") { + decoder.close(); + } + input.dispose(); + return out; + }); + }), + ), + ); + }, + { file }, + 120000, + ); + + // The decoded sound is ffmpeg's: as long, at its rate, as loud, at its + // pitch (garbage, or a decode at the wrong rate, is not). + const expectSine = (sound: any, o: { rate: number; channels: number }) => { + expect(sound.errors).toEqual([]); + expect(sound.sampleRates).toEqual([o.rate]); + expect(sound.channels).toEqual([o.channels]); + // 3 s, give or take the priming and the last frame's padding. + expect(sound.seconds).toBeGreaterThan(2.9); + expect(sound.seconds).toBeLessThan(3.25); + expect(sound.rms).toBeGreaterThan(0.06); + expect(sound.rms).toBeLessThan(0.12); + expect(Math.abs(sound.hz - 440)).toBeLessThan(15); + }; + + // WebCodecs: AAC without a description is ADTS, a header on every frame, + // as Mediabunny's .aac and MPEG-TS demuxers give it. + it("decodes ADTS AAC (no description)", async () => { + if (!supported() || !probes()) { + return; + } + const file = await soundClip("sine-48k.aac", [ + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=3", + "-c:a", + "aac", + "-b:a", + "96k", + "-f", + "adts", + ]); + const sound = await decodeSoundOnDevice(file); + expect(sound.config.description).toBe(false); + expect(sound.supported).toBe(true); + expectSine(sound, { rate: 48000, channels: 1 }); + // One frame of 1024 samples per packet. + expect(sound.frames).toBeGreaterThan((sound.packets - 4) * 1024); + expect(sound.frames).toBeLessThanOrEqual((sound.packets + 1) * 1024); + }, 180000); + + // HE-AAC (SBR) and HE-AAC v2 (SBR and PS) as AudioToolbox's encoder writes + // them: an AudioSpecificConfig of AAC-LC at half the rate (mono for v2), + // with the SBR and PS layers in its extension, and 2048 samples a packet. + // (macOS hosts: ffmpeg's aac_at encoder.) + for (const [name, profile, bitrate] of [ + ["HE-AAC", "4", "48k"], + ["HE-AACv2", "28", "32k"], + ]) { + it(`decodes ${name} at its full rate and channels`, async () => { + if (!supported() || !probes() || !hasEncoder("aac_at")) { + return; + } + const file = await soundClip(`sine-${name}.m4a`, [ + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=44100:duration=3", + "-ac", + "2", + "-c:a", + "aac_at", + "-profile:a", + profile, + "-b:a", + bitrate, + ]); + const sound = await decodeSoundOnDevice(file); + expect(sound.supported).toBe(true); + expectSine(sound, { rate: 44100, channels: 2 }); + expect(sound.frames).toBeGreaterThan((sound.packets - 4) * 2048); + expect(sound.frames).toBeLessThanOrEqual((sound.packets + 1) * 2048); + }, 180000); + } + + // flush() ends the stream and starts a new one: what is decoded after it + // does not overlap the sound before it. A tone, then digital silence: + // decoding the tone, a flush, then the silence must give silence. (iOS: + // Android's MediaCodec flush is its own, and out of scope here.) + it("starts an AudioDecoder over after a flush (iOS)", async () => { + if (!ios() || !probes()) { + return; + } + const file = await soundClip("tone-then-silence.m4a", [ + "-f", + "lavfi", + "-i", + "sine=frequency=440:sample_rate=48000:duration=4", + "-af", + "volume=volume=0:enable='gte(t,2)'", + "-c:a", + "aac", + "-b:a", + "128k", + ]); + 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 all: any[] = []; + const packets = new mb.EncodedPacketSink(track).packets(); + const read = (): Promise => + packets.next().then((r: any) => { + if (r.done) { + return undefined; + } + all.push(r.value); + return read(); + }); + const errors: string[] = []; + let samples: number[] = []; + const decoder = new wc.AudioDecoder({ + output: (data: any) => { + const n = data.numberOfFrames * data.numberOfChannels; + const buffer = new Float32Array(n); + data.copyTo(buffer, { planeIndex: 0, format: "f32" }); + for (let i = 0; i < n; i++) { + samples.push(buffer[i]); + } + data.close(); + }, + error: (e: any) => errors.push(String(e)), + }); + decoder.configure(config); + // The level of the first `count` samples. + const rms = (from: number[], count: number) => { + let sum = 0; + const n = Math.min(from.length, count); + for (let i = 0; i < n; i++) { + sum += from[i] * from[i]; + } + return Math.sqrt(sum / Math.max(1, n)); + }; + const decodeRange = (start: number, end: number) => { + all + .filter((p: any) => p.timestamp >= start && p.timestamp < end) + .forEach((p: any) => decoder.decode(p.toEncodedAudioChunk())); + return decoder.flush(); + }; + const out: any = { errors }; + return read() + .then(() => decodeRange(-1, 1.5)) + .then(() => { + out.tone = rms(samples, samples.length); + samples = []; + return decodeRange(3, 3.5); + }) + .then(() => { + out.samples = samples.length; + out.after = rms(samples, 1024); + decoder.close(); + input.dispose(); + return out; + }); + }), + ); + }, + { file }, + 120000, + ); + expect(result.errors).toEqual([]); + expect(result.tone).toBeGreaterThan(0.05); + expect(result.samples).toBeGreaterThan(0); + // Not the tone's last frame overlapping the first of the silence. + expect(result.after).toBeLessThan(0.001); + }, 180000); + it("flushes a VideoEncoder given two frames with one timestamp", async () => { if (!supported()) { return; diff --git a/src/__tests__/unit/codecs.test.ts b/src/__tests__/unit/codecs.test.ts index c6083da..a55cd7b 100644 --- a/src/__tests__/unit/codecs.test.ts +++ b/src/__tests__/unit/codecs.test.ts @@ -3,6 +3,7 @@ // and frames the codec never returns. import { AudioData, AudioDecoder, AudioEncoder } from "../../lib/audio"; import { + EncodedAudioChunk, EncodedVideoChunk, VideoDecoder, VideoEncoder, @@ -71,10 +72,10 @@ const mockNative = { e: (m: string) => void, ) => fakeCodec(o, e), createAudioDecoder: ( - _c: unknown, + c: unknown, o: Output, e: (m: string) => void, - ) => fakeCodec(o, e), + ) => fakeCodec(o, e, c), }; jest.mock("react-native-nitro-modules", () => ({ @@ -464,4 +465,62 @@ describe("AudioDecoder", () => { }); expect(output).not.toHaveBeenCalled(); }); + + // AAC without a description is ADTS: the native decoders get the + // AudioSpecificConfig and each raw raw, without its header. + it("decodes ADTS as an AudioSpecificConfig and raw frames", () => { + const decoder = new AudioDecoder({ output: jest.fn(), error: jest.fn() }); + decoder.configure({ + codec: "mp4a.40.2", + sampleRate: 48_000, + numberOfChannels: 1, + }); + const codec = last(); + const { description } = codec.config as { description?: ArrayBuffer }; + // AAC-LC (2), 48 kHz (index 3), mono. + expect(Array.from(new Uint8Array(description!))).toEqual([0x11, 0x88]); + // A 7-byte header (protection_absent) and one with a CRC (9 bytes). + const raw = [0x21, 0x10, 0x05]; + const plain = [0xff, 0xf1, 0x4c, 0x40, 0x01, 0x5f, 0xfc]; + const crc = [0xff, 0xf0, 0x4c, 0x40, 0x01, 0x9f, 0xfc, 0x12, 0x34]; + for (const header of [plain, crc]) { + decoder.decode( + new EncodedAudioChunk({ + type: "key", + timestamp: 0, + data: new Uint8Array(header.concat(raw)), + }), + ); + } + // A chunk without the sync word goes through as it is. + decoder.decode( + new EncodedAudioChunk({ + type: "key", + timestamp: 0, + data: new Uint8Array(raw), + }), + ); + const sent = codec.decode.mock.calls.map((c) => + Array.from(new Uint8Array(c[0] as ArrayBuffer)), + ); + expect(sent).toEqual([raw, raw, raw]); + }); + + it("passes the description and HE-AAC codec strings to native", () => { + const decoder = new AudioDecoder({ output: jest.fn(), error: jest.fn() }); + decoder.configure({ + codec: "mp4a.40.5", + sampleRate: 44_100, + numberOfChannels: 2, + description: new Uint8Array([0x13, 0x90, 0x56, 0xe5, 0xa0]), + }); + const { codec, description } = last().config as { + codec: string; + description?: ArrayBuffer; + }; + expect(codec).toBe("aac"); + expect(Array.from(new Uint8Array(description!))).toEqual([ + 0x13, 0x90, 0x56, 0xe5, 0xa0, + ]); + }); }); diff --git a/src/lib/audio.ts b/src/lib/audio.ts index 3ca6bbe..1a87358 100644 --- a/src/lib/audio.ts +++ b/src/lib/audio.ts @@ -384,18 +384,67 @@ export interface AudioDecoderConfig { [key: string]: unknown; } +// The decoders also take HE-AAC and HE-AAC v2 (the encoder makes AAC-LC). +const audioDecoderCodec = (c: string) => + /^mp4a\.40\.(0?5|29)$/.test(c) ? "aac" : audioCodec(c); + +const AAC_RATES = [ + 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, + 8000, 7350, +]; + +// AAC without a description is ADTS (WebCodecs AAC registration): a header +// on each frame and no AudioSpecificConfig, which the platform decoders need +// instead. This is the AAC-LC one for the config (what an ADTS header says, +// HE-AAC there being implicit), or undefined when there is none. +const adtsConfig = (sampleRate: number, channels: number) => { + const index = AAC_RATES.indexOf(sampleRate); + const layout = channels === 8 ? 7 : channels; + if (index < 0 || layout < 1 || layout > 7) { + return undefined; + } + return new Uint8Array([ + (2 << 3) | (index >> 1), + ((index & 1) << 7) | (layout << 3), + ]).buffer; +}; + +// The ADTS header's size, 9 bytes with a CRC: 0 when the chunk does not start +// with one (sync word, layer 0). +const adtsHeaderSize = (b: Uint8Array) => { + const size = b[1] & 1 ? 7 : 9; + return b.length >= size && b[0] === 0xff && (b[1] & 0xf6) === 0xf0 ? size : 0; +}; + +// The description native gets: the config's, or the ADTS one; null when an +// ADTS config has none. +const decoderDescription = (codec: string, config: AudioDecoderConfig) => { + if (config.description) { + return toArrayBuffer(config.description); + } + if (codec !== "aac") { + return undefined; + } + return adtsConfig(config.sampleRate, config.numberOfChannels) ?? null; +}; + export class AudioDecoder extends CodecBase { _output: (data: AudioData) => void; _decoder: NativeAudioDecoder | null = null; + // ADTS: headers are stripped from the chunks. + _adts = false; static async isConfigSupported(config: AudioDecoderConfig) { - const codec = audioCodec(config.codec); + const codec = audioDecoderCodec(config.codec); + const description = codec ? decoderDescription(codec, config) : null; const supported = codec !== null && + description !== null && native().isAudioDecoderConfigSupported({ codec, sampleRate: config.sampleRate, numberOfChannels: config.numberOfChannels, + description, }); return { supported, @@ -419,23 +468,28 @@ export class AudioDecoder extends CodecBase { if (this._state === "closed") { throw domError("InvalidStateError", "AudioDecoder is closed"); } - const codec = audioCodec(config.codec); - if (!codec) { + const codec = audioDecoderCodec(config.codec); + const description = codec ? decoderDescription(codec, config) : null; + if (!codec || description === null) { this._fail( - domError("NotSupportedError", `Unsupported codec ${config.codec}`), + domError( + "NotSupportedError", + codec + ? "Unsupported ADTS sample rate or channels" + : `Unsupported codec ${config.codec}`, + ), ); return; } this._replaceNative(); + this._adts = codec === "aac" && !config.description; try { this._decoder = native().createAudioDecoder( { codec, sampleRate: config.sampleRate, numberOfChannels: config.numberOfChannels, - description: config.description - ? toArrayBuffer(config.description) - : undefined, + description, }, this._bind((data: NativeDecodedAudio) => this._onData(data)), this._bind((message: string) => this._fail(nativeError(message))), @@ -449,9 +503,10 @@ export class AudioDecoder extends CodecBase { decode(chunk: EncodedAudioChunk) { this._assertConfigured(); + const header = this._adts ? adtsHeaderSize(chunk._data) : 0; try { this._decoder!.decode( - toArrayBuffer(chunk._data), + toArrayBuffer(header ? chunk._data.subarray(header) : chunk._data), chunk.timestamp, chunk.duration ?? 0, ); From c6a4a1b189c7365945c27c46e75ff9b9361c27fd Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:55:25 +0200 Subject: [PATCH 06/10] test: decode the range test's stream as limited range, so the RGB retag shows --- src/__tests__/WebCodecs.spec.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index 8509bae..8c4d3e7 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -1742,7 +1742,14 @@ describe("react-native-webcodecs + Mediabunny", () => { }, error: (e: any) => errors.push(`decoder: ${e}`), }); - decoder.configure(decoderConfig); + // Said limited explicitly, so that RGB frames show their own tag. + decoder.configure( + Object.assign({}, decoderConfig, { + colorSpace: Object.assign({}, decoderConfig.colorSpace, { + fullRange: false, + }), + }), + ); chunks.forEach((chunk) => decoder.decode(chunk)); return decoder.flush().then(() => decoder.close()); }) From 7d2c30cf91bf4385a70b394e441c29662a92f905 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 08:58:18 +0200 Subject: [PATCH 07/10] test(audio): measure the decoded sine's pitch between its first and last swings; no ADTS config for 7 channels --- src/__tests__/WebCodecs.spec.ts | 29 +++++++++++++++++++++-------- src/lib/audio.ts | 3 ++- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index a24ba4d..ceb7fed 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -1767,7 +1767,8 @@ describe("react-native-webcodecs + Mediabunny", () => { // Decodes a file's sound track with AudioDecoder (Mediabunny demuxes), and // measures it: frames, format, level and pitch (from channel 0's upward - // zero crossings). + // swings through zero, between the first and the last, so priming and + // padding do not count). const decodeSoundOnDevice = (file: string) => runOnDevice( ({ mediabunny: mb, webcodecs: wc, ctx }) => { @@ -1795,7 +1796,10 @@ describe("react-native-webcodecs + Mediabunny", () => { let sum = 0; let count = 0; let crossings = 0; - let previous = 0; + let below = false; + let first = -1; + let lastCrossing = -1; + let index = 0; const decoder = new wc.AudioDecoder({ output: (data: any) => { out.frames += data.numberOfFrames; @@ -1811,11 +1815,17 @@ describe("react-native-webcodecs + Mediabunny", () => { for (let i = 0; i < samples.length; i++) { sum += samples[i] * samples[i]; } - for (let i = 0; i < samples.length; i += n) { - if (previous <= 0 && samples[i] > 0) { + for (let i = 0; i < samples.length; i += n, index++) { + if (samples[i] < -0.01) { + below = true; + } else if (below && samples[i] > 0.01) { + below = false; crossings++; + if (first < 0) { + first = index; + } + lastCrossing = index; } - previous = samples[i]; } count += samples.length; data.close(); @@ -1843,7 +1853,9 @@ describe("react-native-webcodecs + Mediabunny", () => { const rate = out.sampleRates[0] || 1; out.rms = Math.sqrt(sum / Math.max(1, count)); out.seconds = out.frames / rate; - out.hz = crossings / Math.max(1e-6, out.seconds); + out.hz = + ((crossings - 1) * rate) / + Math.max(1, lastCrossing - first); if (decoder.state !== "closed") { decoder.close(); } @@ -1866,8 +1878,9 @@ describe("react-native-webcodecs + Mediabunny", () => { expect(sound.channels).toEqual([o.channels]); // 3 s, give or take the priming and the last frame's padding. expect(sound.seconds).toBeGreaterThan(2.9); - expect(sound.seconds).toBeLessThan(3.25); - expect(sound.rms).toBeGreaterThan(0.06); + expect(sound.seconds).toBeLessThan(3.3); + // 1/8 (0.088), or 3 dB below for a mono sine made stereo. + expect(sound.rms).toBeGreaterThan(0.04); expect(sound.rms).toBeLessThan(0.12); expect(Math.abs(sound.hz - 440)).toBeLessThan(15); }; diff --git a/src/lib/audio.ts b/src/lib/audio.ts index 1a87358..7269f1a 100644 --- a/src/lib/audio.ts +++ b/src/lib/audio.ts @@ -399,8 +399,9 @@ const AAC_RATES = [ // HE-AAC there being implicit), or undefined when there is none. const adtsConfig = (sampleRate: number, channels: number) => { const index = AAC_RATES.indexOf(sampleRate); + // channelConfiguration 7 is 8 channels; there is none for 7. const layout = channels === 8 ? 7 : channels; - if (index < 0 || layout < 1 || layout > 7) { + if (index < 0 || channels < 1 || channels > 8 || channels === 7) { return undefined; } return new Uint8Array([ From c03fe91e4440a19221e0e384141b41f9aa6940d5 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 09:24:33 +0200 Subject: [PATCH 08/10] test: on Android, check only that every frame of a GOP that goes back in time comes out The emulator's c2 decoders put the earlier GOP out in decode order and hold the later GOP's last frames until the end of the stream; iOS keeps the strict order check. --- src/__tests__/WebCodecs.spec.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index 5d8fdd3..cc2beb3 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -4100,6 +4100,16 @@ describe("react-native-webcodecs + Mediabunny", () => { } const times = (gop: number) => sorted(gopOf(decoded.packets, gop).map((p) => p.timestamp)); + if (!ios()) { + // Android (c2 decoders on the emulator) puts out the first GOP in + // decode order and holds the second GOP's last frames until the + // end of the stream; every frame still comes out, once. + expect(decoded.errors).toEqual([]); + expect(sorted(decoded.runs[0])).toEqual( + sorted(times(1).concat(times(0))), + ); + return; + } expect({ errors: decoded.errors, frames: decoded.runs[0] }).toEqual({ errors: [], frames: times(1).concat(times(0)), From 9cb6fd48e02805cb70a99086322a87e818076ea7 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 10:20:29 +0200 Subject: [PATCH 09/10] fix(ios): start an AudioDecoder over on flush with a new AudioConverter After the end of the stream, a reset AudioConverter put out no more audio on the CI Simulator, so the decode after a flush gave no samples. flush() now makes a new converter from the same formats and magic cookie. --- ios/Audio.swift | 62 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 45 insertions(+), 17 deletions(-) diff --git a/ios/Audio.swift b/ios/Audio.swift index 35f73b5..8a6415b 100644 --- a/ios/Audio.swift +++ b/ios/Audio.swift @@ -281,6 +281,33 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { private var failed = false // flush(): the input procedure ends the stream when it has nothing more. private var endOfStream = false + // What flush() makes a new converter from. + private let sourceFormat: AudioStreamBasicDescription + private let destinationFormat: AudioStreamBasicDescription + private let cookie: Data? + + private static func makeConverter( + _ source: AudioStreamBasicDescription, _ destination: AudioStreamBasicDescription, _ cookie: Data? + ) throws -> AudioConverterRef { + var source = source + var destination = destination + var converter: AudioConverterRef? + let status = AudioConverterNew(&source, &destination, &converter) + guard status == noErr, let converter else { + throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))") + } + if let cookie { + let status = cookie.withUnsafeBytes { + AudioConverterSetProperty( + converter, kAudioConverterDecompressionMagicCookie, UInt32($0.count), $0.baseAddress!) + } + guard status == noErr else { + AudioConverterDispose(converter) + throw WebCodecsError.notSupported("the AAC magic cookie (\(status))") + } + } + return converter + } init( config: NativeAudioDecoderConfig, @@ -304,22 +331,11 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { if source.mSampleRate <= 0 { source.mSampleRate = config.sampleRate } if source.mChannelsPerFrame == 0 { source.mChannelsPerFrame = UInt32(config.numberOfChannels) } framesPerPacket = max(Int(source.mFramesPerPacket), 1024) - var destination = floatFormat(sampleRate: source.mSampleRate, channels: Int(source.mChannelsPerFrame)) - var converter: AudioConverterRef? - let status = AudioConverterNew(&source, &destination, &converter) - guard status == noErr, let converter else { - throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))") - } - if let cookie { - let status = cookie.withUnsafeBytes { - AudioConverterSetProperty( - converter, kAudioConverterDecompressionMagicCookie, UInt32($0.count), $0.baseAddress!) - } - guard status == noErr else { - AudioConverterDispose(converter) - throw WebCodecsError.notSupported("the AAC magic cookie (\(status))") - } - } + let destination = floatFormat(sampleRate: source.mSampleRate, channels: Int(source.mChannelsPerFrame)) + sourceFormat = source + destinationFormat = destination + self.cookie = cookie + let converter = try HybridNativeAudioDecoder.makeConverter(source, destination, cookie) // What the converter outputs, which the AudioData say. var current = destination var currentSize = UInt32(MemoryLayout.size) @@ -431,7 +447,19 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { // (MDCT and SBR state), as after a seek. self.endOfStream = true self.pull() - if let converter = self.converter { AudioConverterReset(converter) } + // A new converter, not AudioConverterReset: after the end of the + // stream, a reset converter put out nothing more on the CI Simulator. + if let old = self.converter { + do { + self.converter = try HybridNativeAudioDecoder.makeConverter( + self.sourceFormat, self.destinationFormat, self.cookie) + } catch { + self.failed = true + self.error(errorMessage("EncodingError", "audio-failed", "\(error)")) + return + } + AudioConverterDispose(old) + } self.endOfStream = false self.packet = nil // A later decode() may jump: start timing from its timestamp again. From f704f4311a9fb303be1ee4a63ec7f8319e65ab03 Mon Sep 17 00:00:00 2001 From: Andrei Alecu Date: Wed, 25 Nov 2026 10:42:34 +0200 Subject: [PATCH 10/10] refactor(ios): share converter setup and stream ending, reuse decode scratch - Audio: makeConverter moves to file scope, and the AudioEncoder uses it instead of its own AudioConverterNew call. - Audio: the AudioDecoder's pull() allocates its sample buffer once per call rather than once per pass of the drain loop. - VideoDecoder: flush() and a key frame that goes back in time share one endStream() helper. - VideoDecoder: the HEVC NAL length size comes from the format description VideoToolbox made of the hvcC record, rather than reading the record a second time. --- ios/Audio.swift | 64 ++++++++++++++++++++---------------------- ios/VideoDecoder.swift | 32 +++++++++++++-------- 2 files changed, 52 insertions(+), 44 deletions(-) diff --git a/ios/Audio.swift b/ios/Audio.swift index 8a6415b..123c1d1 100644 --- a/ios/Audio.swift +++ b/ios/Audio.swift @@ -27,6 +27,30 @@ private func floatFormat(sampleRate: Double, channels: Int) -> AudioStreamBasicD mChannelsPerFrame: UInt32(channels), mBitsPerChannel: 32, mReserved: 0) } +// A converter between two formats, with the decoder's magic cookie if any. +private func makeConverter( + _ source: AudioStreamBasicDescription, _ destination: AudioStreamBasicDescription, _ cookie: Data? +) throws -> AudioConverterRef { + var source = source + var destination = destination + var converter: AudioConverterRef? + let status = AudioConverterNew(&source, &destination, &converter) + guard status == noErr, let converter else { + throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))") + } + if let cookie { + let status = cookie.withUnsafeBytes { + AudioConverterSetProperty( + converter, kAudioConverterDecompressionMagicCookie, UInt32($0.count), $0.baseAddress!) + } + guard status == noErr else { + AudioConverterDispose(converter) + throw WebCodecsError.notSupported("the AAC magic cookie (\(status))") + } + } + return converter +} + private func compressedFormat(codec: String, sampleRate: Double, channels: Int) throws -> AudioStreamBasicDescription { @@ -135,13 +159,9 @@ final class HybridNativeAudioEncoder: HybridNativeAudioEncoderSpec { else { throw WebCodecsError.notSupported("AAC-LC, 1 or 2 channels, at a standard sample rate") } - var source = floatFormat(sampleRate: sampleRate, channels: channels) - var destination = try compressedFormat(codec: "aac", sampleRate: sampleRate, channels: channels) - var converter: AudioConverterRef? - let status = AudioConverterNew(&source, &destination, &converter) - guard status == noErr, let converter else { - throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))") - } + let converter = try makeConverter( + floatFormat(sampleRate: sampleRate, channels: channels), + compressedFormat(codec: "aac", sampleRate: sampleRate, channels: channels), nil) self.converter = converter if let bitrate = config.bitrate, bitrate > 0 { var rate = UInt32(bitrate) @@ -286,29 +306,6 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { private let destinationFormat: AudioStreamBasicDescription private let cookie: Data? - private static func makeConverter( - _ source: AudioStreamBasicDescription, _ destination: AudioStreamBasicDescription, _ cookie: Data? - ) throws -> AudioConverterRef { - var source = source - var destination = destination - var converter: AudioConverterRef? - let status = AudioConverterNew(&source, &destination, &converter) - guard status == noErr, let converter else { - throw WebCodecsError.notSupported("AudioConverterNew failed (\(status))") - } - if let cookie { - let status = cookie.withUnsafeBytes { - AudioConverterSetProperty( - converter, kAudioConverterDecompressionMagicCookie, UInt32($0.count), $0.baseAddress!) - } - guard status == noErr else { - AudioConverterDispose(converter) - throw WebCodecsError.notSupported("the AAC magic cookie (\(status))") - } - } - return converter - } - init( config: NativeAudioDecoderConfig, output: @escaping (NativeDecodedAudio) -> Void, @@ -335,7 +332,7 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { sourceFormat = source destinationFormat = destination self.cookie = cookie - let converter = try HybridNativeAudioDecoder.makeConverter(source, destination, cookie) + let converter = try makeConverter(source, destination, cookie) // What the converter outputs, which the AudioData say. var current = destination var currentSize = UInt32(MemoryLayout.size) @@ -394,9 +391,10 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { private func pull() { guard let converter else { return } let capacity = framesPerPacket * 2 + // Scratch space for each pass, copied out before the next. + var samples = [Float](repeating: 0, count: capacity * channels) var done = false while !done { - var samples = [Float](repeating: 0, count: capacity * channels) var total = 0 while total < capacity { var frames = UInt32(capacity - total) @@ -451,7 +449,7 @@ final class HybridNativeAudioDecoder: HybridNativeAudioDecoderSpec { // stream, a reset converter put out nothing more on the CI Simulator. if let old = self.converter { do { - self.converter = try HybridNativeAudioDecoder.makeConverter( + self.converter = try makeConverter( self.sourceFormat, self.destinationFormat, self.cookie) } catch { self.failed = true diff --git a/ios/VideoDecoder.swift b/ios/VideoDecoder.swift index e03e792..0b5422a 100644 --- a/ios/VideoDecoder.swift +++ b/ios/VideoDecoder.swift @@ -297,9 +297,16 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { let base = ReorderDepth.of(config) baseDepth = base depth = base - if config.codec == "hevc", let description = config.description { - let record = [UInt8](description.toData(copyIfNeeded: true)) - hevcNalLength = record.count > 22 ? Int(record[21] & 0x3) + 1 : nil + // From the format VideoToolbox made of the hvcC record, rather than + // reading the record a second time. + var nalLength: Int32 = 0 + if CMFormatDescriptionGetMediaSubType(format) == kCMVideoCodecType_HEVC, + CMVideoFormatDescriptionGetHEVCParameterSetAtIndex( + format, parameterSetIndex: 0, parameterSetPointerOut: nil, parameterSetSizeOut: nil, + parameterSetCountOut: nil, nalUnitHeaderLengthOut: &nalLength) == noErr, + nalLength > 0 + { + hevcNalLength = Int(nalLength) } else { hevcNalLength = nil } @@ -449,6 +456,15 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { output(frame) } + // On `queue`: the frames VideoToolbox still has, then those held for + // reordering, go out, and what follows starts a new stream. + private func endStream(_ session: VTDecompressionSession) { + VTDecompressionSessionFinishDelayedFrames(session) + VTDecompressionSessionWaitForAsynchronousFrames(session) + if !failed { drainHeld() } + restart() + } + private func drainHeld() { reorder.lock() defer { reorder.unlock() } @@ -466,10 +482,7 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { // new stream. The frames held for reordering go out first, rather // than being sorted in with the new stream's. if key && timestamp < self.lastIn { - VTDecompressionSessionFinishDelayedFrames(session) - VTDecompressionSessionWaitForAsynchronousFrames(session) - if !self.failed { self.drainHeld() } - self.restart() + self.endStream(session) } self.lastIn = max(self.lastIn, timestamp) let first = key && self.start @@ -552,11 +565,8 @@ final class HybridNativeVideoDecoder: HybridNativeVideoDecoderSpec { func flush() throws -> Promise { guard let session else { return Promise.rejected(withError: WebCodecsError.invalidState("the decoder is closed")) } 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.restart() + self.endStream(session) } }