From c595a3b0a336d6b06b8a18e3008a6b7e8f989c2d Mon Sep 17 00:00:00 2001
From: Andreas Rheinhardt <andreas.rheinhardt@outlook.com>
Date: Wed, 19 Mar 2025 12:26:47 +0100
Subject: [PATCH 64/77] avcodec/mpeg12enc, speedhqenc: Optimize writing escape
 codes

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt@outlook.com>
---
 libavcodec/mpeg12enc.c  | 9 ++++-----
 libavcodec/speedhqenc.c | 9 ++++-----
 2 files changed, 8 insertions(+), 10 deletions(-)

diff --git a/libavcodec/mpeg12enc.c b/libavcodec/mpeg12enc.c
index 5a91f9fff1..584573b466 100644
--- a/libavcodec/mpeg12enc.c
+++ b/libavcodec/mpeg12enc.c
@@ -628,12 +628,11 @@ next_coef:
                 put_bits(&s->pb, table_vlc[code][1] + 1,
                          (table_vlc[code][0] << 1) + sign);
             } else {
-                /* Escape seems to be pretty rare <5% so I do not optimize it;
-                 * the following value is the common escape value for both
-                 * possible tables (i.e. table_vlc[111]). */
-                put_bits(&s->pb, 6, 0x01);
+                /* Escape seems to be pretty rare <5% so I do not optimize it.
+                 * The following encodes run together with the common escape
+                 * value of both tables 000001b. */
+                put_bits(&s->pb, 6 + 6, 0x01 << 6 | run);
                 /* escape: only clip in this case */
-                put_bits(&s->pb, 6, run);
                 if (s->c.codec_id == AV_CODEC_ID_MPEG1VIDEO) {
                     if (alevel < 128) {
                         put_sbits(&s->pb, 8, level);
diff --git a/libavcodec/speedhqenc.c b/libavcodec/speedhqenc.c
index 7ddfb92076..ecba2cd840 100644
--- a/libavcodec/speedhqenc.c
+++ b/libavcodec/speedhqenc.c
@@ -194,11 +194,10 @@ static void encode_block(MPVEncContext *const s, const int16_t block[], int n)
                             ff_speedhq_vlc_table[code][0] | (sign << ff_speedhq_vlc_table[code][1]));
             } else {
                 /* escape seems to be pretty rare <5% so I do not optimize it;
-                 * the values correspond to ff_speedhq_vlc_table[121] */
-                put_bits_le(&s->pb, 6, 32);
-                /* escape: only clip in this case */
-                put_bits_le(&s->pb, 6, run);
-                put_bits_le(&s->pb, 12, level + 2048);
+                 * The following encodes the escape value 100000b together with
+                 * run and level. */
+                put_bits_le(&s->pb, 6 + 6 + 12, 0x20 | run << 6 |
+                                                (level + 2048) << 12);
             }
             last_non_zero = i;
         }
-- 
2.45.2