[FFmpeg-devel] [PATCH 2/8] avpriv_find_start_code(): rewrite while loop and add comments for clarity

Scott Theisen scott.the.elm at gmail.com
Tue Feb 1 23:20:50 EET 2022


The expected number of iterations may increase by one for an input of alternating
0 and 1 bytes.  Instead of incrementing by 2 everytime, it now alternates between
incrementing by 1 and by 3.

No functional change, but now much clearer.
---
 libavcodec/utils.c | 25 ++++++++++++++++++++-----
 1 file changed, 20 insertions(+), 5 deletions(-)

diff --git a/libavcodec/utils.c b/libavcodec/utils.c
index cb4437edc2..882f90be79 100644
--- a/libavcodec/utils.c
+++ b/libavcodec/utils.c
@@ -957,12 +957,26 @@ const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
             return p;
     }
 
+    /* with memory address increasing left to right, we are looking for (in hexadecimal):
+     * 00 00 01 XX
+     * p points at the address which should have the value of XX
+     */
     while (p < end) {
-        if      (p[-1] > 1      ) p += 3;
-        else if (p[-2]          ) p += 2;
-        else if (p[-3]|(p[-1]-1)) p++;
+        // UU UU UU
+        if      (p[-1]  > 1) p += 3;    // start check over with 3 new bytes
+        else if (p[-1] == 0) p++;       // could be in a start code, so check next byte
+        // this should be one comparison against 1 since p is unsigned,
+        // i.e. p[-1] == 0 is equivalent to p[-1] < 1
+
+        // UU UU 01
+        else if (p[-2] != 0) p += 2;    // we have UU YY 01, so increment by 2
+                                        // to start check over with 3 new bytes
+        // UU 00 01
+        else if (p[-3] != 0) p += 3;    // we have YY 00 01, so increment by 3
+                                        // to start check over with 3 new bytes
+        // 00 00 01
         else {
-            p++;
+            p++; // p now points at the address following the start code value XX
             break;
         }
     }
@@ -972,7 +986,8 @@ const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p,
     // this will cause the last 4 bytes before end to be read,
     // i.e. no out of bounds memory access occurs
 
-    *state = AV_RB32(p - 4); // read the previous 4 bytes
+    *state = AV_RB32(p - 4);
+    // read the previous 4 bytes, i.e. bytes {p - 4, p - 3, p - 2, p - 1}
 
     return p;
 }
-- 
2.32.0



More information about the ffmpeg-devel mailing list