From 3cd007bf53605e9c37fb396aa60137d13c380f31 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 22:47:01 -0800 Subject: [PATCH] perf(engine): decode opaque 8-bit macOS videos as NV12 with single-pass GPU YUV->RGBA+rotate compute --- crates/engine/src/av_decode.m | 503 +++++++++- crates/engine/src/eval/io.rs | 133 +-- crates/engine/src/eval/nv12.rs | 986 ++++++++++++++++++++ crates/engine/src/media.rs | 143 ++- crates/engine/src/media/prefetch.rs | 66 +- crates/engine/src/media/video.rs | 260 ++++++ crates/engine/src/shaders/nv12_to_rgba.wgsl | 91 ++ 7 files changed, 2028 insertions(+), 154 deletions(-) create mode 100644 crates/engine/src/eval/nv12.rs create mode 100644 crates/engine/src/shaders/nv12_to_rgba.wgsl diff --git a/crates/engine/src/av_decode.m b/crates/engine/src/av_decode.m index 7fd32c0cf7bd6645d030d064e629d065fa7c1238..857864382b5f8d8959a34429fc6f7e98ae1ad65e 100644 --- a/crates/engine/src/av_decode.m +++ b/crates/engine/src/av_decode.m @@ -22,13 +22,22 @@ @property(nonatomic, strong) AVAssetReaderTrackOutput *output; @property(nonatomic, assign) uint32_t width; @property(nonatomic, assign) uint32_t height; +@property(nonatomic, assign) uint32_t rawWidth; +@property(nonatomic, assign) uint32_t rawHeight; @property(nonatomic, assign) int rotation; // 0, 90, 180, 270 clockwise +@property(nonatomic, assign) BOOL useNv12; +@property(nonatomic, assign) BOOL preferFullRange; +@property(nonatomic, assign) uint32_t defaultMatrix; // 0=BT.709, 1=BT.601, 2=BT.2020 @property(nonatomic, assign) double fps; @property(nonatomic, assign) int64_t nbFrames; @property(nonatomic, assign) double trackStartSec; @property(nonatomic, assign) double durSec; @property(nonatomic, assign) int64_t lastFrameIdx; @property(nonatomic, strong) NSMutableData *lastFrameRgba; +@property(nonatomic, strong) NSMutableData *lastFrameY; +@property(nonatomic, strong) NSMutableData *lastFrameUv; +@property(nonatomic, assign) uint32_t lastFrameMatrix; +@property(nonatomic, assign) uint32_t lastFrameFullRange; @property(nonatomic, assign) BOOL hasLastFrame; @property(nonatomic, assign) BOOL lastFrameIsEof; @end @@ -51,8 +60,14 @@ if (!r || err) { return NO; } + OSType pixFmt = kCVPixelFormatType_32BGRA; + if (self.useNv12) { + pixFmt = self.preferFullRange + ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; + } NSDictionary *settings = @{ - (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA), + (NSString *)kCVPixelBufferPixelFormatTypeKey : @(pixFmt), }; AVAssetReaderTrackOutput *out = [[AVAssetReaderTrackOutput alloc] initWithTrack:self.track outputSettings:settings]; @@ -315,6 +330,231 @@ static int copy_bgra_to_rgba( return ok; } +static uint32_t matrix_from_cf_string(CFTypeRef matrixRef, uint32_t fallback) { + if (!matrixRef || CFGetTypeID(matrixRef) != CFStringGetTypeID()) { + return fallback; + } + CFStringRef ms = (CFStringRef)matrixRef; + if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_601_4) || + CFEqual(ms, kCVImageBufferYCbCrMatrix_SMPTE_240M_1995)) { + return 1u; // BT.601 + } + if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_2020)) { + return 2u; // BT.2020 + } + if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_709_2)) { + return 0u; // BT.709 + } + return fallback; +} + +static BOOL track_supports_nv12_8bit_420( + AVAssetTrack *track, + uint32_t rawW, + uint32_t rawH, + BOOL *outFullRange, + uint32_t *outDefaultMatrix +) { + if (outFullRange) { + *outFullRange = NO; + } + // CoreVideo defaults untagged HD/4K to BT.709 and SD to BT.601. + uint32_t defaultMat = (rawW >= 1280 || rawH >= 720) ? 0u : 1u; + if (outDefaultMatrix) { + *outDefaultMatrix = defaultMat; + } + + NSArray *formatDescs = track.formatDescriptions; + if (!formatDescs || formatDescs.count == 0) { + return NO; + } + CMFormatDescriptionRef fmtDesc = (__bridge CMFormatDescriptionRef)formatDescs.firstObject; + if (!fmtDesc) { + return NO; + } + + FourCharCode subType = CMFormatDescriptionGetMediaSubType(fmtDesc); + const FourCharCode kHev1 = 0x68657631; // 'hev1' + BOOL is420Codec = + (subType == kCMVideoCodecType_H264) || + (subType == kCMVideoCodecType_HEVC) || + (subType == kHev1) || + (subType == kCMVideoCodecType_MPEG4Video); + if (!is420Codec) { + return NO; + } + + // Reject alpha-bearing tracks (ProRes 4444, HEVC with alpha, etc.). + CFTypeRef hasAlphaRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_ContainsAlphaChannel); + if (hasAlphaRef && CFGetTypeID(hasAlphaRef) == CFBooleanGetTypeID() && + CFBooleanGetValue((CFBooleanRef)hasAlphaRef)) { + return NO; + } + CFTypeRef depthRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_Depth); + if (depthRef && CFGetTypeID(depthRef) == CFNumberGetTypeID()) { + int depth = 0; + if (CFNumberGetValue((CFNumberRef)depthRef, kCFNumberIntType, &depth) && depth == 32) { + return NO; + } + } + + // Reject >8-bit (10-bit/12-bit) streams. + CFTypeRef bpcRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_BitsPerComponent); + if (bpcRef && CFGetTypeID(bpcRef) == CFNumberGetTypeID()) { + int bpc = 0; + if (CFNumberGetValue((CFNumberRef)bpcRef, kCFNumberIntType, &bpc) && bpc != 8) { + return NO; + } + } + + // Reject HDR transfer functions (HLG, PQ, Linear) so CoreVideo handles HDR tone-mapping. + CFTypeRef tfRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_TransferFunction); + if (tfRef && CFGetTypeID(tfRef) == CFStringGetTypeID()) { + CFStringRef tf = (CFStringRef)tfRef; + if (CFEqual(tf, kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG) || + CFEqual(tf, kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ) || + CFEqual(tf, kCMFormatDescriptionTransferFunction_Linear)) { + return NO; + } + } + + // Inspect avcC / hvcC decoder config records to reject 10-bit or non-4:2:0 profiles + // even when BitsPerComponent is omitted by the container. + CFTypeRef atomsRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms); + if (atomsRef && CFGetTypeID(atomsRef) == CFDictionaryGetTypeID()) { + NSDictionary *atoms = (__bridge NSDictionary *)atomsRef; + if (subType == kCMVideoCodecType_H264) { + NSData *avcC = atoms[@"avcC"]; + if ([avcC isKindOfClass:[NSData class]] && avcC.length >= 4) { + const uint8_t *b = (const uint8_t *)avcC.bytes; + uint8_t profile = b[1]; + // Reject High 10 (110), High 4:2:2 (122), CAVLC 4:4:4 (44), High 4:4:4 (144/244) + if (profile == 44 || profile == 110 || profile == 122 || profile == 144 || profile == 244) { + return NO; + } + } + } else if (subType == kCMVideoCodecType_HEVC || subType == kHev1) { + NSData *hvcC = atoms[@"hvcC"]; + if ([hvcC isKindOfClass:[NSData class]] && hvcC.length >= 22) { + const uint8_t *b = (const uint8_t *)hvcC.bytes; + uint8_t profileIdc = b[1] & 0x1F; + uint8_t chromaFormat = b[16] & 0x03; // 1 = 4:2:0 + uint8_t bitDepthLumaMinus8 = b[17] & 0x07; + uint8_t bitDepthChromaMinus8 = b[18] & 0x07; + if (profileIdc == 2 || chromaFormat != 1 || + bitDepthLumaMinus8 > 0 || bitDepthChromaMinus8 > 0) { + return NO; + } + } + } + } + + CFTypeRef fullRangeRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_FullRangeVideo); + if (fullRangeRef && CFGetTypeID(fullRangeRef) == CFBooleanGetTypeID() && + CFBooleanGetValue((CFBooleanRef)fullRangeRef)) { + if (outFullRange) { + *outFullRange = YES; + } + } + + CFTypeRef matRef = CMFormatDescriptionGetExtension( + fmtDesc, kCMFormatDescriptionExtension_YCbCrMatrix); + if (outDefaultMatrix) { + *outDefaultMatrix = matrix_from_cf_string(matRef, defaultMat); + } + + return YES; +} + +static int copy_nv12_planes( + CVImageBufferRef imgBuf, + uint32_t expectedW, + uint32_t expectedH, + uint32_t defaultMatrix, + uint8_t *outY, + size_t outYLen, + uint8_t *outUv, + size_t outUvLen, + uint32_t *outMatrix, + uint32_t *outFullRange +) { + if (!imgBuf || !outY || !outUv) { + return 0; + } + OSType pf = CVPixelBufferGetPixelFormatType(imgBuf); + if (pf != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange && + pf != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { + return 0; + } + if (!CVPixelBufferIsPlanar(imgBuf) || CVPixelBufferGetPlaneCount(imgBuf) < 2) { + return 0; + } + if (CVPixelBufferLockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) { + return 0; + } + + size_t yW = CVPixelBufferGetWidthOfPlane(imgBuf, 0); + size_t yH = CVPixelBufferGetHeightOfPlane(imgBuf, 0); + size_t yBpr = CVPixelBufferGetBytesPerRowOfPlane(imgBuf, 0); + const uint8_t *yBase = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imgBuf, 0); + + size_t uvW = CVPixelBufferGetWidthOfPlane(imgBuf, 1); + size_t uvH = CVPixelBufferGetHeightOfPlane(imgBuf, 1); + size_t uvBpr = CVPixelBufferGetBytesPerRowOfPlane(imgBuf, 1); + const uint8_t *uvBase = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imgBuf, 1); + + size_t expectedUvW = ((size_t)expectedW + 1) / 2; + size_t expectedUvH = ((size_t)expectedH + 1) / 2; + size_t yRequired = (size_t)expectedW * (size_t)expectedH; + size_t uvRowBytes = expectedUvW * 2; + size_t uvRequired = uvRowBytes * expectedUvH; + + int ok = 0; + if (yBase && uvBase && + yW == expectedW && yH == expectedH && + uvW == expectedUvW && uvH == expectedUvH && + yBpr >= yW && uvBpr >= uvRowBytes && + outYLen >= yRequired && outUvLen >= uvRequired) { + if (yBpr == yW) { + memcpy(outY, yBase, yRequired); + } else { + for (size_t r = 0; r < yH; r++) { + memcpy(outY + r * yW, yBase + r * yBpr, yW); + } + } + if (uvBpr == uvRowBytes) { + memcpy(outUv, uvBase, uvRequired); + } else { + for (size_t r = 0; r < uvH; r++) { + memcpy(outUv + r * uvRowBytes, uvBase + r * uvBpr, uvRowBytes); + } + } + ok = 1; + } + + CVPixelBufferUnlockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly); + + if (ok) { + if (outFullRange) { + *outFullRange = (pf == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) ? 1u : 0u; + } + if (outMatrix) { + CFTypeRef matRef = CVBufferCopyAttachment(imgBuf, kCVImageBufferYCbCrMatrixKey, NULL); + *outMatrix = matrix_from_cf_string(matRef, defaultMatrix); + if (matRef) { + CFRelease(matRef); + } + } + } + return ok; +} + AvVideoDecoder *av_video_open( const char *path, uint32_t *out_w, @@ -402,24 +642,46 @@ AvVideoDecoder *av_video_open( } } + BOOL preferFullRange = NO; + uint32_t defaultMatrix = 0u; + BOOL useNv12 = track_supports_nv12_8bit_420( + track, natW, natH, &preferFullRange, &defaultMatrix); + AvVideoDecoderObj *obj = [[AvVideoDecoderObj alloc] init]; obj.asset = asset; obj.track = track; obj.width = outW; obj.height = outH; + obj.rawWidth = natW; + obj.rawHeight = natH; obj.rotation = rotation; + obj.useNv12 = useNv12; + obj.preferFullRange = preferFullRange; + obj.defaultMatrix = defaultMatrix; obj.fps = fps; obj.nbFrames = nbFrames; obj.trackStartSec = trackStartSec; obj.durSec = durSec; obj.lastFrameIdx = -1; obj.lastFrameRgba = nil; + obj.lastFrameY = nil; + obj.lastFrameUv = nil; + obj.lastFrameMatrix = defaultMatrix; + obj.lastFrameFullRange = preferFullRange ? 1u : 0u; obj.hasLastFrame = NO; obj.lastFrameIsEof = NO; // Verify AVAssetReader can actually open and decode this asset/codec. + // If NV12 output is rejected for an unusual stream, fall back seamlessly to 32BGRA. if (![obj openReaderAtSeconds:0.0]) { - return NULL; + if (obj.useNv12) { + obj.useNv12 = NO; + if (![obj openReaderAtSeconds:0.0]) { + return NULL; + } + } else { + return NULL; + } } *out_w = outW; @@ -430,6 +692,31 @@ AvVideoDecoder *av_video_open( } } +int av_video_is_nv12( + AvVideoDecoder *dec, + uint32_t *out_raw_w, + uint32_t *out_raw_h, + uint32_t *out_rotation +) { + if (!dec) { + return 0; + } + AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; + if (!obj.useNv12) { + return 0; + } + if (out_raw_w) { + *out_raw_w = obj.rawWidth; + } + if (out_raw_h) { + *out_raw_h = obj.rawHeight; + } + if (out_rotation) { + *out_rotation = (uint32_t)obj.rotation; + } + return 1; +} + static CMSampleBufferRef read_target_sample( AvVideoDecoderObj *obj, double targetPts, @@ -473,6 +760,69 @@ static CMSampleBufferRef read_target_sample( return chosen; } +static CMSampleBufferRef acquire_video_sample( + AvVideoDecoderObj *obj, + int64_t frame_idx, + BOOL *outHitEof, + BOOL *outAtEof +) { + double fps = obj.fps > 0.0 ? obj.fps : 30.0; + double targetPts = obj.trackStartSec + ((double)frame_idx) / fps; + double halfFrame = 0.45 / fps; + + BOOL canAdvance = + obj.reader != nil && + obj.reader.status == AVAssetReaderStatusReading && + ((obj.lastFrameIdx == -1 && frame_idx <= 8) || + (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && + frame_idx <= obj.lastFrameIdx + 8)); + + int64_t prevLastFrameIdx = obj.lastFrameIdx; + double seekSec = 0.0; + if (!canAdvance) { + seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); + if (![obj openReaderAtSeconds:seekSec]) { + if (outHitEof) *outHitEof = NO; + if (outAtEof) *outAtEof = NO; + return NULL; + } + } + + BOOL hitEof = NO; + CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); + + // If requesting a frame past EOF (including sequential advance stepping past EOF or + // container duration overestimating the last video sample by > 4 frames), retry from + // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. + if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) { + double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; + double fallbackSec = fmax(0.0, endAnchor - 1.0); + if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { + chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); + } + if (!chosen) { + double lastIdxSec = fmax( + 0.0, + prevLastFrameIdx >= 0 + ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 + : 0.0 + ); + if ([obj openReaderAtSeconds:lastIdxSec]) { + chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); + } + } + } + + if (outHitEof) { + *outHitEof = hitEof; + } + if (!chosen && outAtEof) { + *outAtEof = (obj.reader != nil && obj.reader.status == AVAssetReaderStatusCompleted) || + (obj.nbFrames > 0 && frame_idx >= obj.nbFrames - 2); + } + return chosen; +} + int av_video_decode_frame( AvVideoDecoder *dec, int64_t frame_idx, @@ -484,6 +834,9 @@ int av_video_decode_frame( } @autoreleasepool { AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; + if (obj.useNv12) { + return 0; + } if (frame_idx < 0) { frame_idx = 0; } @@ -491,54 +844,12 @@ int av_video_decode_frame( if (out_len < required) { return 0; } - double fps = obj.fps > 0.0 ? obj.fps : 30.0; - double targetPts = obj.trackStartSec + ((double)frame_idx) / fps; - double halfFrame = 0.45 / fps; - - BOOL canAdvance = - obj.reader != nil && - obj.reader.status == AVAssetReaderStatusReading && - ((obj.lastFrameIdx == -1 && frame_idx <= 8) || - (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && - frame_idx <= obj.lastFrameIdx + 8)); - - int64_t prevLastFrameIdx = obj.lastFrameIdx; - double seekSec = 0.0; - if (!canAdvance) { - seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); - if (![obj openReaderAtSeconds:seekSec]) { - return 0; - } - } BOOL hitEof = NO; - CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); - - // If requesting a frame past EOF (including sequential advance stepping past EOF or - // container duration overestimating the last video sample by > 4 frames), retry from - // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. - if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) { - double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; - double fallbackSec = fmax(0.0, endAnchor - 1.0); - if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { - chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); - } - if (!chosen) { - double lastIdxSec = fmax( - 0.0, - prevLastFrameIdx >= 0 - ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 - : 0.0 - ); - if ([obj openReaderAtSeconds:lastIdxSec]) { - chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); - } - } - } + BOOL atEof = NO; + CMSampleBufferRef chosen = acquire_video_sample(obj, frame_idx, &hitEof, &atEof); if (!chosen) { - BOOL atEof = (obj.reader != nil && obj.reader.status == AVAssetReaderStatusCompleted) || - (obj.nbFrames > 0 && frame_idx >= obj.nbFrames - 2); [obj closeReader]; if (atEof && obj.hasLastFrame && frame_idx > 0 && obj.lastFrameRgba.length >= required) { memcpy(out_rgba, obj.lastFrameRgba.bytes, required); @@ -573,6 +884,106 @@ int av_video_decode_frame( } } +int av_video_decode_nv12_frame( + AvVideoDecoder *dec, + int64_t frame_idx, + uint8_t *out_y, + size_t out_y_len, + uint8_t *out_uv, + size_t out_uv_len, + uint32_t *out_matrix, + uint32_t *out_full_range +) { + if (!dec || !out_y || !out_uv) { + return 0; + } + @autoreleasepool { + AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; + if (!obj.useNv12) { + return 0; + } + if (frame_idx < 0) { + frame_idx = 0; + } + size_t yRequired = (size_t)obj.rawWidth * (size_t)obj.rawHeight; + size_t uvW = ((size_t)obj.rawWidth + 1) / 2; + size_t uvH = ((size_t)obj.rawHeight + 1) / 2; + size_t uvRequired = uvW * uvH * 2; + if (out_y_len < yRequired || out_uv_len < uvRequired) { + return 0; + } + + BOOL hitEof = NO; + BOOL atEof = NO; + CMSampleBufferRef chosen = acquire_video_sample(obj, frame_idx, &hitEof, &atEof); + + if (!chosen) { + [obj closeReader]; + if (atEof && obj.hasLastFrame && frame_idx > 0 && + obj.lastFrameY.length >= yRequired && obj.lastFrameUv.length >= uvRequired) { + memcpy(out_y, obj.lastFrameY.bytes, yRequired); + memcpy(out_uv, obj.lastFrameUv.bytes, uvRequired); + if (out_matrix) { + *out_matrix = obj.lastFrameMatrix; + } + if (out_full_range) { + *out_full_range = obj.lastFrameFullRange; + } + return 1; + } + return 0; + } + + uint32_t matrix = obj.defaultMatrix; + uint32_t fullRange = obj.preferFullRange ? 1u : 0u; + CVImageBufferRef imgBuf = CMSampleBufferGetImageBuffer(chosen); + int ok = copy_nv12_planes( + imgBuf, + obj.rawWidth, + obj.rawHeight, + obj.defaultMatrix, + out_y, + out_y_len, + out_uv, + out_uv_len, + &matrix, + &fullRange + ); + CFRelease(chosen); + + if (ok) { + if (out_matrix) { + *out_matrix = matrix; + } + if (out_full_range) { + *out_full_range = fullRange; + } + if (hitEof || (!obj.lastFrameIsEof && (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4))) { + if (!obj.lastFrameY || obj.lastFrameY.length < yRequired) { + obj.lastFrameY = [NSMutableData dataWithLength:yRequired]; + } + if (!obj.lastFrameUv || obj.lastFrameUv.length < uvRequired) { + obj.lastFrameUv = [NSMutableData dataWithLength:uvRequired]; + } + if (obj.lastFrameY.length >= yRequired && obj.lastFrameUv.length >= uvRequired) { + memcpy(obj.lastFrameY.mutableBytes, out_y, yRequired); + memcpy(obj.lastFrameUv.mutableBytes, out_uv, uvRequired); + obj.lastFrameMatrix = matrix; + obj.lastFrameFullRange = fullRange; + obj.hasLastFrame = YES; + if (hitEof) { + obj.lastFrameIsEof = YES; + } + } + } + obj.lastFrameIdx = frame_idx; + } else { + [obj closeReader]; + } + return ok; + } +} + void av_video_close(AvVideoDecoder *dec) { if (!dec) { return; diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index 103b2bcea9c19518458770e9914f380c54b51936..e359323330048aa8fed964c10eb651e961c8d3bd 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -2,6 +2,9 @@ use super::*; use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; +#[path = "nv12.rs"] +mod nv12; + static DIMS_CACHE: OnceLock>>> = OnceLock::new(); pub(super) fn clear_dims_cache() { @@ -261,9 +264,9 @@ impl Engine { None } else { self.media - .load_clip(&effective_clip, frame_i, post_mult, exr_channels) + .load_clip_media(&effective_clip, frame_i, post_mult, exr_channels) }; - let Some((resolved, local_idx, img, loaded_from_disk)) = loaded else { + let Some((resolved, local_idx, media, loaded_from_disk)) = loaded else { if missing_frames != 1 { return self.dummy.clone(); } @@ -304,13 +307,15 @@ impl Engine { if loaded_from_disk { stats.source_loads += 1; } - let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(self.scaled_dims(img.size[0], img.size[1])), enc, visiting, stats); + let img_size = media.size(); + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(self.scaled_dims(img_size[0], img_size[1])), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); // OpenEXR clips natively produce float HDR in HiQ unless Loader explicitly forces int8/int16. let explicit_depth = comp .eval_number(node, "Depth", time, 0.0, &self.expr) .round() as i32; - let native_depth = if self.hiq && img.rgba_f32.is_some() { + let has_hdr_f32 = matches!(&media, crate::media::CachedMedia::Rgba(img) if img.rgba_f32.is_some()); + let native_depth = if self.hiq && has_hdr_f32 { BitDepth::from_fusion_depth(explicit_depth).unwrap_or_else(|| { if comp.depth_full == BitDepth::Float32 { BitDepth::Float32 @@ -322,8 +327,8 @@ impl Engine { self.node_depth(comp, node, time, None) }; let dst_depth = self.effective_depth(native_depth); - let use_float_upload = self.hiq && dst_depth.is_float() && img.rgba_f32.is_some(); - let target_size = self.scaled_dims(img.size[0], img.size[1]); + let use_float_upload = self.hiq && dst_depth.is_float() && has_hdr_f32; + let target_size = self.scaled_dims(img_size[0], img_size[1]); let mut h = DefaultHasher::new(); self.cache.gpu_salt.hash(&mut h); self.cache.node_salt(node.id).hash(&mut h); @@ -350,25 +355,35 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; - let need_depth_conv = !use_float_upload && dst_depth != BitDepth::Int8; - let need_post = target_size != img.size || mask.is_some() || need_depth_conv; - let full_tex = if use_float_upload { - let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); - let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); - if tex.format == wgpu::TextureFormat::Rgba32Float { - self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size); - } else { - let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); - self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size); + let is_nv12 = matches!(&media, crate::media::CachedMedia::Nv12(_)); + let need_depth_conv = !use_float_upload && !is_nv12 && dst_depth != BitDepth::Int8; + let need_post = target_size != img_size || mask.is_some() || need_depth_conv; + let (full_tex, work_depth) = match &media { + crate::media::CachedMedia::Nv12(nv12_frame) => { + // Single-pass GPU YUV->RGBA + rotation writes directly into target bit depth. + let tex = self.alloc_tex(img_size, dst_depth, if need_post { 0 } else { key }); + nv12::upload_and_convert_nv12(self, enc, nv12_frame, &tex); + (tex, dst_depth) + } + crate::media::CachedMedia::Rgba(img) => { + if use_float_upload { + let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); + let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); + if tex.format == wgpu::TextureFormat::Rgba32Float { + self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size); + } else { + let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); + self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size); + } + (tex, dst_depth) + } else { + let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key }); + self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size); + (tex, BitDepth::Int8) + } } - tex - } else { - let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key }); - self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size); - tex }; - let work_depth = if use_float_upload { dst_depth } else { BitDepth::Int8 }; - let base_tex = if target_size != img.size { + let base_tex = if target_size != img_size { let scaled = self.alloc_tex(target_size, work_depth, if mask.is_some() || need_depth_conv { 0 } else { key }); let mut u = UniformParams::default(); u.p[0] = [1.0, 1.0, 0.0, 0.0]; @@ -394,45 +409,47 @@ impl Engine { } else { masked_tex }; - if let Some(z_vals) = img.z_f32.as_ref() { - let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize); - if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 { - let z_tex = crate::cache::AuxChannelTex::new( - &self.device, - tex.size, - wgpu::TextureFormat::R32Float, - "loader-aux-z", - ); - if z_tex.size == img.size { - self.upload_raw_texture( - enc, - &z_tex.texture, - bytemuck::cast_slice(z_vals), - 4, - img.size, + if let crate::media::CachedMedia::Rgba(img) = &media { + if let Some(z_vals) = img.z_f32.as_ref() { + let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize); + if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 { + let z_tex = crate::cache::AuxChannelTex::new( + &self.device, + tex.size, + wgpu::TextureFormat::R32Float, + "loader-aux-z", ); - } else { - let [sw, sh] = [img.size[0] as usize, img.size[1] as usize]; - let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize]; - let mut resampled = Vec::with_capacity(dw * dh); - for dy in 0..dh { - let sy = ((dy * sh) / dh).min(sh.saturating_sub(1)); - for dx in 0..dw { - let sx = ((dx * sw) / dw).min(sw.saturating_sub(1)); - resampled.push(z_vals[sy * sw + sx]); + if z_tex.size == img.size { + self.upload_raw_texture( + enc, + &z_tex.texture, + bytemuck::cast_slice(z_vals), + 4, + img.size, + ); + } else { + let [sw, sh] = [img.size[0] as usize, img.size[1] as usize]; + let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize]; + let mut resampled = Vec::with_capacity(dw * dh); + for dy in 0..dh { + let sy = ((dy * sh) / dh).min(sh.saturating_sub(1)); + for dx in 0..dw { + let sx = ((dx * sw) / dw).min(sw.saturating_sub(1)); + resampled.push(z_vals[sy * sw + sx]); + } } + self.upload_raw_texture( + enc, + &z_tex.texture, + bytemuck::cast_slice(&resampled), + 4, + z_tex.size, + ); } - self.upload_raw_texture( - enc, - &z_tex.texture, - bytemuck::cast_slice(&resampled), - 4, - z_tex.size, - ); + let mut aux = tex.aux_cloned(); + aux.z = Some(z_tex); + tex.set_aux(Some(std::sync::Arc::new(aux))); } - let mut aux = tex.aux_cloned(); - aux.z = Some(z_tex); - tex.set_aux(Some(std::sync::Arc::new(aux))); } } self.cache.insert(key, tex.clone(), node.id, frame_i); diff --git a/crates/engine/src/eval/nv12.rs b/crates/engine/src/eval/nv12.rs new file mode 100644 index 0000000000000000000000000000000000000000..37c3e5dbdf14e5d62ba5cb8ed635ace80a05df72 --- /dev/null +++ b/crates/engine/src/eval/nv12.rs @@ -0,0 +1,986 @@ +//! Single-pass GPU NV12 -> RGBA (+ rotation) compute pipeline with pooled Y/UV upload textures. +//! +//! Declared as a submodule inside `eval/io.rs` so `eval/mod.rs` stays untouched. + +use crate::cache::CachedTexture; +use crate::media::Nv12Frame; +use bytemuck::{Pod, Zeroable}; +use std::collections::HashMap; +use std::num::NonZeroU64; + +const NV12_WGSL: &str = include_str!("../shaders/nv12_to_rgba.wgsl"); +const NV12_UNIFORM_SLOTS: u32 = 512; +#[cfg(not(target_arch = "wasm32"))] +const MAX_POOLED_PLANE_SIZES: usize = 8; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct Nv12UniformParams { + raw_w: u32, + raw_h: u32, + out_w: u32, + out_h: u32, + rot_deg: u32, + matrix_id: u32, + full_range: u32, + _pad: u32, +} + +struct Nv12FormatPipeline { + bgl: wgpu::BindGroupLayout, + pipeline: wgpu::ComputePipeline, +} + +struct Nv12PlanePair { + y_tex: wgpu::Texture, + y_view: wgpu::TextureView, + uv_tex: wgpu::Texture, + uv_view: wgpu::TextureView, + #[cfg(not(target_arch = "wasm32"))] + last_used: u64, +} + +impl Nv12PlanePair { + fn new(device: &wgpu::Device, raw_w: u32, raw_h: u32) -> Self { + let uv_w = raw_w.div_ceil(2); + let uv_h = raw_h.div_ceil(2); + let y_tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("nv12-y-plane"), + size: wgpu::Extent3d { + width: raw_w, + height: raw_h, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let y_view = y_tex.create_view(&wgpu::TextureViewDescriptor::default()); + + let uv_tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("nv12-uv-plane"), + size: wgpu::Extent3d { + width: uv_w, + height: uv_h, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rg8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let uv_view = uv_tex.create_view(&wgpu::TextureViewDescriptor::default()); + + Self { + y_tex, + y_view, + uv_tex, + uv_view, + #[cfg(not(target_arch = "wasm32"))] + last_used: 0, + } + } +} + +pub(super) struct Nv12Pipelines { + sampler: wgpu::Sampler, + uniform_buf: wgpu::Buffer, + uniform_stride: u32, + uniform_cursor: u32, + pipelines: HashMap, + #[cfg(not(target_arch = "wasm32"))] + plane_pool: HashMap<(u32, u32), Nv12PlanePair>, + #[cfg(not(target_arch = "wasm32"))] + tick: u64, +} + +impl Nv12Pipelines { + fn new(device: &wgpu::Device) -> Self { + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("nv12-uv-linear-sampler"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + address_mode_w: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + }); + + let align = device.limits().min_uniform_buffer_offset_alignment.max(32); + let raw_size = std::mem::size_of::() as u32; + let uniform_stride = raw_size.div_ceil(align) * align; + let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("nv12-uniform-ring"), + size: u64::from(uniform_stride) * u64::from(NV12_UNIFORM_SLOTS), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + + Self { + sampler, + uniform_buf, + uniform_stride, + uniform_cursor: 0, + pipelines: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + plane_pool: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + tick: 0, + } + } + + fn ensure_pipeline(&mut self, device: &wgpu::Device, dst_format: wgpu::TextureFormat) { + if self.pipelines.contains_key(&dst_format) { + return; + } + let storage_fmt = match dst_format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + let src = if storage_fmt == "rgba8unorm" { + std::borrow::Cow::Borrowed(NV12_WGSL) + } else { + std::borrow::Cow::Owned(NV12_WGSL.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + )) + }; + + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("nv12-to-rgba-wgsl"), + source: wgpu::ShaderSource::Wgsl(src), + }); + + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("nv12-to-rgba-bgl"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: dst_format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new( + std::mem::size_of::() as u64, + ), + }, + count: None, + }, + ], + }); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("nv12-to-rgba-layout"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("nv12-to-rgba-pipeline"), + layout: Some(&layout), + module: &module, + entry_point: Some("nv12_to_rgba"), + compilation_options: wgpu::PipelineCompilationOptions::default(), + cache: None, + }); + + self.pipelines.insert(dst_format, Nv12FormatPipeline { bgl, pipeline }); + } + + #[cfg(not(target_arch = "wasm32"))] + fn acquire_pooled_planes( + &mut self, + device: &wgpu::Device, + raw_w: u32, + raw_h: u32, + ) -> &Nv12PlanePair { + self.tick = self.tick.wrapping_add(1); + let tick = self.tick; + let key = (raw_w, raw_h); + if !self.plane_pool.contains_key(&key) { + if self.plane_pool.len() >= MAX_POOLED_PLANE_SIZES { + if let Some(oldest) = self + .plane_pool + .iter() + .min_by_key(|(_, p)| p.last_used) + .map(|(&k, _)| k) + { + self.plane_pool.remove(&oldest); + } + } + self.plane_pool + .insert(key, Nv12PlanePair::new(device, raw_w, raw_h)); + } + let pair = self.plane_pool.get_mut(&key).expect("just inserted"); + pair.last_used = tick; + pair + } + + #[allow(clippy::too_many_arguments)] + fn encode_dispatch( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + y_view: &wgpu::TextureView, + uv_view: &wgpu::TextureView, + nv12: &Nv12Frame, + dst: &CachedTexture, + ) { + self.ensure_pipeline(device, dst.format); + let slot = self.uniform_cursor; + self.uniform_cursor = (self.uniform_cursor + 1) % NV12_UNIFORM_SLOTS; + let dyn_offset = slot * self.uniform_stride; + + let params = Nv12UniformParams { + raw_w: nv12.raw_size[0], + raw_h: nv12.raw_size[1], + out_w: dst.size[0], + out_h: dst.size[1], + rot_deg: nv12.rot_deg, + matrix_id: nv12.matrix as u32, + full_range: u32::from(nv12.is_full_range), + _pad: 0, + }; + queue.write_buffer( + &self.uniform_buf, + u64::from(dyn_offset), + bytemuck::bytes_of(¶ms), + ); + + let fp = &self.pipelines[&dst.format]; + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("nv12-to-rgba-bg"), + layout: &fp.bgl, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(y_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(uv_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&dst.view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniform_buf, + offset: 0, + size: NonZeroU64::new(std::mem::size_of::() as u64), + }), + }, + ], + }); + + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("nv12-to-rgba-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(&fp.pipeline); + pass.set_bind_group(0, &bg, &[dyn_offset]); + pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); + } +} + +#[cfg(target_arch = "wasm32")] +thread_local! { + static WASM_NV12_PIPELINES: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +#[cfg(not(target_arch = "wasm32"))] +fn stage_plane_into_buffer( + media: &crate::media::MediaCache, + device: &wgpu::Device, + data: &[u8], + width: u32, + height: u32, + bytes_per_pixel: u32, +) -> Option<(wgpu::Buffer, u32)> { + let unpadded_bpr = width.checked_mul(bytes_per_pixel)?; + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let padded_bpr = unpadded_bpr.div_ceil(align) * align; + let needed = u64::from(padded_bpr).checked_mul(u64::from(height))?; + let buf = media.acquire_upload_staging(device, needed)?; + let cap = buf.size(); + let copied = if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() { + if padded_bpr == unpadded_bpr { + let total = (unpadded_bpr as usize) * (height as usize); + if data.len() >= total { + view.slice(..total).copy_from_slice(&data[..total]); + true + } else { + false + } + } else { + let src_stride = unpadded_bpr as usize; + let dst_stride = padded_bpr as usize; + if data.len() >= src_stride * (height as usize) { + let mut wo = view.slice(..needed as usize); + for (row_idx, src_row) in data + .chunks_exact(src_stride) + .take(height as usize) + .enumerate() + { + let off = row_idx * dst_stride; + wo.slice(off..off + src_stride).copy_from_slice(src_row); + } + true + } else { + false + } + } + } else { + false + }; + if copied { + buf.unmap(); + Some((buf, padded_bpr)) + } else { + drop(buf); + media.release_failed_upload_staging(cap); + None + } +} + +/// Uploads NV12 Y (`R8Unorm`) and UV (`Rg8Unorm`) planes and runs a single-pass compute shader +/// writing rotated, color-converted RGBA directly into `dst` (`Rgba8Unorm`, `Rgba16Float`, or +/// `Rgba32Float`). +pub(super) fn upload_and_convert_nv12( + engine: &crate::Engine, + enc: &mut wgpu::CommandEncoder, + nv12: &Nv12Frame, + dst: &CachedTexture, +) { + let [raw_w, raw_h] = nv12.raw_size; + let [uv_w, uv_h] = nv12.uv_size(); + if raw_w == 0 || raw_h == 0 || uv_w == 0 || uv_h == 0 || dst.size[0] == 0 || dst.size[1] == 0 { + return; + } + + #[cfg(not(target_arch = "wasm32"))] + { + // Prefer pooled Y/UV textures + in-order `copy_buffer_to_texture` via `UploadStagingPool`: + // zero per-frame GPU texture allocations and zero write hazards even with multiple NV12 + // loaders sharing the same `CommandEncoder`. + let staged_y = stage_plane_into_buffer(&engine.media, &engine.device, &nv12.y, raw_w, raw_h, 1); + let staged_uv = if staged_y.is_some() { + stage_plane_into_buffer(&engine.media, &engine.device, &nv12.uv, uv_w, uv_h, 2) + } else { + None + }; + + match (staged_y, staged_uv) { + (Some((y_buf, y_bpr)), Some((uv_buf, uv_bpr))) => { + engine.media.with_nv12_gpu_state( + || Nv12Pipelines::new(&engine.device), + |pipe| { + pipe.acquire_pooled_planes(&engine.device, raw_w, raw_h); + let pair = &pipe.plane_pool[&(raw_w, raw_h)]; + enc.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: &y_buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(y_bpr), + rows_per_image: Some(raw_h), + }, + }, + pair.y_tex.as_image_copy(), + wgpu::Extent3d { + width: raw_w, + height: raw_h, + depth_or_array_layers: 1, + }, + ); + enc.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: &uv_buf, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(uv_bpr), + rows_per_image: Some(uv_h), + }, + }, + pair.uv_tex.as_image_copy(), + wgpu::Extent3d { + width: uv_w, + height: uv_h, + depth_or_array_layers: 1, + }, + ); + let y_view = pair.y_view.clone(); + let uv_view = pair.uv_view.clone(); + pipe.encode_dispatch( + &engine.device, + &engine.queue, + enc, + &y_view, + &uv_view, + nv12, + dst, + ); + }, + ); + engine.media.recycle_upload_staging(y_buf); + engine.media.recycle_upload_staging(uv_buf); + return; + } + (Some((y_buf, _)), None) => { + engine.media.recycle_upload_staging(y_buf); + } + _ => {} + } + + // Fallback when staging pool is temporarily exhausted: use fresh textures with + // `queue.write_texture` so multiple dispatches in one encoder cannot overwrite each other. + let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); + engine.queue.write_texture( + fresh.y_tex.as_image_copy(), + &nv12.y, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(raw_w), + rows_per_image: Some(raw_h), + }, + wgpu::Extent3d { + width: raw_w, + height: raw_h, + depth_or_array_layers: 1, + }, + ); + engine.queue.write_texture( + fresh.uv_tex.as_image_copy(), + &nv12.uv, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(uv_w * 2), + rows_per_image: Some(uv_h), + }, + wgpu::Extent3d { + width: uv_w, + height: uv_h, + depth_or_array_layers: 1, + }, + ); + engine.media.with_nv12_gpu_state( + || Nv12Pipelines::new(&engine.device), + |pipe| { + pipe.encode_dispatch( + &engine.device, + &engine.queue, + enc, + &fresh.y_view, + &fresh.uv_view, + nv12, + dst, + ); + }, + ); + } + + #[cfg(target_arch = "wasm32")] + { + let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); + engine.queue.write_texture( + fresh.y_tex.as_image_copy(), + &nv12.y, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(raw_w), + rows_per_image: Some(raw_h), + }, + wgpu::Extent3d { + width: raw_w, + height: raw_h, + depth_or_array_layers: 1, + }, + ); + engine.queue.write_texture( + fresh.uv_tex.as_image_copy(), + &nv12.uv, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(uv_w * 2), + rows_per_image: Some(uv_h), + }, + wgpu::Extent3d { + width: uv_w, + height: uv_h, + depth_or_array_layers: 1, + }, + ); + WASM_NV12_PIPELINES.with(|cell| { + let mut slot = cell.borrow_mut(); + let pipe = slot.get_or_insert_with(|| Nv12Pipelines::new(&engine.device)); + pipe.encode_dispatch( + &engine.device, + &engine.queue, + enc, + &fresh.y_view, + &fresh.uv_view, + nv12, + dst, + ); + }); + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::Engine; + use crate::media::YuvMatrix; + use model::{BitDepth, Comp}; + + fn make_pattern_nv12( + raw_w: u32, + raw_h: u32, + rot_deg: u32, + matrix: YuvMatrix, + is_full_range: bool, + ) -> Nv12Frame { + let uv_w = raw_w.div_ceil(2); + let uv_h = raw_h.div_ceil(2); + let mut y = vec![0u8; (raw_w * raw_h) as usize]; + let mut uv = vec![128u8; (uv_w * uv_h * 2) as usize]; + + let (y_min, y_max) = if is_full_range { (0.0_f32, 255.0_f32) } else { (16.0_f32, 235.0_f32) }; + let (c_min, c_max) = if is_full_range { (0.0_f32, 255.0_f32) } else { (16.0_f32, 240.0_f32) }; + + for py in 0..raw_h { + for px in 0..raw_w { + let fx = px as f32 / raw_w.saturating_sub(1).max(1) as f32; + let fy = py as f32 / raw_h.saturating_sub(1).max(1) as f32; + let luma = y_min + (y_max - y_min) * (0.15 + 0.7 * (0.5 * fx + 0.5 * fy)); + y[(py * raw_w + px) as usize] = luma.round().clamp(0.0, 255.0) as u8; + } + } + for cy in 0..uv_h { + for cx in 0..uv_w { + let fx = cx as f32 / uv_w.saturating_sub(1).max(1) as f32; + let fy = cy as f32 / uv_h.saturating_sub(1).max(1) as f32; + let cb = c_min + (c_max - c_min) * (0.2 + 0.6 * fx); + let cr = c_min + (c_max - c_min) * (0.8 - 0.6 * fy); + let idx = ((cy * uv_w + cx) * 2) as usize; + uv[idx] = cb.round().clamp(0.0, 255.0) as u8; + uv[idx + 1] = cr.round().clamp(0.0, 255.0) as u8; + } + } + + let display_size = if rot_deg == 90 || rot_deg == 270 { + [raw_h, raw_w] + } else { + [raw_w, raw_h] + }; + Nv12Frame { + raw_size: [raw_w, raw_h], + display_size, + rot_deg, + matrix, + is_full_range, + y, + uv, + } + } + + fn make_quadrant_nv12(raw_w: u32, raw_h: u32, rot_deg: u32) -> Nv12Frame { + let uv_w = raw_w.div_ceil(2); + let uv_h = raw_h.div_ceil(2); + let mut y = vec![0u8; (raw_w * raw_h) as usize]; + let mut uv = vec![128u8; (uv_w * uv_h * 2) as usize]; + // BT.709 video-range YCbCr for pure Red, Green, Blue, Yellow: + // Red: Y=63, Cb=102, Cr=240 + // Green: Y=173, Cb=42, Cr=26 + // Blue: Y=32, Cb=240, Cr=118 + // Yellow: Y=219, Cb=16, Cr=138 + let quad = |x: u32, y_pos: u32, w: u32, h: u32| -> (u8, u8, u8) { + match (x < w / 2, y_pos < h / 2) { + (true, true) => (63, 102, 240), // top-left: Red + (false, true) => (173, 42, 26), // top-right: Green + (true, false) => (32, 240, 118), // bottom-left: Blue + (false, false) => (219, 16, 138), // bottom-right: Yellow + } + }; + for py in 0..raw_h { + for px in 0..raw_w { + let (yv, _, _) = quad(px, py, raw_w, raw_h); + y[(py * raw_w + px) as usize] = yv; + } + } + for cy in 0..uv_h { + for cx in 0..uv_w { + let (_, cb, cr) = quad(cx * 2, cy * 2, raw_w, raw_h); + let idx = ((cy * uv_w + cx) * 2) as usize; + uv[idx] = cb; + uv[idx + 1] = cr; + } + } + let display_size = if rot_deg == 90 || rot_deg == 270 { + [raw_h, raw_w] + } else { + [raw_w, raw_h] + }; + Nv12Frame { + raw_size: [raw_w, raw_h], + display_size, + rot_deg, + matrix: YuvMatrix::Bt709, + is_full_range: false, + y, + uv, + } + } + + fn run_gpu_nv12(engine: &Engine, frame: &Nv12Frame, depth: BitDepth) -> Vec { + let mut enc = engine + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("nv12-test-enc"), + }); + let dst = engine.alloc_tex(frame.display_size, depth, 0); + upload_and_convert_nv12(engine, &mut enc, frame, &dst); + engine.queue.submit(Some(enc.finish())); + engine.media.flush_upload_staging_after_submit(&engine.device); + engine.readback_rgba(&dst).expect("readback_rgba") + } + + #[test] + fn nv12_gpu_matches_cpu_reference_all_matrices_ranges_and_formats() { + let engine = Engine::new_headless().expect("headless engine"); + for &(raw_w, raw_h) in &[(32u32, 24u32), (17u32, 13u32)] { + for &matrix in &[YuvMatrix::Bt709, YuvMatrix::Bt601, YuvMatrix::Bt2020] { + for &full_range in &[false, true] { + let frame = make_pattern_nv12(raw_w, raw_h, 0, matrix, full_range); + let expected = frame.to_rgba8(); + for &depth in &[BitDepth::Int8, BitDepth::Float16, BitDepth::Float32] { + let got = run_gpu_nv12(&engine, &frame, depth); + assert_eq!(got.len(), expected.len()); + let mut max_diff = 0u8; + for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { + if i % 4 == 3 { + assert_eq!(g, 255, "NV12 alpha must be 255"); + } + max_diff = max_diff.max(g.abs_diff(e)); + } + assert!( + max_diff <= 2, + "NV12 mismatch ({raw_w}x{raw_h}, {matrix:?}, full={full_range}, {depth:?}): max_diff={max_diff}" + ); + } + } + } + } + } + + #[test] + fn nv12_gpu_matches_cpu_reference_all_four_rotations() { + let engine = Engine::new_headless().expect("headless engine"); + for &rot_deg in &[0u32, 90, 180, 270] { + let frame = make_quadrant_nv12(24, 16, rot_deg); + let expected = frame.to_rgba8(); + let got = run_gpu_nv12(&engine, &frame, BitDepth::Int8); + assert_eq!(got.len(), expected.len()); + let mut max_diff = 0u8; + for (&g, &e) in got.iter().zip(expected.iter()) { + max_diff = max_diff.max(g.abs_diff(e)); + } + assert!( + max_diff <= 2, + "rotation {rot_deg} mismatch vs CPU reference: max_diff={max_diff}" + ); + + // Spot-check interior of each rotated quadrant against expected primary colors. + let [ow, oh] = frame.display_size; + let px = |x: u32, y: u32| -> [u8; 4] { + let i = ((y * ow + x) * 4) as usize; + [got[i], got[i + 1], got[i + 2], got[i + 3]] + }; + let tl = px(2, 2); + let tr = px(ow - 3, 2); + let bl = px(2, oh - 3); + let br = px(ow - 3, oh - 3); + match rot_deg { + 0 => { + assert!(tl[0] > 200 && tl[1] < 30 && tl[2] < 30, "0° TL should be red: {tl:?}"); + assert!(tr[1] > 200 && tr[0] < 30 && tr[2] < 30, "0° TR should be green: {tr:?}"); + assert!(bl[2] > 200 && bl[0] < 30 && bl[1] < 30, "0° BL should be blue: {bl:?}"); + assert!(br[0] > 200 && br[1] > 200 && br[2] < 30, "0° BR should be yellow: {br:?}"); + } + 90 => { + // 90° CW: BL(blue)->TL, TL(red)->TR, BR(yellow)->BL, TR(green)->BR + assert!(tl[2] > 200 && tl[0] < 30, "90° TL should be blue: {tl:?}"); + assert!(tr[0] > 200 && tr[1] < 30, "90° TR should be red: {tr:?}"); + assert!(bl[0] > 200 && bl[1] > 200 && bl[2] < 30, "90° BL should be yellow: {bl:?}"); + assert!(br[1] > 200 && br[0] < 30, "90° BR should be green: {br:?}"); + } + 180 => { + assert!(tl[0] > 200 && tl[1] > 200 && tl[2] < 30, "180° TL should be yellow: {tl:?}"); + assert!(tr[2] > 200 && tr[0] < 30, "180° TR should be blue: {tr:?}"); + assert!(bl[1] > 200 && bl[0] < 30, "180° BL should be green: {bl:?}"); + assert!(br[0] > 200 && br[1] < 30, "180° BR should be red: {br:?}"); + } + 270 => { + // 270° CW (90° CCW): TR(green)->TL, BR(yellow)->TR, TL(red)->BL, BL(blue)->BR + assert!(tl[1] > 200 && tl[0] < 30, "270° TL should be green: {tl:?}"); + assert!(tr[0] > 200 && tr[1] > 200 && tr[2] < 30, "270° TR should be yellow: {tr:?}"); + assert!(bl[0] > 200 && bl[1] < 30, "270° BL should be red: {bl:?}"); + assert!(br[2] > 200 && br[0] < 30, "270° BR should be blue: {br:?}"); + } + _ => unreachable!(), + } + } + } + + #[test] + fn nv12_multiple_dispatches_same_encoder_no_hazard() { + let engine = Engine::new_headless().expect("headless engine"); + let red = Nv12Frame { + raw_size: [16, 16], + display_size: [16, 16], + rot_deg: 0, + matrix: YuvMatrix::Bt709, + is_full_range: false, + y: vec![63u8; 16 * 16], + uv: [102u8, 240u8].repeat(8 * 8), + }; + let blue = Nv12Frame { + raw_size: [16, 16], + display_size: [16, 16], + rot_deg: 0, + matrix: YuvMatrix::Bt709, + is_full_range: false, + y: vec![32u8; 16 * 16], + uv: [240u8, 118u8].repeat(8 * 8), + }; + + let mut enc = engine + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("nv12-multi-dispatch"), + }); + let dst_red = engine.alloc_tex([16, 16], BitDepth::Float16, 0); + let dst_blue = engine.alloc_tex([16, 16], BitDepth::Float16, 0); + upload_and_convert_nv12(&engine, &mut enc, &red, &dst_red); + upload_and_convert_nv12(&engine, &mut enc, &blue, &dst_blue); + engine.queue.submit(Some(enc.finish())); + engine.media.flush_upload_staging_after_submit(&engine.device); + + let r_px = engine.readback_rgba(&dst_red).expect("readback red"); + let b_px = engine.readback_rgba(&dst_blue).expect("readback blue"); + assert!(r_px[0] > 220 && r_px[1] < 20 && r_px[2] < 20, "first dispatch corrupted: {:?}", &r_px[..4]); + assert!(b_px[2] > 220 && b_px[0] < 20 && b_px[1] < 20, "second dispatch corrupted: {:?}", &b_px[..4]); + } + + #[cfg(target_os = "macos")] + #[test] + fn nv12_synthetic_mp4_decode_and_eval_loader() { + use crate::media::{AvFoundationDecoder, FfmpegDecoder, VideoDecoder}; + use std::process::Command; + + let dir = std::env::temp_dir().join(format!("fission_nv12_test_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let mp4_path = dir.join("bars_bt709.mp4"); + let ok_mp4 = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "smptehdbars=size=128x96:rate=24:duration=0.25", + "-vf", + "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p", + "-c:v", + "libx264", + "-crf", + "10", + "-colorspace", + "bt709", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", + "-color_range", + "tv", + ]) + .arg(&mp4_path) + .status() + .is_ok_and(|s| s.success()); + if !ok_mp4 { + let _ = std::fs::remove_dir_all(&dir); + return; + } + + // 1. Verify AvFoundationDecoder selects NV12 for opaque 8-bit 4:2:0 H.264 MP4. + let mut av_dec = AvFoundationDecoder::open(&mp4_path).expect("AvFoundationDecoder::open"); + assert!(av_dec.is_nv12(), "8-bit opaque H.264 yuv420p should use NV12 fast path"); + let nv12 = av_dec.decode_nv12_frame(0).expect("decode_nv12_frame(0)"); + assert_eq!(nv12.raw_size, [128, 96]); + assert_eq!(nv12.display_size, [128, 96]); + assert_eq!(nv12.rot_deg, 0); + assert_eq!(nv12.matrix, YuvMatrix::Bt709); + assert!(!nv12.is_full_range); + assert_eq!(nv12.byte_size(), (128 * 96 + 64 * 48 * 2) as u64); + + // Verify EOF frame-hold returns valid last frame when requesting past EOF. + let eof_frame = av_dec.decode_nv12_frame(999).expect("EOF frame hold"); + assert_eq!(eof_frame.raw_size, [128, 96]); + assert_eq!(eof_frame.y.len(), 128 * 96); + + // 2. Verify rotated 90° H.264 MP4 decodes as NV12 with raw sensor dims + rot_deg = 90 + // and rotated display dimensions [96, 128]. + let rot_mp4 = dir.join("bars_rot90.mp4"); + let ok_rot = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-display_rotation", + "270", // FFmpeg display_rotation is CCW; 270 CCW == 90 CW preferredTransform + "-i", + ]) + .arg(&mp4_path) + .args(["-c", "copy"]) + .arg(&rot_mp4) + .status() + .is_ok_and(|s| s.success()); + if ok_rot { + let mut rot_dec = AvFoundationDecoder::open(&rot_mp4).expect("open rot90 mp4"); + assert!(rot_dec.is_nv12(), "rotated 8-bit H.264 should use NV12"); + let rot_frame = rot_dec.decode_nv12_frame(0).expect("decode rot90 frame"); + assert_eq!(rot_frame.raw_size, [128, 96]); + assert_eq!(rot_frame.display_size, [96, 128]); + assert_eq!(rot_frame.rot_deg, 90); + } + + // 2. Verify ProRes 4444 alpha MOV stays on BGRA path (NOT NV12). + let alpha_mov = dir.join("alpha_4444.mov"); + let ok_alpha = Command::new("ffmpeg") + .args([ + "-y", + "-v", + "error", + "-f", + "lavfi", + "-i", + "color=c=red@0.5:size=32x32:rate=24:duration=0.1,format=yuva444p10le", + "-c:v", + "prores_ks", + "-profile:v", + "4", + "-pix_fmt", + "yuva444p10le", + ]) + .arg(&alpha_mov) + .status() + .is_ok_and(|s| s.success()); + if ok_alpha { + if let Some(alpha_dec) = AvFoundationDecoder::open(&alpha_mov) { + assert!( + !alpha_dec.is_nv12(), + "ProRes 4444 alpha video must NOT use NV12 path" + ); + } + } + + // 3. Evaluate Loader through GPU Engine (HiQ Float16) and compare vs ffmpeg reference. + let esc = mp4_path.to_string_lossy().replace('\\', "\\\\"); + let comp_src = format!( + r#"Composition {{ +CurrentTime = 0, +RenderRange = {{ 0, 5 }}, +GlobalRange = {{ 0, 5 }}, +Tools = ordered() {{ + V = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{esc}", + FormatID = "QuickTimeMovies", + Length = 6, + GlobalStart = 0, + GlobalEnd = 5, + }}, + }}, + }}, +}}, +}}"# + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); + let target = comp.find_node("V").expect("V"); + let mut engine = Engine::new_headless().expect("headless engine"); + let (tex, _) = engine.evaluate(&comp, target, 0.0); + let gpu_rgba = engine.readback_rgba(&tex).expect("readback"); + + let mut ff = FfmpegDecoder::open(&mp4_path).expect("FfmpegDecoder"); + let ff_rgba = ff.decode_frame(0).expect("ff decode 0"); + assert_eq!(gpu_rgba.len(), ff_rgba.len()); + let mae: f64 = gpu_rgba + .iter() + .zip(ff_rgba.iter()) + .map(|(&a, &b)| (a as i32 - b as i32).abs() as f64) + .sum::() + / gpu_rgba.len() as f64; + assert!( + mae < 2.5, + "GPU NV12 Loader output diverged from ffmpeg reference: MAE={mae:.2}/255" + ); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index c359ed7f47c95de21d8c1f4364b36d08ea2ff5ac..0f422d3506252bb9d83b1043715a9e88daf736ef 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -15,7 +15,10 @@ pub use prefetch::MediaPrefetchHandle; pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; #[cfg(target_os = "macos")] pub use video::AvFoundationDecoder; -pub use video::{FfmpegDecoder, VideoDecoder, VideoInfo, open_video_decoder}; +pub use video::{ + DecodedVideoFrame, FfmpegDecoder, Nv12Frame, VideoDecoder, VideoInfo, YuvMatrix, + open_video_decoder, +}; use exr::{ apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path, normalize_channel_opt, @@ -77,6 +80,43 @@ impl DecodedImage { } } +/// Internal cached media payload: either decoded RGBA/HDR image buffers or a compact +/// native NV12 video frame (`~2.67×` smaller than 4K RGBA) uploaded directly to GPU. +#[derive(Clone)] +pub(crate) enum CachedMedia { + Rgba(DecodedImage), + Nv12(Arc), +} + +impl CachedMedia { + pub(crate) fn size(&self) -> [u32; 2] { + match self { + Self::Rgba(img) => img.size, + Self::Nv12(frame) => frame.display_size, + } + } + + pub(crate) fn byte_size(&self) -> u64 { + match self { + Self::Rgba(img) => img.byte_size(), + Self::Nv12(frame) => frame.byte_size(), + } + } + + pub(crate) fn into_decoded_image(self) -> DecodedImage { + match self { + Self::Rgba(img) => img, + Self::Nv12(frame) => DecodedImage { + size: frame.display_size, + rgba: Arc::new(frame.to_rgba8()), + rgba_f16: None, + rgba_f32: None, + z_f32: None, + }, + } + } +} + const MAX_VIDEO_DECODERS: usize = 12; struct VirtualFile { @@ -182,7 +222,7 @@ struct VideoDecoderSlot { } struct MediaState { - images: HashMap, + images: HashMap, video_decoders: HashMap, total_bytes: u64, budget_bytes: u64, @@ -251,10 +291,15 @@ impl MediaState { let _ = path; } + #[cfg(not(target_arch = "wasm32"))] fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { - let bytes = decoded.byte_size(); + self.insert_cached_media(cache_key, CachedMedia::Rgba(decoded)); + } + + fn insert_cached_media(&mut self, cache_key: ImageCacheKey, media: CachedMedia) { + let bytes = media.byte_size(); self.tick += 1; - if let Some(prev) = self.images.insert(cache_key.clone(), decoded) { + if let Some(prev) = self.images.insert(cache_key.clone(), media) { self.total_bytes = self.total_bytes.saturating_sub(prev.byte_size()); } self.lru.insert(cache_key, self.tick); @@ -333,6 +378,7 @@ impl MediaShared { } } + #[cfg(not(target_arch = "wasm32"))] fn insert_cached_locked( &self, state: &mut MediaState, @@ -343,6 +389,16 @@ impl MediaShared { self.sync_lookahead_throttle(state) } + fn insert_cached_media_locked( + &self, + state: &mut MediaState, + cache_key: ImageCacheKey, + media: CachedMedia, + ) -> bool { + state.insert_cached_media(cache_key, media); + self.sync_lookahead_throttle(state) + } + fn path_exists_cached(&self, path: &Path) -> bool { if virtual_bytes(path).is_some() { return true; @@ -627,6 +683,8 @@ pub struct MediaCache { shared: Arc, #[cfg(not(target_arch = "wasm32"))] staging_pool: Mutex, + #[cfg(not(target_arch = "wasm32"))] + nv12_gpu_state: Mutex>>, } impl Default for MediaCache { @@ -641,6 +699,8 @@ impl MediaCache { shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))), #[cfg(not(target_arch = "wasm32"))] staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)), + #[cfg(not(target_arch = "wasm32"))] + nv12_gpu_state: Mutex::new(None), } } @@ -689,6 +749,24 @@ impl MediaCache { if let Ok(mut pool) = self.staging_pool.lock() { pool.clear(); } + #[cfg(not(target_arch = "wasm32"))] + if let Ok(mut slot) = self.nv12_gpu_state.lock() { + *slot = None; + } + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn with_nv12_gpu_state( + &self, + init: impl FnOnce() -> T, + f: impl FnOnce(&mut T) -> R, + ) -> R { + let mut slot = self.nv12_gpu_state.lock().unwrap_or_else(|e| e.into_inner()); + let any = slot.get_or_insert_with(|| Box::new(init())); + let state = any + .downcast_mut::() + .expect("nv12_gpu_state type mismatch"); + f(state) } #[cfg(not(target_arch = "wasm32"))] @@ -773,6 +851,19 @@ impl MediaCache { post_multiply: bool, exr_channels: [Option<&str>; 4], ) -> Option<(PathBuf, i64, DecodedImage, bool)> { + self.load_clip_media(clip, frame, post_multiply, exr_channels) + .map(|(resolved, idx, media, from_disk)| (resolved, idx, media.into_decoded_image(), from_disk)) + } + + /// Loads a Fusion `ClipSpec` keeping native `NV12` video frames unconverted for direct + /// single-pass GPU upload and YUV->RGBA+rotation conversion. + pub(crate) fn load_clip_media( + &mut self, + clip: &ClipSpec, + frame: i64, + post_multiply: bool, + exr_channels: [Option<&str>; 4], + ) -> Option<(PathBuf, i64, CachedMedia, bool)> { let base = Path::new(&clip.filename); if is_video_path(base) { if !video_frame_in_range(clip, frame) || !self.shared.path_exists_cached(base) { @@ -791,11 +882,11 @@ impl MediaCache { let cache_gen = { let mut state = self.shared.state.lock().ok()?; loop { - if let Some(img) = state.images.get(&cache_key).cloned() { + if let Some(media) = state.images.get(&cache_key).cloned() { state.tick += 1; let t = state.tick; state.lru.insert(cache_key, t); - return Some((base_buf, idx, img, false)); + return Some((base_buf, idx, media, false)); } #[cfg(not(target_arch = "wasm32"))] if state.in_flight.contains(&cache_key) { @@ -817,19 +908,24 @@ impl MediaCache { key: Some(cache_key.clone()), }; - let mut raw = { + let decoded_frame = { let mut dec_guard = decoder_arc.lock().ok()?; - dec_guard.as_mut()?.decode_frame(idx)? + dec_guard.as_mut()?.decode_frame_native(idx)? }; - if post_multiply { - apply_post_multiply_rgba8(&mut raw); - } - let decoded = DecodedImage { - size: [info.width, info.height], - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - z_f32: None, + let media = match decoded_frame { + DecodedVideoFrame::Nv12(nv12) => CachedMedia::Nv12(Arc::new(nv12)), + DecodedVideoFrame::Rgba(mut raw) => { + if post_multiply { + apply_post_multiply_rgba8(&mut raw); + } + CachedMedia::Rgba(DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + z_f32: None, + }) + } }; let unthrottled = if let Ok(mut state) = self.shared.state.lock() { @@ -840,7 +936,7 @@ impl MediaCache { } let unthrottled = if state.generation == cache_gen { self.shared - .insert_cached_locked(&mut state, cache_key, decoded.clone()) + .insert_cached_media_locked(&mut state, cache_key, media.clone()) } else { self.shared.sync_lookahead_throttle(&state) }; @@ -856,7 +952,7 @@ impl MediaCache { } #[cfg(target_arch = "wasm32")] let _ = unthrottled; - return Some((base_buf, idx, decoded, true)); + return Some((base_buf, idx, media, true)); } let resolved = resolve_clip_candidate_path(clip, frame)?; @@ -881,11 +977,11 @@ impl MediaCache { let cache_gen = { let mut state = self.shared.state.lock().ok()?; loop { - if let Some(img) = state.images.get(&cache_key).cloned() { + if let Some(media) = state.images.get(&cache_key).cloned() { state.tick += 1; let t = state.tick; state.lru.insert(cache_key, t); - return Some((resolved, -1, img, false)); + return Some((resolved, -1, media, false)); } #[cfg(not(target_arch = "wasm32"))] if state.in_flight.contains(&cache_key) { @@ -930,6 +1026,7 @@ impl MediaCache { } return None; }; + let media = CachedMedia::Rgba(decoded); let unthrottled = if let Ok(mut state) = self.shared.state.lock() { #[cfg(not(target_arch = "wasm32"))] @@ -940,7 +1037,7 @@ impl MediaCache { let unthrottled = if state.generation == cache_gen { state.record_existing_path(&resolved); self.shared - .insert_cached_locked(&mut state, cache_key, decoded.clone()) + .insert_cached_media_locked(&mut state, cache_key, media.clone()) } else { self.shared.sync_lookahead_throttle(&state) }; @@ -956,7 +1053,7 @@ impl MediaCache { } #[cfg(target_arch = "wasm32")] let _ = unthrottled; - Some((resolved, -1, decoded, true)) + Some((resolved, -1, media, true)) } } diff --git a/crates/engine/src/media/prefetch.rs b/crates/engine/src/media/prefetch.rs index de4cd225dbd4a4914e3fbf05b1585b1b3958be02..51100ced40e84fcb18fe78f7559cd012a14ff4e4 100644 --- a/crates/engine/src/media/prefetch.rs +++ b/crates/engine/src/media/prefetch.rs @@ -269,27 +269,34 @@ impl MediaCache { shared: &self.shared, key: Some(key.clone()), }; - let decoded_raw = dec_arc + let decoded_frame = dec_arc .lock() .ok() - .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx)); - if let Some(mut raw) = decoded_raw { - if req.post_multiply { - apply_post_multiply_rgba8_parallel(&mut raw, false); - } - let decoded = DecodedImage { - size: [info.width, info.height], - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - z_f32: None, + .and_then(|mut g| g.as_mut()?.decode_frame_native(frame_idx)); + if let Some(frame) = decoded_frame { + let media = match frame { + DecodedVideoFrame::Nv12(nv12) => { + CachedMedia::Nv12(Arc::new(nv12)) + } + DecodedVideoFrame::Rgba(mut raw) => { + if req.post_multiply { + apply_post_multiply_rgba8_parallel(&mut raw, false); + } + CachedMedia::Rgba(DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + z_f32: None, + }) + } }; let unthrottled = if let Ok(mut state) = self.shared.state.lock() { state.in_flight.remove(&key); guard.key = None; let unthrottled = if state.generation == cache_gen { self.shared - .insert_cached_locked(&mut state, key, decoded) + .insert_cached_media_locked(&mut state, key, media) } else { self.shared.sync_lookahead_throttle(&state) }; @@ -707,29 +714,34 @@ impl MediaPrefetchHandle { shared: &shared, key: Some(key.clone()), }; - let decoded_raw = dec_arc + let decoded_frame = dec_arc .lock() .ok() - .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx)); - if let Some(mut raw) = decoded_raw { - if req.post_multiply { - apply_post_multiply_rgba8_parallel(&mut raw, false); - } - let decoded = DecodedImage { - size: [info.width, info.height], - rgba: Arc::new(raw), - rgba_f16: None, - rgba_f32: None, - z_f32: None, + .and_then(|mut g| g.as_mut()?.decode_frame_native(frame_idx)); + if let Some(frame) = decoded_frame { + let media = match frame { + DecodedVideoFrame::Nv12(nv12) => CachedMedia::Nv12(Arc::new(nv12)), + DecodedVideoFrame::Rgba(mut raw) => { + if req.post_multiply { + apply_post_multiply_rgba8_parallel(&mut raw, false); + } + CachedMedia::Rgba(DecodedImage { + size: [info.width, info.height], + rgba: Arc::new(raw), + rgba_f16: None, + rgba_f32: None, + z_f32: None, + }) + } }; let unthrottled = if let Ok(mut state) = shared.state.lock() { state.in_flight.remove(&key); guard.key = None; let unthrottled = if state.generation == cache_gen { if item_seq > cur_seq { - state.record_speculative_decode(decoded.byte_size()); + state.record_speculative_decode(media.byte_size()); } - shared.insert_cached_locked(&mut state, key, decoded) + shared.insert_cached_media_locked(&mut state, key, media) } else { shared.sync_lookahead_throttle(&state) }; diff --git a/crates/engine/src/media/video.rs b/crates/engine/src/media/video.rs index cd15064e2836c6567743db3d30aa400538b5d2c1..d087395ac7616e5ff0b7ad8c16f9a921b4e6f3b6 100644 --- a/crates/engine/src/media/video.rs +++ b/crates/engine/src/media/video.rs @@ -8,9 +8,186 @@ pub struct VideoInfo { pub nb_frames: i64, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u32)] +pub enum YuvMatrix { + Bt709 = 0, + Bt601 = 1, + Bt2020 = 2, +} + +impl YuvMatrix { + pub fn from_u32(v: u32) -> Self { + match v { + 1 => Self::Bt601, + 2 => Self::Bt2020, + _ => Self::Bt709, + } + } +} + +/// Compact 8-bit 4:2:0 bi-planar NV12 video frame (`Y` + interleaved `CbCr`) with +/// colorimetry and rotation metadata for direct single-pass GPU conversion. +#[derive(Clone, Debug)] +pub struct Nv12Frame { + /// Unrotated raw sensor dimensions `[raw_w, raw_h]`. + pub raw_size: [u32; 2], + /// Rotated display dimensions `[out_w, out_h]`. + pub display_size: [u32; 2], + /// Clockwise rotation in degrees (`0`, `90`, `180`, or `270`). + pub rot_deg: u32, + /// YCbCr-to-RGB matrix (`BT.709`, `BT.601`, or `BT.2020`). + pub matrix: YuvMatrix, + /// `true` for full-range (`0..255`), `false` for video-range (`Y: 16..235`, `UV: 16..240`). + pub is_full_range: bool, + /// Tightly packed 8-bit luma plane (`raw_w * raw_h` bytes). + pub y: Vec, + /// Tightly packed interleaved 8-bit CbCr plane (`uv_w * uv_h * 2` bytes). + pub uv: Vec, +} + +impl Nv12Frame { + pub fn uv_size(&self) -> [u32; 2] { + [self.raw_size[0].div_ceil(2), self.raw_size[1].div_ceil(2)] + } + + pub fn byte_size(&self) -> u64 { + (self.y.len() + self.uv.len()) as u64 + } + + /// Reference CPU NV12 -> RGBA8 conversion matching `nv12_to_rgba.wgsl` + /// (center-aligned bilinear chroma sampling, rotation, and ITU-R matrix). + /// Used only by legacy CPU-only callers (`load_clip`, `VideoDecoder::decode_frame`, tests). + pub fn to_rgba8(&self) -> Vec { + let [raw_w, raw_h] = self.raw_size; + let [out_w, out_h] = self.display_size; + let [uv_w, uv_h] = self.uv_size(); + let total_px = (out_w as usize).saturating_mul(out_h as usize); + let mut out = vec![0u8; total_px * 4]; + if raw_w == 0 || raw_h == 0 || uv_w == 0 || uv_h == 0 || out_w == 0 || out_h == 0 { + return out; + } + if self.y.len() < (raw_w as usize) * (raw_h as usize) + || self.uv.len() < (uv_w as usize) * (uv_h as usize) * 2 + { + return out; + } + + let sample_uv = |u_norm: f32, v_norm: f32| -> (f32, f32) { + let fx = u_norm * (uv_w as f32) - 0.5; + let fy = v_norm * (uv_h as f32) - 0.5; + let x0 = (fx.floor() as i32).clamp(0, uv_w as i32 - 1) as usize; + let y0 = (fy.floor() as i32).clamp(0, uv_h as i32 - 1) as usize; + let x1 = (x0 + 1).min(uv_w as usize - 1); + let y1 = (y0 + 1).min(uv_h as usize - 1); + let tx = fx - fx.floor(); + let ty = fy - fy.floor(); + let wx = if fx < 0.0 { + 0.0 + } else if fx >= (uv_w as f32 - 1.0) { + 0.0 + } else { + tx + }; + let wy = if fy < 0.0 { + 0.0 + } else if fy >= (uv_h as f32 - 1.0) { + 0.0 + } else { + ty + }; + + let read_pair = |x: usize, y: usize| -> (f32, f32) { + let idx = (y * (uv_w as usize) + x) * 2; + (self.uv[idx] as f32 / 255.0, self.uv[idx + 1] as f32 / 255.0) + }; + let (c00, r00) = read_pair(x0, y0); + let (c10, r10) = read_pair(x1, y0); + let (c01, r01) = read_pair(x0, y1); + let (c11, r11) = read_pair(x1, y1); + + let c0 = c00 + (c10 - c00) * wx; + let c1 = c01 + (c11 - c01) * wx; + let cb = c0 + (c1 - c0) * wy; + + let r0 = r00 + (r10 - r00) * wx; + let r1 = r01 + (r11 - r01) * wx; + let cr = r0 + (r1 - r0) * wy; + (cb, cr) + }; + + let inv_raw_w = 1.0 / (raw_w as f32); + let inv_raw_h = 1.0 / (raw_h as f32); + let rw = raw_w as usize; + + for dy in 0..out_h { + for dx in 0..out_w { + let (sx, sy) = match self.rot_deg { + 90 => (dy, raw_h.saturating_sub(1).saturating_sub(dx)), + 180 => ( + raw_w.saturating_sub(1).saturating_sub(dx), + raw_h.saturating_sub(1).saturating_sub(dy), + ), + 270 => (raw_w.saturating_sub(1).saturating_sub(dy), dx), + _ => (dx, dy), + }; + let sx = sx.min(raw_w - 1); + let sy = sy.min(raw_h - 1); + + let y_raw = self.y[(sy as usize) * rw + (sx as usize)] as f32 / 255.0; + let (cb_raw, cr_raw) = + sample_uv((sx as f32 + 0.5) * inv_raw_w, (sy as f32 + 0.5) * inv_raw_h); + + let (y, cb, cr) = if self.is_full_range { + (y_raw, cb_raw - (128.0 / 255.0), cr_raw - (128.0 / 255.0)) + } else { + ( + (y_raw - (16.0 / 255.0)) * (255.0 / 219.0), + (cb_raw - (128.0 / 255.0)) * (255.0 / 224.0), + (cr_raw - (128.0 / 255.0)) * (255.0 / 224.0), + ) + }; + + let (r, g, b) = match self.matrix { + YuvMatrix::Bt601 => ( + y + 1.402_f32 * cr, + y - 0.344_136_29_f32 * cb - 0.714_136_29_f32 * cr, + y + 1.772_f32 * cb, + ), + YuvMatrix::Bt2020 => ( + y + 1.4746_f32 * cr, + y - 0.164_553_13_f32 * cb - 0.571_353_13_f32 * cr, + y + 1.8814_f32 * cb, + ), + YuvMatrix::Bt709 => ( + y + 1.5748_f32 * cr, + y - 0.187_324_27_f32 * cb - 0.468_124_27_f32 * cr, + y + 1.8556_f32 * cb, + ), + }; + + let dst = ((dy as usize) * (out_w as usize) + (dx as usize)) * 4; + out[dst] = (r.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + out[dst + 1] = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + out[dst + 2] = (b.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + out[dst + 3] = 255; + } + } + out + } +} + +pub enum DecodedVideoFrame { + Rgba(Vec), + Nv12(Nv12Frame), +} + pub trait VideoDecoder: Send { fn info(&self) -> VideoInfo; fn decode_frame(&mut self, frame_idx: i64) -> Option>; + fn decode_frame_native(&mut self, frame_idx: i64) -> Option { + self.decode_frame(frame_idx).map(DecodedVideoFrame::Rgba) + } fn backend_name(&self) -> &'static str; } @@ -32,6 +209,13 @@ mod av_ffi { out_nb_frames: *mut i64, ) -> *mut AvVideoDecoder; + pub fn av_video_is_nv12( + dec: *mut AvVideoDecoder, + out_raw_w: *mut u32, + out_raw_h: *mut u32, + out_rotation: *mut u32, + ) -> i32; + pub fn av_video_decode_frame( dec: *mut AvVideoDecoder, frame_idx: i64, @@ -39,6 +223,17 @@ mod av_ffi { out_len: usize, ) -> i32; + pub fn av_video_decode_nv12_frame( + dec: *mut AvVideoDecoder, + frame_idx: i64, + out_y: *mut u8, + out_y_len: usize, + out_uv: *mut u8, + out_uv_len: usize, + out_matrix: *mut u32, + out_full_range: *mut u32, + ) -> i32; + pub fn av_video_close(dec: *mut AvVideoDecoder); } } @@ -47,6 +242,7 @@ mod av_ffi { pub struct AvFoundationDecoder { ptr: *mut av_ffi::AvVideoDecoder, info: VideoInfo, + nv12_info: Option<([u32; 2], u32)>, } #[cfg(target_os = "macos")] @@ -87,6 +283,17 @@ impl AvFoundationDecoder { } return None; } + let mut raw_w = 0u32; + let mut raw_h = 0u32; + let mut rot_deg = 0u32; + let is_nv12 = unsafe { + av_ffi::av_video_is_nv12(ptr, &mut raw_w, &mut raw_h, &mut rot_deg) != 0 + }; + let nv12_info = if is_nv12 && raw_w > 0 && raw_h > 0 { + Some(([raw_w, raw_h], rot_deg)) + } else { + None + }; Some(Self { ptr, info: VideoInfo { @@ -95,8 +302,50 @@ impl AvFoundationDecoder { fps: if fps > 0.0 { fps } else { 30.0 }, nb_frames, }, + nv12_info, }) } + + pub fn is_nv12(&self) -> bool { + self.nv12_info.is_some() + } + + pub fn decode_nv12_frame(&mut self, frame_idx: i64) -> Option { + let ([raw_w, raw_h], rot_deg) = self.nv12_info?; + let y_len = (raw_w as usize).checked_mul(raw_h as usize)?; + let uv_w = raw_w.div_ceil(2) as usize; + let uv_h = raw_h.div_ceil(2) as usize; + let uv_len = uv_w.checked_mul(uv_h)?.checked_mul(2)?; + let mut y = vec![0u8; y_len]; + let mut uv = vec![0u8; uv_len]; + let mut matrix = 0u32; + let mut full_range = 0u32; + let ok = unsafe { + av_ffi::av_video_decode_nv12_frame( + self.ptr, + frame_idx.max(0), + y.as_mut_ptr(), + y_len, + uv.as_mut_ptr(), + uv_len, + &mut matrix, + &mut full_range, + ) + }; + if ok != 0 { + Some(Nv12Frame { + raw_size: [raw_w, raw_h], + display_size: [self.info.width, self.info.height], + rot_deg, + matrix: YuvMatrix::from_u32(matrix), + is_full_range: full_range != 0, + y, + uv, + }) + } else { + None + } + } } #[cfg(target_os = "macos")] @@ -106,6 +355,9 @@ impl VideoDecoder for AvFoundationDecoder { } fn decode_frame(&mut self, frame_idx: i64) -> Option> { + if self.nv12_info.is_some() { + return self.decode_nv12_frame(frame_idx).map(|f| f.to_rgba8()); + } let len = (self.info.width as usize) .checked_mul(self.info.height as usize)? .checked_mul(4)?; @@ -120,6 +372,14 @@ impl VideoDecoder for AvFoundationDecoder { } } + fn decode_frame_native(&mut self, frame_idx: i64) -> Option { + if self.nv12_info.is_some() { + self.decode_nv12_frame(frame_idx).map(DecodedVideoFrame::Nv12) + } else { + self.decode_frame(frame_idx).map(DecodedVideoFrame::Rgba) + } + } + fn backend_name(&self) -> &'static str { "AVFoundation/VideoToolbox" } diff --git a/crates/engine/src/shaders/nv12_to_rgba.wgsl b/crates/engine/src/shaders/nv12_to_rgba.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..d578bd3b8ad17c4ea91fb1cf51676556797c2b6f --- /dev/null +++ b/crates/engine/src/shaders/nv12_to_rgba.wgsl @@ -0,0 +1,91 @@ +// Single-pass NV12 (8-bit 4:2:0 bi-planar Y + interleaved CbCr) -> RGBA compute shader +// with integrated clockwise 0/90/180/270 rotation and ITU-R BT.709 / BT.601 / BT.2020 +// video-range or full-range color conversion. 100% WebGPU-safe. + +struct Nv12Params { + raw_w: u32, + raw_h: u32, + out_w: u32, + out_h: u32, + rot_deg: u32, + matrix_id: u32, + full_range: u32, + _pad: u32, +}; + +@group(0) @binding(0) var y_tex: texture_2d; +@group(0) @binding(1) var uv_tex: texture_2d; +@group(0) @binding(2) var uv_sampler: sampler; +@group(0) @binding(3) var dst_tex: texture_storage_2d; +@group(0) @binding(4) var params: Nv12Params; + +@compute @workgroup_size(8, 8, 1) +fn nv12_to_rgba(@builtin(global_invocation_id) gid: vec3) { + let dx = gid.x; + let dy = gid.y; + if (dx >= params.out_w || dy >= params.out_h) { + return; + } + + var sx: u32 = dx; + var sy: u32 = dy; + if (params.rot_deg == 90u) { + sx = dy; + sy = params.raw_h - 1u - dx; + } else if (params.rot_deg == 180u) { + sx = params.raw_w - 1u - dx; + sy = params.raw_h - 1u - dy; + } else if (params.rot_deg == 270u) { + sx = params.raw_w - 1u - dy; + sy = dx; + } + sx = min(sx, params.raw_w - 1u); + sy = min(sy, params.raw_h - 1u); + + let y_raw = textureLoad(y_tex, vec2(i32(sx), i32(sy)), 0).r; + let uv_coord = vec2( + (f32(sx) + 0.5) / f32(params.raw_w), + (f32(sy) + 0.5) / f32(params.raw_h), + ); + let uv_raw = textureSampleLevel(uv_tex, uv_sampler, uv_coord, 0.0).rg; + + var y: f32; + var cb: f32; + var cr: f32; + if (params.full_range != 0u) { + y = y_raw; + cb = uv_raw.x - (128.0 / 255.0); + cr = uv_raw.y - (128.0 / 255.0); + } else { + y = (y_raw - (16.0 / 255.0)) * (255.0 / 219.0); + cb = (uv_raw.x - (128.0 / 255.0)) * (255.0 / 224.0); + cr = (uv_raw.y - (128.0 / 255.0)) * (255.0 / 224.0); + } + + var rgb: vec3; + if (params.matrix_id == 1u) { + // ITU-R BT.601 (Kr = 0.299, Kb = 0.114) + rgb = vec3( + y + 1.402 * cr, + y - 0.34413629 * cb - 0.71413629 * cr, + y + 1.772 * cb, + ); + } else if (params.matrix_id == 2u) { + // ITU-R BT.2020 (Kr = 0.2627, Kb = 0.0593) + rgb = vec3( + y + 1.4746 * cr, + y - 0.16455313 * cb - 0.57135313 * cr, + y + 1.8814 * cb, + ); + } else { + // ITU-R BT.709 (Kr = 0.2126, Kb = 0.0722) + rgb = vec3( + y + 1.5748 * cr, + y - 0.18732427 * cb - 0.46812427 * cr, + y + 1.8556 * cb, + ); + } + + let clamped = clamp(rgb, vec3(0.0), vec3(1.0)); + textureStore(dst_tex, vec2(i32(dx), i32(dy)), vec4(clamped, 1.0)); +} -- 2.54.1