[FFmpeg-devel] [PATCH v3] avfilter/formats: optimize ff_all_formats

quinkblack at foxmail.com quinkblack at foxmail.com
Sat Jan 4 06:13:41 EET 2020


From: Zhao Zhili <zhilizhao at tencent.com>

This is a micro-optimization. Saving almost 200 reallocations makes it
worth a try.
---
v3: fix an obvious infinite loop and pass fate-filter test

 libavfilter/formats.c | 41 ++++++++++++++++++++++++++++++++++-------
 1 file changed, 34 insertions(+), 7 deletions(-)

diff --git a/libavfilter/formats.c b/libavfilter/formats.c
index 33c64668a0..f29cddc250 100644
--- a/libavfilter/formats.c
+++ b/libavfilter/formats.c
@@ -348,21 +348,48 @@ int ff_add_channel_layout(AVFilterChannelLayouts **l, uint64_t channel_layout)
 
 AVFilterFormats *ff_all_formats(enum AVMediaType type)
 {
-    AVFilterFormats *ret = NULL;
+    int count, i;
+    AVFilterFormats *ret = av_mallocz(sizeof(*ret));
+
+    if (!ret)
+        return NULL;
 
     if (type == AVMEDIA_TYPE_VIDEO) {
         const AVPixFmtDescriptor *desc = NULL;
-        while ((desc = av_pix_fmt_desc_next(desc))) {
-            if (ff_add_format(&ret, av_pix_fmt_desc_get_id(desc)) < 0)
-                return NULL;
+
+        count = 0;
+        while ((desc = av_pix_fmt_desc_next(desc)))
+            count++;
+
+        ret->formats = av_malloc_array(count, sizeof(*ret->formats));
+        if (!ret->formats) {
+            av_free(ret);
+            return NULL;
+        }
+        ret->nb_formats = count;
+
+        for (i = 0, desc = NULL; i < count; i++) {
+            desc = av_pix_fmt_desc_next(desc);
+            ret->formats[i] = av_pix_fmt_desc_get_id(desc);
         }
     } else if (type == AVMEDIA_TYPE_AUDIO) {
         enum AVSampleFormat fmt = 0;
-        while (av_get_sample_fmt_name(fmt)) {
-            if (ff_add_format(&ret, fmt) < 0)
-                return NULL;
+
+        while (av_get_sample_fmt_name(fmt))
             fmt++;
+
+        count = fmt;
+        ret->formats = av_malloc_array(count, sizeof(*ret->formats));
+        if (!ret->formats) {
+            av_free(ret);
+            return NULL;
         }
+        ret->nb_formats = count;
+
+        for (fmt = 0; fmt < count; fmt++)
+            ret->formats[fmt] = fmt;
+    } else {
+        av_freep(&ret);
     }
 
     return ret;
-- 
2.22.0





More information about the ffmpeg-devel mailing list