diff mbox series

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

Message ID 20200104041341.22651-1-quinkblack@foxmail.com
State New
Headers show
Series [FFmpeg-devel,v3] avfilter/formats: optimize ff_all_formats | expand

Checks

Context Check Description
andriy/ffmpeg-patchwork success Make fate finished

Commit Message

Zhao Zhili Jan. 4, 2020, 4:13 a.m. UTC
From: Zhao Zhili <zhilizhao@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 mbox series

Patch

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;