diff --git a/libavfilter/avfiltergraph.c b/libavfilter/avfiltergraph.c
index da5015ca88b2270d107613c602343584c397cf5e..997ae451f967562e2c029d1d40dda3d4ae7e276f 100644
--- a/libavfilter/avfiltergraph.c
+++ b/libavfilter/avfiltergraph.c
@@ -238,9 +238,11 @@ static int query_formats(AVFilterGraph *graph, AVClass *log_ctx)
     /* ask all the sub-filters for their supported media formats */
     for (i = 0; i < graph->filter_count; i++) {
         if (graph->filters[i]->filter->query_formats)
-            graph->filters[i]->filter->query_formats(graph->filters[i]);
+            ret = graph->filters[i]->filter->query_formats(graph->filters[i]);
         else
-            ff_default_query_formats(graph->filters[i]);
+            ret = ff_default_query_formats(graph->filters[i]);
+        if (ret < 0)
+            return ret;
     }
 
     /* go through and merge as many format lists as possible */