PR #26244 opened by superuser404
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26244
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26244.patch

`yadif_videotoolbox` commits a command buffer and waits for it once per plane, 
so every NV12 or P010 frame goes to the GPU twice and the filter thread waits 
twice. This puts the planes into one command buffer as dispatches on one 
encoder, with one commit and one wait per frame. The Metal kernel is unchanged.

Because both planes now share a submission, the parameters go by value through 
`setBytes` and the shared `mtlParamsBuffer` is gone (the CPU would otherwise 
overwrite plane 0's values before the GPU reads them). The textures are 
released after the wait. A command buffer that ends in error now returns 
`AVERROR_EXTERNAL`.

Output is unchanged. I compared framemd5 against current master for NV12 and 
P010, `send_field` and `send_frame`, TFF and BFF (testsrc2 at 1080), plus a 
1080i MPEG-2 stream: identical on every frame.

Timing, 1080p59.94 at field rate, per field:

| | before | after |
|---|---|---|
| M1 | 2.34 ms | 1.86 ms |
| M1 Max | 0.81 ms | 0.57 ms |

The M1 Max numbers and the original version of this change are from 
classicjazz, who found it for AetherEngine 
(https://github.com/superuser404notfound/AetherEngine/issues/1101), hence the 
Co-authored-by. Most of what is saved is the calling thread waiting on the GPU; 
on an Apple TV that is also the thread that decodes.

`make fate-source` passes. There is no FATE coverage for VideoToolbox filters, 
so the check above is what I have.



>From 5cd7680cc4cba924c4b5e32135473ca6e8b06437 Mon Sep 17 00:00:00 2001
From: Vincent Herbst <[email protected]>
Date: Sat, 21 Nov 2026 07:03:02 +0100
Subject: [PATCH] avfilter/vf_yadif_videotoolbox: submit each frame to the GPU
 once

The filter committed a command buffer and waited for it once per plane,
so an NV12 or P010 frame went to the GPU twice and the filter thread
waited twice. Encode the planes as dispatches on one compute encoder in
one command buffer, with one commit and one wait per frame.

The parameters now go by value through setBytes. Two planes in one
command buffer cannot share the old parameter buffer, because the CPU
would overwrite the first plane's values before the GPU reads them, so
the buffer is gone. The textures are released after the wait, since the
GPU reads them until then.

With a single wait there is one place to check the command buffer, so a
buffer that ends in error now returns AVERROR_EXTERNAL instead of passing
the frame on.

The output is unchanged: framemd5 of NV12 and P010, send_field and
send_frame, TFF and BFF, and a 1080i MPEG-2 stream match the previous
filter frame for frame. On an M1 a 1080p59.94 field took 1.86 ms instead
of 2.34 ms; on an M1 Max 0.57 ms instead of 0.81 ms.

Co-authored-by: classicjazz <[email protected]>
Signed-off-by: Vincent Herbst <[email protected]>
---
 libavfilter/vf_yadif_videotoolbox.m | 194 ++++++++++++++--------------
 1 file changed, 100 insertions(+), 94 deletions(-)

diff --git a/libavfilter/vf_yadif_videotoolbox.m 
b/libavfilter/vf_yadif_videotoolbox.m
index 4c7dc261d89..1c501c9aa7b 100644
--- a/libavfilter/vf_yadif_videotoolbox.m
+++ b/libavfilter/vf_yadif_videotoolbox.m
@@ -44,7 +44,6 @@ typedef struct API_AVAILABLE(macos(10.11), ios(8.0)) 
YADIFVTContext {
     id<MTLCommandQueue> mtlQueue;
     id<MTLComputePipelineState> mtlPipeline;
     id<MTLFunction> mtlFunction;
-    id<MTLBuffer> mtlParamsBuffer;
 
     CVMetalTextureCacheRef textureCache;
 } YADIFVTContext API_AVAILABLE(macos(10.11), ios(8.0));
@@ -52,7 +51,7 @@ typedef struct API_AVAILABLE(macos(10.11), ios(8.0)) 
YADIFVTContext {
 // Using sizeof(YADIFVTContext) outside of an availability check will error
 // if we're targeting an older OS version, so we need to calculate the size 
ourselves
 // (we'll statically verify it's correct in yadif_videotoolbox_init behind a 
check)
-#define YADIF_VT_CTX_SIZE (sizeof(YADIFContext) + sizeof(void*) * 10)
+#define YADIF_VT_CTX_SIZE (sizeof(YADIFContext) + sizeof(void*) * 9)
 
 struct mtlYadifParams {
     uint channels;
@@ -63,40 +62,34 @@ struct mtlYadifParams {
     int field_mode;
 };
 
-static void call_kernel(AVFilterContext *ctx,
-                        id<MTLTexture> dst,
-                        id<MTLTexture> prev,
-                        id<MTLTexture> cur,
-                        id<MTLTexture> next,
-                        int channels,
-                        int parity,
-                        int tff) API_AVAILABLE(macos(10.11), ios(8.0))
+// The planes of a frame are dispatches on one encoder in one command buffer, 
so the
+// frame goes to the GPU once and waits once, instead of once per plane.
+static void encode_plane(AVFilterContext *ctx,
+                         id<MTLComputeCommandEncoder> encoder,
+                         id<MTLTexture> dst,
+                         id<MTLTexture> prev,
+                         id<MTLTexture> cur,
+                         id<MTLTexture> next,
+                         int channels,
+                         int parity,
+                         int tff) API_AVAILABLE(macos(10.11), ios(8.0))
 {
     YADIFVTContext *s = ctx->priv;
-    @autoreleasepool {
-        id<MTLCommandBuffer> buffer = s->mtlQueue.commandBuffer;
-        id<MTLComputeCommandEncoder> encoder = buffer.computeCommandEncoder;
-        struct mtlYadifParams *params = (struct mtlYadifParams 
*)s->mtlParamsBuffer.contents;
-        *params = (struct mtlYadifParams){
-            .channels = channels,
-            .parity = parity,
-            .tff = tff,
-            .is_second_field = !(parity ^ tff),
-            .skip_spatial_check = s->yadif.mode&2,
-            .field_mode = s->yadif.current_field
-        };
+    struct mtlYadifParams params = {
+        .channels = channels,
+        .parity = parity,
+        .tff = tff,
+        .is_second_field = !(parity ^ tff),
+        .skip_spatial_check = s->yadif.mode&2,
+        .field_mode = s->yadif.current_field
+    };
 
-        [encoder setTexture:dst  atIndex:0];
-        [encoder setTexture:prev atIndex:1];
-        [encoder setTexture:cur  atIndex:2];
-        [encoder setTexture:next atIndex:3];
-        [encoder setBuffer:s->mtlParamsBuffer offset:0 atIndex:4];
-        ff_metal_compute_encoder_dispatch(s->mtlDevice, s->mtlPipeline, 
encoder, dst.width, dst.height);
-        [encoder endEncoding];
-
-        [buffer commit];
-        [buffer waitUntilCompleted];
-    }
+    [encoder setTexture:dst  atIndex:0];
+    [encoder setTexture:prev atIndex:1];
+    [encoder setTexture:cur  atIndex:2];
+    [encoder setTexture:next atIndex:3];
+    [encoder setBytes:&params length:sizeof(params) atIndex:4];
+    ff_metal_compute_encoder_dispatch(s->mtlDevice, s->mtlPipeline, encoder, 
dst.width, dst.height);
 }
 
 static int filter(AVFilterContext *ctx, AVFrame *dst,
@@ -104,69 +97,91 @@ static int filter(AVFilterContext *ctx, AVFrame *dst,
 {
     YADIFVTContext *s = ctx->priv;
     YADIFContext *y = &s->yadif;
+    // Four textures per plane, at most four planes. The GPU reads them until
+    // the command buffer completes, so they are released after the wait.
+    CVMetalTextureRef textures[16] = { NULL };
+    int nb_textures = 0, ret = 0;
 
-    for (int i = 0; i < y->csp->nb_components; i++) {
-        int pixel_size, channels;
-        const AVComponentDescriptor *comp = &y->csp->comp[i];
-        CVMetalTextureRef prev, cur, next, dest;
-        id<MTLTexture> tex_prev, tex_cur, tex_next, tex_dest;
-        MTLPixelFormat format;
+    @autoreleasepool {
+        id<MTLCommandBuffer> buffer = s->mtlQueue.commandBuffer;
+        id<MTLComputeCommandEncoder> encoder = buffer.computeCommandEncoder;
 
-        if (comp->plane < i) {
-            // We process planes as a whole, so don't reprocess
-            // them for additional components
-            continue;
-        }
+        for (int i = 0; i < y->csp->nb_components; i++) {
+            int pixel_size, channels;
+            const AVComponentDescriptor *comp = &y->csp->comp[i];
+            CVMetalTextureRef *tex = &textures[nb_textures];
+            MTLPixelFormat format;
 
-        pixel_size = (comp->depth + comp->shift) / 8;
-        channels = comp->step / pixel_size;
-        if (pixel_size > 2 || channels > 2) {
-            av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n", 
y->csp->name);
-            return AVERROR(EINVAL);
-        }
-        switch (pixel_size) {
-        case 1:
-            format = channels == 1 ? MTLPixelFormatR8Unorm : 
MTLPixelFormatRG8Unorm;
-            break;
-        case 2:
-            format = channels == 1 ? MTLPixelFormatR16Unorm : 
MTLPixelFormatRG16Unorm;
-            break;
-        default:
-            av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n", 
y->csp->name);
-            return AVERROR(EINVAL);
-        }
-        av_log(ctx, AV_LOG_TRACE,
-               "Deinterlacing plane %d: pixel_size: %d channels: %d\n",
-               comp->plane, pixel_size, channels);
+            if (comp->plane < i) {
+                // We process planes as a whole, so don't reprocess
+                // them for additional components
+                continue;
+            }
 
-        prev = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)y->prev->data[3], i, format);
-        cur  = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)y->cur->data[3], i, format);
-        next = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)y->next->data[3], i, format);
-        dest = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)dst->data[3], i, format);
+            pixel_size = (comp->depth + comp->shift) / 8;
+            channels = comp->step / pixel_size;
+            if (pixel_size > 2 || channels > 2) {
+                av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n", 
y->csp->name);
+                ret = AVERROR(EINVAL);
+                break;
+            }
+            switch (pixel_size) {
+            case 1:
+                format = channels == 1 ? MTLPixelFormatR8Unorm : 
MTLPixelFormatRG8Unorm;
+                break;
+            case 2:
+                format = channels == 1 ? MTLPixelFormatR16Unorm : 
MTLPixelFormatRG16Unorm;
+                break;
+            default:
+                av_log(ctx, AV_LOG_ERROR, "Unsupported pixel format: %s\n", 
y->csp->name);
+                ret = AVERROR(EINVAL);
+                break;
+            }
+            if (ret < 0)
+                break;
+            av_log(ctx, AV_LOG_TRACE,
+                   "Deinterlacing plane %d: pixel_size: %d channels: %d\n",
+                   comp->plane, pixel_size, channels);
 
-        if (!prev || !cur || !next || !dest) {
-            av_log(ctx, AV_LOG_ERROR, "Failed to create Metal texture for 
plane %d\n", i);
-            if (prev) CFRelease(prev);
-            if (cur)  CFRelease(cur);
-            if (next) CFRelease(next);
-            if (dest) CFRelease(dest);
-            return AVERROR_EXTERNAL;
-        }
+            tex[0] = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)y->prev->data[3], i, format);
+            tex[1] = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)y->cur->data[3], i, format);
+            tex[2] = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)y->next->data[3], i, format);
+            tex[3] = ff_metal_texture_from_pixbuf(ctx, s->textureCache, 
(CVPixelBufferRef)dst->data[3], i, format);
+            nb_textures += 4;
 
-        tex_prev = CVMetalTextureGetTexture(prev);
-        tex_cur  = CVMetalTextureGetTexture(cur);
-        tex_next = CVMetalTextureGetTexture(next);
-        tex_dest = CVMetalTextureGetTexture(dest);
+            if (!tex[0] || !tex[1] || !tex[2] || !tex[3]) {
+                av_log(ctx, AV_LOG_ERROR, "Failed to create Metal texture for 
plane %d\n", i);
+                ret = AVERROR_EXTERNAL;
+                break;
+            }
 
-        call_kernel(ctx, tex_dest, tex_prev, tex_cur, tex_next,
+            encode_plane(ctx, encoder,
+                         CVMetalTextureGetTexture(tex[3]),
+                         CVMetalTextureGetTexture(tex[0]),
+                         CVMetalTextureGetTexture(tex[1]),
+                         CVMetalTextureGetTexture(tex[2]),
                          channels, parity, tff);
+        }
 
-        CFRelease(prev);
-        CFRelease(cur);
-        CFRelease(next);
-        CFRelease(dest);
+        [encoder endEncoding];
+        if (ret >= 0) {
+            [buffer commit];
+            [buffer waitUntilCompleted];
+            if (buffer.status == MTLCommandBufferStatusError) {
+                av_log(ctx, AV_LOG_ERROR, "Metal command buffer failed: %s\n",
+                       buffer.error.localizedDescription.UTF8String);
+                ret = AVERROR_EXTERNAL;
+            }
+        }
     }
 
+    for (int i = 0; i < nb_textures; i++) {
+        if (textures[i])
+            CFRelease(textures[i]);
+    }
+    if (ret < 0)
+        return ret;
+
     CVBufferPropagateAttachments((CVPixelBufferRef)y->cur->data[3], 
(CVPixelBufferRef)dst->data[3]);
 
     if (y->current_field == YADIF_FIELD_END) {
@@ -186,7 +201,6 @@ static av_cold void do_uninit(AVFilterContext *ctx) 
API_AVAILABLE(macos(10.11),
     av_buffer_unref(&s->input_frames_ref);
     s->input_frames = NULL;
 
-    ff_objc_release(&s->mtlParamsBuffer);
     ff_objc_release(&s->mtlFunction);
     ff_objc_release(&s->mtlPipeline);
     ff_objc_release(&s->mtlQueue);
@@ -254,14 +268,6 @@ static av_cold int do_init(AVFilterContext *ctx) 
API_AVAILABLE(macos(10.11), ios
         goto fail;
     }
 
-    s->mtlParamsBuffer = [s->mtlDevice
-        newBufferWithLength:sizeof(struct mtlYadifParams)
-        options:MTLResourceStorageModeShared];
-    if (!s->mtlParamsBuffer) {
-        av_log(ctx, AV_LOG_ERROR, "Failed to create Metal buffer for 
parameters\n");
-        goto fail;
-    }
-
     ret = CVMetalTextureCacheCreate(
         NULL,
         NULL,
-- 
2.54.1

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to