From f0abfd94263082284c6e434d98dc9a093c9e170d Mon Sep 17 00:00:00 2001
From: Andreas Rheinhardt <andreas.rheinhardt@outlook.com>
Date: Sat, 15 Mar 2025 07:16:33 +0100
Subject: [PATCH 36/77] avcodec/mpegvideo: Add pointer to main context to slice
 contexts

It is a pointer to const to allow the slice threads to inspect
values without modifying them; also make it a simple cast
for codecs that don't support slice threading.

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt@outlook.com>
---
 libavcodec/mpegvideo.c    |  2 ++
 libavcodec/mpegvideo.h    |  4 ++++
 libavcodec/mpegvideoenc.h | 12 ++++++++++++
 3 files changed, 18 insertions(+)

diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index 9cd67151aa..bc367fba07 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -387,6 +387,8 @@ av_cold int ff_mpv_init_duplicate_contexts(MpegEncContext *s)
 {
     int nb_slices = s->slice_context_count, ret;
 
+    s->parent = s;
+
     /* We initialize the copies before the original so that
      * fields allocated in init_duplicate_context are NULL after
      * copying. This prevents double-frees upon allocation error. */
diff --git a/libavcodec/mpegvideo.h b/libavcodec/mpegvideo.h
index bdab782b29..04eade13aa 100644
--- a/libavcodec/mpegvideo.h
+++ b/libavcodec/mpegvideo.h
@@ -86,6 +86,10 @@ typedef struct MpegEncContext {
     uint8_t permutated_intra_v_scantable[64];
 
     struct AVCodecContext *avctx;
+    union {
+        const struct MpegEncContext *parent;
+        const struct MPVMainEncContext *encparent;
+    };
     /* The following pointer is intended for codecs sharing code
      * between decoder and encoder and in need of a common context to do so. */
     void *private_ctx;
diff --git a/libavcodec/mpegvideoenc.h b/libavcodec/mpegvideoenc.h
index 4b74f8eb46..65bb3447b3 100644
--- a/libavcodec/mpegvideoenc.h
+++ b/libavcodec/mpegvideoenc.h
@@ -30,6 +30,7 @@
 
 #include <float.h>
 
+#include "libavutil/avassert.h"
 #include "libavutil/opt.h"
 #include "mpegvideo.h"
 #include "ratecontrol.h"
@@ -91,6 +92,17 @@ typedef struct MPVMainEncContext {
     int64_t mc_mb_var_sum;         ///< motion compensated MB variance for current frame
 } MPVMainEncContext;
 
+static inline const MPVMainEncContext *slice_to_mainenc(const MpegEncContext *s)
+{
+#ifdef NO_SLICE_THREADING_HERE
+    av_assert2(s->slice_context_count <= 1 &&
+               !(s->avctx->codec->capabilities & AV_CODEC_CAP_SLICE_THREADS));
+    return (const MPVMainEncContext*)s;
+#else
+    return s->encparent;
+#endif
+}
+
 #define MAX_FCODE        7
 #define UNI_AC_ENC_INDEX(run,level) ((run)*128 + (level))
 #define INPLACE_OFFSET 16
-- 
2.45.2