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

In `encode_tile()`, `perf report` showed the division in the loop as a hotspot, 
precomputing that seems to reduce cycle count as reported by `perf stat -e 
cycles` by ~5%.

In `put_bits()`, shifting the input bit before the loop also seemed to yield a 
miniscule amount of cycle count decrease.

All tests were run with optimizations enabled, on a Ryzen 5 2600, using GCC 
16.1.1, and `--debug-level=3`.


>From ca05d574f67ddbd6da3a3656a34b18a8a6854375 Mon Sep 17 00:00:00 2001
From: Zsolt Vadasz <[email protected]>
Date: Fri, 3 Jul 2026 19:07:04 +0200
Subject: [PATCH] avcodec/j2kenc: Compute division only once, preshift bit

Pre-shift n to the highest bit in put_bits(), and compute a division
outside of a hot loop in encode_tile().
---
 libavcodec/j2kenc.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/libavcodec/j2kenc.c b/libavcodec/j2kenc.c
index cba4d18adf..ac18c66b99 100644
--- a/libavcodec/j2kenc.c
+++ b/libavcodec/j2kenc.c
@@ -153,13 +153,14 @@ typedef struct {
 /** put n times val bit */
 static void put_bits(Jpeg2000EncoderContext *s, int val, int n) // TODO: 
optimize
 {
+    val <<= 7;
     while (n-- > 0){
         if (s->bit_index == 8)
         {
             s->bit_index = *s->buf == 0xff;
             *(++s->buf) = 0;
         }
-        *s->buf |= val << (7 - s->bit_index++);
+        *s->buf |= val >> s->bit_index++;
     }
 }
 
@@ -1384,11 +1385,12 @@ static int encode_tile(Jpeg2000EncoderContext *s, 
Jpeg2000Tile *tile, int tileno
                                 }
                             }
                         } else{
+                            int64_t multiplier = (int64_t)(16384 * 65536 / 
band->i_stepsize);
                             for (y = yy0; y < yy1; y++){
                                 int *ptr = t1.data + (y-yy0)*t1.stride;
                                 for (x = xx0; x < xx1; x++){
                                     *ptr = (comp->i_data[(comp->coord[0][1] - 
comp->coord[0][0]) * y + x]);
-                                    *ptr = (int64_t)*ptr * (int64_t)(16384 * 
65536 / band->i_stepsize) >> 15 - NMSEDEC_FRACBITS;
+                                    *ptr = (int64_t)*ptr * multiplier >> 15 - 
NMSEDEC_FRACBITS;
                                     ptr++;
                                 }
                             }
-- 
2.52.0

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

Reply via email to