diff --git a/android/src/main/cpp/VideoDecoder.hpp b/android/src/main/cpp/VideoDecoder.hpp index ba9cc61..c976ac6 100644 --- a/android/src/main/cpp/VideoDecoder.hpp +++ b/android/src/main/cpp/VideoDecoder.hpp @@ -11,6 +11,7 @@ #include #include "HybridNativeVideoDecoderSpec.hpp" +#include "NativeColorSpace.hpp" #include "NativeDecodedFrame.hpp" #include "Capabilities.hpp" #include "NativeVideoDecoderConfig.hpp" @@ -19,6 +20,59 @@ namespace margelo::nitro::webcodecs { +// MediaFormat's color aspects (KEY_COLOR_STANDARD, _TRANSFER, _RANGE) as a +// WebCodecs color space. 0 (unspecified) and values WebCodecs has no name for +// leave the member out. SDR video's transfer is BT.601's or BT.709's curve, +// the same one, named after the standard. +inline NativeColorSpace colorSpaceOf(int32_t standard, int32_t transfer, int32_t range) { + NativeColorSpace colorSpace; + bool bt601 = false; + switch (standard) { + case 1: // BT.709 + colorSpace.primaries = "bt709"; + colorSpace.matrix = "bt709"; + break; + case 2: // BT.601 625 (PAL) + case 3: // BT.601 625, unadjusted + colorSpace.primaries = "bt470bg"; + colorSpace.matrix = "bt470bg"; + bt601 = true; + break; + case 4: // BT.601 525 (NTSC) + case 5: // BT.601 525, unadjusted + colorSpace.primaries = "smpte170m"; + colorSpace.matrix = "smpte170m"; + bt601 = true; + break; + case 6: // BT.2020 + colorSpace.primaries = "bt2020"; + colorSpace.matrix = "bt2020-ncl"; + break; + default: + break; + } + switch (transfer) { + case 1: + colorSpace.transfer = "linear"; + break; + case 3: // SDR video + colorSpace.transfer = bt601 ? "smpte170m" : "bt709"; + break; + case 6: + colorSpace.transfer = "pq"; + break; + case 7: + colorSpace.transfer = "hlg"; + break; + default: + break; + } + if (range == 1 || range == 2) { + colorSpace.fullRange = range == 1; + } + return colorSpace; +} + struct ReaderOwner { AImageReader* reader; explicit ReaderOwner(AImageReader* reader) : reader(reader) {} @@ -361,8 +415,11 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { while (draining()) { AMediaCodecBufferInfo info{}; ssize_t index = AMediaCodec_dequeueOutputBuffer(_codec, &info, 10000); - if (index == AMEDIACODEC_INFO_TRY_AGAIN_LATER || index == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED || - index == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { + if (index == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { + readColorSpace(); + continue; + } + if (index == AMEDIACODEC_INFO_TRY_AGAIN_LATER || index == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) { continue; } if (isCodecError(index)) { @@ -486,10 +543,35 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { // 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)); + std::optional colorSpace; + { + std::lock_guard lock(_mutex); + colorSpace = _colorSpace; + } + _output(NativeDecodedFrame(surface, static_cast(pts), duration, colorSpace)); countDelivered(); } + // On the drain thread: the color space of the pictures to come, from the + // output format's color aspects (the stream's VUI). Pictures come out after + // the format change that describes them. + void readColorSpace() { + AMediaFormat* format = AMediaCodec_getOutputFormat(_codec); + if (!format) { + return; + } + int32_t standard = 0; + int32_t transfer = 0; + int32_t range = 0; + AMediaFormat_getInt32(format, "color-standard", &standard); + AMediaFormat_getInt32(format, "color-transfer", &transfer); + AMediaFormat_getInt32(format, "color-range", &range); + AMediaFormat_delete(format); + auto colorSpace = colorSpaceOf(standard, transfer, range); + std::lock_guard lock(_mutex); + _colorSpace = colorSpace; + } + double takeDuration(int64_t ts) { std::lock_guard lock(_mutex); auto it = _durations.find(ts); @@ -576,6 +658,8 @@ class HybridNativeVideoDecoder : public HybridNativeVideoDecoderSpec { std::mutex _mutex; std::condition_variable _cv; std::map _durations; + // The stream's color space, as the decoder last reported it. + std::optional _colorSpace; int64_t _rendered = 0; int64_t _delivered = 0; int64_t _acquired = 0; diff --git a/docs/guides.md b/docs/guides.md index 0d10298..107f5c8 100644 --- a/docs/guides.md +++ b/docs/guides.md @@ -160,8 +160,9 @@ frame.close(); | 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 -their own, so pass it to `createNativeBufferFromPointer`: without it, +track's to `configure`; on Android, what the config leaves out is what the +decoder reads in the stream). Android's buffers carry no color information +of their own, so pass it to `createNativeBufferFromPointer`: without it, BT.709 video is read with the BT.601 matrix, and pure red comes out as (225, 0, 31). The option takes react-native-webgpu 0.26.0 or later, and names color spaces as Dawn does (`"rec709"`, `range: "narrow"`), not as diff --git a/ios/VideoDecoder.swift b/ios/VideoDecoder.swift index 0b5422a..77f1ae5 100644 --- a/ios/VideoDecoder.swift +++ b/ios/VideoDecoder.swift @@ -554,7 +554,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.hold(NativeDecodedFrame(surface: HybridNativeSurface(pixelBuffer: imageBuffer), timestamp: ts, duration: d)) + self.hold(NativeDecodedFrame(surface: HybridNativeSurface(pixelBuffer: imageBuffer), timestamp: ts, duration: d, colorSpace: nil)) } if status != noErr && status != kVTVideoDecoderReferenceMissingErr { self.fail(HybridNativeVideoEncoder.describe(status).replacingOccurrences(of: "encoder", with: "decoder")) diff --git a/nitrogen/generated/ios/NitroWebCodecs-Swift-Cxx-Bridge.hpp b/nitrogen/generated/ios/NitroWebCodecs-Swift-Cxx-Bridge.hpp index e98be43..a923986 100644 --- a/nitrogen/generated/ios/NitroWebCodecs-Swift-Cxx-Bridge.hpp +++ b/nitrogen/generated/ios/NitroWebCodecs-Swift-Cxx-Bridge.hpp @@ -26,6 +26,8 @@ namespace margelo::nitro::webcodecs { class HybridNativeVideoDecoderSpec; } namespace margelo::nitro::webcodecs { class HybridNativeVideoEncoderSpec; } // Forward declaration of `HybridWebCodecsSpec` to properly resolve imports. namespace margelo::nitro::webcodecs { class HybridWebCodecsSpec; } +// Forward declaration of `NativeColorSpace` to properly resolve imports. +namespace margelo::nitro::webcodecs { struct NativeColorSpace; } // Forward declaration of `NativeDecodedAudio` to properly resolve imports. namespace margelo::nitro::webcodecs { struct NativeDecodedAudio; } // Forward declaration of `NativeDecodedFrame` to properly resolve imports. @@ -60,6 +62,7 @@ namespace NitroWebCodecs { class HybridWebCodecsSpec_cxx; } #include "HybridNativeVideoDecoderSpec.hpp" #include "HybridNativeVideoEncoderSpec.hpp" #include "HybridWebCodecsSpec.hpp" +#include "NativeColorSpace.hpp" #include "NativeDecodedAudio.hpp" #include "NativeDecodedFrame.hpp" #include "NativeEncodedChunk.hpp" @@ -394,6 +397,21 @@ namespace margelo::nitro::webcodecs::bridge::swift { return Func_void_std__string_Wrapper(std::move(value)); } + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_NativeColorSpace_ = std::optional; + inline std::optional create_std__optional_NativeColorSpace_(const NativeColorSpace& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_NativeColorSpace_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline NativeColorSpace get_std__optional_NativeColorSpace_(const std::optional& optional) noexcept { + return optional.value(); + } + // pragma MARK: std::function /** * Specialized version of `std::function`. diff --git a/nitrogen/generated/ios/c++/HybridWebCodecsSpecSwift.hpp b/nitrogen/generated/ios/c++/HybridWebCodecsSpecSwift.hpp index c7a18cf..39d94e1 100644 --- a/nitrogen/generated/ios/c++/HybridWebCodecsSpecSwift.hpp +++ b/nitrogen/generated/ios/c++/HybridWebCodecsSpecSwift.hpp @@ -30,6 +30,8 @@ namespace margelo::nitro::webcodecs { struct NativeVideoDecoderConfig; } namespace margelo::nitro::webcodecs { class HybridNativeVideoDecoderSpec; } // Forward declaration of `NativeDecodedFrame` to properly resolve imports. namespace margelo::nitro::webcodecs { struct NativeDecodedFrame; } +// Forward declaration of `NativeColorSpace` to properly resolve imports. +namespace margelo::nitro::webcodecs { struct NativeColorSpace; } // Forward declaration of `NativeAudioEncoderConfig` to properly resolve imports. namespace margelo::nitro::webcodecs { struct NativeAudioEncoderConfig; } // Forward declaration of `HybridNativeAudioEncoderSpec` to properly resolve imports. @@ -57,6 +59,7 @@ namespace margelo::nitro::webcodecs { class HybridNativeFileSpec; } #include "NativeVideoDecoderConfig.hpp" #include "HybridNativeVideoDecoderSpec.hpp" #include "NativeDecodedFrame.hpp" +#include "NativeColorSpace.hpp" #include "NativeAudioEncoderConfig.hpp" #include "HybridNativeAudioEncoderSpec.hpp" #include "NativeAudioDecoderConfig.hpp" diff --git a/nitrogen/generated/ios/swift/NativeDecodedFrame.swift b/nitrogen/generated/ios/swift/NativeDecodedFrame.swift index 2e590e6..fc9c3b2 100644 --- a/nitrogen/generated/ios/swift/NativeDecodedFrame.swift +++ b/nitrogen/generated/ios/swift/NativeDecodedFrame.swift @@ -18,11 +18,17 @@ public extension NativeDecodedFrame { /** * Create a new instance of `NativeDecodedFrame`. */ - init(surface: (any HybridNativeSurfaceSpec), timestamp: Double, duration: Double) { + init(surface: (any HybridNativeSurfaceSpec), timestamp: Double, duration: Double, colorSpace: NativeColorSpace?) { self.init({ () -> bridge.std__shared_ptr_HybridNativeSurfaceSpec_ in let __cxxWrapped = surface.getCxxWrapper() return __cxxWrapped.getCxxPart() - }(), timestamp, duration) + }(), timestamp, duration, { () -> bridge.std__optional_NativeColorSpace_ in + if let __unwrappedValue = colorSpace { + return bridge.create_std__optional_NativeColorSpace_(__unwrappedValue) + } else { + return .init() + } + }()) } @inline(__always) @@ -43,4 +49,9 @@ public extension NativeDecodedFrame { var duration: Double { return self.__duration } + + @inline(__always) + var colorSpace: NativeColorSpace? { + return self.__colorSpace.value + } } diff --git a/nitrogen/generated/shared/c++/NativeDecodedFrame.hpp b/nitrogen/generated/shared/c++/NativeDecodedFrame.hpp index 365221d..bcf27eb 100644 --- a/nitrogen/generated/shared/c++/NativeDecodedFrame.hpp +++ b/nitrogen/generated/shared/c++/NativeDecodedFrame.hpp @@ -30,9 +30,13 @@ // Forward declaration of `HybridNativeSurfaceSpec` to properly resolve imports. namespace margelo::nitro::webcodecs { class HybridNativeSurfaceSpec; } +// Forward declaration of `NativeColorSpace` to properly resolve imports. +namespace margelo::nitro::webcodecs { struct NativeColorSpace; } #include #include "HybridNativeSurfaceSpec.hpp" +#include "NativeColorSpace.hpp" +#include namespace margelo::nitro::webcodecs { @@ -44,10 +48,11 @@ namespace margelo::nitro::webcodecs { std::shared_ptr surface SWIFT_PRIVATE; double timestamp SWIFT_PRIVATE; double duration SWIFT_PRIVATE; + std::optional colorSpace SWIFT_PRIVATE; public: NativeDecodedFrame() = default; - explicit NativeDecodedFrame(std::shared_ptr surface, double timestamp, double duration): surface(surface), timestamp(timestamp), duration(duration) {} + explicit NativeDecodedFrame(std::shared_ptr surface, double timestamp, double duration, std::optional colorSpace): surface(surface), timestamp(timestamp), duration(duration), colorSpace(colorSpace) {} public: friend bool operator==(const NativeDecodedFrame& lhs, const NativeDecodedFrame& rhs) = default; @@ -65,7 +70,8 @@ namespace margelo::nitro { return margelo::nitro::webcodecs::NativeDecodedFrame( JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "surface"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "timestamp"))), - JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "duration"))) + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "duration"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "colorSpace"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::webcodecs::NativeDecodedFrame& arg) { @@ -73,6 +79,7 @@ namespace margelo::nitro { obj.setProperty(runtime, PropNameIDCache::get(runtime, "surface"), JSIConverter>::toJSI(runtime, arg.surface)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "timestamp"), JSIConverter::toJSI(runtime, arg.timestamp)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "duration"), JSIConverter::toJSI(runtime, arg.duration)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "colorSpace"), JSIConverter>::toJSI(runtime, arg.colorSpace)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -86,6 +93,7 @@ namespace margelo::nitro { if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "surface")))) return false; if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "timestamp")))) return false; if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "duration")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "colorSpace")))) return false; return true; } }; diff --git a/src/__tests__/WebCodecs.spec.ts b/src/__tests__/WebCodecs.spec.ts index bf6f037..62b9c90 100644 --- a/src/__tests__/WebCodecs.spec.ts +++ b/src/__tests__/WebCodecs.spec.ts @@ -3856,6 +3856,113 @@ describe("react-native-webcodecs + Mediabunny", () => { }); }, 300000); + // A config without a colorSpace (a VideoDecoder used without Mediabunny): + // the frames have the stream's own, from its VUI, not BT.709. Members the + // config gives win over the stream's, as in WebCodecs. Android only for + // now: iOS takes the config's. + it("gives decoded frames the stream's color space when the config has none (Android)", async () => { + if (client.OS !== "android" || !probes()) { + return; + } + const clip = path.join(clipDirectory, "clip-bt601-full.mp4"); + fs.mkdirSync(clipDirectory, { recursive: true }); + if (!fs.existsSync(clip)) { + execFileSync("ffmpeg", [ + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + "color=c=red:s=320x240:r=30:d=0.5", + "-c:v", + "libx264", + "-pix_fmt", + "yuvj420p", + // In the VUI: -color_primaries and -color_trc leave them unspecified. + "-x264-params", + "colorprim=smpte170m:transfer=smpte170m:colormatrix=smpte170m:fullrange=on", + clip, + ]); + } + const file = await pushFile(clip); + const decoded = await runOnDevice<{ + errors: string[]; + stream: unknown; + overridden: unknown; + }>( + ({ mediabunny: mb, webcodecs: wc, ctx }) => { + const input = new mb.Input({ + source: new mb.CustomSource(wc.fileSourceOptions(ctx.file)), + formats: mb.ALL_FORMATS, + }); + const errors: string[] = []; + // The first frame's colorSpace, decoding with `config`. + const firstColorSpace = (track: any, config: any) => { + let first: any = null; + const decoder = new wc.VideoDecoder({ + output: (frame: any) => { + first = first || frame.colorSpace.toJSON(); + frame.close(); + }, + error: (e: any) => errors.push(`decoder: ${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(); + return first; + }); + }; + return input.getPrimaryVideoTrack().then((track: any) => + track.getDecoderConfig().then((trackConfig: any) => { + const config = Object.assign({}, trackConfig); + delete config.colorSpace; + return firstColorSpace(track, config).then((stream: any) => + firstColorSpace( + track, + Object.assign({}, config, { + colorSpace: { matrix: "bt709" }, + }), + ).then((overridden: any) => { + input.dispose(); + return { errors, stream, overridden }; + }), + ); + }), + ); + }, + { file }, + 120000, + ); + console.log(`stream color space: ${JSON.stringify(decoded)}`); + expect(decoded).toEqual({ + errors: [], + stream: { + primaries: "smpte170m", + transfer: "smpte170m", + matrix: "smpte170m", + fullRange: true, + }, + overridden: { + primaries: "smpte170m", + transfer: "smpte170m", + matrix: "bt709", + fullRange: 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 diff --git a/src/lib/video.ts b/src/lib/video.ts index 0ba3540..1eab8a9 100644 --- a/src/lib/video.ts +++ b/src/lib/video.ts @@ -862,16 +862,23 @@ 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. + // The config's color space, and for what it leaves out, the stream's as + // the decoder reports it (Android), as in WebCodecs. 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 given = this._colorSpace; + const stream = frame.colorSpace; const rgb = frame.surface.format === "BGRA" || frame.surface.format === "RGBA"; const videoFrame = new VideoFrame(frame.surface, { timestamp: frame.timestamp, duration: frame.duration || undefined, - colorSpace: rgb - ? { ...this._colorSpace, fullRange: true } - : this._colorSpace, + colorSpace: { + primaries: given?.primaries ?? stream?.primaries, + transfer: given?.transfer ?? stream?.transfer, + matrix: given?.matrix ?? stream?.matrix, + fullRange: rgb ? true : (given?.fullRange ?? stream?.fullRange), + }, }); try { this._output(videoFrame); diff --git a/src/specs/WebCodecs.nitro.ts b/src/specs/WebCodecs.nitro.ts index 72360c4..ddcf4f7 100644 --- a/src/specs/WebCodecs.nitro.ts +++ b/src/specs/WebCodecs.nitro.ts @@ -122,6 +122,9 @@ export interface NativeDecodedFrame { surface: NativeSurface; timestamp: number; duration: number; + // The stream's color space as the decoder reports it (Android: the output + // format's color aspects, from the VUI); unset members it does not know. + colorSpace?: NativeColorSpace; } export interface NativeVideoDecoder extends HybridObject {