| author | |
| committer | |
| log | 3cd007bf53605e9c37fb396aa60137d13c380f31 |
| tree | 748abdb0f9ae9f8c9e933eb425ef2c23fbaa6e0f |
| parent | 0e0496e04ce4737c013b1a715b37cfe35c4aca31 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
7 files changed, 2028 insertions(+), 154 deletions(-)
crates/engine/src/av_decode.m+457-46| ... | @@ -22,13 +22,22 @@ | ... | @@ -22,13 +22,22 @@ |
| 22 | @property(nonatomic, strong) AVAssetReaderTrackOutput *output; | 22 | @property(nonatomic, strong) AVAssetReaderTrackOutput *output; |
| 23 | @property(nonatomic, assign) uint32_t width; | 23 | @property(nonatomic, assign) uint32_t width; |
| 24 | @property(nonatomic, assign) uint32_t height; | 24 | @property(nonatomic, assign) uint32_t height; |
| 25 | @property(nonatomic, assign) uint32_t rawWidth; | ||
| 26 | @property(nonatomic, assign) uint32_t rawHeight; | ||
| 25 | @property(nonatomic, assign) int rotation; // 0, 90, 180, 270 clockwise | 27 | @property(nonatomic, assign) int rotation; // 0, 90, 180, 270 clockwise |
| 28 | @property(nonatomic, assign) BOOL useNv12; | ||
| 29 | @property(nonatomic, assign) BOOL preferFullRange; | ||
| 30 | @property(nonatomic, assign) uint32_t defaultMatrix; // 0=BT.709, 1=BT.601, 2=BT.2020 | ||
| 26 | @property(nonatomic, assign) double fps; | 31 | @property(nonatomic, assign) double fps; |
| 27 | @property(nonatomic, assign) int64_t nbFrames; | 32 | @property(nonatomic, assign) int64_t nbFrames; |
| 28 | @property(nonatomic, assign) double trackStartSec; | 33 | @property(nonatomic, assign) double trackStartSec; |
| 29 | @property(nonatomic, assign) double durSec; | 34 | @property(nonatomic, assign) double durSec; |
| 30 | @property(nonatomic, assign) int64_t lastFrameIdx; | 35 | @property(nonatomic, assign) int64_t lastFrameIdx; |
| 31 | @property(nonatomic, strong) NSMutableData *lastFrameRgba; | 36 | @property(nonatomic, strong) NSMutableData *lastFrameRgba; |
| 37 | @property(nonatomic, strong) NSMutableData *lastFrameY; | ||
| 38 | @property(nonatomic, strong) NSMutableData *lastFrameUv; | ||
| 39 | @property(nonatomic, assign) uint32_t lastFrameMatrix; | ||
| 40 | @property(nonatomic, assign) uint32_t lastFrameFullRange; | ||
| 32 | @property(nonatomic, assign) BOOL hasLastFrame; | 41 | @property(nonatomic, assign) BOOL hasLastFrame; |
| 33 | @property(nonatomic, assign) BOOL lastFrameIsEof; | 42 | @property(nonatomic, assign) BOOL lastFrameIsEof; |
| 34 | @end | 43 | @end |
| ... | @@ -51,8 +60,14 @@ | ... | @@ -51,8 +60,14 @@ |
| 51 | if (!r || err) { | 60 | if (!r || err) { |
| 52 | return NO; | 61 | return NO; |
| 53 | } | 62 | } |
| 63 | OSType pixFmt = kCVPixelFormatType_32BGRA; | ||
| 64 | if (self.useNv12) { | ||
| 65 | pixFmt = self.preferFullRange | ||
| 66 | ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange | ||
| 67 | : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; | ||
| 68 | } | ||
| 54 | NSDictionary *settings = @{ | 69 | NSDictionary *settings = @{ |
| 55 | (NSString *)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA), | 70 | (NSString *)kCVPixelBufferPixelFormatTypeKey : @(pixFmt), |
| 56 | }; | 71 | }; |
| 57 | AVAssetReaderTrackOutput *out = | 72 | AVAssetReaderTrackOutput *out = |
| 58 | [[AVAssetReaderTrackOutput alloc] initWithTrack:self.track outputSettings:settings]; | 73 | [[AVAssetReaderTrackOutput alloc] initWithTrack:self.track outputSettings:settings]; |
| ... | @@ -315,6 +330,231 @@ static int copy_bgra_to_rgba( | ... | @@ -315,6 +330,231 @@ static int copy_bgra_to_rgba( |
| 315 | return ok; | 330 | return ok; |
| 316 | } | 331 | } |
| 317 | 332 | ||
| 333 | static uint32_t matrix_from_cf_string(CFTypeRef matrixRef, uint32_t fallback) { | ||
| 334 | if (!matrixRef || CFGetTypeID(matrixRef) != CFStringGetTypeID()) { | ||
| 335 | return fallback; | ||
| 336 | } | ||
| 337 | CFStringRef ms = (CFStringRef)matrixRef; | ||
| 338 | if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_601_4) || | ||
| 339 | CFEqual(ms, kCVImageBufferYCbCrMatrix_SMPTE_240M_1995)) { | ||
| 340 | return 1u; // BT.601 | ||
| 341 | } | ||
| 342 | if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_2020)) { | ||
| 343 | return 2u; // BT.2020 | ||
| 344 | } | ||
| 345 | if (CFEqual(ms, kCVImageBufferYCbCrMatrix_ITU_R_709_2)) { | ||
| 346 | return 0u; // BT.709 | ||
| 347 | } | ||
| 348 | return fallback; | ||
| 349 | } | ||
| 350 | |||
| 351 | static BOOL track_supports_nv12_8bit_420( | ||
| 352 | AVAssetTrack *track, | ||
| 353 | uint32_t rawW, | ||
| 354 | uint32_t rawH, | ||
| 355 | BOOL *outFullRange, | ||
| 356 | uint32_t *outDefaultMatrix | ||
| 357 | ) { | ||
| 358 | if (outFullRange) { | ||
| 359 | *outFullRange = NO; | ||
| 360 | } | ||
| 361 | // CoreVideo defaults untagged HD/4K to BT.709 and SD to BT.601. | ||
| 362 | uint32_t defaultMat = (rawW >= 1280 || rawH >= 720) ? 0u : 1u; | ||
| 363 | if (outDefaultMatrix) { | ||
| 364 | *outDefaultMatrix = defaultMat; | ||
| 365 | } | ||
| 366 | |||
| 367 | NSArray *formatDescs = track.formatDescriptions; | ||
| 368 | if (!formatDescs || formatDescs.count == 0) { | ||
| 369 | return NO; | ||
| 370 | } | ||
| 371 | CMFormatDescriptionRef fmtDesc = (__bridge CMFormatDescriptionRef)formatDescs.firstObject; | ||
| 372 | if (!fmtDesc) { | ||
| 373 | return NO; | ||
| 374 | } | ||
| 375 | |||
| 376 | FourCharCode subType = CMFormatDescriptionGetMediaSubType(fmtDesc); | ||
| 377 | const FourCharCode kHev1 = 0x68657631; // 'hev1' | ||
| 378 | BOOL is420Codec = | ||
| 379 | (subType == kCMVideoCodecType_H264) || | ||
| 380 | (subType == kCMVideoCodecType_HEVC) || | ||
| 381 | (subType == kHev1) || | ||
| 382 | (subType == kCMVideoCodecType_MPEG4Video); | ||
| 383 | if (!is420Codec) { | ||
| 384 | return NO; | ||
| 385 | } | ||
| 386 | |||
| 387 | // Reject alpha-bearing tracks (ProRes 4444, HEVC with alpha, etc.). | ||
| 388 | CFTypeRef hasAlphaRef = CMFormatDescriptionGetExtension( | ||
| 389 | fmtDesc, kCMFormatDescriptionExtension_ContainsAlphaChannel); | ||
| 390 | if (hasAlphaRef && CFGetTypeID(hasAlphaRef) == CFBooleanGetTypeID() && | ||
| 391 | CFBooleanGetValue((CFBooleanRef)hasAlphaRef)) { | ||
| 392 | return NO; | ||
| 393 | } | ||
| 394 | CFTypeRef depthRef = CMFormatDescriptionGetExtension( | ||
| 395 | fmtDesc, kCMFormatDescriptionExtension_Depth); | ||
| 396 | if (depthRef && CFGetTypeID(depthRef) == CFNumberGetTypeID()) { | ||
| 397 | int depth = 0; | ||
| 398 | if (CFNumberGetValue((CFNumberRef)depthRef, kCFNumberIntType, &depth) && depth == 32) { | ||
| 399 | return NO; | ||
| 400 | } | ||
| 401 | } | ||
| 402 | |||
| 403 | // Reject >8-bit (10-bit/12-bit) streams. | ||
| 404 | CFTypeRef bpcRef = CMFormatDescriptionGetExtension( | ||
| 405 | fmtDesc, kCMFormatDescriptionExtension_BitsPerComponent); | ||
| 406 | if (bpcRef && CFGetTypeID(bpcRef) == CFNumberGetTypeID()) { | ||
| 407 | int bpc = 0; | ||
| 408 | if (CFNumberGetValue((CFNumberRef)bpcRef, kCFNumberIntType, &bpc) && bpc != 8) { | ||
| 409 | return NO; | ||
| 410 | } | ||
| 411 | } | ||
| 412 | |||
| 413 | // Reject HDR transfer functions (HLG, PQ, Linear) so CoreVideo handles HDR tone-mapping. | ||
| 414 | CFTypeRef tfRef = CMFormatDescriptionGetExtension( | ||
| 415 | fmtDesc, kCMFormatDescriptionExtension_TransferFunction); | ||
| 416 | if (tfRef && CFGetTypeID(tfRef) == CFStringGetTypeID()) { | ||
| 417 | CFStringRef tf = (CFStringRef)tfRef; | ||
| 418 | if (CFEqual(tf, kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG) || | ||
| 419 | CFEqual(tf, kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ) || | ||
| 420 | CFEqual(tf, kCMFormatDescriptionTransferFunction_Linear)) { | ||
| 421 | return NO; | ||
| 422 | } | ||
| 423 | } | ||
| 424 | |||
| 425 | // Inspect avcC / hvcC decoder config records to reject 10-bit or non-4:2:0 profiles | ||
| 426 | // even when BitsPerComponent is omitted by the container. | ||
| 427 | CFTypeRef atomsRef = CMFormatDescriptionGetExtension( | ||
| 428 | fmtDesc, kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms); | ||
| 429 | if (atomsRef && CFGetTypeID(atomsRef) == CFDictionaryGetTypeID()) { | ||
| 430 | NSDictionary *atoms = (__bridge NSDictionary *)atomsRef; | ||
| 431 | if (subType == kCMVideoCodecType_H264) { | ||
| 432 | NSData *avcC = atoms[@"avcC"]; | ||
| 433 | if ([avcC isKindOfClass:[NSData class]] && avcC.length >= 4) { | ||
| 434 | const uint8_t *b = (const uint8_t *)avcC.bytes; | ||
| 435 | uint8_t profile = b[1]; | ||
| 436 | // Reject High 10 (110), High 4:2:2 (122), CAVLC 4:4:4 (44), High 4:4:4 (144/244) | ||
| 437 | if (profile == 44 || profile == 110 || profile == 122 || profile == 144 || profile == 244) { | ||
| 438 | return NO; | ||
| 439 | } | ||
| 440 | } | ||
| 441 | } else if (subType == kCMVideoCodecType_HEVC || subType == kHev1) { | ||
| 442 | NSData *hvcC = atoms[@"hvcC"]; | ||
| 443 | if ([hvcC isKindOfClass:[NSData class]] && hvcC.length >= 22) { | ||
| 444 | const uint8_t *b = (const uint8_t *)hvcC.bytes; | ||
| 445 | uint8_t profileIdc = b[1] & 0x1F; | ||
| 446 | uint8_t chromaFormat = b[16] & 0x03; // 1 = 4:2:0 | ||
| 447 | uint8_t bitDepthLumaMinus8 = b[17] & 0x07; | ||
| 448 | uint8_t bitDepthChromaMinus8 = b[18] & 0x07; | ||
| 449 | if (profileIdc == 2 || chromaFormat != 1 || | ||
| 450 | bitDepthLumaMinus8 > 0 || bitDepthChromaMinus8 > 0) { | ||
| 451 | return NO; | ||
| 452 | } | ||
| 453 | } | ||
| 454 | } | ||
| 455 | } | ||
| 456 | |||
| 457 | CFTypeRef fullRangeRef = CMFormatDescriptionGetExtension( | ||
| 458 | fmtDesc, kCMFormatDescriptionExtension_FullRangeVideo); | ||
| 459 | if (fullRangeRef && CFGetTypeID(fullRangeRef) == CFBooleanGetTypeID() && | ||
| 460 | CFBooleanGetValue((CFBooleanRef)fullRangeRef)) { | ||
| 461 | if (outFullRange) { | ||
| 462 | *outFullRange = YES; | ||
| 463 | } | ||
| 464 | } | ||
| 465 | |||
| 466 | CFTypeRef matRef = CMFormatDescriptionGetExtension( | ||
| 467 | fmtDesc, kCMFormatDescriptionExtension_YCbCrMatrix); | ||
| 468 | if (outDefaultMatrix) { | ||
| 469 | *outDefaultMatrix = matrix_from_cf_string(matRef, defaultMat); | ||
| 470 | } | ||
| 471 | |||
| 472 | return YES; | ||
| 473 | } | ||
| 474 | |||
| 475 | static int copy_nv12_planes( | ||
| 476 | CVImageBufferRef imgBuf, | ||
| 477 | uint32_t expectedW, | ||
| 478 | uint32_t expectedH, | ||
| 479 | uint32_t defaultMatrix, | ||
| 480 | uint8_t *outY, | ||
| 481 | size_t outYLen, | ||
| 482 | uint8_t *outUv, | ||
| 483 | size_t outUvLen, | ||
| 484 | uint32_t *outMatrix, | ||
| 485 | uint32_t *outFullRange | ||
| 486 | ) { | ||
| 487 | if (!imgBuf || !outY || !outUv) { | ||
| 488 | return 0; | ||
| 489 | } | ||
| 490 | OSType pf = CVPixelBufferGetPixelFormatType(imgBuf); | ||
| 491 | if (pf != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange && | ||
| 492 | pf != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { | ||
| 493 | return 0; | ||
| 494 | } | ||
| 495 | if (!CVPixelBufferIsPlanar(imgBuf) || CVPixelBufferGetPlaneCount(imgBuf) < 2) { | ||
| 496 | return 0; | ||
| 497 | } | ||
| 498 | if (CVPixelBufferLockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) { | ||
| 499 | return 0; | ||
| 500 | } | ||
| 501 | |||
| 502 | size_t yW = CVPixelBufferGetWidthOfPlane(imgBuf, 0); | ||
| 503 | size_t yH = CVPixelBufferGetHeightOfPlane(imgBuf, 0); | ||
| 504 | size_t yBpr = CVPixelBufferGetBytesPerRowOfPlane(imgBuf, 0); | ||
| 505 | const uint8_t *yBase = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imgBuf, 0); | ||
| 506 | |||
| 507 | size_t uvW = CVPixelBufferGetWidthOfPlane(imgBuf, 1); | ||
| 508 | size_t uvH = CVPixelBufferGetHeightOfPlane(imgBuf, 1); | ||
| 509 | size_t uvBpr = CVPixelBufferGetBytesPerRowOfPlane(imgBuf, 1); | ||
| 510 | const uint8_t *uvBase = (const uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imgBuf, 1); | ||
| 511 | |||
| 512 | size_t expectedUvW = ((size_t)expectedW + 1) / 2; | ||
| 513 | size_t expectedUvH = ((size_t)expectedH + 1) / 2; | ||
| 514 | size_t yRequired = (size_t)expectedW * (size_t)expectedH; | ||
| 515 | size_t uvRowBytes = expectedUvW * 2; | ||
| 516 | size_t uvRequired = uvRowBytes * expectedUvH; | ||
| 517 | |||
| 518 | int ok = 0; | ||
| 519 | if (yBase && uvBase && | ||
| 520 | yW == expectedW && yH == expectedH && | ||
| 521 | uvW == expectedUvW && uvH == expectedUvH && | ||
| 522 | yBpr >= yW && uvBpr >= uvRowBytes && | ||
| 523 | outYLen >= yRequired && outUvLen >= uvRequired) { | ||
| 524 | if (yBpr == yW) { | ||
| 525 | memcpy(outY, yBase, yRequired); | ||
| 526 | } else { | ||
| 527 | for (size_t r = 0; r < yH; r++) { | ||
| 528 | memcpy(outY + r * yW, yBase + r * yBpr, yW); | ||
| 529 | } | ||
| 530 | } | ||
| 531 | if (uvBpr == uvRowBytes) { | ||
| 532 | memcpy(outUv, uvBase, uvRequired); | ||
| 533 | } else { | ||
| 534 | for (size_t r = 0; r < uvH; r++) { | ||
| 535 | memcpy(outUv + r * uvRowBytes, uvBase + r * uvBpr, uvRowBytes); | ||
| 536 | } | ||
| 537 | } | ||
| 538 | ok = 1; | ||
| 539 | } | ||
| 540 | |||
| 541 | CVPixelBufferUnlockBaseAddress(imgBuf, kCVPixelBufferLock_ReadOnly); | ||
| 542 | |||
| 543 | if (ok) { | ||
| 544 | if (outFullRange) { | ||
| 545 | *outFullRange = (pf == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) ? 1u : 0u; | ||
| 546 | } | ||
| 547 | if (outMatrix) { | ||
| 548 | CFTypeRef matRef = CVBufferCopyAttachment(imgBuf, kCVImageBufferYCbCrMatrixKey, NULL); | ||
| 549 | *outMatrix = matrix_from_cf_string(matRef, defaultMatrix); | ||
| 550 | if (matRef) { | ||
| 551 | CFRelease(matRef); | ||
| 552 | } | ||
| 553 | } | ||
| 554 | } | ||
| 555 | return ok; | ||
| 556 | } | ||
| 557 | |||
| 318 | AvVideoDecoder *av_video_open( | 558 | AvVideoDecoder *av_video_open( |
| 319 | const char *path, | 559 | const char *path, |
| 320 | uint32_t *out_w, | 560 | uint32_t *out_w, |
| ... | @@ -402,24 +642,46 @@ AvVideoDecoder *av_video_open( | ... | @@ -402,24 +642,46 @@ AvVideoDecoder *av_video_open( |
| 402 | } | 642 | } |
| 403 | } | 643 | } |
| 404 | 644 | ||
| 645 | BOOL preferFullRange = NO; | ||
| 646 | uint32_t defaultMatrix = 0u; | ||
| 647 | BOOL useNv12 = track_supports_nv12_8bit_420( | ||
| 648 | track, natW, natH, &preferFullRange, &defaultMatrix); | ||
| 649 | |||
| 405 | AvVideoDecoderObj *obj = [[AvVideoDecoderObj alloc] init]; | 650 | AvVideoDecoderObj *obj = [[AvVideoDecoderObj alloc] init]; |
| 406 | obj.asset = asset; | 651 | obj.asset = asset; |
| 407 | obj.track = track; | 652 | obj.track = track; |
| 408 | obj.width = outW; | 653 | obj.width = outW; |
| 409 | obj.height = outH; | 654 | obj.height = outH; |
| 655 | obj.rawWidth = natW; | ||
| 656 | obj.rawHeight = natH; | ||
| 410 | obj.rotation = rotation; | 657 | obj.rotation = rotation; |
| 658 | obj.useNv12 = useNv12; | ||
| 659 | obj.preferFullRange = preferFullRange; | ||
| 660 | obj.defaultMatrix = defaultMatrix; | ||
| 411 | obj.fps = fps; | 661 | obj.fps = fps; |
| 412 | obj.nbFrames = nbFrames; | 662 | obj.nbFrames = nbFrames; |
| 413 | obj.trackStartSec = trackStartSec; | 663 | obj.trackStartSec = trackStartSec; |
| 414 | obj.durSec = durSec; | 664 | obj.durSec = durSec; |
| 415 | obj.lastFrameIdx = -1; | 665 | obj.lastFrameIdx = -1; |
| 416 | obj.lastFrameRgba = nil; | 666 | obj.lastFrameRgba = nil; |
| 667 | obj.lastFrameY = nil; | ||
| 668 | obj.lastFrameUv = nil; | ||
| 669 | obj.lastFrameMatrix = defaultMatrix; | ||
| 670 | obj.lastFrameFullRange = preferFullRange ? 1u : 0u; | ||
| 417 | obj.hasLastFrame = NO; | 671 | obj.hasLastFrame = NO; |
| 418 | obj.lastFrameIsEof = NO; | 672 | obj.lastFrameIsEof = NO; |
| 419 | 673 | ||
| 420 | // Verify AVAssetReader can actually open and decode this asset/codec. | 674 | // Verify AVAssetReader can actually open and decode this asset/codec. |
| 675 | // If NV12 output is rejected for an unusual stream, fall back seamlessly to 32BGRA. | ||
| 421 | if (![obj openReaderAtSeconds:0.0]) { | 676 | if (![obj openReaderAtSeconds:0.0]) { |
| 422 | return NULL; | 677 | if (obj.useNv12) { |
| 678 | obj.useNv12 = NO; | ||
| 679 | if (![obj openReaderAtSeconds:0.0]) { | ||
| 680 | return NULL; | ||
| 681 | } | ||
| 682 | } else { | ||
| 683 | return NULL; | ||
| 684 | } | ||
| 423 | } | 685 | } |
| 424 | 686 | ||
| 425 | *out_w = outW; | 687 | *out_w = outW; |
| ... | @@ -430,6 +692,31 @@ AvVideoDecoder *av_video_open( | ... | @@ -430,6 +692,31 @@ AvVideoDecoder *av_video_open( |
| 430 | } | 692 | } |
| 431 | } | 693 | } |
| 432 | 694 | ||
| 695 | int av_video_is_nv12( | ||
| 696 | AvVideoDecoder *dec, | ||
| 697 | uint32_t *out_raw_w, | ||
| 698 | uint32_t *out_raw_h, | ||
| 699 | uint32_t *out_rotation | ||
| 700 | ) { | ||
| 701 | if (!dec) { | ||
| 702 | return 0; | ||
| 703 | } | ||
| 704 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; | ||
| 705 | if (!obj.useNv12) { | ||
| 706 | return 0; | ||
| 707 | } | ||
| 708 | if (out_raw_w) { | ||
| 709 | *out_raw_w = obj.rawWidth; | ||
| 710 | } | ||
| 711 | if (out_raw_h) { | ||
| 712 | *out_raw_h = obj.rawHeight; | ||
| 713 | } | ||
| 714 | if (out_rotation) { | ||
| 715 | *out_rotation = (uint32_t)obj.rotation; | ||
| 716 | } | ||
| 717 | return 1; | ||
| 718 | } | ||
| 719 | |||
| 433 | static CMSampleBufferRef read_target_sample( | 720 | static CMSampleBufferRef read_target_sample( |
| 434 | AvVideoDecoderObj *obj, | 721 | AvVideoDecoderObj *obj, |
| 435 | double targetPts, | 722 | double targetPts, |
| ... | @@ -473,6 +760,69 @@ static CMSampleBufferRef read_target_sample( | ... | @@ -473,6 +760,69 @@ static CMSampleBufferRef read_target_sample( |
| 473 | return chosen; | 760 | return chosen; |
| 474 | } | 761 | } |
| 475 | 762 | ||
| 763 | static CMSampleBufferRef acquire_video_sample( | ||
| 764 | AvVideoDecoderObj *obj, | ||
| 765 | int64_t frame_idx, | ||
| 766 | BOOL *outHitEof, | ||
| 767 | BOOL *outAtEof | ||
| 768 | ) { | ||
| 769 | double fps = obj.fps > 0.0 ? obj.fps : 30.0; | ||
| 770 | double targetPts = obj.trackStartSec + ((double)frame_idx) / fps; | ||
| 771 | double halfFrame = 0.45 / fps; | ||
| 772 | |||
| 773 | BOOL canAdvance = | ||
| 774 | obj.reader != nil && | ||
| 775 | obj.reader.status == AVAssetReaderStatusReading && | ||
| 776 | ((obj.lastFrameIdx == -1 && frame_idx <= 8) || | ||
| 777 | (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && | ||
| 778 | frame_idx <= obj.lastFrameIdx + 8)); | ||
| 779 | |||
| 780 | int64_t prevLastFrameIdx = obj.lastFrameIdx; | ||
| 781 | double seekSec = 0.0; | ||
| 782 | if (!canAdvance) { | ||
| 783 | seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); | ||
| 784 | if (![obj openReaderAtSeconds:seekSec]) { | ||
| 785 | if (outHitEof) *outHitEof = NO; | ||
| 786 | if (outAtEof) *outAtEof = NO; | ||
| 787 | return NULL; | ||
| 788 | } | ||
| 789 | } | ||
| 790 | |||
| 791 | BOOL hitEof = NO; | ||
| 792 | CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | ||
| 793 | |||
| 794 | // If requesting a frame past EOF (including sequential advance stepping past EOF or | ||
| 795 | // container duration overestimating the last video sample by > 4 frames), retry from | ||
| 796 | // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. | ||
| 797 | if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) { | ||
| 798 | double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; | ||
| 799 | double fallbackSec = fmax(0.0, endAnchor - 1.0); | ||
| 800 | if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { | ||
| 801 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | ||
| 802 | } | ||
| 803 | if (!chosen) { | ||
| 804 | double lastIdxSec = fmax( | ||
| 805 | 0.0, | ||
| 806 | prevLastFrameIdx >= 0 | ||
| 807 | ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 | ||
| 808 | : 0.0 | ||
| 809 | ); | ||
| 810 | if ([obj openReaderAtSeconds:lastIdxSec]) { | ||
| 811 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | ||
| 812 | } | ||
| 813 | } | ||
| 814 | } | ||
| 815 | |||
| 816 | if (outHitEof) { | ||
| 817 | *outHitEof = hitEof; | ||
| 818 | } | ||
| 819 | if (!chosen && outAtEof) { | ||
| 820 | *outAtEof = (obj.reader != nil && obj.reader.status == AVAssetReaderStatusCompleted) || | ||
| 821 | (obj.nbFrames > 0 && frame_idx >= obj.nbFrames - 2); | ||
| 822 | } | ||
| 823 | return chosen; | ||
| 824 | } | ||
| 825 | |||
| 476 | int av_video_decode_frame( | 826 | int av_video_decode_frame( |
| 477 | AvVideoDecoder *dec, | 827 | AvVideoDecoder *dec, |
| 478 | int64_t frame_idx, | 828 | int64_t frame_idx, |
| ... | @@ -484,6 +834,9 @@ int av_video_decode_frame( | ... | @@ -484,6 +834,9 @@ int av_video_decode_frame( |
| 484 | } | 834 | } |
| 485 | @autoreleasepool { | 835 | @autoreleasepool { |
| 486 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; | 836 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; |
| 837 | if (obj.useNv12) { | ||
| 838 | return 0; | ||
| 839 | } | ||
| 487 | if (frame_idx < 0) { | 840 | if (frame_idx < 0) { |
| 488 | frame_idx = 0; | 841 | frame_idx = 0; |
| 489 | } | 842 | } |
| ... | @@ -491,54 +844,12 @@ int av_video_decode_frame( | ... | @@ -491,54 +844,12 @@ int av_video_decode_frame( |
| 491 | if (out_len < required) { | 844 | if (out_len < required) { |
| 492 | return 0; | 845 | return 0; |
| 493 | } | 846 | } |
| 494 | double fps = obj.fps > 0.0 ? obj.fps : 30.0; | ||
| 495 | double targetPts = obj.trackStartSec + ((double)frame_idx) / fps; | ||
| 496 | double halfFrame = 0.45 / fps; | ||
| 497 | |||
| 498 | BOOL canAdvance = | ||
| 499 | obj.reader != nil && | ||
| 500 | obj.reader.status == AVAssetReaderStatusReading && | ||
| 501 | ((obj.lastFrameIdx == -1 && frame_idx <= 8) || | ||
| 502 | (obj.lastFrameIdx >= 0 && frame_idx > obj.lastFrameIdx && | ||
| 503 | frame_idx <= obj.lastFrameIdx + 8)); | ||
| 504 | |||
| 505 | int64_t prevLastFrameIdx = obj.lastFrameIdx; | ||
| 506 | double seekSec = 0.0; | ||
| 507 | if (!canAdvance) { | ||
| 508 | seekSec = (frame_idx == 0) ? 0.0 : fmax(0.0, targetPts - (1.5 / fps)); | ||
| 509 | if (![obj openReaderAtSeconds:seekSec]) { | ||
| 510 | return 0; | ||
| 511 | } | ||
| 512 | } | ||
| 513 | 847 | ||
| 514 | BOOL hitEof = NO; | 848 | BOOL hitEof = NO; |
| 515 | CMSampleBufferRef chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | 849 | BOOL atEof = NO; |
| 516 | 850 | CMSampleBufferRef chosen = acquire_video_sample(obj, frame_idx, &hitEof, &atEof); | |
| 517 | // If requesting a frame past EOF (including sequential advance stepping past EOF or | ||
| 518 | // container duration overestimating the last video sample by > 4 frames), retry from | ||
| 519 | // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp. | ||
| 520 | if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) { | ||
| 521 | double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts; | ||
| 522 | double fallbackSec = fmax(0.0, endAnchor - 1.0); | ||
| 523 | if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) { | ||
| 524 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | ||
| 525 | } | ||
| 526 | if (!chosen) { | ||
| 527 | double lastIdxSec = fmax( | ||
| 528 | 0.0, | ||
| 529 | prevLastFrameIdx >= 0 | ||
| 530 | ? obj.trackStartSec + (double)prevLastFrameIdx / fps - 0.1 | ||
| 531 | : 0.0 | ||
| 532 | ); | ||
| 533 | if ([obj openReaderAtSeconds:lastIdxSec]) { | ||
| 534 | chosen = read_target_sample(obj, targetPts, halfFrame, &hitEof); | ||
| 535 | } | ||
| 536 | } | ||
| 537 | } | ||
| 538 | 851 | ||
| 539 | if (!chosen) { | 852 | if (!chosen) { |
| 540 | BOOL atEof = (obj.reader != nil && obj.reader.status == AVAssetReaderStatusCompleted) || | ||
| 541 | (obj.nbFrames > 0 && frame_idx >= obj.nbFrames - 2); | ||
| 542 | [obj closeReader]; | 853 | [obj closeReader]; |
| 543 | if (atEof && obj.hasLastFrame && frame_idx > 0 && obj.lastFrameRgba.length >= required) { | 854 | if (atEof && obj.hasLastFrame && frame_idx > 0 && obj.lastFrameRgba.length >= required) { |
| 544 | memcpy(out_rgba, obj.lastFrameRgba.bytes, required); | 855 | memcpy(out_rgba, obj.lastFrameRgba.bytes, required); |
| ... | @@ -573,6 +884,106 @@ int av_video_decode_frame( | ... | @@ -573,6 +884,106 @@ int av_video_decode_frame( |
| 573 | } | 884 | } |
| 574 | } | 885 | } |
| 575 | 886 | ||
| 887 | int av_video_decode_nv12_frame( | ||
| 888 | AvVideoDecoder *dec, | ||
| 889 | int64_t frame_idx, | ||
| 890 | uint8_t *out_y, | ||
| 891 | size_t out_y_len, | ||
| 892 | uint8_t *out_uv, | ||
| 893 | size_t out_uv_len, | ||
| 894 | uint32_t *out_matrix, | ||
| 895 | uint32_t *out_full_range | ||
| 896 | ) { | ||
| 897 | if (!dec || !out_y || !out_uv) { | ||
| 898 | return 0; | ||
| 899 | } | ||
| 900 | @autoreleasepool { | ||
| 901 | AvVideoDecoderObj *obj = (__bridge AvVideoDecoderObj *)dec; | ||
| 902 | if (!obj.useNv12) { | ||
| 903 | return 0; | ||
| 904 | } | ||
| 905 | if (frame_idx < 0) { | ||
| 906 | frame_idx = 0; | ||
| 907 | } | ||
| 908 | size_t yRequired = (size_t)obj.rawWidth * (size_t)obj.rawHeight; | ||
| 909 | size_t uvW = ((size_t)obj.rawWidth + 1) / 2; | ||
| 910 | size_t uvH = ((size_t)obj.rawHeight + 1) / 2; | ||
| 911 | size_t uvRequired = uvW * uvH * 2; | ||
| 912 | if (out_y_len < yRequired || out_uv_len < uvRequired) { | ||
| 913 | return 0; | ||
| 914 | } | ||
| 915 | |||
| 916 | BOOL hitEof = NO; | ||
| 917 | BOOL atEof = NO; | ||
| 918 | CMSampleBufferRef chosen = acquire_video_sample(obj, frame_idx, &hitEof, &atEof); | ||
| 919 | |||
| 920 | if (!chosen) { | ||
| 921 | [obj closeReader]; | ||
| 922 | if (atEof && obj.hasLastFrame && frame_idx > 0 && | ||
| 923 | obj.lastFrameY.length >= yRequired && obj.lastFrameUv.length >= uvRequired) { | ||
| 924 | memcpy(out_y, obj.lastFrameY.bytes, yRequired); | ||
| 925 | memcpy(out_uv, obj.lastFrameUv.bytes, uvRequired); | ||
| 926 | if (out_matrix) { | ||
| 927 | *out_matrix = obj.lastFrameMatrix; | ||
| 928 | } | ||
| 929 | if (out_full_range) { | ||
| 930 | *out_full_range = obj.lastFrameFullRange; | ||
| 931 | } | ||
| 932 | return 1; | ||
| 933 | } | ||
| 934 | return 0; | ||
| 935 | } | ||
| 936 | |||
| 937 | uint32_t matrix = obj.defaultMatrix; | ||
| 938 | uint32_t fullRange = obj.preferFullRange ? 1u : 0u; | ||
| 939 | CVImageBufferRef imgBuf = CMSampleBufferGetImageBuffer(chosen); | ||
| 940 | int ok = copy_nv12_planes( | ||
| 941 | imgBuf, | ||
| 942 | obj.rawWidth, | ||
| 943 | obj.rawHeight, | ||
| 944 | obj.defaultMatrix, | ||
| 945 | out_y, | ||
| 946 | out_y_len, | ||
| 947 | out_uv, | ||
| 948 | out_uv_len, | ||
| 949 | &matrix, | ||
| 950 | &fullRange | ||
| 951 | ); | ||
| 952 | CFRelease(chosen); | ||
| 953 | |||
| 954 | if (ok) { | ||
| 955 | if (out_matrix) { | ||
| 956 | *out_matrix = matrix; | ||
| 957 | } | ||
| 958 | if (out_full_range) { | ||
| 959 | *out_full_range = fullRange; | ||
| 960 | } | ||
| 961 | if (hitEof || (!obj.lastFrameIsEof && (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4))) { | ||
| 962 | if (!obj.lastFrameY || obj.lastFrameY.length < yRequired) { | ||
| 963 | obj.lastFrameY = [NSMutableData dataWithLength:yRequired]; | ||
| 964 | } | ||
| 965 | if (!obj.lastFrameUv || obj.lastFrameUv.length < uvRequired) { | ||
| 966 | obj.lastFrameUv = [NSMutableData dataWithLength:uvRequired]; | ||
| 967 | } | ||
| 968 | if (obj.lastFrameY.length >= yRequired && obj.lastFrameUv.length >= uvRequired) { | ||
| 969 | memcpy(obj.lastFrameY.mutableBytes, out_y, yRequired); | ||
| 970 | memcpy(obj.lastFrameUv.mutableBytes, out_uv, uvRequired); | ||
| 971 | obj.lastFrameMatrix = matrix; | ||
| 972 | obj.lastFrameFullRange = fullRange; | ||
| 973 | obj.hasLastFrame = YES; | ||
| 974 | if (hitEof) { | ||
| 975 | obj.lastFrameIsEof = YES; | ||
| 976 | } | ||
| 977 | } | ||
| 978 | } | ||
| 979 | obj.lastFrameIdx = frame_idx; | ||
| 980 | } else { | ||
| 981 | [obj closeReader]; | ||
| 982 | } | ||
| 983 | return ok; | ||
| 984 | } | ||
| 985 | } | ||
| 986 | |||
| 576 | void av_video_close(AvVideoDecoder *dec) { | 987 | void av_video_close(AvVideoDecoder *dec) { |
| 577 | if (!dec) { | 988 | if (!dec) { |
| 578 | return; | 989 | return; |
crates/engine/src/eval/io.rs+75-58| ... | @@ -2,6 +2,9 @@ use super::*; | ... | @@ -2,6 +2,9 @@ use super::*; |
| 2 | use std::path::PathBuf; | 2 | use std::path::PathBuf; |
| 3 | use std::sync::{Mutex, OnceLock}; | 3 | use std::sync::{Mutex, OnceLock}; |
| 4 | 4 | ||
| 5 | #[path = "nv12.rs"] | ||
| 6 | mod nv12; | ||
| 7 | |||
| 5 | static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new(); | 8 | static DIMS_CACHE: OnceLock<Mutex<HashMap<PathBuf, Option<[u32; 2]>>>> = OnceLock::new(); |
| 6 | 9 | ||
| 7 | pub(super) fn clear_dims_cache() { | 10 | pub(super) fn clear_dims_cache() { |
| ... | @@ -261,9 +264,9 @@ impl Engine { | ... | @@ -261,9 +264,9 @@ impl Engine { |
| 261 | None | 264 | None |
| 262 | } else { | 265 | } else { |
| 263 | self.media | 266 | self.media |
| 264 | .load_clip(&effective_clip, frame_i, post_mult, exr_channels) | 267 | .load_clip_media(&effective_clip, frame_i, post_mult, exr_channels) |
| 265 | }; | 268 | }; |
| 266 | let Some((resolved, local_idx, img, loaded_from_disk)) = loaded else { | 269 | let Some((resolved, local_idx, media, loaded_from_disk)) = loaded else { |
| 267 | if missing_frames != 1 { | 270 | if missing_frames != 1 { |
| 268 | return self.dummy.clone(); | 271 | return self.dummy.clone(); |
| 269 | } | 272 | } |
| ... | @@ -304,13 +307,15 @@ impl Engine { | ... | @@ -304,13 +307,15 @@ impl Engine { |
| 304 | if loaded_from_disk { | 307 | if loaded_from_disk { |
| 305 | stats.source_loads += 1; | 308 | stats.source_loads += 1; |
| 306 | } | 309 | } |
| 307 | 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); | 310 | let img_size = media.size(); |
| 311 | 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); | ||
| 308 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); | 312 | let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); |
| 309 | // OpenEXR clips natively produce float HDR in HiQ unless Loader explicitly forces int8/int16. | 313 | // OpenEXR clips natively produce float HDR in HiQ unless Loader explicitly forces int8/int16. |
| 310 | let explicit_depth = comp | 314 | let explicit_depth = comp |
| 311 | .eval_number(node, "Depth", time, 0.0, &self.expr) | 315 | .eval_number(node, "Depth", time, 0.0, &self.expr) |
| 312 | .round() as i32; | 316 | .round() as i32; |
| 313 | let native_depth = if self.hiq && img.rgba_f32.is_some() { | 317 | let has_hdr_f32 = matches!(&media, crate::media::CachedMedia::Rgba(img) if img.rgba_f32.is_some()); |
| 318 | let native_depth = if self.hiq && has_hdr_f32 { | ||
| 314 | BitDepth::from_fusion_depth(explicit_depth).unwrap_or_else(|| { | 319 | BitDepth::from_fusion_depth(explicit_depth).unwrap_or_else(|| { |
| 315 | if comp.depth_full == BitDepth::Float32 { | 320 | if comp.depth_full == BitDepth::Float32 { |
| 316 | BitDepth::Float32 | 321 | BitDepth::Float32 |
| ... | @@ -322,8 +327,8 @@ impl Engine { | ... | @@ -322,8 +327,8 @@ impl Engine { |
| 322 | self.node_depth(comp, node, time, None) | 327 | self.node_depth(comp, node, time, None) |
| 323 | }; | 328 | }; |
| 324 | let dst_depth = self.effective_depth(native_depth); | 329 | let dst_depth = self.effective_depth(native_depth); |
| 325 | let use_float_upload = self.hiq && dst_depth.is_float() && img.rgba_f32.is_some(); | 330 | let use_float_upload = self.hiq && dst_depth.is_float() && has_hdr_f32; |
| 326 | let target_size = self.scaled_dims(img.size[0], img.size[1]); | 331 | let target_size = self.scaled_dims(img_size[0], img_size[1]); |
| 327 | let mut h = DefaultHasher::new(); | 332 | let mut h = DefaultHasher::new(); |
| 328 | self.cache.gpu_salt.hash(&mut h); | 333 | self.cache.gpu_salt.hash(&mut h); |
| 329 | self.cache.node_salt(node.id).hash(&mut h); | 334 | self.cache.node_salt(node.id).hash(&mut h); |
| ... | @@ -350,25 +355,35 @@ impl Engine { | ... | @@ -350,25 +355,35 @@ impl Engine { |
| 350 | stats.cache_misses += 1; | 355 | stats.cache_misses += 1; |
| 351 | stats.nodes_evaluated += 1; | 356 | stats.nodes_evaluated += 1; |
| 352 | 357 | ||
| 353 | let need_depth_conv = !use_float_upload && dst_depth != BitDepth::Int8; | 358 | let is_nv12 = matches!(&media, crate::media::CachedMedia::Nv12(_)); |
| 354 | let need_post = target_size != img.size || mask.is_some() || need_depth_conv; | 359 | let need_depth_conv = !use_float_upload && !is_nv12 && dst_depth != BitDepth::Int8; |
| 355 | let full_tex = if use_float_upload { | 360 | let need_post = target_size != img_size || mask.is_some() || need_depth_conv; |
| 356 | let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); | 361 | let (full_tex, work_depth) = match &media { |
| 357 | let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); | 362 | crate::media::CachedMedia::Nv12(nv12_frame) => { |
| 358 | if tex.format == wgpu::TextureFormat::Rgba32Float { | 363 | // Single-pass GPU YUV->RGBA + rotation writes directly into target bit depth. |
| 359 | self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size); | 364 | let tex = self.alloc_tex(img_size, dst_depth, if need_post { 0 } else { key }); |
| 360 | } else { | 365 | nv12::upload_and_convert_nv12(self, enc, nv12_frame, &tex); |
| 361 | let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); | 366 | (tex, dst_depth) |
| 362 | self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size); | 367 | } |
| 368 | crate::media::CachedMedia::Rgba(img) => { | ||
| 369 | if use_float_upload { | ||
| 370 | let f32_px = img.rgba_f32.as_ref().expect("checked is_some"); | ||
| 371 | let tex = self.alloc_tex(img.size, dst_depth, if need_post { 0 } else { key }); | ||
| 372 | if tex.format == wgpu::TextureFormat::Rgba32Float { | ||
| 373 | self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f32_px), 16, img.size); | ||
| 374 | } else { | ||
| 375 | let f16_bits = img.rgba_f16.as_ref().expect("EXR populates rgba_f16"); | ||
| 376 | self.upload_loader_texture(enc, &tex, bytemuck::cast_slice(f16_bits), 8, img.size); | ||
| 377 | } | ||
| 378 | (tex, dst_depth) | ||
| 379 | } else { | ||
| 380 | let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key }); | ||
| 381 | self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size); | ||
| 382 | (tex, BitDepth::Int8) | ||
| 383 | } | ||
| 363 | } | 384 | } |
| 364 | tex | ||
| 365 | } else { | ||
| 366 | let tex = self.alloc_tex(img.size, BitDepth::Int8, if need_post { 0 } else { key }); | ||
| 367 | self.upload_loader_texture(enc, &tex, &img.rgba, 4, img.size); | ||
| 368 | tex | ||
| 369 | }; | 385 | }; |
| 370 | let work_depth = if use_float_upload { dst_depth } else { BitDepth::Int8 }; | 386 | let base_tex = if target_size != img_size { |
| 371 | let base_tex = if target_size != img.size { | ||
| 372 | let scaled = self.alloc_tex(target_size, work_depth, if mask.is_some() || need_depth_conv { 0 } else { key }); | 387 | let scaled = self.alloc_tex(target_size, work_depth, if mask.is_some() || need_depth_conv { 0 } else { key }); |
| 373 | let mut u = UniformParams::default(); | 388 | let mut u = UniformParams::default(); |
| 374 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; | 389 | u.p[0] = [1.0, 1.0, 0.0, 0.0]; |
| ... | @@ -394,45 +409,47 @@ impl Engine { | ... | @@ -394,45 +409,47 @@ impl Engine { |
| 394 | } else { | 409 | } else { |
| 395 | masked_tex | 410 | masked_tex |
| 396 | }; | 411 | }; |
| 397 | if let Some(z_vals) = img.z_f32.as_ref() { | 412 | if let crate::media::CachedMedia::Rgba(img) = &media { |
| 398 | let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize); | 413 | if let Some(z_vals) = img.z_f32.as_ref() { |
| 399 | if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 { | 414 | let expected_len = (img.size[0] as usize).saturating_mul(img.size[1] as usize); |
| 400 | let z_tex = crate::cache::AuxChannelTex::new( | 415 | if z_vals.len() == expected_len && tex.size[0] > 0 && tex.size[1] > 0 { |
| 401 | &self.device, | 416 | let z_tex = crate::cache::AuxChannelTex::new( |
| 402 | tex.size, | 417 | &self.device, |
| 403 | wgpu::TextureFormat::R32Float, | 418 | tex.size, |
| 404 | "loader-aux-z", | 419 | wgpu::TextureFormat::R32Float, |
| 405 | ); | 420 | "loader-aux-z", |
| 406 | if z_tex.size == img.size { | ||
| 407 | self.upload_raw_texture( | ||
| 408 | enc, | ||
| 409 | &z_tex.texture, | ||
| 410 | bytemuck::cast_slice(z_vals), | ||
| 411 | 4, | ||
| 412 | img.size, | ||
| 413 | ); | 421 | ); |
| 414 | } else { | 422 | if z_tex.size == img.size { |
| 415 | let [sw, sh] = [img.size[0] as usize, img.size[1] as usize]; | 423 | self.upload_raw_texture( |
| 416 | let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize]; | 424 | enc, |
| 417 | let mut resampled = Vec::with_capacity(dw * dh); | 425 | &z_tex.texture, |
| 418 | for dy in 0..dh { | 426 | bytemuck::cast_slice(z_vals), |
| 419 | let sy = ((dy * sh) / dh).min(sh.saturating_sub(1)); | 427 | 4, |
| 420 | for dx in 0..dw { | 428 | img.size, |
| 421 | let sx = ((dx * sw) / dw).min(sw.saturating_sub(1)); | 429 | ); |
| 422 | resampled.push(z_vals[sy * sw + sx]); | 430 | } else { |
| 431 | let [sw, sh] = [img.size[0] as usize, img.size[1] as usize]; | ||
| 432 | let [dw, dh] = [z_tex.size[0] as usize, z_tex.size[1] as usize]; | ||
| 433 | let mut resampled = Vec::with_capacity(dw * dh); | ||
| 434 | for dy in 0..dh { | ||
| 435 | let sy = ((dy * sh) / dh).min(sh.saturating_sub(1)); | ||
| 436 | for dx in 0..dw { | ||
| 437 | let sx = ((dx * sw) / dw).min(sw.saturating_sub(1)); | ||
| 438 | resampled.push(z_vals[sy * sw + sx]); | ||
| 439 | } | ||
| 423 | } | 440 | } |
| 441 | self.upload_raw_texture( | ||
| 442 | enc, | ||
| 443 | &z_tex.texture, | ||
| 444 | bytemuck::cast_slice(&resampled), | ||
| 445 | 4, | ||
| 446 | z_tex.size, | ||
| 447 | ); | ||
| 424 | } | 448 | } |
| 425 | self.upload_raw_texture( | 449 | let mut aux = tex.aux_cloned(); |
| 426 | enc, | 450 | aux.z = Some(z_tex); |
| 427 | &z_tex.texture, | 451 | tex.set_aux(Some(std::sync::Arc::new(aux))); |
| 428 | bytemuck::cast_slice(&resampled), | ||
| 429 | 4, | ||
| 430 | z_tex.size, | ||
| 431 | ); | ||
| 432 | } | 452 | } |
| 433 | let mut aux = tex.aux_cloned(); | ||
| 434 | aux.z = Some(z_tex); | ||
| 435 | tex.set_aux(Some(std::sync::Arc::new(aux))); | ||
| 436 | } | 453 | } |
| 437 | } | 454 | } |
| 438 | self.cache.insert(key, tex.clone(), node.id, frame_i); | 455 | self.cache.insert(key, tex.clone(), node.id, frame_i); |
crates/engine/src/eval/nv12.rs created+986| ... | @@ -0,0 +1,986 @@ | ||
| 1 | //! Single-pass GPU NV12 -> RGBA (+ rotation) compute pipeline with pooled Y/UV upload textures. | ||
| 2 | //! | ||
| 3 | //! Declared as a submodule inside `eval/io.rs` so `eval/mod.rs` stays untouched. | ||
| 4 | |||
| 5 | use crate::cache::CachedTexture; | ||
| 6 | use crate::media::Nv12Frame; | ||
| 7 | use bytemuck::{Pod, Zeroable}; | ||
| 8 | use std::collections::HashMap; | ||
| 9 | use std::num::NonZeroU64; | ||
| 10 | |||
| 11 | const NV12_WGSL: &str = include_str!("../shaders/nv12_to_rgba.wgsl"); | ||
| 12 | const NV12_UNIFORM_SLOTS: u32 = 512; | ||
| 13 | #[cfg(not(target_arch = "wasm32"))] | ||
| 14 | const MAX_POOLED_PLANE_SIZES: usize = 8; | ||
| 15 | |||
| 16 | #[repr(C)] | ||
| 17 | #[derive(Clone, Copy, Pod, Zeroable)] | ||
| 18 | struct Nv12UniformParams { | ||
| 19 | raw_w: u32, | ||
| 20 | raw_h: u32, | ||
| 21 | out_w: u32, | ||
| 22 | out_h: u32, | ||
| 23 | rot_deg: u32, | ||
| 24 | matrix_id: u32, | ||
| 25 | full_range: u32, | ||
| 26 | _pad: u32, | ||
| 27 | } | ||
| 28 | |||
| 29 | struct Nv12FormatPipeline { | ||
| 30 | bgl: wgpu::BindGroupLayout, | ||
| 31 | pipeline: wgpu::ComputePipeline, | ||
| 32 | } | ||
| 33 | |||
| 34 | struct Nv12PlanePair { | ||
| 35 | y_tex: wgpu::Texture, | ||
| 36 | y_view: wgpu::TextureView, | ||
| 37 | uv_tex: wgpu::Texture, | ||
| 38 | uv_view: wgpu::TextureView, | ||
| 39 | #[cfg(not(target_arch = "wasm32"))] | ||
| 40 | last_used: u64, | ||
| 41 | } | ||
| 42 | |||
| 43 | impl Nv12PlanePair { | ||
| 44 | fn new(device: &wgpu::Device, raw_w: u32, raw_h: u32) -> Self { | ||
| 45 | let uv_w = raw_w.div_ceil(2); | ||
| 46 | let uv_h = raw_h.div_ceil(2); | ||
| 47 | let y_tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 48 | label: Some("nv12-y-plane"), | ||
| 49 | size: wgpu::Extent3d { | ||
| 50 | width: raw_w, | ||
| 51 | height: raw_h, | ||
| 52 | depth_or_array_layers: 1, | ||
| 53 | }, | ||
| 54 | mip_level_count: 1, | ||
| 55 | sample_count: 1, | ||
| 56 | dimension: wgpu::TextureDimension::D2, | ||
| 57 | format: wgpu::TextureFormat::R8Unorm, | ||
| 58 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, | ||
| 59 | view_formats: &[], | ||
| 60 | }); | ||
| 61 | let y_view = y_tex.create_view(&wgpu::TextureViewDescriptor::default()); | ||
| 62 | |||
| 63 | let uv_tex = device.create_texture(&wgpu::TextureDescriptor { | ||
| 64 | label: Some("nv12-uv-plane"), | ||
| 65 | size: wgpu::Extent3d { | ||
| 66 | width: uv_w, | ||
| 67 | height: uv_h, | ||
| 68 | depth_or_array_layers: 1, | ||
| 69 | }, | ||
| 70 | mip_level_count: 1, | ||
| 71 | sample_count: 1, | ||
| 72 | dimension: wgpu::TextureDimension::D2, | ||
| 73 | format: wgpu::TextureFormat::Rg8Unorm, | ||
| 74 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, | ||
| 75 | view_formats: &[], | ||
| 76 | }); | ||
| 77 | let uv_view = uv_tex.create_view(&wgpu::TextureViewDescriptor::default()); | ||
| 78 | |||
| 79 | Self { | ||
| 80 | y_tex, | ||
| 81 | y_view, | ||
| 82 | uv_tex, | ||
| 83 | uv_view, | ||
| 84 | #[cfg(not(target_arch = "wasm32"))] | ||
| 85 | last_used: 0, | ||
| 86 | } | ||
| 87 | } | ||
| 88 | } | ||
| 89 | |||
| 90 | pub(super) struct Nv12Pipelines { | ||
| 91 | sampler: wgpu::Sampler, | ||
| 92 | uniform_buf: wgpu::Buffer, | ||
| 93 | uniform_stride: u32, | ||
| 94 | uniform_cursor: u32, | ||
| 95 | pipelines: HashMap<wgpu::TextureFormat, Nv12FormatPipeline>, | ||
| 96 | #[cfg(not(target_arch = "wasm32"))] | ||
| 97 | plane_pool: HashMap<(u32, u32), Nv12PlanePair>, | ||
| 98 | #[cfg(not(target_arch = "wasm32"))] | ||
| 99 | tick: u64, | ||
| 100 | } | ||
| 101 | |||
| 102 | impl Nv12Pipelines { | ||
| 103 | fn new(device: &wgpu::Device) -> Self { | ||
| 104 | let sampler = device.create_sampler(&wgpu::SamplerDescriptor { | ||
| 105 | label: Some("nv12-uv-linear-sampler"), | ||
| 106 | address_mode_u: wgpu::AddressMode::ClampToEdge, | ||
| 107 | address_mode_v: wgpu::AddressMode::ClampToEdge, | ||
| 108 | address_mode_w: wgpu::AddressMode::ClampToEdge, | ||
| 109 | mag_filter: wgpu::FilterMode::Linear, | ||
| 110 | min_filter: wgpu::FilterMode::Linear, | ||
| 111 | mipmap_filter: wgpu::MipmapFilterMode::Nearest, | ||
| 112 | ..Default::default() | ||
| 113 | }); | ||
| 114 | |||
| 115 | let align = device.limits().min_uniform_buffer_offset_alignment.max(32); | ||
| 116 | let raw_size = std::mem::size_of::<Nv12UniformParams>() as u32; | ||
| 117 | let uniform_stride = raw_size.div_ceil(align) * align; | ||
| 118 | let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { | ||
| 119 | label: Some("nv12-uniform-ring"), | ||
| 120 | size: u64::from(uniform_stride) * u64::from(NV12_UNIFORM_SLOTS), | ||
| 121 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, | ||
| 122 | mapped_at_creation: false, | ||
| 123 | }); | ||
| 124 | |||
| 125 | Self { | ||
| 126 | sampler, | ||
| 127 | uniform_buf, | ||
| 128 | uniform_stride, | ||
| 129 | uniform_cursor: 0, | ||
| 130 | pipelines: HashMap::new(), | ||
| 131 | #[cfg(not(target_arch = "wasm32"))] | ||
| 132 | plane_pool: HashMap::new(), | ||
| 133 | #[cfg(not(target_arch = "wasm32"))] | ||
| 134 | tick: 0, | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 138 | fn ensure_pipeline(&mut self, device: &wgpu::Device, dst_format: wgpu::TextureFormat) { | ||
| 139 | if self.pipelines.contains_key(&dst_format) { | ||
| 140 | return; | ||
| 141 | } | ||
| 142 | let storage_fmt = match dst_format { | ||
| 143 | wgpu::TextureFormat::Rgba16Float => "rgba16float", | ||
| 144 | wgpu::TextureFormat::Rgba32Float => "rgba32float", | ||
| 145 | _ => "rgba8unorm", | ||
| 146 | }; | ||
| 147 | let src = if storage_fmt == "rgba8unorm" { | ||
| 148 | std::borrow::Cow::Borrowed(NV12_WGSL) | ||
| 149 | } else { | ||
| 150 | std::borrow::Cow::Owned(NV12_WGSL.replace( | ||
| 151 | "texture_storage_2d<rgba8unorm, write>", | ||
| 152 | &format!("texture_storage_2d<{storage_fmt}, write>"), | ||
| 153 | )) | ||
| 154 | }; | ||
| 155 | |||
| 156 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { | ||
| 157 | label: Some("nv12-to-rgba-wgsl"), | ||
| 158 | source: wgpu::ShaderSource::Wgsl(src), | ||
| 159 | }); | ||
| 160 | |||
| 161 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { | ||
| 162 | label: Some("nv12-to-rgba-bgl"), | ||
| 163 | entries: &[ | ||
| 164 | wgpu::BindGroupLayoutEntry { | ||
| 165 | binding: 0, | ||
| 166 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 167 | ty: wgpu::BindingType::Texture { | ||
| 168 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, | ||
| 169 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 170 | multisampled: false, | ||
| 171 | }, | ||
| 172 | count: None, | ||
| 173 | }, | ||
| 174 | wgpu::BindGroupLayoutEntry { | ||
| 175 | binding: 1, | ||
| 176 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 177 | ty: wgpu::BindingType::Texture { | ||
| 178 | sample_type: wgpu::TextureSampleType::Float { filterable: true }, | ||
| 179 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 180 | multisampled: false, | ||
| 181 | }, | ||
| 182 | count: None, | ||
| 183 | }, | ||
| 184 | wgpu::BindGroupLayoutEntry { | ||
| 185 | binding: 2, | ||
| 186 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 187 | ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), | ||
| 188 | count: None, | ||
| 189 | }, | ||
| 190 | wgpu::BindGroupLayoutEntry { | ||
| 191 | binding: 3, | ||
| 192 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 193 | ty: wgpu::BindingType::StorageTexture { | ||
| 194 | access: wgpu::StorageTextureAccess::WriteOnly, | ||
| 195 | format: dst_format, | ||
| 196 | view_dimension: wgpu::TextureViewDimension::D2, | ||
| 197 | }, | ||
| 198 | count: None, | ||
| 199 | }, | ||
| 200 | wgpu::BindGroupLayoutEntry { | ||
| 201 | binding: 4, | ||
| 202 | visibility: wgpu::ShaderStages::COMPUTE, | ||
| 203 | ty: wgpu::BindingType::Buffer { | ||
| 204 | ty: wgpu::BufferBindingType::Uniform, | ||
| 205 | has_dynamic_offset: true, | ||
| 206 | min_binding_size: NonZeroU64::new( | ||
| 207 | std::mem::size_of::<Nv12UniformParams>() as u64, | ||
| 208 | ), | ||
| 209 | }, | ||
| 210 | count: None, | ||
| 211 | }, | ||
| 212 | ], | ||
| 213 | }); | ||
| 214 | |||
| 215 | let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { | ||
| 216 | label: Some("nv12-to-rgba-layout"), | ||
| 217 | bind_group_layouts: &[Some(&bgl)], | ||
| 218 | immediate_size: 0, | ||
| 219 | }); | ||
| 220 | |||
| 221 | let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { | ||
| 222 | label: Some("nv12-to-rgba-pipeline"), | ||
| 223 | layout: Some(&layout), | ||
| 224 | module: &module, | ||
| 225 | entry_point: Some("nv12_to_rgba"), | ||
| 226 | compilation_options: wgpu::PipelineCompilationOptions::default(), | ||
| 227 | cache: None, | ||
| 228 | }); | ||
| 229 | |||
| 230 | self.pipelines.insert(dst_format, Nv12FormatPipeline { bgl, pipeline }); | ||
| 231 | } | ||
| 232 | |||
| 233 | #[cfg(not(target_arch = "wasm32"))] | ||
| 234 | fn acquire_pooled_planes( | ||
| 235 | &mut self, | ||
| 236 | device: &wgpu::Device, | ||
| 237 | raw_w: u32, | ||
| 238 | raw_h: u32, | ||
| 239 | ) -> &Nv12PlanePair { | ||
| 240 | self.tick = self.tick.wrapping_add(1); | ||
| 241 | let tick = self.tick; | ||
| 242 | let key = (raw_w, raw_h); | ||
| 243 | if !self.plane_pool.contains_key(&key) { | ||
| 244 | if self.plane_pool.len() >= MAX_POOLED_PLANE_SIZES { | ||
| 245 | if let Some(oldest) = self | ||
| 246 | .plane_pool | ||
| 247 | .iter() | ||
| 248 | .min_by_key(|(_, p)| p.last_used) | ||
| 249 | .map(|(&k, _)| k) | ||
| 250 | { | ||
| 251 | self.plane_pool.remove(&oldest); | ||
| 252 | } | ||
| 253 | } | ||
| 254 | self.plane_pool | ||
| 255 | .insert(key, Nv12PlanePair::new(device, raw_w, raw_h)); | ||
| 256 | } | ||
| 257 | let pair = self.plane_pool.get_mut(&key).expect("just inserted"); | ||
| 258 | pair.last_used = tick; | ||
| 259 | pair | ||
| 260 | } | ||
| 261 | |||
| 262 | #[allow(clippy::too_many_arguments)] | ||
| 263 | fn encode_dispatch( | ||
| 264 | &mut self, | ||
| 265 | device: &wgpu::Device, | ||
| 266 | queue: &wgpu::Queue, | ||
| 267 | enc: &mut wgpu::CommandEncoder, | ||
| 268 | y_view: &wgpu::TextureView, | ||
| 269 | uv_view: &wgpu::TextureView, | ||
| 270 | nv12: &Nv12Frame, | ||
| 271 | dst: &CachedTexture, | ||
| 272 | ) { | ||
| 273 | self.ensure_pipeline(device, dst.format); | ||
| 274 | let slot = self.uniform_cursor; | ||
| 275 | self.uniform_cursor = (self.uniform_cursor + 1) % NV12_UNIFORM_SLOTS; | ||
| 276 | let dyn_offset = slot * self.uniform_stride; | ||
| 277 | |||
| 278 | let params = Nv12UniformParams { | ||
| 279 | raw_w: nv12.raw_size[0], | ||
| 280 | raw_h: nv12.raw_size[1], | ||
| 281 | out_w: dst.size[0], | ||
| 282 | out_h: dst.size[1], | ||
| 283 | rot_deg: nv12.rot_deg, | ||
| 284 | matrix_id: nv12.matrix as u32, | ||
| 285 | full_range: u32::from(nv12.is_full_range), | ||
| 286 | _pad: 0, | ||
| 287 | }; | ||
| 288 | queue.write_buffer( | ||
| 289 | &self.uniform_buf, | ||
| 290 | u64::from(dyn_offset), | ||
| 291 | bytemuck::bytes_of(&params), | ||
| 292 | ); | ||
| 293 | |||
| 294 | let fp = &self.pipelines[&dst.format]; | ||
| 295 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { | ||
| 296 | label: Some("nv12-to-rgba-bg"), | ||
| 297 | layout: &fp.bgl, | ||
| 298 | entries: &[ | ||
| 299 | wgpu::BindGroupEntry { | ||
| 300 | binding: 0, | ||
| 301 | resource: wgpu::BindingResource::TextureView(y_view), | ||
| 302 | }, | ||
| 303 | wgpu::BindGroupEntry { | ||
| 304 | binding: 1, | ||
| 305 | resource: wgpu::BindingResource::TextureView(uv_view), | ||
| 306 | }, | ||
| 307 | wgpu::BindGroupEntry { | ||
| 308 | binding: 2, | ||
| 309 | resource: wgpu::BindingResource::Sampler(&self.sampler), | ||
| 310 | }, | ||
| 311 | wgpu::BindGroupEntry { | ||
| 312 | binding: 3, | ||
| 313 | resource: wgpu::BindingResource::TextureView(&dst.view), | ||
| 314 | }, | ||
| 315 | wgpu::BindGroupEntry { | ||
| 316 | binding: 4, | ||
| 317 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { | ||
| 318 | buffer: &self.uniform_buf, | ||
| 319 | offset: 0, | ||
| 320 | size: NonZeroU64::new(std::mem::size_of::<Nv12UniformParams>() as u64), | ||
| 321 | }), | ||
| 322 | }, | ||
| 323 | ], | ||
| 324 | }); | ||
| 325 | |||
| 326 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { | ||
| 327 | label: Some("nv12-to-rgba-pass"), | ||
| 328 | timestamp_writes: None, | ||
| 329 | }); | ||
| 330 | pass.set_pipeline(&fp.pipeline); | ||
| 331 | pass.set_bind_group(0, &bg, &[dyn_offset]); | ||
| 332 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); | ||
| 333 | } | ||
| 334 | } | ||
| 335 | |||
| 336 | #[cfg(target_arch = "wasm32")] | ||
| 337 | thread_local! { | ||
| 338 | static WASM_NV12_PIPELINES: std::cell::RefCell<Option<Nv12Pipelines>> = | ||
| 339 | const { std::cell::RefCell::new(None) }; | ||
| 340 | } | ||
| 341 | |||
| 342 | #[cfg(not(target_arch = "wasm32"))] | ||
| 343 | fn stage_plane_into_buffer( | ||
| 344 | media: &crate::media::MediaCache, | ||
| 345 | device: &wgpu::Device, | ||
| 346 | data: &[u8], | ||
| 347 | width: u32, | ||
| 348 | height: u32, | ||
| 349 | bytes_per_pixel: u32, | ||
| 350 | ) -> Option<(wgpu::Buffer, u32)> { | ||
| 351 | let unpadded_bpr = width.checked_mul(bytes_per_pixel)?; | ||
| 352 | let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; | ||
| 353 | let padded_bpr = unpadded_bpr.div_ceil(align) * align; | ||
| 354 | let needed = u64::from(padded_bpr).checked_mul(u64::from(height))?; | ||
| 355 | let buf = media.acquire_upload_staging(device, needed)?; | ||
| 356 | let cap = buf.size(); | ||
| 357 | let copied = if let Ok(mut view) = buf.slice(..needed).get_mapped_range_mut() { | ||
| 358 | if padded_bpr == unpadded_bpr { | ||
| 359 | let total = (unpadded_bpr as usize) * (height as usize); | ||
| 360 | if data.len() >= total { | ||
| 361 | view.slice(..total).copy_from_slice(&data[..total]); | ||
| 362 | true | ||
| 363 | } else { | ||
| 364 | false | ||
| 365 | } | ||
| 366 | } else { | ||
| 367 | let src_stride = unpadded_bpr as usize; | ||
| 368 | let dst_stride = padded_bpr as usize; | ||
| 369 | if data.len() >= src_stride * (height as usize) { | ||
| 370 | let mut wo = view.slice(..needed as usize); | ||
| 371 | for (row_idx, src_row) in data | ||
| 372 | .chunks_exact(src_stride) | ||
| 373 | .take(height as usize) | ||
| 374 | .enumerate() | ||
| 375 | { | ||
| 376 | let off = row_idx * dst_stride; | ||
| 377 | wo.slice(off..off + src_stride).copy_from_slice(src_row); | ||
| 378 | } | ||
| 379 | true | ||
| 380 | } else { | ||
| 381 | false | ||
| 382 | } | ||
| 383 | } | ||
| 384 | } else { | ||
| 385 | false | ||
| 386 | }; | ||
| 387 | if copied { | ||
| 388 | buf.unmap(); | ||
| 389 | Some((buf, padded_bpr)) | ||
| 390 | } else { | ||
| 391 | drop(buf); | ||
| 392 | media.release_failed_upload_staging(cap); | ||
| 393 | None | ||
| 394 | } | ||
| 395 | } | ||
| 396 | |||
| 397 | /// Uploads NV12 Y (`R8Unorm`) and UV (`Rg8Unorm`) planes and runs a single-pass compute shader | ||
| 398 | /// writing rotated, color-converted RGBA directly into `dst` (`Rgba8Unorm`, `Rgba16Float`, or | ||
| 399 | /// `Rgba32Float`). | ||
| 400 | pub(super) fn upload_and_convert_nv12( | ||
| 401 | engine: &crate::Engine, | ||
| 402 | enc: &mut wgpu::CommandEncoder, | ||
| 403 | nv12: &Nv12Frame, | ||
| 404 | dst: &CachedTexture, | ||
| 405 | ) { | ||
| 406 | let [raw_w, raw_h] = nv12.raw_size; | ||
| 407 | let [uv_w, uv_h] = nv12.uv_size(); | ||
| 408 | if raw_w == 0 || raw_h == 0 || uv_w == 0 || uv_h == 0 || dst.size[0] == 0 || dst.size[1] == 0 { | ||
| 409 | return; | ||
| 410 | } | ||
| 411 | |||
| 412 | #[cfg(not(target_arch = "wasm32"))] | ||
| 413 | { | ||
| 414 | // Prefer pooled Y/UV textures + in-order `copy_buffer_to_texture` via `UploadStagingPool`: | ||
| 415 | // zero per-frame GPU texture allocations and zero write hazards even with multiple NV12 | ||
| 416 | // loaders sharing the same `CommandEncoder`. | ||
| 417 | let staged_y = stage_plane_into_buffer(&engine.media, &engine.device, &nv12.y, raw_w, raw_h, 1); | ||
| 418 | let staged_uv = if staged_y.is_some() { | ||
| 419 | stage_plane_into_buffer(&engine.media, &engine.device, &nv12.uv, uv_w, uv_h, 2) | ||
| 420 | } else { | ||
| 421 | None | ||
| 422 | }; | ||
| 423 | |||
| 424 | match (staged_y, staged_uv) { | ||
| 425 | (Some((y_buf, y_bpr)), Some((uv_buf, uv_bpr))) => { | ||
| 426 | engine.media.with_nv12_gpu_state( | ||
| 427 | || Nv12Pipelines::new(&engine.device), | ||
| 428 | |pipe| { | ||
| 429 | pipe.acquire_pooled_planes(&engine.device, raw_w, raw_h); | ||
| 430 | let pair = &pipe.plane_pool[&(raw_w, raw_h)]; | ||
| 431 | enc.copy_buffer_to_texture( | ||
| 432 | wgpu::TexelCopyBufferInfo { | ||
| 433 | buffer: &y_buf, | ||
| 434 | layout: wgpu::TexelCopyBufferLayout { | ||
| 435 | offset: 0, | ||
| 436 | bytes_per_row: Some(y_bpr), | ||
| 437 | rows_per_image: Some(raw_h), | ||
| 438 | }, | ||
| 439 | }, | ||
| 440 | pair.y_tex.as_image_copy(), | ||
| 441 | wgpu::Extent3d { | ||
| 442 | width: raw_w, | ||
| 443 | height: raw_h, | ||
| 444 | depth_or_array_layers: 1, | ||
| 445 | }, | ||
| 446 | ); | ||
| 447 | enc.copy_buffer_to_texture( | ||
| 448 | wgpu::TexelCopyBufferInfo { | ||
| 449 | buffer: &uv_buf, | ||
| 450 | layout: wgpu::TexelCopyBufferLayout { | ||
| 451 | offset: 0, | ||
| 452 | bytes_per_row: Some(uv_bpr), | ||
| 453 | rows_per_image: Some(uv_h), | ||
| 454 | }, | ||
| 455 | }, | ||
| 456 | pair.uv_tex.as_image_copy(), | ||
| 457 | wgpu::Extent3d { | ||
| 458 | width: uv_w, | ||
| 459 | height: uv_h, | ||
| 460 | depth_or_array_layers: 1, | ||
| 461 | }, | ||
| 462 | ); | ||
| 463 | let y_view = pair.y_view.clone(); | ||
| 464 | let uv_view = pair.uv_view.clone(); | ||
| 465 | pipe.encode_dispatch( | ||
| 466 | &engine.device, | ||
| 467 | &engine.queue, | ||
| 468 | enc, | ||
| 469 | &y_view, | ||
| 470 | &uv_view, | ||
| 471 | nv12, | ||
| 472 | dst, | ||
| 473 | ); | ||
| 474 | }, | ||
| 475 | ); | ||
| 476 | engine.media.recycle_upload_staging(y_buf); | ||
| 477 | engine.media.recycle_upload_staging(uv_buf); | ||
| 478 | return; | ||
| 479 | } | ||
| 480 | (Some((y_buf, _)), None) => { | ||
| 481 | engine.media.recycle_upload_staging(y_buf); | ||
| 482 | } | ||
| 483 | _ => {} | ||
| 484 | } | ||
| 485 | |||
| 486 | // Fallback when staging pool is temporarily exhausted: use fresh textures with | ||
| 487 | // `queue.write_texture` so multiple dispatches in one encoder cannot overwrite each other. | ||
| 488 | let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); | ||
| 489 | engine.queue.write_texture( | ||
| 490 | fresh.y_tex.as_image_copy(), | ||
| 491 | &nv12.y, | ||
| 492 | wgpu::TexelCopyBufferLayout { | ||
| 493 | offset: 0, | ||
| 494 | bytes_per_row: Some(raw_w), | ||
| 495 | rows_per_image: Some(raw_h), | ||
| 496 | }, | ||
| 497 | wgpu::Extent3d { | ||
| 498 | width: raw_w, | ||
| 499 | height: raw_h, | ||
| 500 | depth_or_array_layers: 1, | ||
| 501 | }, | ||
| 502 | ); | ||
| 503 | engine.queue.write_texture( | ||
| 504 | fresh.uv_tex.as_image_copy(), | ||
| 505 | &nv12.uv, | ||
| 506 | wgpu::TexelCopyBufferLayout { | ||
| 507 | offset: 0, | ||
| 508 | bytes_per_row: Some(uv_w * 2), | ||
| 509 | rows_per_image: Some(uv_h), | ||
| 510 | }, | ||
| 511 | wgpu::Extent3d { | ||
| 512 | width: uv_w, | ||
| 513 | height: uv_h, | ||
| 514 | depth_or_array_layers: 1, | ||
| 515 | }, | ||
| 516 | ); | ||
| 517 | engine.media.with_nv12_gpu_state( | ||
| 518 | || Nv12Pipelines::new(&engine.device), | ||
| 519 | |pipe| { | ||
| 520 | pipe.encode_dispatch( | ||
| 521 | &engine.device, | ||
| 522 | &engine.queue, | ||
| 523 | enc, | ||
| 524 | &fresh.y_view, | ||
| 525 | &fresh.uv_view, | ||
| 526 | nv12, | ||
| 527 | dst, | ||
| 528 | ); | ||
| 529 | }, | ||
| 530 | ); | ||
| 531 | } | ||
| 532 | |||
| 533 | #[cfg(target_arch = "wasm32")] | ||
| 534 | { | ||
| 535 | let fresh = Nv12PlanePair::new(&engine.device, raw_w, raw_h); | ||
| 536 | engine.queue.write_texture( | ||
| 537 | fresh.y_tex.as_image_copy(), | ||
| 538 | &nv12.y, | ||
| 539 | wgpu::TexelCopyBufferLayout { | ||
| 540 | offset: 0, | ||
| 541 | bytes_per_row: Some(raw_w), | ||
| 542 | rows_per_image: Some(raw_h), | ||
| 543 | }, | ||
| 544 | wgpu::Extent3d { | ||
| 545 | width: raw_w, | ||
| 546 | height: raw_h, | ||
| 547 | depth_or_array_layers: 1, | ||
| 548 | }, | ||
| 549 | ); | ||
| 550 | engine.queue.write_texture( | ||
| 551 | fresh.uv_tex.as_image_copy(), | ||
| 552 | &nv12.uv, | ||
| 553 | wgpu::TexelCopyBufferLayout { | ||
| 554 | offset: 0, | ||
| 555 | bytes_per_row: Some(uv_w * 2), | ||
| 556 | rows_per_image: Some(uv_h), | ||
| 557 | }, | ||
| 558 | wgpu::Extent3d { | ||
| 559 | width: uv_w, | ||
| 560 | height: uv_h, | ||
| 561 | depth_or_array_layers: 1, | ||
| 562 | }, | ||
| 563 | ); | ||
| 564 | WASM_NV12_PIPELINES.with(|cell| { | ||
| 565 | let mut slot = cell.borrow_mut(); | ||
| 566 | let pipe = slot.get_or_insert_with(|| Nv12Pipelines::new(&engine.device)); | ||
| 567 | pipe.encode_dispatch( | ||
| 568 | &engine.device, | ||
| 569 | &engine.queue, | ||
| 570 | enc, | ||
| 571 | &fresh.y_view, | ||
| 572 | &fresh.uv_view, | ||
| 573 | nv12, | ||
| 574 | dst, | ||
| 575 | ); | ||
| 576 | }); | ||
| 577 | } | ||
| 578 | } | ||
| 579 | |||
| 580 | #[cfg(all(test, not(target_arch = "wasm32")))] | ||
| 581 | mod tests { | ||
| 582 | use super::*; | ||
| 583 | use crate::Engine; | ||
| 584 | use crate::media::YuvMatrix; | ||
| 585 | use model::{BitDepth, Comp}; | ||
| 586 | |||
| 587 | fn make_pattern_nv12( | ||
| 588 | raw_w: u32, | ||
| 589 | raw_h: u32, | ||
| 590 | rot_deg: u32, | ||
| 591 | matrix: YuvMatrix, | ||
| 592 | is_full_range: bool, | ||
| 593 | ) -> Nv12Frame { | ||
| 594 | let uv_w = raw_w.div_ceil(2); | ||
| 595 | let uv_h = raw_h.div_ceil(2); | ||
| 596 | let mut y = vec![0u8; (raw_w * raw_h) as usize]; | ||
| 597 | let mut uv = vec![128u8; (uv_w * uv_h * 2) as usize]; | ||
| 598 | |||
| 599 | let (y_min, y_max) = if is_full_range { (0.0_f32, 255.0_f32) } else { (16.0_f32, 235.0_f32) }; | ||
| 600 | let (c_min, c_max) = if is_full_range { (0.0_f32, 255.0_f32) } else { (16.0_f32, 240.0_f32) }; | ||
| 601 | |||
| 602 | for py in 0..raw_h { | ||
| 603 | for px in 0..raw_w { | ||
| 604 | let fx = px as f32 / raw_w.saturating_sub(1).max(1) as f32; | ||
| 605 | let fy = py as f32 / raw_h.saturating_sub(1).max(1) as f32; | ||
| 606 | let luma = y_min + (y_max - y_min) * (0.15 + 0.7 * (0.5 * fx + 0.5 * fy)); | ||
| 607 | y[(py * raw_w + px) as usize] = luma.round().clamp(0.0, 255.0) as u8; | ||
| 608 | } | ||
| 609 | } | ||
| 610 | for cy in 0..uv_h { | ||
| 611 | for cx in 0..uv_w { | ||
| 612 | let fx = cx as f32 / uv_w.saturating_sub(1).max(1) as f32; | ||
| 613 | let fy = cy as f32 / uv_h.saturating_sub(1).max(1) as f32; | ||
| 614 | let cb = c_min + (c_max - c_min) * (0.2 + 0.6 * fx); | ||
| 615 | let cr = c_min + (c_max - c_min) * (0.8 - 0.6 * fy); | ||
| 616 | let idx = ((cy * uv_w + cx) * 2) as usize; | ||
| 617 | uv[idx] = cb.round().clamp(0.0, 255.0) as u8; | ||
| 618 | uv[idx + 1] = cr.round().clamp(0.0, 255.0) as u8; | ||
| 619 | } | ||
| 620 | } | ||
| 621 | |||
| 622 | let display_size = if rot_deg == 90 || rot_deg == 270 { | ||
| 623 | [raw_h, raw_w] | ||
| 624 | } else { | ||
| 625 | [raw_w, raw_h] | ||
| 626 | }; | ||
| 627 | Nv12Frame { | ||
| 628 | raw_size: [raw_w, raw_h], | ||
| 629 | display_size, | ||
| 630 | rot_deg, | ||
| 631 | matrix, | ||
| 632 | is_full_range, | ||
| 633 | y, | ||
| 634 | uv, | ||
| 635 | } | ||
| 636 | } | ||
| 637 | |||
| 638 | fn make_quadrant_nv12(raw_w: u32, raw_h: u32, rot_deg: u32) -> Nv12Frame { | ||
| 639 | let uv_w = raw_w.div_ceil(2); | ||
| 640 | let uv_h = raw_h.div_ceil(2); | ||
| 641 | let mut y = vec![0u8; (raw_w * raw_h) as usize]; | ||
| 642 | let mut uv = vec![128u8; (uv_w * uv_h * 2) as usize]; | ||
| 643 | // BT.709 video-range YCbCr for pure Red, Green, Blue, Yellow: | ||
| 644 | // Red: Y=63, Cb=102, Cr=240 | ||
| 645 | // Green: Y=173, Cb=42, Cr=26 | ||
| 646 | // Blue: Y=32, Cb=240, Cr=118 | ||
| 647 | // Yellow: Y=219, Cb=16, Cr=138 | ||
| 648 | let quad = |x: u32, y_pos: u32, w: u32, h: u32| -> (u8, u8, u8) { | ||
| 649 | match (x < w / 2, y_pos < h / 2) { | ||
| 650 | (true, true) => (63, 102, 240), // top-left: Red | ||
| 651 | (false, true) => (173, 42, 26), // top-right: Green | ||
| 652 | (true, false) => (32, 240, 118), // bottom-left: Blue | ||
| 653 | (false, false) => (219, 16, 138), // bottom-right: Yellow | ||
| 654 | } | ||
| 655 | }; | ||
| 656 | for py in 0..raw_h { | ||
| 657 | for px in 0..raw_w { | ||
| 658 | let (yv, _, _) = quad(px, py, raw_w, raw_h); | ||
| 659 | y[(py * raw_w + px) as usize] = yv; | ||
| 660 | } | ||
| 661 | } | ||
| 662 | for cy in 0..uv_h { | ||
| 663 | for cx in 0..uv_w { | ||
| 664 | let (_, cb, cr) = quad(cx * 2, cy * 2, raw_w, raw_h); | ||
| 665 | let idx = ((cy * uv_w + cx) * 2) as usize; | ||
| 666 | uv[idx] = cb; | ||
| 667 | uv[idx + 1] = cr; | ||
| 668 | } | ||
| 669 | } | ||
| 670 | let display_size = if rot_deg == 90 || rot_deg == 270 { | ||
| 671 | [raw_h, raw_w] | ||
| 672 | } else { | ||
| 673 | [raw_w, raw_h] | ||
| 674 | }; | ||
| 675 | Nv12Frame { | ||
| 676 | raw_size: [raw_w, raw_h], | ||
| 677 | display_size, | ||
| 678 | rot_deg, | ||
| 679 | matrix: YuvMatrix::Bt709, | ||
| 680 | is_full_range: false, | ||
| 681 | y, | ||
| 682 | uv, | ||
| 683 | } | ||
| 684 | } | ||
| 685 | |||
| 686 | fn run_gpu_nv12(engine: &Engine, frame: &Nv12Frame, depth: BitDepth) -> Vec<u8> { | ||
| 687 | let mut enc = engine | ||
| 688 | .device | ||
| 689 | .create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 690 | label: Some("nv12-test-enc"), | ||
| 691 | }); | ||
| 692 | let dst = engine.alloc_tex(frame.display_size, depth, 0); | ||
| 693 | upload_and_convert_nv12(engine, &mut enc, frame, &dst); | ||
| 694 | engine.queue.submit(Some(enc.finish())); | ||
| 695 | engine.media.flush_upload_staging_after_submit(&engine.device); | ||
| 696 | engine.readback_rgba(&dst).expect("readback_rgba") | ||
| 697 | } | ||
| 698 | |||
| 699 | #[test] | ||
| 700 | fn nv12_gpu_matches_cpu_reference_all_matrices_ranges_and_formats() { | ||
| 701 | let engine = Engine::new_headless().expect("headless engine"); | ||
| 702 | for &(raw_w, raw_h) in &[(32u32, 24u32), (17u32, 13u32)] { | ||
| 703 | for &matrix in &[YuvMatrix::Bt709, YuvMatrix::Bt601, YuvMatrix::Bt2020] { | ||
| 704 | for &full_range in &[false, true] { | ||
| 705 | let frame = make_pattern_nv12(raw_w, raw_h, 0, matrix, full_range); | ||
| 706 | let expected = frame.to_rgba8(); | ||
| 707 | for &depth in &[BitDepth::Int8, BitDepth::Float16, BitDepth::Float32] { | ||
| 708 | let got = run_gpu_nv12(&engine, &frame, depth); | ||
| 709 | assert_eq!(got.len(), expected.len()); | ||
| 710 | let mut max_diff = 0u8; | ||
| 711 | for (i, (&g, &e)) in got.iter().zip(expected.iter()).enumerate() { | ||
| 712 | if i % 4 == 3 { | ||
| 713 | assert_eq!(g, 255, "NV12 alpha must be 255"); | ||
| 714 | } | ||
| 715 | max_diff = max_diff.max(g.abs_diff(e)); | ||
| 716 | } | ||
| 717 | assert!( | ||
| 718 | max_diff <= 2, | ||
| 719 | "NV12 mismatch ({raw_w}x{raw_h}, {matrix:?}, full={full_range}, {depth:?}): max_diff={max_diff}" | ||
| 720 | ); | ||
| 721 | } | ||
| 722 | } | ||
| 723 | } | ||
| 724 | } | ||
| 725 | } | ||
| 726 | |||
| 727 | #[test] | ||
| 728 | fn nv12_gpu_matches_cpu_reference_all_four_rotations() { | ||
| 729 | let engine = Engine::new_headless().expect("headless engine"); | ||
| 730 | for &rot_deg in &[0u32, 90, 180, 270] { | ||
| 731 | let frame = make_quadrant_nv12(24, 16, rot_deg); | ||
| 732 | let expected = frame.to_rgba8(); | ||
| 733 | let got = run_gpu_nv12(&engine, &frame, BitDepth::Int8); | ||
| 734 | assert_eq!(got.len(), expected.len()); | ||
| 735 | let mut max_diff = 0u8; | ||
| 736 | for (&g, &e) in got.iter().zip(expected.iter()) { | ||
| 737 | max_diff = max_diff.max(g.abs_diff(e)); | ||
| 738 | } | ||
| 739 | assert!( | ||
| 740 | max_diff <= 2, | ||
| 741 | "rotation {rot_deg} mismatch vs CPU reference: max_diff={max_diff}" | ||
| 742 | ); | ||
| 743 | |||
| 744 | // Spot-check interior of each rotated quadrant against expected primary colors. | ||
| 745 | let [ow, oh] = frame.display_size; | ||
| 746 | let px = |x: u32, y: u32| -> [u8; 4] { | ||
| 747 | let i = ((y * ow + x) * 4) as usize; | ||
| 748 | [got[i], got[i + 1], got[i + 2], got[i + 3]] | ||
| 749 | }; | ||
| 750 | let tl = px(2, 2); | ||
| 751 | let tr = px(ow - 3, 2); | ||
| 752 | let bl = px(2, oh - 3); | ||
| 753 | let br = px(ow - 3, oh - 3); | ||
| 754 | match rot_deg { | ||
| 755 | 0 => { | ||
| 756 | assert!(tl[0] > 200 && tl[1] < 30 && tl[2] < 30, "0° TL should be red: {tl:?}"); | ||
| 757 | assert!(tr[1] > 200 && tr[0] < 30 && tr[2] < 30, "0° TR should be green: {tr:?}"); | ||
| 758 | assert!(bl[2] > 200 && bl[0] < 30 && bl[1] < 30, "0° BL should be blue: {bl:?}"); | ||
| 759 | assert!(br[0] > 200 && br[1] > 200 && br[2] < 30, "0° BR should be yellow: {br:?}"); | ||
| 760 | } | ||
| 761 | 90 => { | ||
| 762 | // 90° CW: BL(blue)->TL, TL(red)->TR, BR(yellow)->BL, TR(green)->BR | ||
| 763 | assert!(tl[2] > 200 && tl[0] < 30, "90° TL should be blue: {tl:?}"); | ||
| 764 | assert!(tr[0] > 200 && tr[1] < 30, "90° TR should be red: {tr:?}"); | ||
| 765 | assert!(bl[0] > 200 && bl[1] > 200 && bl[2] < 30, "90° BL should be yellow: {bl:?}"); | ||
| 766 | assert!(br[1] > 200 && br[0] < 30, "90° BR should be green: {br:?}"); | ||
| 767 | } | ||
| 768 | 180 => { | ||
| 769 | assert!(tl[0] > 200 && tl[1] > 200 && tl[2] < 30, "180° TL should be yellow: {tl:?}"); | ||
| 770 | assert!(tr[2] > 200 && tr[0] < 30, "180° TR should be blue: {tr:?}"); | ||
| 771 | assert!(bl[1] > 200 && bl[0] < 30, "180° BL should be green: {bl:?}"); | ||
| 772 | assert!(br[0] > 200 && br[1] < 30, "180° BR should be red: {br:?}"); | ||
| 773 | } | ||
| 774 | 270 => { | ||
| 775 | // 270° CW (90° CCW): TR(green)->TL, BR(yellow)->TR, TL(red)->BL, BL(blue)->BR | ||
| 776 | assert!(tl[1] > 200 && tl[0] < 30, "270° TL should be green: {tl:?}"); | ||
| 777 | assert!(tr[0] > 200 && tr[1] > 200 && tr[2] < 30, "270° TR should be yellow: {tr:?}"); | ||
| 778 | assert!(bl[0] > 200 && bl[1] < 30, "270° BL should be red: {bl:?}"); | ||
| 779 | assert!(br[2] > 200 && br[0] < 30, "270° BR should be blue: {br:?}"); | ||
| 780 | } | ||
| 781 | _ => unreachable!(), | ||
| 782 | } | ||
| 783 | } | ||
| 784 | } | ||
| 785 | |||
| 786 | #[test] | ||
| 787 | fn nv12_multiple_dispatches_same_encoder_no_hazard() { | ||
| 788 | let engine = Engine::new_headless().expect("headless engine"); | ||
| 789 | let red = Nv12Frame { | ||
| 790 | raw_size: [16, 16], | ||
| 791 | display_size: [16, 16], | ||
| 792 | rot_deg: 0, | ||
| 793 | matrix: YuvMatrix::Bt709, | ||
| 794 | is_full_range: false, | ||
| 795 | y: vec![63u8; 16 * 16], | ||
| 796 | uv: [102u8, 240u8].repeat(8 * 8), | ||
| 797 | }; | ||
| 798 | let blue = Nv12Frame { | ||
| 799 | raw_size: [16, 16], | ||
| 800 | display_size: [16, 16], | ||
| 801 | rot_deg: 0, | ||
| 802 | matrix: YuvMatrix::Bt709, | ||
| 803 | is_full_range: false, | ||
| 804 | y: vec![32u8; 16 * 16], | ||
| 805 | uv: [240u8, 118u8].repeat(8 * 8), | ||
| 806 | }; | ||
| 807 | |||
| 808 | let mut enc = engine | ||
| 809 | .device | ||
| 810 | .create_command_encoder(&wgpu::CommandEncoderDescriptor { | ||
| 811 | label: Some("nv12-multi-dispatch"), | ||
| 812 | }); | ||
| 813 | let dst_red = engine.alloc_tex([16, 16], BitDepth::Float16, 0); | ||
| 814 | let dst_blue = engine.alloc_tex([16, 16], BitDepth::Float16, 0); | ||
| 815 | upload_and_convert_nv12(&engine, &mut enc, &red, &dst_red); | ||
| 816 | upload_and_convert_nv12(&engine, &mut enc, &blue, &dst_blue); | ||
| 817 | engine.queue.submit(Some(enc.finish())); | ||
| 818 | engine.media.flush_upload_staging_after_submit(&engine.device); | ||
| 819 | |||
| 820 | let r_px = engine.readback_rgba(&dst_red).expect("readback red"); | ||
| 821 | let b_px = engine.readback_rgba(&dst_blue).expect("readback blue"); | ||
| 822 | assert!(r_px[0] > 220 && r_px[1] < 20 && r_px[2] < 20, "first dispatch corrupted: {:?}", &r_px[..4]); | ||
| 823 | assert!(b_px[2] > 220 && b_px[0] < 20 && b_px[1] < 20, "second dispatch corrupted: {:?}", &b_px[..4]); | ||
| 824 | } | ||
| 825 | |||
| 826 | #[cfg(target_os = "macos")] | ||
| 827 | #[test] | ||
| 828 | fn nv12_synthetic_mp4_decode_and_eval_loader() { | ||
| 829 | use crate::media::{AvFoundationDecoder, FfmpegDecoder, VideoDecoder}; | ||
| 830 | use std::process::Command; | ||
| 831 | |||
| 832 | let dir = std::env::temp_dir().join(format!("fission_nv12_test_{}", std::process::id())); | ||
| 833 | let _ = std::fs::remove_dir_all(&dir); | ||
| 834 | std::fs::create_dir_all(&dir).unwrap(); | ||
| 835 | |||
| 836 | let mp4_path = dir.join("bars_bt709.mp4"); | ||
| 837 | let ok_mp4 = Command::new("ffmpeg") | ||
| 838 | .args([ | ||
| 839 | "-y", | ||
| 840 | "-v", | ||
| 841 | "error", | ||
| 842 | "-f", | ||
| 843 | "lavfi", | ||
| 844 | "-i", | ||
| 845 | "smptehdbars=size=128x96:rate=24:duration=0.25", | ||
| 846 | "-vf", | ||
| 847 | "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p", | ||
| 848 | "-c:v", | ||
| 849 | "libx264", | ||
| 850 | "-crf", | ||
| 851 | "10", | ||
| 852 | "-colorspace", | ||
| 853 | "bt709", | ||
| 854 | "-color_primaries", | ||
| 855 | "bt709", | ||
| 856 | "-color_trc", | ||
| 857 | "bt709", | ||
| 858 | "-color_range", | ||
| 859 | "tv", | ||
| 860 | ]) | ||
| 861 | .arg(&mp4_path) | ||
| 862 | .status() | ||
| 863 | .is_ok_and(|s| s.success()); | ||
| 864 | if !ok_mp4 { | ||
| 865 | let _ = std::fs::remove_dir_all(&dir); | ||
| 866 | return; | ||
| 867 | } | ||
| 868 | |||
| 869 | // 1. Verify AvFoundationDecoder selects NV12 for opaque 8-bit 4:2:0 H.264 MP4. | ||
| 870 | let mut av_dec = AvFoundationDecoder::open(&mp4_path).expect("AvFoundationDecoder::open"); | ||
| 871 | assert!(av_dec.is_nv12(), "8-bit opaque H.264 yuv420p should use NV12 fast path"); | ||
| 872 | let nv12 = av_dec.decode_nv12_frame(0).expect("decode_nv12_frame(0)"); | ||
| 873 | assert_eq!(nv12.raw_size, [128, 96]); | ||
| 874 | assert_eq!(nv12.display_size, [128, 96]); | ||
| 875 | assert_eq!(nv12.rot_deg, 0); | ||
| 876 | assert_eq!(nv12.matrix, YuvMatrix::Bt709); | ||
| 877 | assert!(!nv12.is_full_range); | ||
| 878 | assert_eq!(nv12.byte_size(), (128 * 96 + 64 * 48 * 2) as u64); | ||
| 879 | |||
| 880 | // Verify EOF frame-hold returns valid last frame when requesting past EOF. | ||
| 881 | let eof_frame = av_dec.decode_nv12_frame(999).expect("EOF frame hold"); | ||
| 882 | assert_eq!(eof_frame.raw_size, [128, 96]); | ||
| 883 | assert_eq!(eof_frame.y.len(), 128 * 96); | ||
| 884 | |||
| 885 | // 2. Verify rotated 90° H.264 MP4 decodes as NV12 with raw sensor dims + rot_deg = 90 | ||
| 886 | // and rotated display dimensions [96, 128]. | ||
| 887 | let rot_mp4 = dir.join("bars_rot90.mp4"); | ||
| 888 | let ok_rot = Command::new("ffmpeg") | ||
| 889 | .args([ | ||
| 890 | "-y", | ||
| 891 | "-v", | ||
| 892 | "error", | ||
| 893 | "-display_rotation", | ||
| 894 | "270", // FFmpeg display_rotation is CCW; 270 CCW == 90 CW preferredTransform | ||
| 895 | "-i", | ||
| 896 | ]) | ||
| 897 | .arg(&mp4_path) | ||
| 898 | .args(["-c", "copy"]) | ||
| 899 | .arg(&rot_mp4) | ||
| 900 | .status() | ||
| 901 | .is_ok_and(|s| s.success()); | ||
| 902 | if ok_rot { | ||
| 903 | let mut rot_dec = AvFoundationDecoder::open(&rot_mp4).expect("open rot90 mp4"); | ||
| 904 | assert!(rot_dec.is_nv12(), "rotated 8-bit H.264 should use NV12"); | ||
| 905 | let rot_frame = rot_dec.decode_nv12_frame(0).expect("decode rot90 frame"); | ||
| 906 | assert_eq!(rot_frame.raw_size, [128, 96]); | ||
| 907 | assert_eq!(rot_frame.display_size, [96, 128]); | ||
| 908 | assert_eq!(rot_frame.rot_deg, 90); | ||
| 909 | } | ||
| 910 | |||
| 911 | // 2. Verify ProRes 4444 alpha MOV stays on BGRA path (NOT NV12). | ||
| 912 | let alpha_mov = dir.join("alpha_4444.mov"); | ||
| 913 | let ok_alpha = Command::new("ffmpeg") | ||
| 914 | .args([ | ||
| 915 | "-y", | ||
| 916 | "-v", | ||
| 917 | "error", | ||
| 918 | "-f", | ||
| 919 | "lavfi", | ||
| 920 | "-i", | ||
| 921 | "color=c=red@0.5:size=32x32:rate=24:duration=0.1,format=yuva444p10le", | ||
| 922 | "-c:v", | ||
| 923 | "prores_ks", | ||
| 924 | "-profile:v", | ||
| 925 | "4", | ||
| 926 | "-pix_fmt", | ||
| 927 | "yuva444p10le", | ||
| 928 | ]) | ||
| 929 | .arg(&alpha_mov) | ||
| 930 | .status() | ||
| 931 | .is_ok_and(|s| s.success()); | ||
| 932 | if ok_alpha { | ||
| 933 | if let Some(alpha_dec) = AvFoundationDecoder::open(&alpha_mov) { | ||
| 934 | assert!( | ||
| 935 | !alpha_dec.is_nv12(), | ||
| 936 | "ProRes 4444 alpha video must NOT use NV12 path" | ||
| 937 | ); | ||
| 938 | } | ||
| 939 | } | ||
| 940 | |||
| 941 | // 3. Evaluate Loader through GPU Engine (HiQ Float16) and compare vs ffmpeg reference. | ||
| 942 | let esc = mp4_path.to_string_lossy().replace('\\', "\\\\"); | ||
| 943 | let comp_src = format!( | ||
| 944 | r#"Composition {{ | ||
| 945 | CurrentTime = 0, | ||
| 946 | RenderRange = {{ 0, 5 }}, | ||
| 947 | GlobalRange = {{ 0, 5 }}, | ||
| 948 | Tools = ordered() {{ | ||
| 949 | V = Loader {{ | ||
| 950 | Clips = {{ | ||
| 951 | Clip {{ | ||
| 952 | ID = "Clip1", | ||
| 953 | Filename = "{esc}", | ||
| 954 | FormatID = "QuickTimeMovies", | ||
| 955 | Length = 6, | ||
| 956 | GlobalStart = 0, | ||
| 957 | GlobalEnd = 5, | ||
| 958 | }}, | ||
| 959 | }}, | ||
| 960 | }}, | ||
| 961 | }}, | ||
| 962 | }}"# | ||
| 963 | ); | ||
| 964 | let comp = Comp::from_fusion_str(&comp_src).expect("parse comp"); | ||
| 965 | let target = comp.find_node("V").expect("V"); | ||
| 966 | let mut engine = Engine::new_headless().expect("headless engine"); | ||
| 967 | let (tex, _) = engine.evaluate(&comp, target, 0.0); | ||
| 968 | let gpu_rgba = engine.readback_rgba(&tex).expect("readback"); | ||
| 969 | |||
| 970 | let mut ff = FfmpegDecoder::open(&mp4_path).expect("FfmpegDecoder"); | ||
| 971 | let ff_rgba = ff.decode_frame(0).expect("ff decode 0"); | ||
| 972 | assert_eq!(gpu_rgba.len(), ff_rgba.len()); | ||
| 973 | let mae: f64 = gpu_rgba | ||
| 974 | .iter() | ||
| 975 | .zip(ff_rgba.iter()) | ||
| 976 | .map(|(&a, &b)| (a as i32 - b as i32).abs() as f64) | ||
| 977 | .sum::<f64>() | ||
| 978 | / gpu_rgba.len() as f64; | ||
| 979 | assert!( | ||
| 980 | mae < 2.5, | ||
| 981 | "GPU NV12 Loader output diverged from ffmpeg reference: MAE={mae:.2}/255" | ||
| 982 | ); | ||
| 983 | |||
| 984 | let _ = std::fs::remove_dir_all(&dir); | ||
| 985 | } | ||
| 986 | } | ||
crates/engine/src/media.rs+120-23| ... | @@ -15,7 +15,10 @@ pub use prefetch::MediaPrefetchHandle; | ... | @@ -15,7 +15,10 @@ pub use prefetch::MediaPrefetchHandle; |
| 15 | pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; | 15 | pub use raster::{TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; |
| 16 | #[cfg(target_os = "macos")] | 16 | #[cfg(target_os = "macos")] |
| 17 | pub use video::AvFoundationDecoder; | 17 | pub use video::AvFoundationDecoder; |
| 18 | pub use video::{FfmpegDecoder, VideoDecoder, VideoInfo, open_video_decoder}; | 18 | pub use video::{ |
| 19 | DecodedVideoFrame, FfmpegDecoder, Nv12Frame, VideoDecoder, VideoInfo, YuvMatrix, | ||
| 20 | open_video_decoder, | ||
| 21 | }; | ||
| 19 | use exr::{ | 22 | use exr::{ |
| 20 | apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path, | 23 | apply_post_multiply_rgba8, apply_post_multiply_rgba8_parallel, decode_exr_rgba, is_exr_path, |
| 21 | normalize_channel_opt, | 24 | normalize_channel_opt, |
| ... | @@ -77,6 +80,43 @@ impl DecodedImage { | ... | @@ -77,6 +80,43 @@ impl DecodedImage { |
| 77 | } | 80 | } |
| 78 | } | 81 | } |
| 79 | 82 | ||
| 83 | /// Internal cached media payload: either decoded RGBA/HDR image buffers or a compact | ||
| 84 | /// native NV12 video frame (`~2.67×` smaller than 4K RGBA) uploaded directly to GPU. | ||
| 85 | #[derive(Clone)] | ||
| 86 | pub(crate) enum CachedMedia { | ||
| 87 | Rgba(DecodedImage), | ||
| 88 | Nv12(Arc<Nv12Frame>), | ||
| 89 | } | ||
| 90 | |||
| 91 | impl CachedMedia { | ||
| 92 | pub(crate) fn size(&self) -> [u32; 2] { | ||
| 93 | match self { | ||
| 94 | Self::Rgba(img) => img.size, | ||
| 95 | Self::Nv12(frame) => frame.display_size, | ||
| 96 | } | ||
| 97 | } | ||
| 98 | |||
| 99 | pub(crate) fn byte_size(&self) -> u64 { | ||
| 100 | match self { | ||
| 101 | Self::Rgba(img) => img.byte_size(), | ||
| 102 | Self::Nv12(frame) => frame.byte_size(), | ||
| 103 | } | ||
| 104 | } | ||
| 105 | |||
| 106 | pub(crate) fn into_decoded_image(self) -> DecodedImage { | ||
| 107 | match self { | ||
| 108 | Self::Rgba(img) => img, | ||
| 109 | Self::Nv12(frame) => DecodedImage { | ||
| 110 | size: frame.display_size, | ||
| 111 | rgba: Arc::new(frame.to_rgba8()), | ||
| 112 | rgba_f16: None, | ||
| 113 | rgba_f32: None, | ||
| 114 | z_f32: None, | ||
| 115 | }, | ||
| 116 | } | ||
| 117 | } | ||
| 118 | } | ||
| 119 | |||
| 80 | const MAX_VIDEO_DECODERS: usize = 12; | 120 | const MAX_VIDEO_DECODERS: usize = 12; |
| 81 | 121 | ||
| 82 | struct VirtualFile { | 122 | struct VirtualFile { |
| ... | @@ -182,7 +222,7 @@ struct VideoDecoderSlot { | ... | @@ -182,7 +222,7 @@ struct VideoDecoderSlot { |
| 182 | } | 222 | } |
| 183 | 223 | ||
| 184 | struct MediaState { | 224 | struct MediaState { |
| 185 | images: HashMap<ImageCacheKey, DecodedImage>, | 225 | images: HashMap<ImageCacheKey, CachedMedia>, |
| 186 | video_decoders: HashMap<PathBuf, VideoDecoderSlot>, | 226 | video_decoders: HashMap<PathBuf, VideoDecoderSlot>, |
| 187 | total_bytes: u64, | 227 | total_bytes: u64, |
| 188 | budget_bytes: u64, | 228 | budget_bytes: u64, |
| ... | @@ -251,10 +291,15 @@ impl MediaState { | ... | @@ -251,10 +291,15 @@ impl MediaState { |
| 251 | let _ = path; | 291 | let _ = path; |
| 252 | } | 292 | } |
| 253 | 293 | ||
| 294 | #[cfg(not(target_arch = "wasm32"))] | ||
| 254 | fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { | 295 | fn insert_cached(&mut self, cache_key: ImageCacheKey, decoded: DecodedImage) { |
| 255 | let bytes = decoded.byte_size(); | 296 | self.insert_cached_media(cache_key, CachedMedia::Rgba(decoded)); |
| 297 | } | ||
| 298 | |||
| 299 | fn insert_cached_media(&mut self, cache_key: ImageCacheKey, media: CachedMedia) { | ||
| 300 | let bytes = media.byte_size(); | ||
| 256 | self.tick += 1; | 301 | self.tick += 1; |
| 257 | if let Some(prev) = self.images.insert(cache_key.clone(), decoded) { | 302 | if let Some(prev) = self.images.insert(cache_key.clone(), media) { |
| 258 | self.total_bytes = self.total_bytes.saturating_sub(prev.byte_size()); | 303 | self.total_bytes = self.total_bytes.saturating_sub(prev.byte_size()); |
| 259 | } | 304 | } |
| 260 | self.lru.insert(cache_key, self.tick); | 305 | self.lru.insert(cache_key, self.tick); |
| ... | @@ -333,6 +378,7 @@ impl MediaShared { | ... | @@ -333,6 +378,7 @@ impl MediaShared { |
| 333 | } | 378 | } |
| 334 | } | 379 | } |
| 335 | 380 | ||
| 381 | #[cfg(not(target_arch = "wasm32"))] | ||
| 336 | fn insert_cached_locked( | 382 | fn insert_cached_locked( |
| 337 | &self, | 383 | &self, |
| 338 | state: &mut MediaState, | 384 | state: &mut MediaState, |
| ... | @@ -343,6 +389,16 @@ impl MediaShared { | ... | @@ -343,6 +389,16 @@ impl MediaShared { |
| 343 | self.sync_lookahead_throttle(state) | 389 | self.sync_lookahead_throttle(state) |
| 344 | } | 390 | } |
| 345 | 391 | ||
| 392 | fn insert_cached_media_locked( | ||
| 393 | &self, | ||
| 394 | state: &mut MediaState, | ||
| 395 | cache_key: ImageCacheKey, | ||
| 396 | media: CachedMedia, | ||
| 397 | ) -> bool { | ||
| 398 | state.insert_cached_media(cache_key, media); | ||
| 399 | self.sync_lookahead_throttle(state) | ||
| 400 | } | ||
| 401 | |||
| 346 | fn path_exists_cached(&self, path: &Path) -> bool { | 402 | fn path_exists_cached(&self, path: &Path) -> bool { |
| 347 | if virtual_bytes(path).is_some() { | 403 | if virtual_bytes(path).is_some() { |
| 348 | return true; | 404 | return true; |
| ... | @@ -627,6 +683,8 @@ pub struct MediaCache { | ... | @@ -627,6 +683,8 @@ pub struct MediaCache { |
| 627 | shared: Arc<MediaShared>, | 683 | shared: Arc<MediaShared>, |
| 628 | #[cfg(not(target_arch = "wasm32"))] | 684 | #[cfg(not(target_arch = "wasm32"))] |
| 629 | staging_pool: Mutex<UploadStagingPool>, | 685 | staging_pool: Mutex<UploadStagingPool>, |
| 686 | #[cfg(not(target_arch = "wasm32"))] | ||
| 687 | nv12_gpu_state: Mutex<Option<Box<dyn std::any::Any + Send>>>, | ||
| 630 | } | 688 | } |
| 631 | 689 | ||
| 632 | impl Default for MediaCache { | 690 | impl Default for MediaCache { |
| ... | @@ -641,6 +699,8 @@ impl MediaCache { | ... | @@ -641,6 +699,8 @@ impl MediaCache { |
| 641 | shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))), | 699 | shared: Arc::new(MediaShared::new(budget_mb.saturating_mul(1024 * 1024))), |
| 642 | #[cfg(not(target_arch = "wasm32"))] | 700 | #[cfg(not(target_arch = "wasm32"))] |
| 643 | staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)), | 701 | staging_pool: Mutex::new(UploadStagingPool::new(320 * 1024 * 1024)), |
| 702 | #[cfg(not(target_arch = "wasm32"))] | ||
| 703 | nv12_gpu_state: Mutex::new(None), | ||
| 644 | } | 704 | } |
| 645 | } | 705 | } |
| 646 | 706 | ||
| ... | @@ -689,6 +749,24 @@ impl MediaCache { | ... | @@ -689,6 +749,24 @@ impl MediaCache { |
| 689 | if let Ok(mut pool) = self.staging_pool.lock() { | 749 | if let Ok(mut pool) = self.staging_pool.lock() { |
| 690 | pool.clear(); | 750 | pool.clear(); |
| 691 | } | 751 | } |
| 752 | #[cfg(not(target_arch = "wasm32"))] | ||
| 753 | if let Ok(mut slot) = self.nv12_gpu_state.lock() { | ||
| 754 | *slot = None; | ||
| 755 | } | ||
| 756 | } | ||
| 757 | |||
| 758 | #[cfg(not(target_arch = "wasm32"))] | ||
| 759 | pub(crate) fn with_nv12_gpu_state<T: Send + 'static, R>( | ||
| 760 | &self, | ||
| 761 | init: impl FnOnce() -> T, | ||
| 762 | f: impl FnOnce(&mut T) -> R, | ||
| 763 | ) -> R { | ||
| 764 | let mut slot = self.nv12_gpu_state.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 765 | let any = slot.get_or_insert_with(|| Box::new(init())); | ||
| 766 | let state = any | ||
| 767 | .downcast_mut::<T>() | ||
| 768 | .expect("nv12_gpu_state type mismatch"); | ||
| 769 | f(state) | ||
| 692 | } | 770 | } |
| 693 | 771 | ||
| 694 | #[cfg(not(target_arch = "wasm32"))] | 772 | #[cfg(not(target_arch = "wasm32"))] |
| ... | @@ -773,6 +851,19 @@ impl MediaCache { | ... | @@ -773,6 +851,19 @@ impl MediaCache { |
| 773 | post_multiply: bool, | 851 | post_multiply: bool, |
| 774 | exr_channels: [Option<&str>; 4], | 852 | exr_channels: [Option<&str>; 4], |
| 775 | ) -> Option<(PathBuf, i64, DecodedImage, bool)> { | 853 | ) -> Option<(PathBuf, i64, DecodedImage, bool)> { |
| 854 | self.load_clip_media(clip, frame, post_multiply, exr_channels) | ||
| 855 | .map(|(resolved, idx, media, from_disk)| (resolved, idx, media.into_decoded_image(), from_disk)) | ||
| 856 | } | ||
| 857 | |||
| 858 | /// Loads a Fusion `ClipSpec` keeping native `NV12` video frames unconverted for direct | ||
| 859 | /// single-pass GPU upload and YUV->RGBA+rotation conversion. | ||
| 860 | pub(crate) fn load_clip_media( | ||
| 861 | &mut self, | ||
| 862 | clip: &ClipSpec, | ||
| 863 | frame: i64, | ||
| 864 | post_multiply: bool, | ||
| 865 | exr_channels: [Option<&str>; 4], | ||
| 866 | ) -> Option<(PathBuf, i64, CachedMedia, bool)> { | ||
| 776 | let base = Path::new(&clip.filename); | 867 | let base = Path::new(&clip.filename); |
| 777 | if is_video_path(base) { | 868 | if is_video_path(base) { |
| 778 | if !video_frame_in_range(clip, frame) || !self.shared.path_exists_cached(base) { | 869 | if !video_frame_in_range(clip, frame) || !self.shared.path_exists_cached(base) { |
| ... | @@ -791,11 +882,11 @@ impl MediaCache { | ... | @@ -791,11 +882,11 @@ impl MediaCache { |
| 791 | let cache_gen = { | 882 | let cache_gen = { |
| 792 | let mut state = self.shared.state.lock().ok()?; | 883 | let mut state = self.shared.state.lock().ok()?; |
| 793 | loop { | 884 | loop { |
| 794 | if let Some(img) = state.images.get(&cache_key).cloned() { | 885 | if let Some(media) = state.images.get(&cache_key).cloned() { |
| 795 | state.tick += 1; | 886 | state.tick += 1; |
| 796 | let t = state.tick; | 887 | let t = state.tick; |
| 797 | state.lru.insert(cache_key, t); | 888 | state.lru.insert(cache_key, t); |
| 798 | return Some((base_buf, idx, img, false)); | 889 | return Some((base_buf, idx, media, false)); |
| 799 | } | 890 | } |
| 800 | #[cfg(not(target_arch = "wasm32"))] | 891 | #[cfg(not(target_arch = "wasm32"))] |
| 801 | if state.in_flight.contains(&cache_key) { | 892 | if state.in_flight.contains(&cache_key) { |
| ... | @@ -817,19 +908,24 @@ impl MediaCache { | ... | @@ -817,19 +908,24 @@ impl MediaCache { |
| 817 | key: Some(cache_key.clone()), | 908 | key: Some(cache_key.clone()), |
| 818 | }; | 909 | }; |
| 819 | 910 | ||
| 820 | let mut raw = { | 911 | let decoded_frame = { |
| 821 | let mut dec_guard = decoder_arc.lock().ok()?; | 912 | let mut dec_guard = decoder_arc.lock().ok()?; |
| 822 | dec_guard.as_mut()?.decode_frame(idx)? | 913 | dec_guard.as_mut()?.decode_frame_native(idx)? |
| 823 | }; | 914 | }; |
| 824 | if post_multiply { | 915 | let media = match decoded_frame { |
| 825 | apply_post_multiply_rgba8(&mut raw); | 916 | DecodedVideoFrame::Nv12(nv12) => CachedMedia::Nv12(Arc::new(nv12)), |
| 826 | } | 917 | DecodedVideoFrame::Rgba(mut raw) => { |
| 827 | let decoded = DecodedImage { | 918 | if post_multiply { |
| 828 | size: [info.width, info.height], | 919 | apply_post_multiply_rgba8(&mut raw); |
| 829 | rgba: Arc::new(raw), | 920 | } |
| 830 | rgba_f16: None, | 921 | CachedMedia::Rgba(DecodedImage { |
| 831 | rgba_f32: None, | 922 | size: [info.width, info.height], |
| 832 | z_f32: None, | 923 | rgba: Arc::new(raw), |
| 924 | rgba_f16: None, | ||
| 925 | rgba_f32: None, | ||
| 926 | z_f32: None, | ||
| 927 | }) | ||
| 928 | } | ||
| 833 | }; | 929 | }; |
| 834 | 930 | ||
| 835 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | 931 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { |
| ... | @@ -840,7 +936,7 @@ impl MediaCache { | ... | @@ -840,7 +936,7 @@ impl MediaCache { |
| 840 | } | 936 | } |
| 841 | let unthrottled = if state.generation == cache_gen { | 937 | let unthrottled = if state.generation == cache_gen { |
| 842 | self.shared | 938 | self.shared |
| 843 | .insert_cached_locked(&mut state, cache_key, decoded.clone()) | 939 | .insert_cached_media_locked(&mut state, cache_key, media.clone()) |
| 844 | } else { | 940 | } else { |
| 845 | self.shared.sync_lookahead_throttle(&state) | 941 | self.shared.sync_lookahead_throttle(&state) |
| 846 | }; | 942 | }; |
| ... | @@ -856,7 +952,7 @@ impl MediaCache { | ... | @@ -856,7 +952,7 @@ impl MediaCache { |
| 856 | } | 952 | } |
| 857 | #[cfg(target_arch = "wasm32")] | 953 | #[cfg(target_arch = "wasm32")] |
| 858 | let _ = unthrottled; | 954 | let _ = unthrottled; |
| 859 | return Some((base_buf, idx, decoded, true)); | 955 | return Some((base_buf, idx, media, true)); |
| 860 | } | 956 | } |
| 861 | 957 | ||
| 862 | let resolved = resolve_clip_candidate_path(clip, frame)?; | 958 | let resolved = resolve_clip_candidate_path(clip, frame)?; |
| ... | @@ -881,11 +977,11 @@ impl MediaCache { | ... | @@ -881,11 +977,11 @@ impl MediaCache { |
| 881 | let cache_gen = { | 977 | let cache_gen = { |
| 882 | let mut state = self.shared.state.lock().ok()?; | 978 | let mut state = self.shared.state.lock().ok()?; |
| 883 | loop { | 979 | loop { |
| 884 | if let Some(img) = state.images.get(&cache_key).cloned() { | 980 | if let Some(media) = state.images.get(&cache_key).cloned() { |
| 885 | state.tick += 1; | 981 | state.tick += 1; |
| 886 | let t = state.tick; | 982 | let t = state.tick; |
| 887 | state.lru.insert(cache_key, t); | 983 | state.lru.insert(cache_key, t); |
| 888 | return Some((resolved, -1, img, false)); | 984 | return Some((resolved, -1, media, false)); |
| 889 | } | 985 | } |
| 890 | #[cfg(not(target_arch = "wasm32"))] | 986 | #[cfg(not(target_arch = "wasm32"))] |
| 891 | if state.in_flight.contains(&cache_key) { | 987 | if state.in_flight.contains(&cache_key) { |
| ... | @@ -930,6 +1026,7 @@ impl MediaCache { | ... | @@ -930,6 +1026,7 @@ impl MediaCache { |
| 930 | } | 1026 | } |
| 931 | return None; | 1027 | return None; |
| 932 | }; | 1028 | }; |
| 1029 | let media = CachedMedia::Rgba(decoded); | ||
| 933 | 1030 | ||
| 934 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | 1031 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { |
| 935 | #[cfg(not(target_arch = "wasm32"))] | 1032 | #[cfg(not(target_arch = "wasm32"))] |
| ... | @@ -940,7 +1037,7 @@ impl MediaCache { | ... | @@ -940,7 +1037,7 @@ impl MediaCache { |
| 940 | let unthrottled = if state.generation == cache_gen { | 1037 | let unthrottled = if state.generation == cache_gen { |
| 941 | state.record_existing_path(&resolved); | 1038 | state.record_existing_path(&resolved); |
| 942 | self.shared | 1039 | self.shared |
| 943 | .insert_cached_locked(&mut state, cache_key, decoded.clone()) | 1040 | .insert_cached_media_locked(&mut state, cache_key, media.clone()) |
| 944 | } else { | 1041 | } else { |
| 945 | self.shared.sync_lookahead_throttle(&state) | 1042 | self.shared.sync_lookahead_throttle(&state) |
| 946 | }; | 1043 | }; |
| ... | @@ -956,7 +1053,7 @@ impl MediaCache { | ... | @@ -956,7 +1053,7 @@ impl MediaCache { |
| 956 | } | 1053 | } |
| 957 | #[cfg(target_arch = "wasm32")] | 1054 | #[cfg(target_arch = "wasm32")] |
| 958 | let _ = unthrottled; | 1055 | let _ = unthrottled; |
| 959 | Some((resolved, -1, decoded, true)) | 1056 | Some((resolved, -1, media, true)) |
| 960 | } | 1057 | } |
| 961 | } | 1058 | } |
| 962 | 1059 |
crates/engine/src/media/prefetch.rs+39-27| ... | @@ -269,27 +269,34 @@ impl MediaCache { | ... | @@ -269,27 +269,34 @@ impl MediaCache { |
| 269 | shared: &self.shared, | 269 | shared: &self.shared, |
| 270 | key: Some(key.clone()), | 270 | key: Some(key.clone()), |
| 271 | }; | 271 | }; |
| 272 | let decoded_raw = dec_arc | 272 | let decoded_frame = dec_arc |
| 273 | .lock() | 273 | .lock() |
| 274 | .ok() | 274 | .ok() |
| 275 | .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx)); | 275 | .and_then(|mut g| g.as_mut()?.decode_frame_native(frame_idx)); |
| 276 | if let Some(mut raw) = decoded_raw { | 276 | if let Some(frame) = decoded_frame { |
| 277 | if req.post_multiply { | 277 | let media = match frame { |
| 278 | apply_post_multiply_rgba8_parallel(&mut raw, false); | 278 | DecodedVideoFrame::Nv12(nv12) => { |
| 279 | } | 279 | CachedMedia::Nv12(Arc::new(nv12)) |
| 280 | let decoded = DecodedImage { | 280 | } |
| 281 | size: [info.width, info.height], | 281 | DecodedVideoFrame::Rgba(mut raw) => { |
| 282 | rgba: Arc::new(raw), | 282 | if req.post_multiply { |
| 283 | rgba_f16: None, | 283 | apply_post_multiply_rgba8_parallel(&mut raw, false); |
| 284 | rgba_f32: None, | 284 | } |
| 285 | z_f32: None, | 285 | CachedMedia::Rgba(DecodedImage { |
| 286 | size: [info.width, info.height], | ||
| 287 | rgba: Arc::new(raw), | ||
| 288 | rgba_f16: None, | ||
| 289 | rgba_f32: None, | ||
| 290 | z_f32: None, | ||
| 291 | }) | ||
| 292 | } | ||
| 286 | }; | 293 | }; |
| 287 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { | 294 | let unthrottled = if let Ok(mut state) = self.shared.state.lock() { |
| 288 | state.in_flight.remove(&key); | 295 | state.in_flight.remove(&key); |
| 289 | guard.key = None; | 296 | guard.key = None; |
| 290 | let unthrottled = if state.generation == cache_gen { | 297 | let unthrottled = if state.generation == cache_gen { |
| 291 | self.shared | 298 | self.shared |
| 292 | .insert_cached_locked(&mut state, key, decoded) | 299 | .insert_cached_media_locked(&mut state, key, media) |
| 293 | } else { | 300 | } else { |
| 294 | self.shared.sync_lookahead_throttle(&state) | 301 | self.shared.sync_lookahead_throttle(&state) |
| 295 | }; | 302 | }; |
| ... | @@ -707,29 +714,34 @@ impl MediaPrefetchHandle { | ... | @@ -707,29 +714,34 @@ impl MediaPrefetchHandle { |
| 707 | shared: &shared, | 714 | shared: &shared, |
| 708 | key: Some(key.clone()), | 715 | key: Some(key.clone()), |
| 709 | }; | 716 | }; |
| 710 | let decoded_raw = dec_arc | 717 | let decoded_frame = dec_arc |
| 711 | .lock() | 718 | .lock() |
| 712 | .ok() | 719 | .ok() |
| 713 | .and_then(|mut g| g.as_mut()?.decode_frame(frame_idx)); | 720 | .and_then(|mut g| g.as_mut()?.decode_frame_native(frame_idx)); |
| 714 | if let Some(mut raw) = decoded_raw { | 721 | if let Some(frame) = decoded_frame { |
| 715 | if req.post_multiply { | 722 | let media = match frame { |
| 716 | apply_post_multiply_rgba8_parallel(&mut raw, false); | 723 | DecodedVideoFrame::Nv12(nv12) => CachedMedia::Nv12(Arc::new(nv12)), |
| 717 | } | 724 | DecodedVideoFrame::Rgba(mut raw) => { |
| 718 | let decoded = DecodedImage { | 725 | if req.post_multiply { |
| 719 | size: [info.width, info.height], | 726 | apply_post_multiply_rgba8_parallel(&mut raw, false); |
| 720 | rgba: Arc::new(raw), | 727 | } |
| 721 | rgba_f16: None, | 728 | CachedMedia::Rgba(DecodedImage { |
| 722 | rgba_f32: None, | 729 | size: [info.width, info.height], |
| 723 | z_f32: None, | 730 | rgba: Arc::new(raw), |
| 731 | rgba_f16: None, | ||
| 732 | rgba_f32: None, | ||
| 733 | z_f32: None, | ||
| 734 | }) | ||
| 735 | } | ||
| 724 | }; | 736 | }; |
| 725 | let unthrottled = if let Ok(mut state) = shared.state.lock() { | 737 | let unthrottled = if let Ok(mut state) = shared.state.lock() { |
| 726 | state.in_flight.remove(&key); | 738 | state.in_flight.remove(&key); |
| 727 | guard.key = None; | 739 | guard.key = None; |
| 728 | let unthrottled = if state.generation == cache_gen { | 740 | let unthrottled = if state.generation == cache_gen { |
| 729 | if item_seq > cur_seq { | 741 | if item_seq > cur_seq { |
| 730 | state.record_speculative_decode(decoded.byte_size()); | 742 | state.record_speculative_decode(media.byte_size()); |
| 731 | } | 743 | } |
| 732 | shared.insert_cached_locked(&mut state, key, decoded) | 744 | shared.insert_cached_media_locked(&mut state, key, media) |
| 733 | } else { | 745 | } else { |
| 734 | shared.sync_lookahead_throttle(&state) | 746 | shared.sync_lookahead_throttle(&state) |
| 735 | }; | 747 | }; |
crates/engine/src/media/video.rs+260| ... | @@ -8,9 +8,186 @@ pub struct VideoInfo { | ... | @@ -8,9 +8,186 @@ pub struct VideoInfo { |
| 8 | pub nb_frames: i64, | 8 | pub nb_frames: i64, |
| 9 | } | 9 | } |
| 10 | 10 | ||
| 11 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
| 12 | #[repr(u32)] | ||
| 13 | pub enum YuvMatrix { | ||
| 14 | Bt709 = 0, | ||
| 15 | Bt601 = 1, | ||
| 16 | Bt2020 = 2, | ||
| 17 | } | ||
| 18 | |||
| 19 | impl YuvMatrix { | ||
| 20 | pub fn from_u32(v: u32) -> Self { | ||
| 21 | match v { | ||
| 22 | 1 => Self::Bt601, | ||
| 23 | 2 => Self::Bt2020, | ||
| 24 | _ => Self::Bt709, | ||
| 25 | } | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | /// Compact 8-bit 4:2:0 bi-planar NV12 video frame (`Y` + interleaved `CbCr`) with | ||
| 30 | /// colorimetry and rotation metadata for direct single-pass GPU conversion. | ||
| 31 | #[derive(Clone, Debug)] | ||
| 32 | pub struct Nv12Frame { | ||
| 33 | /// Unrotated raw sensor dimensions `[raw_w, raw_h]`. | ||
| 34 | pub raw_size: [u32; 2], | ||
| 35 | /// Rotated display dimensions `[out_w, out_h]`. | ||
| 36 | pub display_size: [u32; 2], | ||
| 37 | /// Clockwise rotation in degrees (`0`, `90`, `180`, or `270`). | ||
| 38 | pub rot_deg: u32, | ||
| 39 | /// YCbCr-to-RGB matrix (`BT.709`, `BT.601`, or `BT.2020`). | ||
| 40 | pub matrix: YuvMatrix, | ||
| 41 | /// `true` for full-range (`0..255`), `false` for video-range (`Y: 16..235`, `UV: 16..240`). | ||
| 42 | pub is_full_range: bool, | ||
| 43 | /// Tightly packed 8-bit luma plane (`raw_w * raw_h` bytes). | ||
| 44 | pub y: Vec<u8>, | ||
| 45 | /// Tightly packed interleaved 8-bit CbCr plane (`uv_w * uv_h * 2` bytes). | ||
| 46 | pub uv: Vec<u8>, | ||
| 47 | } | ||
| 48 | |||
| 49 | impl Nv12Frame { | ||
| 50 | pub fn uv_size(&self) -> [u32; 2] { | ||
| 51 | [self.raw_size[0].div_ceil(2), self.raw_size[1].div_ceil(2)] | ||
| 52 | } | ||
| 53 | |||
| 54 | pub fn byte_size(&self) -> u64 { | ||
| 55 | (self.y.len() + self.uv.len()) as u64 | ||
| 56 | } | ||
| 57 | |||
| 58 | /// Reference CPU NV12 -> RGBA8 conversion matching `nv12_to_rgba.wgsl` | ||
| 59 | /// (center-aligned bilinear chroma sampling, rotation, and ITU-R matrix). | ||
| 60 | /// Used only by legacy CPU-only callers (`load_clip`, `VideoDecoder::decode_frame`, tests). | ||
| 61 | pub fn to_rgba8(&self) -> Vec<u8> { | ||
| 62 | let [raw_w, raw_h] = self.raw_size; | ||
| 63 | let [out_w, out_h] = self.display_size; | ||
| 64 | let [uv_w, uv_h] = self.uv_size(); | ||
| 65 | let total_px = (out_w as usize).saturating_mul(out_h as usize); | ||
| 66 | let mut out = vec![0u8; total_px * 4]; | ||
| 67 | if raw_w == 0 || raw_h == 0 || uv_w == 0 || uv_h == 0 || out_w == 0 || out_h == 0 { | ||
| 68 | return out; | ||
| 69 | } | ||
| 70 | if self.y.len() < (raw_w as usize) * (raw_h as usize) | ||
| 71 | || self.uv.len() < (uv_w as usize) * (uv_h as usize) * 2 | ||
| 72 | { | ||
| 73 | return out; | ||
| 74 | } | ||
| 75 | |||
| 76 | let sample_uv = |u_norm: f32, v_norm: f32| -> (f32, f32) { | ||
| 77 | let fx = u_norm * (uv_w as f32) - 0.5; | ||
| 78 | let fy = v_norm * (uv_h as f32) - 0.5; | ||
| 79 | let x0 = (fx.floor() as i32).clamp(0, uv_w as i32 - 1) as usize; | ||
| 80 | let y0 = (fy.floor() as i32).clamp(0, uv_h as i32 - 1) as usize; | ||
| 81 | let x1 = (x0 + 1).min(uv_w as usize - 1); | ||
| 82 | let y1 = (y0 + 1).min(uv_h as usize - 1); | ||
| 83 | let tx = fx - fx.floor(); | ||
| 84 | let ty = fy - fy.floor(); | ||
| 85 | let wx = if fx < 0.0 { | ||
| 86 | 0.0 | ||
| 87 | } else if fx >= (uv_w as f32 - 1.0) { | ||
| 88 | 0.0 | ||
| 89 | } else { | ||
| 90 | tx | ||
| 91 | }; | ||
| 92 | let wy = if fy < 0.0 { | ||
| 93 | 0.0 | ||
| 94 | } else if fy >= (uv_h as f32 - 1.0) { | ||
| 95 | 0.0 | ||
| 96 | } else { | ||
| 97 | ty | ||
| 98 | }; | ||
| 99 | |||
| 100 | let read_pair = |x: usize, y: usize| -> (f32, f32) { | ||
| 101 | let idx = (y * (uv_w as usize) + x) * 2; | ||
| 102 | (self.uv[idx] as f32 / 255.0, self.uv[idx + 1] as f32 / 255.0) | ||
| 103 | }; | ||
| 104 | let (c00, r00) = read_pair(x0, y0); | ||
| 105 | let (c10, r10) = read_pair(x1, y0); | ||
| 106 | let (c01, r01) = read_pair(x0, y1); | ||
| 107 | let (c11, r11) = read_pair(x1, y1); | ||
| 108 | |||
| 109 | let c0 = c00 + (c10 - c00) * wx; | ||
| 110 | let c1 = c01 + (c11 - c01) * wx; | ||
| 111 | let cb = c0 + (c1 - c0) * wy; | ||
| 112 | |||
| 113 | let r0 = r00 + (r10 - r00) * wx; | ||
| 114 | let r1 = r01 + (r11 - r01) * wx; | ||
| 115 | let cr = r0 + (r1 - r0) * wy; | ||
| 116 | (cb, cr) | ||
| 117 | }; | ||
| 118 | |||
| 119 | let inv_raw_w = 1.0 / (raw_w as f32); | ||
| 120 | let inv_raw_h = 1.0 / (raw_h as f32); | ||
| 121 | let rw = raw_w as usize; | ||
| 122 | |||
| 123 | for dy in 0..out_h { | ||
| 124 | for dx in 0..out_w { | ||
| 125 | let (sx, sy) = match self.rot_deg { | ||
| 126 | 90 => (dy, raw_h.saturating_sub(1).saturating_sub(dx)), | ||
| 127 | 180 => ( | ||
| 128 | raw_w.saturating_sub(1).saturating_sub(dx), | ||
| 129 | raw_h.saturating_sub(1).saturating_sub(dy), | ||
| 130 | ), | ||
| 131 | 270 => (raw_w.saturating_sub(1).saturating_sub(dy), dx), | ||
| 132 | _ => (dx, dy), | ||
| 133 | }; | ||
| 134 | let sx = sx.min(raw_w - 1); | ||
| 135 | let sy = sy.min(raw_h - 1); | ||
| 136 | |||
| 137 | let y_raw = self.y[(sy as usize) * rw + (sx as usize)] as f32 / 255.0; | ||
| 138 | let (cb_raw, cr_raw) = | ||
| 139 | sample_uv((sx as f32 + 0.5) * inv_raw_w, (sy as f32 + 0.5) * inv_raw_h); | ||
| 140 | |||
| 141 | let (y, cb, cr) = if self.is_full_range { | ||
| 142 | (y_raw, cb_raw - (128.0 / 255.0), cr_raw - (128.0 / 255.0)) | ||
| 143 | } else { | ||
| 144 | ( | ||
| 145 | (y_raw - (16.0 / 255.0)) * (255.0 / 219.0), | ||
| 146 | (cb_raw - (128.0 / 255.0)) * (255.0 / 224.0), | ||
| 147 | (cr_raw - (128.0 / 255.0)) * (255.0 / 224.0), | ||
| 148 | ) | ||
| 149 | }; | ||
| 150 | |||
| 151 | let (r, g, b) = match self.matrix { | ||
| 152 | YuvMatrix::Bt601 => ( | ||
| 153 | y + 1.402_f32 * cr, | ||
| 154 | y - 0.344_136_29_f32 * cb - 0.714_136_29_f32 * cr, | ||
| 155 | y + 1.772_f32 * cb, | ||
| 156 | ), | ||
| 157 | YuvMatrix::Bt2020 => ( | ||
| 158 | y + 1.4746_f32 * cr, | ||
| 159 | y - 0.164_553_13_f32 * cb - 0.571_353_13_f32 * cr, | ||
| 160 | y + 1.8814_f32 * cb, | ||
| 161 | ), | ||
| 162 | YuvMatrix::Bt709 => ( | ||
| 163 | y + 1.5748_f32 * cr, | ||
| 164 | y - 0.187_324_27_f32 * cb - 0.468_124_27_f32 * cr, | ||
| 165 | y + 1.8556_f32 * cb, | ||
| 166 | ), | ||
| 167 | }; | ||
| 168 | |||
| 169 | let dst = ((dy as usize) * (out_w as usize) + (dx as usize)) * 4; | ||
| 170 | out[dst] = (r.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; | ||
| 171 | out[dst + 1] = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; | ||
| 172 | out[dst + 2] = (b.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; | ||
| 173 | out[dst + 3] = 255; | ||
| 174 | } | ||
| 175 | } | ||
| 176 | out | ||
| 177 | } | ||
| 178 | } | ||
| 179 | |||
| 180 | pub enum DecodedVideoFrame { | ||
| 181 | Rgba(Vec<u8>), | ||
| 182 | Nv12(Nv12Frame), | ||
| 183 | } | ||
| 184 | |||
| 11 | pub trait VideoDecoder: Send { | 185 | pub trait VideoDecoder: Send { |
| 12 | fn info(&self) -> VideoInfo; | 186 | fn info(&self) -> VideoInfo; |
| 13 | fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>>; | 187 | fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>>; |
| 188 | fn decode_frame_native(&mut self, frame_idx: i64) -> Option<DecodedVideoFrame> { | ||
| 189 | self.decode_frame(frame_idx).map(DecodedVideoFrame::Rgba) | ||
| 190 | } | ||
| 14 | fn backend_name(&self) -> &'static str; | 191 | fn backend_name(&self) -> &'static str; |
| 15 | } | 192 | } |
| 16 | 193 | ||
| ... | @@ -32,6 +209,13 @@ mod av_ffi { | ... | @@ -32,6 +209,13 @@ mod av_ffi { |
| 32 | out_nb_frames: *mut i64, | 209 | out_nb_frames: *mut i64, |
| 33 | ) -> *mut AvVideoDecoder; | 210 | ) -> *mut AvVideoDecoder; |
| 34 | 211 | ||
| 212 | pub fn av_video_is_nv12( | ||
| 213 | dec: *mut AvVideoDecoder, | ||
| 214 | out_raw_w: *mut u32, | ||
| 215 | out_raw_h: *mut u32, | ||
| 216 | out_rotation: *mut u32, | ||
| 217 | ) -> i32; | ||
| 218 | |||
| 35 | pub fn av_video_decode_frame( | 219 | pub fn av_video_decode_frame( |
| 36 | dec: *mut AvVideoDecoder, | 220 | dec: *mut AvVideoDecoder, |
| 37 | frame_idx: i64, | 221 | frame_idx: i64, |
| ... | @@ -39,6 +223,17 @@ mod av_ffi { | ... | @@ -39,6 +223,17 @@ mod av_ffi { |
| 39 | out_len: usize, | 223 | out_len: usize, |
| 40 | ) -> i32; | 224 | ) -> i32; |
| 41 | 225 | ||
| 226 | pub fn av_video_decode_nv12_frame( | ||
| 227 | dec: *mut AvVideoDecoder, | ||
| 228 | frame_idx: i64, | ||
| 229 | out_y: *mut u8, | ||
| 230 | out_y_len: usize, | ||
| 231 | out_uv: *mut u8, | ||
| 232 | out_uv_len: usize, | ||
| 233 | out_matrix: *mut u32, | ||
| 234 | out_full_range: *mut u32, | ||
| 235 | ) -> i32; | ||
| 236 | |||
| 42 | pub fn av_video_close(dec: *mut AvVideoDecoder); | 237 | pub fn av_video_close(dec: *mut AvVideoDecoder); |
| 43 | } | 238 | } |
| 44 | } | 239 | } |
| ... | @@ -47,6 +242,7 @@ mod av_ffi { | ... | @@ -47,6 +242,7 @@ mod av_ffi { |
| 47 | pub struct AvFoundationDecoder { | 242 | pub struct AvFoundationDecoder { |
| 48 | ptr: *mut av_ffi::AvVideoDecoder, | 243 | ptr: *mut av_ffi::AvVideoDecoder, |
| 49 | info: VideoInfo, | 244 | info: VideoInfo, |
| 245 | nv12_info: Option<([u32; 2], u32)>, | ||
| 50 | } | 246 | } |
| 51 | 247 | ||
| 52 | #[cfg(target_os = "macos")] | 248 | #[cfg(target_os = "macos")] |
| ... | @@ -87,6 +283,17 @@ impl AvFoundationDecoder { | ... | @@ -87,6 +283,17 @@ impl AvFoundationDecoder { |
| 87 | } | 283 | } |
| 88 | return None; | 284 | return None; |
| 89 | } | 285 | } |
| 286 | let mut raw_w = 0u32; | ||
| 287 | let mut raw_h = 0u32; | ||
| 288 | let mut rot_deg = 0u32; | ||
| 289 | let is_nv12 = unsafe { | ||
| 290 | av_ffi::av_video_is_nv12(ptr, &mut raw_w, &mut raw_h, &mut rot_deg) != 0 | ||
| 291 | }; | ||
| 292 | let nv12_info = if is_nv12 && raw_w > 0 && raw_h > 0 { | ||
| 293 | Some(([raw_w, raw_h], rot_deg)) | ||
| 294 | } else { | ||
| 295 | None | ||
| 296 | }; | ||
| 90 | Some(Self { | 297 | Some(Self { |
| 91 | ptr, | 298 | ptr, |
| 92 | info: VideoInfo { | 299 | info: VideoInfo { |
| ... | @@ -95,8 +302,50 @@ impl AvFoundationDecoder { | ... | @@ -95,8 +302,50 @@ impl AvFoundationDecoder { |
| 95 | fps: if fps > 0.0 { fps } else { 30.0 }, | 302 | fps: if fps > 0.0 { fps } else { 30.0 }, |
| 96 | nb_frames, | 303 | nb_frames, |
| 97 | }, | 304 | }, |
| 305 | nv12_info, | ||
| 98 | }) | 306 | }) |
| 99 | } | 307 | } |
| 308 | |||
| 309 | pub fn is_nv12(&self) -> bool { | ||
| 310 | self.nv12_info.is_some() | ||
| 311 | } | ||
| 312 | |||
| 313 | pub fn decode_nv12_frame(&mut self, frame_idx: i64) -> Option<Nv12Frame> { | ||
| 314 | let ([raw_w, raw_h], rot_deg) = self.nv12_info?; | ||
| 315 | let y_len = (raw_w as usize).checked_mul(raw_h as usize)?; | ||
| 316 | let uv_w = raw_w.div_ceil(2) as usize; | ||
| 317 | let uv_h = raw_h.div_ceil(2) as usize; | ||
| 318 | let uv_len = uv_w.checked_mul(uv_h)?.checked_mul(2)?; | ||
| 319 | let mut y = vec![0u8; y_len]; | ||
| 320 | let mut uv = vec![0u8; uv_len]; | ||
| 321 | let mut matrix = 0u32; | ||
| 322 | let mut full_range = 0u32; | ||
| 323 | let ok = unsafe { | ||
| 324 | av_ffi::av_video_decode_nv12_frame( | ||
| 325 | self.ptr, | ||
| 326 | frame_idx.max(0), | ||
| 327 | y.as_mut_ptr(), | ||
| 328 | y_len, | ||
| 329 | uv.as_mut_ptr(), | ||
| 330 | uv_len, | ||
| 331 | &mut matrix, | ||
| 332 | &mut full_range, | ||
| 333 | ) | ||
| 334 | }; | ||
| 335 | if ok != 0 { | ||
| 336 | Some(Nv12Frame { | ||
| 337 | raw_size: [raw_w, raw_h], | ||
| 338 | display_size: [self.info.width, self.info.height], | ||
| 339 | rot_deg, | ||
| 340 | matrix: YuvMatrix::from_u32(matrix), | ||
| 341 | is_full_range: full_range != 0, | ||
| 342 | y, | ||
| 343 | uv, | ||
| 344 | }) | ||
| 345 | } else { | ||
| 346 | None | ||
| 347 | } | ||
| 348 | } | ||
| 100 | } | 349 | } |
| 101 | 350 | ||
| 102 | #[cfg(target_os = "macos")] | 351 | #[cfg(target_os = "macos")] |
| ... | @@ -106,6 +355,9 @@ impl VideoDecoder for AvFoundationDecoder { | ... | @@ -106,6 +355,9 @@ impl VideoDecoder for AvFoundationDecoder { |
| 106 | } | 355 | } |
| 107 | 356 | ||
| 108 | fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>> { | 357 | fn decode_frame(&mut self, frame_idx: i64) -> Option<Vec<u8>> { |
| 358 | if self.nv12_info.is_some() { | ||
| 359 | return self.decode_nv12_frame(frame_idx).map(|f| f.to_rgba8()); | ||
| 360 | } | ||
| 109 | let len = (self.info.width as usize) | 361 | let len = (self.info.width as usize) |
| 110 | .checked_mul(self.info.height as usize)? | 362 | .checked_mul(self.info.height as usize)? |
| 111 | .checked_mul(4)?; | 363 | .checked_mul(4)?; |
| ... | @@ -120,6 +372,14 @@ impl VideoDecoder for AvFoundationDecoder { | ... | @@ -120,6 +372,14 @@ impl VideoDecoder for AvFoundationDecoder { |
| 120 | } | 372 | } |
| 121 | } | 373 | } |
| 122 | 374 | ||
| 375 | fn decode_frame_native(&mut self, frame_idx: i64) -> Option<DecodedVideoFrame> { | ||
| 376 | if self.nv12_info.is_some() { | ||
| 377 | self.decode_nv12_frame(frame_idx).map(DecodedVideoFrame::Nv12) | ||
| 378 | } else { | ||
| 379 | self.decode_frame(frame_idx).map(DecodedVideoFrame::Rgba) | ||
| 380 | } | ||
| 381 | } | ||
| 382 | |||
| 123 | fn backend_name(&self) -> &'static str { | 383 | fn backend_name(&self) -> &'static str { |
| 124 | "AVFoundation/VideoToolbox" | 384 | "AVFoundation/VideoToolbox" |
| 125 | } | 385 | } |
crates/engine/src/shaders/nv12_to_rgba.wgsl created+91| ... | @@ -0,0 +1,91 @@ | ||
| 1 | // Single-pass NV12 (8-bit 4:2:0 bi-planar Y + interleaved CbCr) -> RGBA compute shader | ||
| 2 | // with integrated clockwise 0/90/180/270 rotation and ITU-R BT.709 / BT.601 / BT.2020 | ||
| 3 | // video-range or full-range color conversion. 100% WebGPU-safe. | ||
| 4 | |||
| 5 | struct Nv12Params { | ||
| 6 | raw_w: u32, | ||
| 7 | raw_h: u32, | ||
| 8 | out_w: u32, | ||
| 9 | out_h: u32, | ||
| 10 | rot_deg: u32, | ||
| 11 | matrix_id: u32, | ||
| 12 | full_range: u32, | ||
| 13 | _pad: u32, | ||
| 14 | }; | ||
| 15 | |||
| 16 | @group(0) @binding(0) var y_tex: texture_2d<f32>; | ||
| 17 | @group(0) @binding(1) var uv_tex: texture_2d<f32>; | ||
| 18 | @group(0) @binding(2) var uv_sampler: sampler; | ||
| 19 | @group(0) @binding(3) var dst_tex: texture_storage_2d<rgba8unorm, write>; | ||
| 20 | @group(0) @binding(4) var<uniform> params: Nv12Params; | ||
| 21 | |||
| 22 | @compute @workgroup_size(8, 8, 1) | ||
| 23 | fn nv12_to_rgba(@builtin(global_invocation_id) gid: vec3<u32>) { | ||
| 24 | let dx = gid.x; | ||
| 25 | let dy = gid.y; | ||
| 26 | if (dx >= params.out_w || dy >= params.out_h) { | ||
| 27 | return; | ||
| 28 | } | ||
| 29 | |||
| 30 | var sx: u32 = dx; | ||
| 31 | var sy: u32 = dy; | ||
| 32 | if (params.rot_deg == 90u) { | ||
| 33 | sx = dy; | ||
| 34 | sy = params.raw_h - 1u - dx; | ||
| 35 | } else if (params.rot_deg == 180u) { | ||
| 36 | sx = params.raw_w - 1u - dx; | ||
| 37 | sy = params.raw_h - 1u - dy; | ||
| 38 | } else if (params.rot_deg == 270u) { | ||
| 39 | sx = params.raw_w - 1u - dy; | ||
| 40 | sy = dx; | ||
| 41 | } | ||
| 42 | sx = min(sx, params.raw_w - 1u); | ||
| 43 | sy = min(sy, params.raw_h - 1u); | ||
| 44 | |||
| 45 | let y_raw = textureLoad(y_tex, vec2<i32>(i32(sx), i32(sy)), 0).r; | ||
| 46 | let uv_coord = vec2<f32>( | ||
| 47 | (f32(sx) + 0.5) / f32(params.raw_w), | ||
| 48 | (f32(sy) + 0.5) / f32(params.raw_h), | ||
| 49 | ); | ||
| 50 | let uv_raw = textureSampleLevel(uv_tex, uv_sampler, uv_coord, 0.0).rg; | ||
| 51 | |||
| 52 | var y: f32; | ||
| 53 | var cb: f32; | ||
| 54 | var cr: f32; | ||
| 55 | if (params.full_range != 0u) { | ||
| 56 | y = y_raw; | ||
| 57 | cb = uv_raw.x - (128.0 / 255.0); | ||
| 58 | cr = uv_raw.y - (128.0 / 255.0); | ||
| 59 | } else { | ||
| 60 | y = (y_raw - (16.0 / 255.0)) * (255.0 / 219.0); | ||
| 61 | cb = (uv_raw.x - (128.0 / 255.0)) * (255.0 / 224.0); | ||
| 62 | cr = (uv_raw.y - (128.0 / 255.0)) * (255.0 / 224.0); | ||
| 63 | } | ||
| 64 | |||
| 65 | var rgb: vec3<f32>; | ||
| 66 | if (params.matrix_id == 1u) { | ||
| 67 | // ITU-R BT.601 (Kr = 0.299, Kb = 0.114) | ||
| 68 | rgb = vec3<f32>( | ||
| 69 | y + 1.402 * cr, | ||
| 70 | y - 0.34413629 * cb - 0.71413629 * cr, | ||
| 71 | y + 1.772 * cb, | ||
| 72 | ); | ||
| 73 | } else if (params.matrix_id == 2u) { | ||
| 74 | // ITU-R BT.2020 (Kr = 0.2627, Kb = 0.0593) | ||
| 75 | rgb = vec3<f32>( | ||
| 76 | y + 1.4746 * cr, | ||
| 77 | y - 0.16455313 * cb - 0.57135313 * cr, | ||
| 78 | y + 1.8814 * cb, | ||
| 79 | ); | ||
| 80 | } else { | ||
| 81 | // ITU-R BT.709 (Kr = 0.2126, Kb = 0.0722) | ||
| 82 | rgb = vec3<f32>( | ||
| 83 | y + 1.5748 * cr, | ||
| 84 | y - 0.18732427 * cb - 0.46812427 * cr, | ||
| 85 | y + 1.8556 * cb, | ||
| 86 | ); | ||
| 87 | } | ||
| 88 | |||
| 89 | let clamped = clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0)); | ||
| 90 | textureStore(dst_tex, vec2<i32>(i32(dx), i32(dy)), vec4<f32>(clamped, 1.0)); | ||
| 91 | } | ||