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

This adds frame threading to the VC-1 and WMV3 decoders (not the image/sprite 
decoders).

- Patch 1 adds the basic support: an update_thread_context callback, per-row 
progress reporting behind the loop filter, and waits on the referenced rows in 
all motion compensation paths, for skipped pictures and for B-frame direct mode.
- Patch 2 lets field B-pictures finish setup right after their header.
- Patch 3 lets field I/P pictures overlap as well: per-field progress, the 
field MV flags in a refcounted per-picture buffer, and setup finished after the 
second field header.

Testing:
- FATE passes with THREADS=1 and with THREADS=4 THREAD_TYPE=frame; the VC-1 
tests also pass repeatedly at 2, 8 and 16 threads.
- AddressSanitizer is clean on the VC-1 FATE samples and on randomly corrupted 
versions of them; no hangs with corrupted input. ThreadSanitizer was clean on 
the same code before the last rebase.
- A stress test with artificially stalled producer threads and poisoned frame 
buffers passes with the row margins used here and fails when they are reduced 
by one step.

Performance, 1080p progressive Advanced Profile (Blu-ray style), x86-64:

| Threads | Time | Speedup |
|---|---|---|
| 1 | 10.0 s | 1.0x |
| 4 | 3.62 s | 2.8x |
| 8 | 2.31 s | 4.3x |

Also tested in Kodi with software decoding on a Fire TV Stick 4K Max (4x 
Cortex-A55) and a Pixel 8 Pro. Without the patch, 1080p VC-1 stuttered on the 
Fire TV with one core fully loaded; with it, playback is smooth with the load 
spread over all four cores. (Observed with the per-core CPU display from 
https://github.com/xbmc/xbmc/pull/30596.)

Known limitations:
- With frame threads, output for damaged streams can differ from 
single-threaded decoding, as with the other frame-threaded decoders.
- Field-coded streams scale less: the next I/P picture can only start once the 
previous one starts its second field.
- Not tested with hwaccels. None of the FATE samples uses intensity 
compensation in field pictures; that path was tested with injected parameters 
only.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01WgE6y4SVchXBTWL3yw2uiB


From 504d4d9dfa1c9d898d0b0f0a306148d19857da58 Mon Sep 17 00:00:00 2001
From: isarrider <[email protected]>
Date: Tue, 17 Nov 2026 08:23:58 +0000
Subject: [PATCH 1/3] avcodec/vc1dec: add frame threading support

Decode VC-1 and WMV3 with frame threading:

- Set up the picture pool in init, so that the frame-thread copies
  share the pool of the first thread; the MpegEncContext itself is still
  initialized lazily on the first frame header.
- Add an update_thread_context callback that (re)initializes the
  size-dependent tables and copies the sequence/entry-point state, the
  persistent picture-level state (rounding control, MV range, RESPIC,
  REFDIST), the intensity compensation LUTs and the field MV flags of the
  last field-coded anchor.
- Finish setup right after the picture header, except for software
  decoded field pictures (decoded with doubled line sizes in the shared
  context; the second field header and the field MV flags can still
  change state used by subsequent pictures) and pictures whose slices
  repeat the picture header. Field-coded streams therefore get little
  parallelism for now.
- Report decoding progress per MB row for frame-coded reference
  pictures (trailing the loop filter), and wait for the referenced rows
  in all motion compensation paths, before copying rows of skipped
  pictures and before reading co-located motion for direct mode.
- Unblock waiting threads if a reference picture fails to decode.
- Wait for a picture decoded by another thread to be finished before
  outputting its frame, as error concealment sets decode_error_flags.

The image (sprite) decoders are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WgE6y4SVchXBTWL3yw2uiB
---
 libavcodec/vc1_block.c |  31 +++++++++
 libavcodec/vc1_mc.c    |  52 ++++++++++++++
 libavcodec/vc1dec.c    | 155 +++++++++++++++++++++++++++++++++++++++--
 3 files changed, 231 insertions(+), 7 deletions(-)

diff --git a/libavcodec/vc1_block.c b/libavcodec/vc1_block.c
index a84c853b6f1..4f508b9f1ff 100644
--- a/libavcodec/vc1_block.c
+++ b/libavcodec/vc1_block.c
@@ -31,6 +31,7 @@
 #include "mpegvideo.h"
 #include "mpegvideodec.h"
 #include "msmpeg4_vc1_data.h"
+#include "threadprogress.h"
 #include "unary.h"
 #include "vc1.h"
 #include "vc1_pred.h"
@@ -74,6 +75,25 @@ static inline void update_block_index(MpegEncContext *s)
 
 /** @} */ //Bitplane group
 
+/**
+ * Report the MB rows of a frame-coded reference picture that are final.
+ *
+ * Called once MB row s->mb_y is decoded. The loop filters trail the decoding
+ * loop by two MB rows (see ff_vc1_i_loop_filter(), ff_vc1_p_loop_filter()
+ * and ff_vc1_p_intfr_loop_filter()): while row y is decoded, the last edges
+ * touching row y - 2 are filtered, and no later row modifies it anymore.
+ * Overlap smoothing and the delayed pixel output trail by one row only.
+ * Field pictures are only reported as a whole by ff_mpv_frame_end().
+ */
+static void vc1_report_decode_progress(VC1Context *v)
+{
+    MpegEncContext *s = &v->s;
+
+    if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME) &&
+        s->cur_pic.reference && !v->field_mode && !s->er.error_occurred)
+        ff_thread_progress_report(&s->cur_pic.ptr->progress, s->mb_y - 2);
+}
+
 static void vc1_put_blocks_clamped(VC1Context *v, int put_signed)
 {
     MpegEncContext *s = &v->s;
@@ -2606,6 +2626,7 @@ static void vc1_decode_i_blocks(VC1Context *v)
             v->cur_blk_idx = (v->cur_blk_idx + 1) % (v->end_mb_x + 2);
         }
 
+        vc1_report_decode_progress(v);
         s->first_slice_line = 0;
     }
 
@@ -2739,6 +2760,7 @@ static int vc1_decode_i_blocks_adv(VC1Context *v)
             inc_blk_idx(v->left_blk_idx);
             inc_blk_idx(v->cur_blk_idx);
         }
+        vc1_report_decode_progress(v);
         s->first_slice_line = 0;
     }
 
@@ -2830,6 +2852,7 @@ static void vc1_decode_p_blocks(VC1Context *v)
         memmove(v->luma_mv_base,
                 v->luma_mv - s->mb_stride,
                 sizeof(v->luma_mv_base[0]) * 2 * s->mb_stride);
+        vc1_report_decode_progress(v);
         s->first_slice_line = 0;
     }
     ff_er_add_slice(&s->er, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
@@ -2869,6 +2892,11 @@ static void vc1_decode_b_blocks(VC1Context *v)
     for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
         s->mb_x = 0;
         init_block_index(v);
+        /* direct mode reads the co-located motion of the next anchor */
+        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME) &&
+            s->next_pic.ptr)
+            ff_thread_progress_await(&s->next_pic.ptr->progress,
+                                     s->mb_y + v->mb_off / s->mb_stride);
         for (; s->mb_x < s->mb_width; s->mb_x++) {
             update_block_index(s);
 
@@ -2927,9 +2955,12 @@ static void vc1_decode_skip_blocks(VC1Context *v)
         s->mb_x = 0;
         init_block_index(v);
         update_block_index(s);
+        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
+            ff_thread_progress_await(&s->last_pic.ptr->progress, s->mb_y);
         memcpy(s->dest[0], s->last_pic.data[0] + s->mb_y * 16 * s->linesize,   
s->linesize   * 16);
         memcpy(s->dest[1], s->last_pic.data[1] + s->mb_y *  8 * s->uvlinesize, 
s->uvlinesize *  8);
         memcpy(s->dest[2], s->last_pic.data[2] + s->mb_y *  8 * s->uvlinesize, 
s->uvlinesize *  8);
+        vc1_report_decode_progress(v);
         s->first_slice_line = 0;
     }
 }
diff --git a/libavcodec/vc1_mc.c b/libavcodec/vc1_mc.c
index db19d95ef93..9bdbeb8ab8e 100644
--- a/libavcodec/vc1_mc.c
+++ b/libavcodec/vc1_mc.c
@@ -30,8 +30,38 @@
 #include "h264chroma.h"
 #include "mathops.h"
 #include "mpegvideo.h"
+#include "threadprogress.h"
 #include "vc1.h"
 
+/**
+ * With frame threading, wait until the rows of the reference picture a
+ * block can read from have been decoded.
+ *
+ * @param ref   reference picture, NULL if it is the current picture
+ * @param src_y first luma line of the referenced block (chroma lines
+ *              doubled), in lines of the current frame or field
+ */
+static av_always_inline void vc1_await_ref(const VC1Context *v,
+                                           const MPVWorkPicture *ref,
+                                           int src_y)
+{
+    const MpegEncContext *s = &v->s;
+
+    if (HAVE_THREADS && ref && ref->ptr &&
+        (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
+        /* Last line read below src_y, in the units of src_y:
+         *   16x16 luma, bicubic:          src_y - 1 + 18     = src_y + 17
+         *   8x8 chroma, bilinear:      2 * (uvsrc_y + 8) + 1 = src_y + 17
+         *   8x8 luma of a field MV in an interlaced frame,
+         *   every other line:             src_y - 2 + 2 * 10 = src_y + 18
+         * In field pictures, line n of the bottom field is line 2 * n + 1
+         * of the frame, which the shift below covers as 18 > 17. */
+        int y = FFMAX(src_y + 18, 0) << v->field_mode;
+
+        ff_thread_progress_await(&ref->ptr->progress, y >> 4);
+    }
+}
+
 static av_always_inline void vc1_scale_luma(uint8_t *srcY,
                                             int k, int linesize)
 {
@@ -178,6 +208,7 @@ void ff_vc1_mc_1mv(VC1Context *v, int dir)
     int v_edge_pos = s->v_edge_pos >> v->field_mode;
     int i;
     const uint8_t (*luty)[256], (*lutuv)[256];
+    const MPVWorkPicture *ref;
     int use_ic;
     int interlace;
     int linesize, uvlinesize;
@@ -226,6 +257,7 @@ void ff_vc1_mc_1mv(VC1Context *v, int dir)
             lutuv = v->curr_lutuv;
             use_ic = *v->curr_use_ic;
             interlace = 1;
+            ref = NULL;
         } else {
             srcY = s->last_pic.data[0];
             srcU = s->last_pic.data[1];
@@ -234,6 +266,7 @@ void ff_vc1_mc_1mv(VC1Context *v, int dir)
             lutuv = v->last_lutuv;
             use_ic = v->last_use_ic;
             interlace = v->last_interlaced;
+            ref = &s->last_pic;
         }
     } else {
         srcY = s->next_pic.data[0];
@@ -243,6 +276,7 @@ void ff_vc1_mc_1mv(VC1Context *v, int dir)
         lutuv = v->next_lutuv;
         use_ic = v->next_use_ic;
         interlace = v->next_interlaced;
+        ref = &s->next_pic;
     }
 
     if (!srcY || !srcU) {
@@ -272,6 +306,8 @@ void ff_vc1_mc_1mv(VC1Context *v, int dir)
         }
     }
 
+    vc1_await_ref(v, ref, FFMAX(src_y, 2 * uvsrc_y));
+
     srcY += src_y   * s->linesize   + src_x;
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
     srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
@@ -458,6 +494,7 @@ void ff_vc1_mc_4mv_luma(VC1Context *v, int n, int dir, int 
avg)
     int fieldmv = (v->fcm == ILACE_FRAME) ? v->blk_mv_type[s->block_index[n]] 
: 0;
     int v_edge_pos = s->v_edge_pos >> v->field_mode;
     const uint8_t (*luty)[256];
+    const MPVWorkPicture *ref;
     int use_ic;
     int interlace;
     int linesize;
@@ -478,17 +515,20 @@ void ff_vc1_mc_4mv_luma(VC1Context *v, int n, int dir, 
int avg)
             luty = v->curr_luty;
             use_ic = *v->curr_use_ic;
             interlace = 1;
+            ref = NULL;
         } else {
             srcY = s->last_pic.data[0];
             luty = v->last_luty;
             use_ic = v->last_use_ic;
             interlace = v->last_interlaced;
+            ref = &s->last_pic;
         }
     } else {
         srcY = s->next_pic.data[0];
         luty = v->next_luty;
         use_ic = v->next_use_ic;
         interlace = v->next_interlaced;
+        ref = &s->next_pic;
     }
 
     if (!srcY) {
@@ -553,6 +593,8 @@ void ff_vc1_mc_4mv_luma(VC1Context *v, int n, int dir, int 
avg)
             src_y = av_clip(src_y, -18, s->avctx->coded_height + 1);
     }
 
+    vc1_await_ref(v, ref, src_y);
+
     srcY += src_y * s->linesize + src_x;
     if (v->field_mode && v->ref_field_type[dir])
         srcY += linesize;
@@ -641,6 +683,7 @@ void ff_vc1_mc_4mv_chroma(VC1Context *v, int dir)
     int chroma_ref_type;
     int v_edge_pos = s->v_edge_pos >> v->field_mode;
     const uint8_t (*lutuv)[256];
+    const MPVWorkPicture *ref;
     int use_ic;
     int interlace;
     int uvlinesize;
@@ -703,12 +746,14 @@ void ff_vc1_mc_4mv_chroma(VC1Context *v, int dir)
             lutuv = v->curr_lutuv;
             use_ic = *v->curr_use_ic;
             interlace = 1;
+            ref = NULL;
         } else {
             srcU = s->last_pic.data[1];
             srcV = s->last_pic.data[2];
             lutuv = v->last_lutuv;
             use_ic = v->last_use_ic;
             interlace = v->last_interlaced;
+            ref = &s->last_pic;
         }
     } else {
         srcU = s->next_pic.data[1];
@@ -716,6 +761,7 @@ void ff_vc1_mc_4mv_chroma(VC1Context *v, int dir)
         lutuv = v->next_lutuv;
         use_ic = v->next_use_ic;
         interlace = v->next_interlaced;
+        ref = &s->next_pic;
     }
 
     if (!srcU) {
@@ -723,6 +769,8 @@ void ff_vc1_mc_4mv_chroma(VC1Context *v, int dir)
         return;
     }
 
+    vc1_await_ref(v, ref, 2 * uvsrc_y);
+
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
     srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
 
@@ -885,12 +933,14 @@ void ff_vc1_mc_4mv_chroma4(VC1Context *v, int dir, int 
dir2, int avg)
             lutuv  = v->next_lutuv;
             use_ic = v->next_use_ic;
             interlace = v->next_interlaced;
+            vc1_await_ref(v, &s->next_pic, 2 * uvsrc_y);
         } else {
             srcU = s->last_pic.data[1];
             srcV = s->last_pic.data[2];
             lutuv  = v->last_lutuv;
             use_ic = v->last_use_ic;
             interlace = v->last_interlaced;
+            vc1_await_ref(v, &s->last_pic, 2 * uvsrc_y);
         }
         if (!srcU)
             return;
@@ -1056,6 +1106,8 @@ void ff_vc1_interp_mc(VC1Context *v)
         }
     }
 
+    vc1_await_ref(v, &s->next_pic, FFMAX(src_y, 2 * uvsrc_y));
+
     srcY += src_y   * s->linesize   + src_x;
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
     srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index a4d465dd0b3..729088cc8e8 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -42,6 +42,8 @@
 #include "msmpeg4_vc1_data.h"
 #include "profiles.h"
 #include "simple_idct.h"
+#include "thread.h"
+#include "threadprogress.h"
 #include "vc1.h"
 #include "vc1data.h"
 #include "vc1_vlc_data.h"
@@ -356,6 +358,14 @@ static av_cold void vc1_sprite_flush(AVCodecContext *avctx)
 
 #endif
 
+/** Size of one of the two planes of v->mv_f / v->mv_f_next. */
+static size_t vc1_mv_f_plane_size(const MpegEncContext *s)
+{
+    int mb_height = FFALIGN(s->mb_height, 2);
+
+    return s->b8_stride * (mb_height * 2 + 1) + s->mb_stride * (mb_height + 1) 
* 2;
+}
+
 static av_cold int vc1_decode_init_alloc_tables(VC1Context *v)
 {
     MpegEncContext *s = &v->s;
@@ -403,16 +413,16 @@ static av_cold int 
vc1_decode_init_alloc_tables(VC1Context *v)
     if (!v->blk_mv_type_base)
         return AVERROR(ENOMEM);
     v->blk_mv_type      = v->blk_mv_type_base + s->b8_stride + 1;
-    v->mv_f_base        = av_mallocz(2 * (s->b8_stride * (mb_height * 2 + 1) + 
s->mb_stride * (mb_height + 1) * 2));
+    v->mv_f_base        = av_mallocz(2 * vc1_mv_f_plane_size(s));
     if (!v->mv_f_base)
         return AVERROR(ENOMEM);
     v->mv_f[0]          = v->mv_f_base + s->b8_stride + 1;
-    v->mv_f[1]          = v->mv_f[0] + (s->b8_stride * (mb_height * 2 + 1) + 
s->mb_stride * (mb_height + 1) * 2);
-    v->mv_f_next_base   = av_mallocz(2 * (s->b8_stride * (mb_height * 2 + 1) + 
s->mb_stride * (mb_height + 1) * 2));
+    v->mv_f[1]          = v->mv_f[0] + vc1_mv_f_plane_size(s);
+    v->mv_f_next_base   = av_mallocz(2 * vc1_mv_f_plane_size(s));
     if (!v->mv_f_next_base)
         return AVERROR(ENOMEM);
     v->mv_f_next[0]     = v->mv_f_next_base + s->b8_stride + 1;
-    v->mv_f_next[1]     = v->mv_f_next[0] + (s->b8_stride * (mb_height * 2 + 
1) + s->mb_stride * (mb_height + 1) * 2);
+    v->mv_f_next[1]     = v->mv_f_next[0] + vc1_mv_f_plane_size(s);
 
     if (s->avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || s->avctx->codec_id == 
AV_CODEC_ID_VC1IMAGE) {
         for (i = 0; i < 4; i++)
@@ -731,7 +741,12 @@ static av_cold int vc1_decode_init(AVCodecContext *avctx)
             return AVERROR_PATCHWELCOME;
         }
     }
-    return 0;
+
+    /* The MpegEncContext is only fully initialized once the first frame
+     * header has been parsed, but the picture pool has to be set up here:
+     * with frame threading, all threads share the pool of the first one,
+     * which can only be synced during init. */
+    return ff_mpv_decode_init(s, avctx);
 }
 
 static av_cold void vc1_decode_reset(AVCodecContext *avctx)
@@ -772,6 +787,102 @@ av_cold int ff_vc1_decode_end(AVCodecContext *avctx)
     return ff_mpv_decode_close(avctx);
 }
 
+#if HAVE_THREADS
+/* point dst's field at the same member that src's field points to */
+#define REMAP_PTR(field, a, b, c)                                         \
+    v->field = v1->field == &v1->a ? &v->a :                              \
+               v1->field == &v1->b ? &v->b :                              \
+               v1->field == &v1->c ? &v->c : NULL
+
+static int vc1_update_thread_context(AVCodecContext *dst,
+                                     const AVCodecContext *src)
+{
+    VC1Context       *const v  = dst->priv_data;
+    const VC1Context *const v1 = src->priv_data;
+    MpegEncContext       *const s  = &v->s;
+    const MpegEncContext *const s1 = &v1->s;
+    int ret;
+
+    if (dst == src || !s1->context_initialized)
+        return 0;
+
+    /* The size-dependent VC-1 tables are allocated together with the
+     * MpegEncContext, so (re)initialize everything here instead of letting
+     * ff_mpeg_update_thread_context() resize only the latter. */
+    if (s->context_initialized &&
+        (s->width != s1->width || s->height != s1->height))
+        vc1_decode_reset(dst);
+    if (!s->context_initialized) {
+        ret = ff_vc1_decode_init(dst);
+        if (ret < 0)
+            return ret;
+    }
+
+    ret = ff_mpeg_update_thread_context(dst, src);
+    if (ret < 0)
+        return ret;
+
+    s->h_edge_pos = s1->h_edge_pos;
+    s->v_edge_pos = s1->v_edge_pos;
+    s->mspel      = s1->mspel;
+
+    /* sequence header and entry point */
+    memcpy(&v->res_sprite, &v1->res_sprite,
+           (const char *)&v1->finterpflag + sizeof(v1->finterpflag) -
+           (const char *)&v1->res_sprite);
+    v->zz_8x4           = v1->zz_8x4;
+    v->zz_4x8           = v1->zz_4x8;
+    v->range_mapy_flag  = v1->range_mapy_flag;
+    v->range_mapuv_flag = v1->range_mapuv_flag;
+    v->range_mapy       = v1->range_mapy;
+    v->range_mapuv      = v1->range_mapuv;
+    v->broken_link      = v1->broken_link;
+    v->closed_entry     = v1->closed_entry;
+    v->resync_marker    = v1->resync_marker;
+
+    /* picture-level state that carries over to following pictures */
+    v->rnd      = v1->rnd;
+    v->mvrange  = v1->mvrange;
+    v->respic   = v1->respic;
+    v->refdist  = v1->refdist;
+
+    /* intensity compensation of the reference pictures */
+    memcpy(v->last_luty,  v1->last_luty,  sizeof(v->last_luty));
+    memcpy(v->last_lutuv, v1->last_lutuv, sizeof(v->last_lutuv));
+    memcpy(v->next_luty,  v1->next_luty,  sizeof(v->next_luty));
+    memcpy(v->next_lutuv, v1->next_lutuv, sizeof(v->next_lutuv));
+    memcpy(v->aux_luty,   v1->aux_luty,   sizeof(v->aux_luty));
+    memcpy(v->aux_lutuv,  v1->aux_lutuv,  sizeof(v->aux_lutuv));
+    v->last_use_ic = v1->last_use_ic;
+    v->next_use_ic = v1->next_use_ic;
+    v->aux_use_ic  = v1->aux_use_ic;
+    REMAP_PTR(curr_luty,   last_luty[0],  next_luty[0],  aux_luty[0]);
+    REMAP_PTR(curr_lutuv,  last_lutuv[0], next_lutuv[0], aux_lutuv[0]);
+    REMAP_PTR(curr_use_ic, last_use_ic,   next_use_ic,   aux_use_ic);
+
+    /* Field MV flags of the last field-coded anchor, used by direct-mode
+     * prediction in field B-pictures. The source thread does not call
+     * ff_thread_finish_setup() before it has swapped them in place. */
+    memcpy(v->mv_f_next[0]  - (s->b8_stride  + 1),
+           v1->mv_f_next[0] - (s1->b8_stride + 1),
+           2 * vc1_mv_f_plane_size(s));
+
+    return 0;
+}
+#undef REMAP_PTR
+#endif
+
+/**
+ * With frame threading, wait until another thread has finished decoding a
+ * picture, so that the properties of its frame are final before the frame
+ * is output. The frame threading code only guarantees that for the data.
+ */
+static void vc1_await_picture(const AVCodecContext *avctx, const MPVPicture 
*pic)
+{
+    if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_FRAME))
+        ff_thread_progress_await(&pic->progress, INT_MAX);
+}
+
 /** Decode a VC1/WMV3 frame
  * @todo TODO: Handle VC-1 IDUs (Transport level?)
  */
@@ -793,6 +904,7 @@ static int vc1_decode_frame(AVCodecContext *avctx, AVFrame 
*pict,
         int raw_size;
     } *slices = NULL, *tmp;
     unsigned slices_allocated = 0;
+    int frame_started = 0, late_setup;
 
     v->second_field = 0;
 
@@ -806,6 +918,7 @@ static int vc1_decode_frame(AVCodecContext *avctx, AVFrame 
*pict,
     if (buf_size == 0) {
         /* special case for last picture */
         if (s->low_delay == 0 && s->next_pic.ptr) {
+            vc1_await_picture(avctx, s->next_pic.ptr);
             if ((ret = av_frame_ref(pict, s->next_pic.ptr->f)) < 0)
                 return ret;
             ff_mpv_unref_picture(&s->next_pic);
@@ -1041,6 +1154,7 @@ static int vc1_decode_frame(AVCodecContext *avctx, 
AVFrame *pict,
     if ((ret = ff_mpv_frame_start(s, avctx)) < 0) {
         goto err;
     }
+    frame_started = 1;
 
     v->s.cur_pic.ptr->field_picture = v->field_mode;
     v->s.cur_pic.ptr->f->flags |= AV_FRAME_FLAG_INTERLACED * (v->fcm != 
PROGRESSIVE);
@@ -1059,6 +1173,24 @@ static int vc1_decode_frame(AVCodecContext *avctx, 
AVFrame *pict,
         s->cur_pic.ptr->f->repeat_pict = v->rptfrm * 2;
     }
 
+    /* Everything later pictures depend on is known at this point, unless
+     * the software decoding below can still change it, in which case setup
+     * is finished after decoding:
+     * - field pictures are decoded with s->linesize and the work picture
+     *   line sizes doubled, which must not be copied to other threads;
+     *   also, the second field header of I/P pictures can update the
+     *   intensity compensation state, and the field MV flags needed by
+     *   subsequent field B-pictures are final only once both fields are
+     *   decoded
+     * - slices can repeat the picture header
+     * Hardware decoding does not use any of that, and requires setup to be
+     * finished before the hwaccel is called. */
+    late_setup = v->field_mode;
+    for (i = 0; i < n_slices && !late_setup; i++)
+        late_setup = show_bits1(&slices[i].gb);
+    if (avctx->hwaccel || !late_setup)
+        ff_thread_finish_setup(avctx);
+
     if (avctx->hwaccel) {
         const FFHWAccel *hwaccel = ffhwaccel(avctx->hwaccel);
         s->mb_y = 0;
@@ -1341,6 +1473,7 @@ image:
             ff_print_debug_info(s, s->cur_pic.ptr, pict);
             *got_frame = 1;
         } else if (s->last_pic.ptr) {
+            vc1_await_picture(avctx, s->last_pic.ptr);
             if ((ret = av_frame_ref(pict, s->last_pic.ptr->f)) < 0)
                 goto err;
             ff_print_debug_info(s, s->last_pic.ptr, pict);
@@ -1351,6 +1484,10 @@ image:
 end:
     ret = buf_size;
 err:
+    /* Unblock threads using this picture as reference if decoding stopped
+     * before ff_mpv_frame_end(). */
+    if (ret < 0 && frame_started)
+        ff_thread_progress_report(&s->cur_pic.ptr->progress, INT_MAX);
     av_free(buf2);
     for (i = 0; i < n_slices; i++)
         av_free(slices[i].buf);
@@ -1368,8 +1505,10 @@ const FFCodec ff_vc1_decoder = {
     .init           = vc1_decode_init,
     .close          = ff_vc1_decode_end,
     FF_CODEC_DECODE_CB(vc1_decode_frame),
+    UPDATE_THREAD_CONTEXT(vc1_update_thread_context),
     .flush          = ff_mpeg_flush,
-    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
+    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
+                      AV_CODEC_CAP_FRAME_THREADS,
     .hw_configs     = (const AVCodecHWConfigInternal *const []) {
 #if CONFIG_VC1_DXVA2_HWACCEL
                         HWACCEL_DXVA2(vc1),
@@ -1410,8 +1549,10 @@ const FFCodec ff_wmv3_decoder = {
     .init           = vc1_decode_init,
     .close          = ff_vc1_decode_end,
     FF_CODEC_DECODE_CB(vc1_decode_frame),
+    UPDATE_THREAD_CONTEXT(vc1_update_thread_context),
     .flush          = ff_mpeg_flush,
-    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
+    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
+                      AV_CODEC_CAP_FRAME_THREADS,
     .hw_configs     = (const AVCodecHWConfigInternal *const []) {
 #if CONFIG_WMV3_DXVA2_HWACCEL
                         HWACCEL_DXVA2(wmv3),
-- 
2.54.0


From 9f46c836961992b608c512ad90ce96108eee41f8 Mon Sep 17 00:00:00 2001
From: isarrider <[email protected]>
Date: Tue, 17 Nov 2026 08:26:31 +0000
Subject: [PATCH 2/3] avcodec/vc1dec: finish frame thread setup early for field
 B-pictures

Field pictures are decoded with s->linesize, s->uvlinesize and the line
sizes of the current work picture doubled in place, and their second
field header rewrites quarter_sample and MVRANGE. With
ff_mpeg_update_thread_context(), the next thread could copy any of that
mid-decode, so the previous commit had every field picture finish setup
only after decoding, leaving interlaced field-coded streams nearly
serial.

Sync the reference pictures from their MPVPicture pointers, which do not
change during decoding, instead of copying the work pictures and line
sizes, and stop copying state that every picture header sets again
(quarter_sample, mspel, and MVRANGE in Advanced profile). Field
B-pictures then no longer modify anything vc1_update_thread_context()
reads after their picture header, and can finish setup right after it.
Field I/P pictures still finish setup after decoding: their second field
header can update the intensity compensation state, and their field MV
flags are swapped in only at the end.

Also document the frame threading design at the top of vc1dec.c.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WgE6y4SVchXBTWL3yw2uiB
---
 libavcodec/vc1dec.c | 128 ++++++++++++++++++++++++++++++++------------
 1 file changed, 94 insertions(+), 34 deletions(-)

diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index 729088cc8e8..8548e8ac27c 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -24,6 +24,32 @@
 /**
  * @file
  * VC-1 and WMV3 decoder
+ *
+ * Frame threading
+ *
+ * The vc1 and wmv3 decoders support frame threading; the image (sprite)
+ * decoders do not. Each thread has its own VC1Context and decodes whole
+ * pictures, and a picture can be decoded while the pictures it references
+ * are still being decoded by other threads:
+ *
+ * - Before a thread decodes a picture, vc1_update_thread_context() copies
+ *   the state its headers build on from the thread that decoded the
+ *   previous one: sequence and entry point parameters, the reference
+ *   pictures, intensity compensation and the field MV flags of the last
+ *   field-coded anchor. This happens once the previous thread has called
+ *   ff_thread_finish_setup(), which vc1_decode_frame() does as early as
+ *   possible: right after the picture header for most pictures, after
+ *   decoding for those whose later headers can still change that state.
+ *
+ * - Reference pictures report their progress in MB rows of the frame as
+ *   they are decoded, trailing the overlap and loop filters (see
+ *   vc1_report_decode_progress() in vc1_block.c). Field-coded pictures are
+ *   only reported as a whole, by ff_mpv_frame_end().
+ *
+ * - Before a block is predicted from a reference picture, the decoding
+ *   thread waits until the rows it reads are available (vc1_await_ref() in
+ *   vc1_mc.c). The same applies to the rows copied for skipped pictures and
+ *   to the co-located motion read by B-picture direct mode (vc1_block.c).
  */
 
 #include "config_components.h"
@@ -788,12 +814,21 @@ av_cold int ff_vc1_decode_end(AVCodecContext *avctx)
 }
 
 #if HAVE_THREADS
-/* point dst's field at the same member that src's field points to */
+/* Point v->field at the member of v that v1->field points to in v1. */
 #define REMAP_PTR(field, a, b, c)                                         \
     v->field = v1->field == &v1->a ? &v->a :                              \
                v1->field == &v1->b ? &v->b :                              \
                v1->field == &v1->c ? &v->c : NULL
 
+/**
+ * Bring the context of the thread about to decode the next picture (dst) up
+ * to date with the thread that decoded the previous one (src).
+ *
+ * This is called once src has finished setup (see the comment before
+ * ff_thread_finish_setup() in vc1_decode_frame()), while src may still be
+ * decoding its picture. Only state that src no longer modifies at that point
+ * may be read here.
+ */
 static int vc1_update_thread_context(AVCodecContext *dst,
                                      const AVCodecContext *src)
 {
@@ -807,8 +842,8 @@ static int vc1_update_thread_context(AVCodecContext *dst,
         return 0;
 
     /* The size-dependent VC-1 tables are allocated together with the
-     * MpegEncContext, so (re)initialize everything here instead of letting
-     * ff_mpeg_update_thread_context() resize only the latter. */
+     * MpegEncContext, so (re)initialize both when the picture size changed
+     * or dst has not decoded anything yet. */
     if (s->context_initialized &&
         (s->width != s1->width || s->height != s1->height))
         vc1_decode_reset(dst);
@@ -818,15 +853,24 @@ static int vc1_update_thread_context(AVCodecContext *dst,
             return ret;
     }
 
-    ret = ff_mpeg_update_thread_context(dst, src);
-    if (ret < 0)
-        return ret;
+    /* Reference pictures. ff_mpeg_update_thread_context() is not used: it
+     * copies the work pictures and line sizes as they are in src, but field
+     * pictures are decoded with those doubled in place (see the software
+     * decoding path in vc1_decode_frame()), possibly at this very moment.
+     * The MPVPicture pointers stay the same throughout decoding, so derive
+     * the work pictures from them instead. The line sizes are set up by
+     * ff_mpv_frame_start() in dst itself; quarter_sample and mspel are set
+     * by every picture header that needs them. */
+    ff_mpv_workpic_from_pic(&s->cur_pic,  s1->cur_pic.ptr);
+    ff_mpv_workpic_from_pic(&s->last_pic, s1->last_pic.ptr);
+    ff_mpv_workpic_from_pic(&s->next_pic, s1->next_pic.ptr);
+    s->low_delay       = s1->low_delay;
+    s->workaround_bugs = s1->workaround_bugs;
+    s->h_edge_pos      = s1->h_edge_pos;
+    s->v_edge_pos      = s1->v_edge_pos;
 
-    s->h_edge_pos = s1->h_edge_pos;
-    s->v_edge_pos = s1->v_edge_pos;
-    s->mspel      = s1->mspel;
-
-    /* sequence header and entry point */
+    /* Sequence header and entry point; in-band entry points can change these
+     * between pictures. The first block is a run of plain ints. */
     memcpy(&v->res_sprite, &v1->res_sprite,
            (const char *)&v1->finterpflag + sizeof(v1->finterpflag) -
            (const char *)&v1->res_sprite);
@@ -840,13 +884,21 @@ static int vc1_update_thread_context(AVCodecContext *dst,
     v->closed_entry     = v1->closed_entry;
     v->resync_marker    = v1->resync_marker;
 
-    /* picture-level state that carries over to following pictures */
-    v->rnd      = v1->rnd;
-    v->mvrange  = v1->mvrange;
-    v->respic   = v1->respic;
-    v->refdist  = v1->refdist;
+    /* Picture header state that the next header builds on instead of
+     * re-reading it: in Simple/Main profile, P-pictures toggle the rounding
+     * control, B-pictures inherit RESPIC, and MVRANGE is kept unless the
+     * header signals it. Field B-pictures, which finish setup early, can
+     * rewrite MVRANGE in their second field header, but they never use the
+     * Simple/Main syntax. REFDIST carries over to field B-pictures. */
+    v->rnd     = v1->rnd;
+    v->respic  = v1->respic;
+    v->refdist = v1->refdist;
+    if (v1->profile != PROFILE_ADVANCED)
+        v->mvrange = v1->mvrange;
 
-    /* intensity compensation of the reference pictures */
+    /* Intensity compensation of the reference pictures. The LUTs and flags
+     * are rotated along with the references when a picture header is
+     * parsed, and the current ones are pointed to by curr_*. */
     memcpy(v->last_luty,  v1->last_luty,  sizeof(v->last_luty));
     memcpy(v->last_lutuv, v1->last_lutuv, sizeof(v->last_lutuv));
     memcpy(v->next_luty,  v1->next_luty,  sizeof(v->next_luty));
@@ -860,9 +912,10 @@ static int vc1_update_thread_context(AVCodecContext *dst,
     REMAP_PTR(curr_lutuv,  last_lutuv[0], next_lutuv[0], aux_lutuv[0]);
     REMAP_PTR(curr_use_ic, last_use_ic,   next_use_ic,   aux_use_ic);
 
-    /* Field MV flags of the last field-coded anchor, used by direct-mode
-     * prediction in field B-pictures. The source thread does not call
-     * ff_thread_finish_setup() before it has swapped them in place. */
+    /* Field MV flags of the last field-coded anchor, read by direct-mode
+     * prediction in field B-pictures. Anchors swap them in place only after
+     * decoding, and do not finish setup before that. B-pictures only read
+     * them. */
     memcpy(v->mv_f_next[0]  - (s->b8_stride  + 1),
            v1->mv_f_next[0] - (s1->b8_stride + 1),
            2 * vc1_mv_f_plane_size(s));
@@ -1173,21 +1226,28 @@ static int vc1_decode_frame(AVCodecContext *avctx, 
AVFrame *pict,
         s->cur_pic.ptr->f->repeat_pict = v->rptfrm * 2;
     }
 
-    /* Everything later pictures depend on is known at this point, unless
-     * the software decoding below can still change it, in which case setup
-     * is finished after decoding:
-     * - field pictures are decoded with s->linesize and the work picture
-     *   line sizes doubled, which must not be copied to other threads;
-     *   also, the second field header of I/P pictures can update the
-     *   intensity compensation state, and the field MV flags needed by
-     *   subsequent field B-pictures are final only once both fields are
-     *   decoded
-     * - slices can repeat the picture header
-     * Hardware decoding does not use any of that, and requires setup to be
+    /* Frame threading: let the next picture start decoding in another
+     * thread as soon as everything it depends on is known. That is the case
+     * now, except when the software decoding below can still change it:
+     * - The header of the second field of an I/P field picture can update
+     *   the intensity compensation state, and the field MV flags that
+     *   subsequent field B-pictures predict from are swapped into
+     *   v->mv_f_next only once both fields are decoded.
+     * - Slices can repeat the picture header.
+     * Setup is then finished by the generic code once decoding returns.
+     * Field B-pictures do not have this problem; what their second field
+     * header changes is not used by later pictures (see
+     * vc1_update_thread_context()).
+     * Hardware decoding uses none of this state, and requires setup to be
      * finished before the hwaccel is called. */
-    late_setup = v->field_mode;
-    for (i = 0; i < n_slices && !late_setup; i++)
-        late_setup = show_bits1(&slices[i].gb);
+    late_setup = v->field_mode && s->pict_type != AV_PICTURE_TYPE_B;
+    for (i = 0; i < n_slices && !late_setup; i++) {
+        /* the first bit after a slice address is the PIC_HEADER_FLAG; field
+         * markers carry a second field header instead, but then late_setup
+         * is either already set or the picture is a B-picture */
+        if (!(v->field_mode && i == n_slices1 + 1))
+            late_setup = show_bits1(&slices[i].gb);
+    }
     if (avctx->hwaccel || !late_setup)
         ff_thread_finish_setup(avctx);
 
-- 
2.54.0


From 52dcc621ffefbbec5d93d332ca1c39215601819b Mon Sep 17 00:00:00 2001
From: isarrider <[email protected]>
Date: Tue, 17 Nov 2026 08:27:33 +0000
Subject: [PATCH 3/3] avcodec/vc1dec: let field I/P pictures overlap with frame
 threading

Field-coded I/P pictures finished setup only once they were completely
decoded, and reported their progress only as a whole, so that streams
coded as field pictures were decoded nearly serially. Remove what
required that:

- Report the progress of field pictures per MB row, too: the rows of the
  first field, followed by those of the second field. Wait for the row
  in the field that is actually read, for field pictures referencing
  frame pictures and vice versa as well (ff_vc1_ref_progress()).
- Keep the field MV flags of a field I/P picture in a buffer of its own,
  shared by reference with the threads decoding the following field
  B-pictures, instead of in a per-thread buffer that is swapped in after
  decoding and then copied. Such a buffer starts out zeroed instead of
  with the flags of older pictures; the flags of a picture are only read
  for blocks it has written them for.
- Finish setup of field I/P pictures once the header of their second
  field is parsed. Only that header can still change what the following
  pictures inherit, namely the intensity compensation of the reference
  fields.

The next I/P picture can now start when the second field of the
previous one does, and the B-pictures in between overlap with both.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WgE6y4SVchXBTWL3yw2uiB
---
 libavcodec/vc1.h       |  42 ++++++++++++++
 libavcodec/vc1_block.c |  22 ++++++--
 libavcodec/vc1_mc.c    |  30 +++++-----
 libavcodec/vc1dec.c    | 125 ++++++++++++++++++++++++++++-------------
 4 files changed, 160 insertions(+), 59 deletions(-)

diff --git a/libavcodec/vc1.h b/libavcodec/vc1.h
index 006cefd58e2..07df336b7a5 100644
--- a/libavcodec/vc1.h
+++ b/libavcodec/vc1.h
@@ -31,6 +31,7 @@
 #include "vc1_common.h"
 #include "vc1dsp.h"
 
+#include "libavutil/frame.h"
 #include "libavutil/mem_internal.h"
 
 #define AC_VLC_BITS 9
@@ -353,6 +354,12 @@ typedef struct VC1Context{
     uint8_t *blk_mv_type_base, *blk_mv_type;    ///< 0: frame MV, 1: field MV 
(interlaced frame)
     uint8_t *mv_f_base, *mv_f[2];               ///< 0: MV obtained from same 
field, 1: opposite field
     uint8_t *mv_f_next_base, *mv_f_next[2];
+    /**
+     * RefStruct reference: mv_f of the last field-coded I/P picture. That
+     * picture writes it through mv_f while it is decoded, field B-pictures
+     * read it through mv_f_next. NULL until there has been such a picture.
+     */
+    uint8_t *mv_f_next_buf;
     int field_mode;         ///< 1 for interlaced field pictures
     int fptype;
     int second_field;
@@ -442,6 +449,41 @@ void ff_vc1_init_transposed_scantables(VC1Context *v);
 int  ff_vc1_decode_end(AVCodecContext *avctx);
 void ff_vc1_decode_blocks(VC1Context *v);
 
+/**
+ * Frame threading: get the progress a reference picture has to report before
+ * one of its lines may be read.
+ *
+ * Frame-coded pictures report the last final MB row. Field-coded pictures
+ * report the last final MB row of the field they decode first, followed by
+ * mb_height / 2 plus the last final MB row of their second field, so that
+ * in both cases the progress also covers the rows of the motion vector
+ * arrays of the picture with that index.
+ *
+ * @param ref   the reference picture
+ * @param line  the last line read
+ * @param field -1 if line is a line of the frame, otherwise the parity of
+ *              the field it is a line of
+ */
+static inline int ff_vc1_ref_progress(const MpegEncContext *s,
+                                      const MPVPicture *ref,
+                                      int line, int field)
+{
+    line = FFMAX(line, 0);
+    if (!ref->field_picture) {
+        return (field < 0 ? line : 2 * line + field) >> 4;
+    } else {
+        int field_mb_height = FFALIGN(s->mb_height, 2) >> 1;
+        int first_field     = !(ref->f->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST);
+
+        if (field < 0)                  // both fields up to this frame line
+            return field_mb_height + (line >> 5);
+        else if (field == first_field)
+            return FFMIN(line >> 4, field_mb_height - 1);
+        else
+            return field_mb_height + (line >> 4);
+    }
+}
+
 void ff_vc1_i_overlap_filter(VC1Context *v);
 void ff_vc1_p_overlap_filter(VC1Context *v);
 void ff_vc1_i_loop_filter(VC1Context *v);
diff --git a/libavcodec/vc1_block.c b/libavcodec/vc1_block.c
index 4f508b9f1ff..f5646036783 100644
--- a/libavcodec/vc1_block.c
+++ b/libavcodec/vc1_block.c
@@ -76,22 +76,27 @@ static inline void update_block_index(MpegEncContext *s)
 /** @} */ //Bitplane group
 
 /**
- * Report the MB rows of a frame-coded reference picture that are final.
+ * Report the MB rows of a reference picture that are final.
  *
  * Called once MB row s->mb_y is decoded. The loop filters trail the decoding
  * loop by two MB rows (see ff_vc1_i_loop_filter(), ff_vc1_p_loop_filter()
  * and ff_vc1_p_intfr_loop_filter()): while row y is decoded, the last edges
  * touching row y - 2 are filtered, and no later row modifies it anymore.
  * Overlap smoothing and the delayed pixel output trail by one row only.
- * Field pictures are only reported as a whole by ff_mpv_frame_end().
+ *
+ * In field pictures, the rows of the second field are counted on from those
+ * of the first, see ff_vc1_ref_progress(). The last rows of the first field
+ * are reported by vc1_decode_frame(), those of the picture by
+ * ff_mpv_frame_end().
  */
 static void vc1_report_decode_progress(VC1Context *v)
 {
     MpegEncContext *s = &v->s;
 
     if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME) &&
-        s->cur_pic.reference && !v->field_mode && !s->er.error_occurred)
-        ff_thread_progress_report(&s->cur_pic.ptr->progress, s->mb_y - 2);
+        s->cur_pic.reference && !s->er.error_occurred)
+        ff_thread_progress_report(&s->cur_pic.ptr->progress,
+                                  s->mb_y - 2 + v->mb_off / s->mb_stride);
 }
 
 static void vc1_put_blocks_clamped(VC1Context *v, int put_signed)
@@ -2892,7 +2897,10 @@ static void vc1_decode_b_blocks(VC1Context *v)
     for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
         s->mb_x = 0;
         init_block_index(v);
-        /* direct mode reads the co-located motion of the next anchor */
+        /* Direct mode reads the co-located motion of the next anchor, and
+         * its field MV flags in field pictures. The progress of a picture
+         * also covers this row of its motion arrays, whether it is coded as
+         * a frame or as fields, see ff_vc1_ref_progress(). */
         if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME) &&
             s->next_pic.ptr)
             ff_thread_progress_await(&s->next_pic.ptr->progress,
@@ -2956,7 +2964,9 @@ static void vc1_decode_skip_blocks(VC1Context *v)
         init_block_index(v);
         update_block_index(s);
         if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
-            ff_thread_progress_await(&s->last_pic.ptr->progress, s->mb_y);
+            ff_thread_progress_await(&s->last_pic.ptr->progress,
+                                     ff_vc1_ref_progress(s, s->last_pic.ptr,
+                                                         s->mb_y * 16 + 15, 
-1));
         memcpy(s->dest[0], s->last_pic.data[0] + s->mb_y * 16 * s->linesize,   
s->linesize   * 16);
         memcpy(s->dest[1], s->last_pic.data[1] + s->mb_y *  8 * s->uvlinesize, 
s->uvlinesize *  8);
         memcpy(s->dest[2], s->last_pic.data[2] + s->mb_y *  8 * s->uvlinesize, 
s->uvlinesize *  8);
diff --git a/libavcodec/vc1_mc.c b/libavcodec/vc1_mc.c
index 9bdbeb8ab8e..83663f2c47d 100644
--- a/libavcodec/vc1_mc.c
+++ b/libavcodec/vc1_mc.c
@@ -37,13 +37,14 @@
  * With frame threading, wait until the rows of the reference picture a
  * block can read from have been decoded.
  *
- * @param ref   reference picture, NULL if it is the current picture
- * @param src_y first luma line of the referenced block (chroma lines
- *              doubled), in lines of the current frame or field
+ * @param ref       reference picture, NULL if it is the current picture
+ * @param src_y     first luma line of the referenced block (chroma lines
+ *                  doubled), in lines of the current frame or field
+ * @param ref_field in field pictures, the parity of the referenced field
  */
 static av_always_inline void vc1_await_ref(const VC1Context *v,
                                            const MPVWorkPicture *ref,
-                                           int src_y)
+                                           int src_y, int ref_field)
 {
     const MpegEncContext *s = &v->s;
 
@@ -53,12 +54,11 @@ static av_always_inline void vc1_await_ref(const VC1Context 
*v,
          *   16x16 luma, bicubic:          src_y - 1 + 18     = src_y + 17
          *   8x8 chroma, bilinear:      2 * (uvsrc_y + 8) + 1 = src_y + 17
          *   8x8 luma of a field MV in an interlaced frame,
-         *   every other line:             src_y - 2 + 2 * 10 = src_y + 18
-         * In field pictures, line n of the bottom field is line 2 * n + 1
-         * of the frame, which the shift below covers as 18 > 17. */
-        int y = FFMAX(src_y + 18, 0) << v->field_mode;
+         *   every other line:             src_y - 2 + 2 * 10 = src_y + 18 */
+        int progress = ff_vc1_ref_progress(s, ref->ptr, src_y + 18,
+                                           v->field_mode ? ref_field : -1);
 
-        ff_thread_progress_await(&ref->ptr->progress, y >> 4);
+        ff_thread_progress_await(&ref->ptr->progress, progress);
     }
 }
 
@@ -306,7 +306,7 @@ void ff_vc1_mc_1mv(VC1Context *v, int dir)
         }
     }
 
-    vc1_await_ref(v, ref, FFMAX(src_y, 2 * uvsrc_y));
+    vc1_await_ref(v, ref, FFMAX(src_y, 2 * uvsrc_y), v->ref_field_type[dir]);
 
     srcY += src_y   * s->linesize   + src_x;
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
@@ -593,7 +593,7 @@ void ff_vc1_mc_4mv_luma(VC1Context *v, int n, int dir, int 
avg)
             src_y = av_clip(src_y, -18, s->avctx->coded_height + 1);
     }
 
-    vc1_await_ref(v, ref, src_y);
+    vc1_await_ref(v, ref, src_y, v->ref_field_type[dir]);
 
     srcY += src_y * s->linesize + src_x;
     if (v->field_mode && v->ref_field_type[dir])
@@ -769,7 +769,7 @@ void ff_vc1_mc_4mv_chroma(VC1Context *v, int dir)
         return;
     }
 
-    vc1_await_ref(v, ref, 2 * uvsrc_y);
+    vc1_await_ref(v, ref, 2 * uvsrc_y, chroma_ref_type);
 
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
     srcV += uvsrc_y * s->uvlinesize + uvsrc_x;
@@ -933,14 +933,14 @@ void ff_vc1_mc_4mv_chroma4(VC1Context *v, int dir, int 
dir2, int avg)
             lutuv  = v->next_lutuv;
             use_ic = v->next_use_ic;
             interlace = v->next_interlaced;
-            vc1_await_ref(v, &s->next_pic, 2 * uvsrc_y);
+            vc1_await_ref(v, &s->next_pic, 2 * uvsrc_y, 0);
         } else {
             srcU = s->last_pic.data[1];
             srcV = s->last_pic.data[2];
             lutuv  = v->last_lutuv;
             use_ic = v->last_use_ic;
             interlace = v->last_interlaced;
-            vc1_await_ref(v, &s->last_pic, 2 * uvsrc_y);
+            vc1_await_ref(v, &s->last_pic, 2 * uvsrc_y, 0);
         }
         if (!srcU)
             return;
@@ -1106,7 +1106,7 @@ void ff_vc1_interp_mc(VC1Context *v)
         }
     }
 
-    vc1_await_ref(v, &s->next_pic, FFMAX(src_y, 2 * uvsrc_y));
+    vc1_await_ref(v, &s->next_pic, FFMAX(src_y, 2 * uvsrc_y), 
v->ref_field_type[1]);
 
     srcY += src_y   * s->linesize   + src_x;
     srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
diff --git a/libavcodec/vc1dec.c b/libavcodec/vc1dec.c
index 8548e8ac27c..c34ff37c858 100644
--- a/libavcodec/vc1dec.c
+++ b/libavcodec/vc1dec.c
@@ -38,18 +38,20 @@
  *   pictures, intensity compensation and the field MV flags of the last
  *   field-coded anchor. This happens once the previous thread has called
  *   ff_thread_finish_setup(), which vc1_decode_frame() does as early as
- *   possible: right after the picture header for most pictures, after
- *   decoding for those whose later headers can still change that state.
+ *   possible: right after the picture header for most pictures, after the
+ *   header of the second field for field-coded I/P pictures, and after
+ *   decoding if slices repeat the picture header.
  *
- * - Reference pictures report their progress in MB rows of the frame as
- *   they are decoded, trailing the overlap and loop filters (see
- *   vc1_report_decode_progress() in vc1_block.c). Field-coded pictures are
- *   only reported as a whole, by ff_mpv_frame_end().
+ * - Reference pictures report their progress in MB rows as they are
+ *   decoded, trailing the loop filters (see vc1_report_decode_progress() in
+ *   vc1_block.c). Field-coded pictures report the rows of their first
+ *   field, then those of their second field (see ff_vc1_ref_progress()).
  *
  * - Before a block is predicted from a reference picture, the decoding
- *   thread waits until the rows it reads are available (vc1_await_ref() in
- *   vc1_mc.c). The same applies to the rows copied for skipped pictures and
- *   to the co-located motion read by B-picture direct mode (vc1_block.c).
+ *   thread waits until the rows it reads are available, in the field it
+ *   reads them from (vc1_await_ref() in vc1_mc.c). The same applies to the
+ *   rows copied for skipped pictures and to the co-located motion read by
+ *   B-picture direct mode (vc1_block.c).
  */
 
 #include "config_components.h"
@@ -77,6 +79,7 @@
 #include "libavutil/avassert.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/mem.h"
+#include "libavutil/refstruct.h"
 #include "libavutil/thread.h"
 
 
@@ -796,6 +799,7 @@ static av_cold void vc1_decode_reset(AVCodecContext *avctx)
     av_freep(&v->blk_mv_type_base);
     av_freep(&v->mv_f_base);
     av_freep(&v->mv_f_next_base);
+    av_refstruct_unref(&v->mv_f_next_buf);
     av_freep(&v->block);
     av_freep(&v->cbp_base);
     av_freep(&v->ttblk_base);
@@ -813,6 +817,41 @@ av_cold int ff_vc1_decode_end(AVCodecContext *avctx)
     return ff_mpv_decode_close(avctx);
 }
 
+/**
+ * Set up the field MV flags for the picture about to be decoded.
+ *
+ * A field-coded I/P picture gets a new buffer of its own, which then is also
+ * what the field B-pictures after it (in coding order) predict direct mode
+ * from. With frame threading, those can be decoded by other threads while
+ * this picture still is, so the buffer is shared by reference; what they
+ * read of it is covered by the progress of this picture. All other pictures
+ * only need scratch space for their own flags.
+ */
+static int vc1_setup_mv_f(VC1Context *v)
+{
+    const MpegEncContext *s = &v->s;
+    size_t plane_size = vc1_mv_f_plane_size(s);
+    uint8_t *buf;
+
+    if (v->field_mode && !(v->fptype & 4)) {
+        buf = av_refstruct_allocz(2 * plane_size);
+        if (!buf)
+            return AVERROR(ENOMEM);
+        av_refstruct_unref(&v->mv_f_next_buf);
+        v->mv_f_next_buf = buf;
+    } else {
+        buf = v->mv_f_base;
+    }
+    v->mv_f[0] = buf + s->b8_stride + 1;
+    v->mv_f[1] = v->mv_f[0] + plane_size;
+
+    buf = v->mv_f_next_buf ? v->mv_f_next_buf : v->mv_f_next_base;
+    v->mv_f_next[0] = buf + s->b8_stride + 1;
+    v->mv_f_next[1] = v->mv_f_next[0] + plane_size;
+
+    return 0;
+}
+
 #if HAVE_THREADS
 /* Point v->field at the member of v that v1->field points to in v1. */
 #define REMAP_PTR(field, a, b, c)                                         \
@@ -913,12 +952,8 @@ static int vc1_update_thread_context(AVCodecContext *dst,
     REMAP_PTR(curr_use_ic, last_use_ic,   next_use_ic,   aux_use_ic);
 
     /* Field MV flags of the last field-coded anchor, read by direct-mode
-     * prediction in field B-pictures. Anchors swap them in place only after
-     * decoding, and do not finish setup before that. B-pictures only read
-     * them. */
-    memcpy(v->mv_f_next[0]  - (s->b8_stride  + 1),
-           v1->mv_f_next[0] - (s1->b8_stride + 1),
-           2 * vc1_mv_f_plane_size(s));
+     * prediction in field B-pictures; see vc1_setup_mv_f(). */
+    av_refstruct_replace(&v->mv_f_next_buf, v1->mv_f_next_buf);
 
     return 0;
 }
@@ -957,7 +992,8 @@ static int vc1_decode_frame(AVCodecContext *avctx, AVFrame 
*pict,
         int raw_size;
     } *slices = NULL, *tmp;
     unsigned slices_allocated = 0;
-    int frame_started = 0, late_setup;
+    int frame_started = 0;
+    enum { SETUP_NOW, SETUP_SECOND_FIELD, SETUP_END } setup = SETUP_NOW;
 
     v->second_field = 0;
 
@@ -1226,29 +1262,36 @@ static int vc1_decode_frame(AVCodecContext *avctx, 
AVFrame *pict,
         s->cur_pic.ptr->f->repeat_pict = v->rptfrm * 2;
     }
 
+    if ((ret = vc1_setup_mv_f(v)) < 0)
+        goto err;
+
     /* Frame threading: let the next picture start decoding in another
-     * thread as soon as everything it depends on is known. That is the case
-     * now, except when the software decoding below can still change it:
+     * thread as soon as everything it depends on is known, that is, what
+     * vc1_update_thread_context() copies. That is the case now, except when
+     * the software decoding below can still change it:
      * - The header of the second field of an I/P field picture can update
-     *   the intensity compensation state, and the field MV flags that
-     *   subsequent field B-pictures predict from are swapped into
-     *   v->mv_f_next only once both fields are decoded.
-     * - Slices can repeat the picture header.
-     * Setup is then finished by the generic code once decoding returns.
-     * Field B-pictures do not have this problem; what their second field
-     * header changes is not used by later pictures (see
-     * vc1_update_thread_context()).
+     *   the intensity compensation of the reference fields, including the
+     *   first field of the picture itself. Setup is finished once that
+     *   header is parsed, see below. Field B-pictures do not have this
+     *   problem; what their second field header changes is not used by
+     *   later pictures.
+     * - Slices can repeat the picture header. Setup is then finished by the
+     *   generic code once decoding returns.
      * Hardware decoding uses none of this state, and requires setup to be
      * finished before the hwaccel is called. */
-    late_setup = v->field_mode && s->pict_type != AV_PICTURE_TYPE_B;
-    for (i = 0; i < n_slices && !late_setup; i++) {
-        /* the first bit after a slice address is the PIC_HEADER_FLAG; field
-         * markers carry a second field header instead, but then late_setup
-         * is either already set or the picture is a B-picture */
-        if (!(v->field_mode && i == n_slices1 + 1))
-            late_setup = show_bits1(&slices[i].gb);
+    setup = SETUP_NOW;
+    if (!avctx->hwaccel) {
+        if (v->field_mode && !(v->fptype & 4))
+            setup = SETUP_SECOND_FIELD;
+        for (i = 0; i < n_slices; i++) {
+            /* the first bit after a slice address is the PIC_HEADER_FLAG;
+             * field markers carry the second field header instead */
+            if (!(v->field_mode && i == n_slices1 + 1) &&
+                show_bits1(&slices[i].gb))
+                setup = SETUP_END;
+        }
     }
-    if (avctx->hwaccel || !late_setup)
+    if (setup == SETUP_NOW)
         ff_thread_finish_setup(avctx);
 
     if (avctx->hwaccel) {
@@ -1442,6 +1485,16 @@ static int vc1_decode_frame(AVCodecContext *avctx, 
AVFrame *pict,
                             goto err;
                         continue;
                     }
+                    /* The first field is complete, including its last two
+                     * MB rows, which vc1_report_decode_progress() could not
+                     * report. */
+                    if (HAVE_THREADS && s->cur_pic.reference &&
+                        (avctx->active_thread_type & FF_THREAD_FRAME) &&
+                        !s->er.error_occurred)
+                        ff_thread_progress_report(&s->cur_pic.ptr->progress,
+                                                  mb_height - 1);
+                    if (setup == SETUP_SECOND_FIELD)
+                        ff_thread_finish_setup(avctx);
                 } else if (get_bits1(&v->gb)) {
                     v->pic_header_flag = 1;
                     if ((header_ret = ff_vc1_parse_frame_header_adv(v, 
&v->gb)) < 0) {
@@ -1487,10 +1540,6 @@ static int vc1_decode_frame(AVCodecContext *avctx, 
AVFrame *pict,
             s->cur_pic.linesize[2] >>= 1;
             s->linesize                      >>= 1;
             s->uvlinesize                    >>= 1;
-            if (v->s.pict_type != AV_PICTURE_TYPE_BI && v->s.pict_type != 
AV_PICTURE_TYPE_B) {
-                FFSWAP(uint8_t *, v->mv_f_next[0], v->mv_f[0]);
-                FFSWAP(uint8_t *, v->mv_f_next[1], v->mv_f[1]);
-            }
         }
         ff_dlog(s->avctx, "Consumed %i/%i bits\n",
                 get_bits_count(&v->gb), v->gb.size_in_bits);
-- 
2.54.0

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

Reply via email to