From b79aa2b89ed9027a72a10c1d26ccdf2bb385d57b Mon Sep 17 00:00:00 2001
From: Ben Avison <bavison@riscosopen.org>
Date: Mon, 5 Aug 2013 13:12:49 +0100
Subject: [PATCH 54/54] [ffmpeg] - backport - mpegts: Remove one 64-bit
 integer modulus operation per packet
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

The common case of the pointer having increased by one packet (which results
in no change to the modulus) can be detected with a 64-bit subtraction,
which is far cheaper than a division on many platforms.

           Before          After
           Mean   StdDev   Mean   StdDev  Change
Divisions   248.3  8.8      51.5   7.4    +381.7%
Overall    2773.2 25.6     2372.5 43.1     +16.9%

Signed-off-by: Martin Storsjö <martin@martin.st>
---
 lib/ffmpeg/libavcodec/mathops.h |    9 +++++++++
 lib/ffmpeg/libavformat/mpegts.c |    5 ++++-
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/lib/ffmpeg/libavcodec/mathops.h b/lib/ffmpeg/libavcodec/mathops.h
index 592f5a5..1d57342 100644
--- a/lib/ffmpeg/libavcodec/mathops.h
+++ b/lib/ffmpeg/libavcodec/mathops.h
@@ -195,6 +195,15 @@ if ((y) < (x)) {\
 #   define FASTDIV(a,b) ((uint32_t)((((uint64_t)a) * ff_inverse[b]) >> 32))
 #endif /* FASTDIV */

+#ifndef MOD_UNLIKELY
+#   define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \
+    do { \
+        if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \
+            (modulus) = (dividend) % (divisor); \
+        (prev_dividend) = (dividend); \
+    } while (0)
+#endif
+
 static inline av_const unsigned int ff_sqrt(unsigned int a)
 {
     unsigned int b;
diff --git a/lib/ffmpeg/libavformat/mpegts.c b/lib/ffmpeg/libavformat/mpegts.c
index 82dd209..b995f60 100644
--- a/lib/ffmpeg/libavformat/mpegts.c
+++ b/lib/ffmpeg/libavformat/mpegts.c
@@ -28,6 +28,7 @@
 #include "libavutil/avassert.h"
 #include "libavcodec/bytestream.h"
 #include "libavcodec/get_bits.h"
+#include "libavcodec/mathops.h"
 #include "avformat.h"
 #include "mpegts.h"
 #include "internal.h"
@@ -99,6 +100,8 @@ struct MpegTSContext {
     int raw_packet_size;

     int pos47;
+    /** position corresponding to pos47, or 0 if pos47 invalid */
+    int64_t pos;

     /** if true, all pids are analyzed to find streams       */
     int auto_guess;
@@ -1814,7 +1817,7 @@ static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
         return 0;

     pos = avio_tell(ts->stream->pb);
-    ts->pos47= pos % ts->raw_packet_size;
+    MOD_UNLIKELY(ts->pos47, pos, ts->raw_packet_size, ts->pos);

     if (tss->type == MPEGTS_SECTION) {
         if (is_start) {
--
1.7.9.5
