libavfilter/graphparser.c
27afb09d
 /*
  * filter graph parser
3fa77bde
  * Copyright (c) 2008 Vitor Sessak
  * Copyright (c) 2007 Bobby Bingham
27afb09d
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <string.h>
1d9c2dc8
 #include <stdio.h>
27afb09d
 
372e2884
 #include "libavutil/avstring.h"
1d9c2dc8
 #include "libavutil/mem.h"
27afb09d
 #include "avfilter.h"
 
fd548e5b
 #define WHITESPACES " \n\t"
 
d2874a9d
 /**
  * Link two filters together.
  *
  * @see avfilter_link()
  */
9710beaf
 static int link_filter(AVFilterContext *src, int srcpad,
3a70bb2d
                        AVFilterContext *dst, int dstpad,
86909dd5
                        void *log_ctx)
27afb09d
 {
99ac59ca
     int ret;
     if ((ret = avfilter_link(src, srcpad, dst, dstpad))) {
3a70bb2d
         av_log(log_ctx, AV_LOG_ERROR,
bb90d855
                "Cannot create the link %s:%d -> %s:%d\n",
9710beaf
                src->filter->name, srcpad, dst->filter->name, dstpad);
99ac59ca
         return ret;
27afb09d
     }
 
     return 0;
 }
 
 /**
94b2120d
  * Parse the name of a link, which has the format "[linkname]".
  *
  * @return a pointer (that need to be freed after use) to the name
  * between parenthesis
27afb09d
  */
86909dd5
 static char *parse_link_name(const char **buf, void *log_ctx)
27afb09d
 {
22260824
     const char *start = *buf;
bd80b349
     char *name;
27afb09d
     (*buf)++;
 
dd04911c
     name = av_get_token(buf, "]");
27afb09d
 
f219eee5
     if (!name[0]) {
3a70bb2d
         av_log(log_ctx, AV_LOG_ERROR,
22260824
                "Bad (empty?) label found in the following: \"%s\".\n", start);
27afb09d
         goto fail;
22260824
     }
27afb09d
 
f219eee5
     if (*(*buf)++ != ']') {
3a70bb2d
         av_log(log_ctx, AV_LOG_ERROR,
22260824
                "Mismatched '[' found in the following: \"%s\".\n", start);
85cb8af7
     fail:
bd80b349
         av_freep(&name);
22260824
     }
bd80b349
 
     return name;
27afb09d
 }
 
98137a1a
 /**
  * Create an instance of a filter, initialize and insert it in the
  * filtergraph in *ctx.
  *
24c9baba
  * @param filt_ctx put here a filter context in case of successful creation and configuration, NULL otherwise.
98137a1a
  * @param ctx the filtergraph context
  * @param index an index which is supposed to be unique for each filter instance added to the filtergraph
  * @param filt_name the name of the filter to create
  * @param args the arguments provided to the filter during its initialization
  * @param log_ctx the log context to use
d5ec8ba7
  * @return >= 0 in case of success, a negative AVERROR code otherwise
98137a1a
  */
c58572f8
 static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index,
86909dd5
                          const char *filt_name, const char *args, void *log_ctx)
8e74c889
 {
e4a5f397
     AVFilter *filt;
8e74c889
     char inst_name[30];
61af627d
     char *tmp_args = NULL;
c58572f8
     int ret;
8e74c889
 
cc2b4e88
     snprintf(inst_name, sizeof(inst_name), "Parsed_%s_%d", filt_name, index);
8e74c889
 
e4a5f397
     filt = avfilter_get_by_name(filt_name);
5e600185
 
f219eee5
     if (!filt) {
8e74c889
         av_log(log_ctx, AV_LOG_ERROR,
bb90d855
                "No such filter: '%s'\n", filt_name);
c58572f8
         return AVERROR(EINVAL);
8e74c889
     }
 
bc1a985b
     *filt_ctx = avfilter_graph_alloc_filter(ctx, filt, inst_name);
c58572f8
     if (!*filt_ctx) {
8e74c889
         av_log(log_ctx, AV_LOG_ERROR,
bb90d855
                "Error creating filter '%s'\n", filt_name);
bc1a985b
         return AVERROR(ENOMEM);
64b164f4
     }
8e74c889
 
6e3c13a5
     if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags") &&
         ctx->scale_sws_opts) {
61af627d
         tmp_args = av_asprintf("%s:%s",
b5049814
                  args, ctx->scale_sws_opts);
61af627d
         if (!tmp_args)
             return AVERROR(ENOMEM);
b5049814
         args = tmp_args;
     }
 
48a5adab
     ret = avfilter_init_str(*filt_ctx, args);
     if (ret < 0) {
8e74c889
         av_log(log_ctx, AV_LOG_ERROR,
c22263d3
                "Error initializing filter '%s'", filt_name);
         if (args)
             av_log(log_ctx, AV_LOG_ERROR, " with args '%s'", args);
         av_log(log_ctx, AV_LOG_ERROR, "\n");
8e74c889
     }
 
61af627d
     av_free(tmp_args);
     return ret;
8e74c889
 }
 
f5cbde2e
 /**
55b2a9ba
  * Parse a string of the form FILTER_NAME[=PARAMS], and create a
  * corresponding filter instance which is added to graph with
  * create_filter().
  *
96c1e6d4
  * @param filt_ctx Pointer that is set to the created and configured filter
  *                 context on success, set to NULL on failure.
55b2a9ba
  * @param filt_ctx put here a pointer to the created filter context on
  * success, NULL otherwise
  * @param buf pointer to the buffer to parse, *buf will be updated to
  * point to the char next after the parsed string
  * @param index an index which is assigned to the created filter
  * instance, and which is supposed to be unique for each filter
  * instance added to the filtergraph
d5ec8ba7
  * @return >= 0 in case of success, a negative AVERROR code otherwise
f5cbde2e
  */
688b9dad
 static int parse_filter(AVFilterContext **filt_ctx, const char **buf, AVFilterGraph *graph,
86909dd5
                         int index, void *log_ctx)
f5cbde2e
 {
ba3fed2f
     char *opts = NULL;
15a316c0
     char *name = av_get_token(buf, "=,;[\n");
c58572f8
     int ret;
f5cbde2e
 
f219eee5
     if (**buf == '=') {
f5cbde2e
         (*buf)++;
15a316c0
         opts = av_get_token(buf, "[],;\n");
12849837
     }
f5cbde2e
 
688b9dad
     ret = create_filter(filt_ctx, graph, index, name, opts, log_ctx);
64b164f4
     av_free(name);
     av_free(opts);
688b9dad
     return ret;
f5cbde2e
 }
 
c5354942
 AVFilterInOut *avfilter_inout_alloc(void)
27afb09d
 {
c5354942
     return av_mallocz(sizeof(AVFilterInOut));
 }
 
 void avfilter_inout_free(AVFilterInOut **inout)
 {
     while (*inout) {
         AVFilterInOut *next = (*inout)->next;
         av_freep(&(*inout)->name);
         av_freep(inout);
         *inout = next;
27afb09d
     }
 }
 
c9987633
 static AVFilterInOut *extract_inout(const char *label, AVFilterInOut **links)
 {
     AVFilterInOut *ret;
 
d7bcc71d
     while (*links && (!(*links)->name || strcmp((*links)->name, label)))
f6557d5e
         links = &((*links)->next);
c9987633
 
f6557d5e
     ret = *links;
c9987633
 
d7bcc71d
     if (ret) {
f6557d5e
         *links = ret->next;
d7bcc71d
         ret->next = NULL;
     }
c9987633
 
     return ret;
 }
 
e97908ee
 static void insert_inout(AVFilterInOut **inouts, AVFilterInOut *element)
 {
     element->next = *inouts;
     *inouts = element;
 }
c9987633
 
d7bcc71d
 static void append_inout(AVFilterInOut **inouts, AVFilterInOut **element)
 {
     while (*inouts && (*inouts)->next)
         inouts = &((*inouts)->next);
 
     if (!*inouts)
         *inouts = *element;
     else
         (*inouts)->next = *element;
     *element = NULL;
 }
 
ed581e65
 static int link_filter_inouts(AVFilterContext *filt_ctx,
7f9b3266
                               AVFilterInOut **curr_inputs,
86909dd5
                               AVFilterInOut **open_inputs, void *log_ctx)
c9987633
 {
4e781c25
     int pad, ret;
c9987633
 
9baeff95
     for (pad = 0; pad < filt_ctx->nb_inputs; pad++) {
7f9b3266
         AVFilterInOut *p = *curr_inputs;
c9987633
 
aff01de6
         if (p) {
d7bcc71d
             *curr_inputs = (*curr_inputs)->next;
aff01de6
             p->next = NULL;
         } else if (!(p = av_mallocz(sizeof(*p))))
d7bcc71d
             return AVERROR(ENOMEM);
4d11beb2
 
7313132b
         if (p->filter_ctx) {
285b706b
             ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx);
64b164f4
             av_free(p->name);
c9987633
             av_free(p);
285b706b
             if (ret < 0)
                 return ret;
c9987633
         } else {
7313132b
             p->filter_ctx = filt_ctx;
c9987633
             p->pad_idx = pad;
7af99a01
             append_inout(open_inputs, &p);
c9987633
         }
     }
 
f219eee5
     if (*curr_inputs) {
c9987633
         av_log(log_ctx, AV_LOG_ERROR,
                "Too many inputs specified for the \"%s\" filter.\n",
ed581e65
                filt_ctx->filter->name);
684ade49
         return AVERROR(EINVAL);
c9987633
     }
 
9baeff95
     pad = filt_ctx->nb_outputs;
f219eee5
     while (pad--) {
c956dd43
         AVFilterInOut *currlinkn = av_mallocz(sizeof(AVFilterInOut));
fbd97184
         if (!currlinkn)
             return AVERROR(ENOMEM);
7313132b
         currlinkn->filter_ctx  = filt_ctx;
c9987633
         currlinkn->pad_idx = pad;
7f9b3266
         insert_inout(curr_inputs, currlinkn);
c9987633
     }
 
     return 0;
 }
 
7f9b3266
 static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,
86909dd5
                         AVFilterInOut **open_outputs, void *log_ctx)
27afb09d
 {
4e781c25
     AVFilterInOut *parsed_inputs = NULL;
c9987633
     int pad = 0;
 
f219eee5
     while (**buf == '[') {
bd80b349
         char *name = parse_link_name(buf, log_ctx);
b2ac16da
         AVFilterInOut *match;
22260824
 
f219eee5
         if (!name)
42e7f6d7
             return AVERROR(EINVAL);
22260824
 
7f9b3266
         /* First check if the label is not in the open_outputs list */
         match = extract_inout(name, open_outputs);
cf4f7d38
 
f219eee5
         if (match) {
64fbf5e2
             av_free(name);
0de3407b
         } else {
             /* Not in the list, so add it as an input */
285b706b
             if (!(match = av_mallocz(sizeof(AVFilterInOut)))) {
                 av_free(name);
00b3ca3c
                 return AVERROR(ENOMEM);
285b706b
             }
c880791f
             match->name    = name;
             match->pad_idx = pad;
cf4f7d38
         }
e97908ee
 
4e781c25
         append_inout(&parsed_inputs, &match);
e97908ee
 
fd548e5b
         *buf += strspn(*buf, WHITESPACES);
c9987633
         pad++;
27afb09d
     }
cf4f7d38
 
4e781c25
     append_inout(&parsed_inputs, curr_inputs);
     *curr_inputs = parsed_inputs;
 
27afb09d
     return pad;
 }
 
7f9b3266
 static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,
                          AVFilterInOut **open_inputs,
86909dd5
                          AVFilterInOut **open_outputs, void *log_ctx)
9710beaf
 {
0cc8b659
     int ret, pad = 0;
c9987633
 
f219eee5
     while (**buf == '[') {
bd80b349
         char *name = parse_link_name(buf, log_ctx);
c9987633
         AVFilterInOut *match;
 
7f9b3266
         AVFilterInOut *input = *curr_inputs;
285b706b
 
         if (!name)
             return AVERROR(EINVAL);
 
668673f1
         if (!input) {
             av_log(log_ctx, AV_LOG_ERROR,
285b706b
                    "No output pad can be associated to link label '%s'.\n", name);
             av_free(name);
668673f1
             return AVERROR(EINVAL);
         }
7f9b3266
         *curr_inputs = (*curr_inputs)->next;
443c10ef
 
7f9b3266
         /* First check if the label is not in the open_inputs list */
         match = extract_inout(name, open_inputs);
c9987633
 
f219eee5
         if (match) {
7313132b
             if ((ret = link_filter(input->filter_ctx, input->pad_idx,
285b706b
                                    match->filter_ctx, match->pad_idx, log_ctx)) < 0) {
                 av_free(name);
0cc8b659
                 return ret;
285b706b
             }
64b164f4
             av_free(match->name);
             av_free(name);
c9987633
             av_free(match);
7baa6210
             av_free(input);
0de3407b
         } else {
7f9b3266
             /* Not in the list, so add the first input as a open_output */
7baa6210
             input->name = name;
7f9b3266
             insert_inout(open_outputs, input);
c9987633
         }
fd548e5b
         *buf += strspn(*buf, WHITESPACES);
c9987633
         pad++;
8095a014
     }
9710beaf
 
c9987633
     return pad;
 }
9710beaf
 
12e7e1d0
 static int parse_sws_flags(const char **buf, AVFilterGraph *graph)
 {
     char *p = strchr(*buf, ';');
 
     if (strncmp(*buf, "sws_flags=", 10))
         return 0;
 
     if (!p) {
8d900aa4
         av_log(graph, AV_LOG_ERROR, "sws_flags not terminated with ';'.\n");
12e7e1d0
         return AVERROR(EINVAL);
     }
 
     *buf += 4;  // keep the 'flags=' part
 
     av_freep(&graph->scale_sws_opts);
     if (!(graph->scale_sws_opts = av_mallocz(p - *buf + 1)))
         return AVERROR(ENOMEM);
     av_strlcpy(graph->scale_sws_opts, *buf, p - *buf + 1);
 
     *buf = p + 1;
     return 0;
 }
 
d7bcc71d
 int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters,
                           AVFilterInOut **inputs,
                           AVFilterInOut **outputs)
27afb09d
 {
7432bcfe
     int index = 0, ret = 0;
27afb09d
     char chr = 0;
 
d7bcc71d
     AVFilterInOut *curr_inputs = NULL, *open_inputs = NULL, *open_outputs = NULL;
27afb09d
 
12e7e1d0
     filters += strspn(filters, WHITESPACES);
 
     if ((ret = parse_sws_flags(&filters, graph)) < 0)
         goto fail;
 
27afb09d
     do {
9710beaf
         AVFilterContext *filter;
fd548e5b
         filters += strspn(filters, WHITESPACES);
27afb09d
 
8d900aa4
         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, graph)) < 0)
7432bcfe
             goto end;
8d900aa4
         if ((ret = parse_filter(&filter, &filters, graph, index, graph)) < 0)
7432bcfe
             goto end;
27afb09d
 
 
8d900aa4
         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, graph)) < 0)
7432bcfe
             goto end;
da790674
 
c24f76b9
         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
8d900aa4
                                  graph)) < 0)
7432bcfe
             goto end;
e84f0b62
 
fd548e5b
         filters += strspn(filters, WHITESPACES);
27afb09d
         chr = *filters++;
 
d7bcc71d
         if (chr == ';' && curr_inputs)
             append_inout(&open_outputs, &curr_inputs);
c9987633
         index++;
f219eee5
     } while (chr == ',' || chr == ';');
27afb09d
 
fd51ff16
     if (chr) {
8d900aa4
         av_log(graph, AV_LOG_ERROR,
78471234
                "Unable to parse graph description substring: \"%s\"\n",
                filters - 1);
c24f76b9
         ret = AVERROR(EINVAL);
7432bcfe
         goto end;
78471234
     }
 
d7bcc71d
     append_inout(&open_outputs, &curr_inputs);
27afb09d
 
7432bcfe
 
d7bcc71d
     *inputs  = open_inputs;
     *outputs = open_outputs;
27afb09d
     return 0;
 
7432bcfe
  fail:end:
1565cbc6
     while (graph->nb_filters)
         avfilter_free(graph->filters[0]);
e8e5dde7
     av_freep(&graph->filters);
91d3cbe0
     avfilter_inout_free(&open_inputs);
     avfilter_inout_free(&open_outputs);
     avfilter_inout_free(&curr_inputs);
d7bcc71d
 
     *inputs  = NULL;
     *outputs = NULL;
 
     return ret;
 }
 
838bd731
 #if HAVE_INCOMPATIBLE_LIBAV_ABI || !FF_API_OLD_GRAPH_PARSE
86a47378
 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
838bd731
                          AVFilterInOut *open_inputs,
                          AVFilterInOut *open_outputs, void *log_ctx)
27afb09d
 {
d7bcc71d
     int ret;
     AVFilterInOut *cur, *match, *inputs = NULL, *outputs = NULL;
 
     if ((ret = avfilter_graph_parse2(graph, filters, &inputs, &outputs)) < 0)
         goto fail;
 
     /* First input can be omitted if it is "[in]" */
     if (inputs && !inputs->name)
         inputs->name = av_strdup("in");
     for (cur = inputs; cur; cur = cur->next) {
         if (!cur->name) {
               av_log(log_ctx, AV_LOG_ERROR,
                      "Not enough inputs specified for the \"%s\" filter.\n",
                      cur->filter_ctx->filter->name);
               ret = AVERROR(EINVAL);
               goto fail;
         }
         if (!(match = extract_inout(cur->name, &open_outputs)))
             continue;
         ret = avfilter_link(match->filter_ctx, match->pad_idx,
                             cur->filter_ctx,   cur->pad_idx);
91d3cbe0
         avfilter_inout_free(&match);
d7bcc71d
         if (ret < 0)
             goto fail;
     }
 
     /* Last output can be omitted if it is "[out]" */
     if (outputs && !outputs->name)
         outputs->name = av_strdup("out");
     for (cur = outputs; cur; cur = cur->next) {
         if (!cur->name) {
             av_log(log_ctx, AV_LOG_ERROR,
                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
                    filters);
             ret = AVERROR(EINVAL);
             goto fail;
         }
         if (!(match = extract_inout(cur->name, &open_inputs)))
             continue;
         ret = avfilter_link(cur->filter_ctx,   cur->pad_idx,
                             match->filter_ctx, match->pad_idx);
91d3cbe0
         avfilter_inout_free(&match);
d7bcc71d
         if (ret < 0)
             goto fail;
     }
 
  fail:
     if (ret < 0) {
1565cbc6
         while (graph->nb_filters)
             avfilter_free(graph->filters[0]);
d7bcc71d
         av_freep(&graph->filters);
     }
91d3cbe0
     avfilter_inout_free(&inputs);
     avfilter_inout_free(&outputs);
838bd731
     avfilter_inout_free(&open_inputs);
     avfilter_inout_free(&open_outputs);
7432bcfe
     return ret;
 #else
838bd731
 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
                          AVFilterInOut **inputs, AVFilterInOut **outputs,
                          void *log_ctx)
 {
     return avfilter_graph_parse_ptr(graph, filters, inputs, outputs, log_ctx);
 #endif
d5de1231
 }
838bd731
 
 int avfilter_graph_parse_ptr(AVFilterGraph *graph, const char *filters,
                          AVFilterInOut **open_inputs_ptr, AVFilterInOut **open_outputs_ptr,
                          void *log_ctx)
 {
df8c675f
     int index = 0, ret = 0;
27afb09d
     char chr = 0;
 
7f9b3266
     AVFilterInOut *curr_inputs = NULL;
df8c675f
     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
27afb09d
 
39747d87
     if ((ret = parse_sws_flags(&filters, graph)) < 0)
         goto end;
 
27afb09d
     do {
9710beaf
         AVFilterContext *filter;
9241cd20
         const char *filterchain = filters;
fd548e5b
         filters += strspn(filters, WHITESPACES);
27afb09d
 
df8c675f
         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)
             goto end;
27afb09d
 
c24f76b9
         if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)
df8c675f
             goto end;
22260824
 
1350a5c4
         if (filter->nb_inputs == 1 && !curr_inputs && !index) {
6ce05bc7
             /* First input pad, assume it is "[in]" if not specified */
c9987633
             const char *tmp = "[in]";
df8c675f
             if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)
                 goto end;
27afb09d
         }
 
df8c675f
         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)
             goto end;
da790674
 
df8c675f
         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
c24f76b9
                                  log_ctx)) < 0)
df8c675f
             goto end;
e84f0b62
 
fd548e5b
         filters += strspn(filters, WHITESPACES);
27afb09d
         chr = *filters++;
 
f219eee5
         if (chr == ';' && curr_inputs) {
c9987633
             av_log(log_ctx, AV_LOG_ERROR,
9241cd20
                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
                    filterchain);
c24f76b9
             ret = AVERROR(EINVAL);
df8c675f
             goto end;
27afb09d
         }
c9987633
         index++;
f219eee5
     } while (chr == ',' || chr == ';');
27afb09d
 
fd51ff16
     if (chr) {
78471234
         av_log(log_ctx, AV_LOG_ERROR,
                "Unable to parse graph description substring: \"%s\"\n",
                filters - 1);
c24f76b9
         ret = AVERROR(EINVAL);
df8c675f
         goto end;
78471234
     }
 
24207636
     if (curr_inputs) {
6ce05bc7
         /* Last output pad, assume it is "[out]" if not specified */
c9987633
         const char *tmp = "[out]";
df8c675f
         if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,
c24f76b9
                                  log_ctx)) < 0)
df8c675f
             goto end;
27afb09d
     }
 
df8c675f
 end:
     /* clear open_in/outputs only if not passed as parameters */
     if (open_inputs_ptr) *open_inputs_ptr = open_inputs;
     else avfilter_inout_free(&open_inputs);
     if (open_outputs_ptr) *open_outputs_ptr = open_outputs;
     else avfilter_inout_free(&open_outputs);
c5354942
     avfilter_inout_free(&curr_inputs);
df8c675f
 
     if (ret < 0) {
6b5ec762
         while (graph->nb_filters)
             avfilter_free(graph->filters[0]);
df8c675f
         av_freep(&graph->filters);
     }
c24f76b9
     return ret;
27afb09d
 }