]> git.sesse.net Git - ffmpeg/blob - libavfilter/graphparser.c
avfilter: x86: Use more precise compile template names
[ffmpeg] / libavfilter / graphparser.c
1 /*
2  * filter graph parser
3  * Copyright (c) 2008 Vitor Sessak
4  * Copyright (c) 2007 Bobby Bingham
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <ctype.h>
24 #include <string.h>
25 #include <stdio.h>
26
27 #include "libavutil/avstring.h"
28 #include "libavutil/mem.h"
29 #include "avfilter.h"
30 #include "avfiltergraph.h"
31
32 #define WHITESPACES " \n\t"
33
34 /**
35  * Link two filters together.
36  *
37  * @see avfilter_link()
38  */
39 static int link_filter(AVFilterContext *src, int srcpad,
40                        AVFilterContext *dst, int dstpad,
41                        void *log_ctx)
42 {
43     int ret;
44     if ((ret = avfilter_link(src, srcpad, dst, dstpad))) {
45         av_log(log_ctx, AV_LOG_ERROR,
46                "Cannot create the link %s:%d -> %s:%d\n",
47                src->filter->name, srcpad, dst->filter->name, dstpad);
48         return ret;
49     }
50
51     return 0;
52 }
53
54 /**
55  * Parse the name of a link, which has the format "[linkname]".
56  *
57  * @return a pointer (that need to be freed after use) to the name
58  * between parenthesis
59  */
60 static char *parse_link_name(const char **buf, void *log_ctx)
61 {
62     const char *start = *buf;
63     char *name;
64     (*buf)++;
65
66     name = av_get_token(buf, "]");
67
68     if (!name[0]) {
69         av_log(log_ctx, AV_LOG_ERROR,
70                "Bad (empty?) label found in the following: \"%s\".\n", start);
71         goto fail;
72     }
73
74     if (*(*buf)++ != ']') {
75         av_log(log_ctx, AV_LOG_ERROR,
76                "Mismatched '[' found in the following: \"%s\".\n", start);
77     fail:
78         av_freep(&name);
79     }
80
81     return name;
82 }
83
84 /**
85  * Create an instance of a filter, initialize and insert it in the
86  * filtergraph in *ctx.
87  *
88  * @param filt_ctx put here a filter context in case of successful creation and configuration, NULL otherwise.
89  * @param ctx the filtergraph context
90  * @param index an index which is supposed to be unique for each filter instance added to the filtergraph
91  * @param filt_name the name of the filter to create
92  * @param args the arguments provided to the filter during its initialization
93  * @param log_ctx the log context to use
94  * @return 0 in case of success, a negative AVERROR code otherwise
95  */
96 static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index,
97                          const char *filt_name, const char *args, void *log_ctx)
98 {
99     AVFilter *filt;
100     char inst_name[30];
101     char tmp_args[256];
102     int ret;
103
104     snprintf(inst_name, sizeof(inst_name), "Parsed filter %d %s", index, filt_name);
105
106     filt = avfilter_get_by_name(filt_name);
107
108     if (!filt) {
109         av_log(log_ctx, AV_LOG_ERROR,
110                "No such filter: '%s'\n", filt_name);
111         return AVERROR(EINVAL);
112     }
113
114     ret = avfilter_open(filt_ctx, filt, inst_name);
115     if (!*filt_ctx) {
116         av_log(log_ctx, AV_LOG_ERROR,
117                "Error creating filter '%s'\n", filt_name);
118         return ret;
119     }
120
121     if ((ret = avfilter_graph_add_filter(ctx, *filt_ctx)) < 0) {
122         avfilter_free(*filt_ctx);
123         return ret;
124     }
125
126     if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags")) {
127         snprintf(tmp_args, sizeof(tmp_args), "%s:%s",
128                  args, ctx->scale_sws_opts);
129         args = tmp_args;
130     }
131
132     if ((ret = avfilter_init_filter(*filt_ctx, args, NULL)) < 0) {
133         av_log(log_ctx, AV_LOG_ERROR,
134                "Error initializing filter '%s' with args '%s'\n", filt_name, args);
135         return ret;
136     }
137
138     return 0;
139 }
140
141 /**
142  * Parse a string of the form FILTER_NAME[=PARAMS], and create a
143  * corresponding filter instance which is added to graph with
144  * create_filter().
145  *
146  * @param filt_ctx Pointer that is set to the created and configured filter
147  *                 context on success, set to NULL on failure.
148  * @param filt_ctx put here a pointer to the created filter context on
149  * success, NULL otherwise
150  * @param buf pointer to the buffer to parse, *buf will be updated to
151  * point to the char next after the parsed string
152  * @param index an index which is assigned to the created filter
153  * instance, and which is supposed to be unique for each filter
154  * instance added to the filtergraph
155  * @return 0 in case of success, a negative AVERROR code otherwise
156  */
157 static int parse_filter(AVFilterContext **filt_ctx, const char **buf, AVFilterGraph *graph,
158                         int index, void *log_ctx)
159 {
160     char *opts = NULL;
161     char *name = av_get_token(buf, "=,;[\n");
162     int ret;
163
164     if (**buf == '=') {
165         (*buf)++;
166         opts = av_get_token(buf, "[],;\n");
167     }
168
169     ret = create_filter(filt_ctx, graph, index, name, opts, log_ctx);
170     av_free(name);
171     av_free(opts);
172     return ret;
173 }
174
175 AVFilterInOut *avfilter_inout_alloc(void)
176 {
177     return av_mallocz(sizeof(AVFilterInOut));
178 }
179
180 void avfilter_inout_free(AVFilterInOut **inout)
181 {
182     while (*inout) {
183         AVFilterInOut *next = (*inout)->next;
184         av_freep(&(*inout)->name);
185         av_freep(inout);
186         *inout = next;
187     }
188 }
189
190 static AVFilterInOut *extract_inout(const char *label, AVFilterInOut **links)
191 {
192     AVFilterInOut *ret;
193
194     while (*links && (!(*links)->name || strcmp((*links)->name, label)))
195         links = &((*links)->next);
196
197     ret = *links;
198
199     if (ret) {
200         *links = ret->next;
201         ret->next = NULL;
202     }
203
204     return ret;
205 }
206
207 static void insert_inout(AVFilterInOut **inouts, AVFilterInOut *element)
208 {
209     element->next = *inouts;
210     *inouts = element;
211 }
212
213 static void append_inout(AVFilterInOut **inouts, AVFilterInOut **element)
214 {
215     while (*inouts && (*inouts)->next)
216         inouts = &((*inouts)->next);
217
218     if (!*inouts)
219         *inouts = *element;
220     else
221         (*inouts)->next = *element;
222     *element = NULL;
223 }
224
225 static int link_filter_inouts(AVFilterContext *filt_ctx,
226                               AVFilterInOut **curr_inputs,
227                               AVFilterInOut **open_inputs, void *log_ctx)
228 {
229     int pad, ret;
230
231     for (pad = 0; pad < filt_ctx->nb_inputs; pad++) {
232         AVFilterInOut *p = *curr_inputs;
233
234         if (p) {
235             *curr_inputs = (*curr_inputs)->next;
236             p->next = NULL;
237         } else if (!(p = av_mallocz(sizeof(*p))))
238             return AVERROR(ENOMEM);
239
240         if (p->filter_ctx) {
241             if ((ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx)) < 0)
242                 return ret;
243             av_free(p->name);
244             av_free(p);
245         } else {
246             p->filter_ctx = filt_ctx;
247             p->pad_idx = pad;
248             append_inout(open_inputs, &p);
249         }
250     }
251
252     if (*curr_inputs) {
253         av_log(log_ctx, AV_LOG_ERROR,
254                "Too many inputs specified for the \"%s\" filter.\n",
255                filt_ctx->filter->name);
256         return AVERROR(EINVAL);
257     }
258
259     pad = filt_ctx->nb_outputs;
260     while (pad--) {
261         AVFilterInOut *currlinkn = av_mallocz(sizeof(AVFilterInOut));
262         if (!currlinkn)
263             return AVERROR(ENOMEM);
264         currlinkn->filter_ctx  = filt_ctx;
265         currlinkn->pad_idx = pad;
266         insert_inout(curr_inputs, currlinkn);
267     }
268
269     return 0;
270 }
271
272 static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,
273                         AVFilterInOut **open_outputs, void *log_ctx)
274 {
275     AVFilterInOut *parsed_inputs = NULL;
276     int pad = 0;
277
278     while (**buf == '[') {
279         char *name = parse_link_name(buf, log_ctx);
280         AVFilterInOut *match;
281
282         if (!name)
283             return AVERROR(EINVAL);
284
285         /* First check if the label is not in the open_outputs list */
286         match = extract_inout(name, open_outputs);
287
288         if (match) {
289             av_free(name);
290         } else {
291             /* Not in the list, so add it as an input */
292             if (!(match = av_mallocz(sizeof(AVFilterInOut))))
293                 return AVERROR(ENOMEM);
294             match->name    = name;
295             match->pad_idx = pad;
296         }
297
298         append_inout(&parsed_inputs, &match);
299
300         *buf += strspn(*buf, WHITESPACES);
301         pad++;
302     }
303
304     append_inout(&parsed_inputs, curr_inputs);
305     *curr_inputs = parsed_inputs;
306
307     return pad;
308 }
309
310 static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,
311                          AVFilterInOut **open_inputs,
312                          AVFilterInOut **open_outputs, void *log_ctx)
313 {
314     int ret, pad = 0;
315
316     while (**buf == '[') {
317         char *name = parse_link_name(buf, log_ctx);
318         AVFilterInOut *match;
319
320         AVFilterInOut *input = *curr_inputs;
321         if (!input) {
322             av_log(log_ctx, AV_LOG_ERROR,
323                    "No output pad can be associated to link label '%s'.\n",
324                    name);
325             return AVERROR(EINVAL);
326         }
327         *curr_inputs = (*curr_inputs)->next;
328
329         if (!name)
330             return AVERROR(EINVAL);
331
332         /* First check if the label is not in the open_inputs list */
333         match = extract_inout(name, open_inputs);
334
335         if (match) {
336             if ((ret = link_filter(input->filter_ctx, input->pad_idx,
337                                    match->filter_ctx, match->pad_idx, log_ctx)) < 0)
338                 return ret;
339             av_free(match->name);
340             av_free(name);
341             av_free(match);
342             av_free(input);
343         } else {
344             /* Not in the list, so add the first input as a open_output */
345             input->name = name;
346             insert_inout(open_outputs, input);
347         }
348         *buf += strspn(*buf, WHITESPACES);
349         pad++;
350     }
351
352     return pad;
353 }
354
355 static int parse_sws_flags(const char **buf, AVFilterGraph *graph)
356 {
357     char *p = strchr(*buf, ';');
358
359     if (strncmp(*buf, "sws_flags=", 10))
360         return 0;
361
362     if (!p) {
363         av_log(graph, AV_LOG_ERROR, "sws_flags not terminated with ';'.\n");
364         return AVERROR(EINVAL);
365     }
366
367     *buf += 4;  // keep the 'flags=' part
368
369     av_freep(&graph->scale_sws_opts);
370     if (!(graph->scale_sws_opts = av_mallocz(p - *buf + 1)))
371         return AVERROR(ENOMEM);
372     av_strlcpy(graph->scale_sws_opts, *buf, p - *buf + 1);
373
374     *buf = p + 1;
375     return 0;
376 }
377
378 int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters,
379                           AVFilterInOut **inputs,
380                           AVFilterInOut **outputs)
381 {
382     int index = 0, ret;
383     char chr = 0;
384
385     AVFilterInOut *curr_inputs = NULL, *open_inputs = NULL, *open_outputs = NULL;
386
387     filters += strspn(filters, WHITESPACES);
388
389     if ((ret = parse_sws_flags(&filters, graph)) < 0)
390         goto fail;
391
392     do {
393         AVFilterContext *filter;
394         filters += strspn(filters, WHITESPACES);
395
396         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, graph)) < 0)
397             goto fail;
398
399         if ((ret = parse_filter(&filter, &filters, graph, index, graph)) < 0)
400             goto fail;
401
402
403         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, graph)) < 0)
404             goto fail;
405
406         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
407                                  graph)) < 0)
408             goto fail;
409
410         filters += strspn(filters, WHITESPACES);
411         chr = *filters++;
412
413         if (chr == ';' && curr_inputs)
414             append_inout(&open_outputs, &curr_inputs);
415         index++;
416     } while (chr == ',' || chr == ';');
417
418     if (chr) {
419         av_log(graph, AV_LOG_ERROR,
420                "Unable to parse graph description substring: \"%s\"\n",
421                filters - 1);
422         ret = AVERROR(EINVAL);
423         goto fail;
424     }
425
426     append_inout(&open_outputs, &curr_inputs);
427
428     *inputs  = open_inputs;
429     *outputs = open_outputs;
430     return 0;
431
432  fail:
433     for (; graph->filter_count > 0; graph->filter_count--)
434         avfilter_free(graph->filters[graph->filter_count - 1]);
435     av_freep(&graph->filters);
436     avfilter_inout_free(&open_inputs);
437     avfilter_inout_free(&open_outputs);
438     avfilter_inout_free(&curr_inputs);
439
440     *inputs  = NULL;
441     *outputs = NULL;
442
443     return ret;
444 }
445
446 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
447                          AVFilterInOut *open_inputs,
448                          AVFilterInOut *open_outputs, void *log_ctx)
449 {
450     int ret;
451     AVFilterInOut *cur, *match, *inputs = NULL, *outputs = NULL;
452
453     if ((ret = avfilter_graph_parse2(graph, filters, &inputs, &outputs)) < 0)
454         goto fail;
455
456     /* First input can be omitted if it is "[in]" */
457     if (inputs && !inputs->name)
458         inputs->name = av_strdup("in");
459     for (cur = inputs; cur; cur = cur->next) {
460         if (!cur->name) {
461               av_log(log_ctx, AV_LOG_ERROR,
462                      "Not enough inputs specified for the \"%s\" filter.\n",
463                      cur->filter_ctx->filter->name);
464               ret = AVERROR(EINVAL);
465               goto fail;
466         }
467         if (!(match = extract_inout(cur->name, &open_outputs)))
468             continue;
469         ret = avfilter_link(match->filter_ctx, match->pad_idx,
470                             cur->filter_ctx,   cur->pad_idx);
471         avfilter_inout_free(&match);
472         if (ret < 0)
473             goto fail;
474     }
475
476     /* Last output can be omitted if it is "[out]" */
477     if (outputs && !outputs->name)
478         outputs->name = av_strdup("out");
479     for (cur = outputs; cur; cur = cur->next) {
480         if (!cur->name) {
481             av_log(log_ctx, AV_LOG_ERROR,
482                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
483                    filters);
484             ret = AVERROR(EINVAL);
485             goto fail;
486         }
487         if (!(match = extract_inout(cur->name, &open_inputs)))
488             continue;
489         ret = avfilter_link(cur->filter_ctx,   cur->pad_idx,
490                             match->filter_ctx, match->pad_idx);
491         avfilter_inout_free(&match);
492         if (ret < 0)
493             goto fail;
494     }
495
496  fail:
497     if (ret < 0) {
498         for (; graph->filter_count > 0; graph->filter_count--)
499             avfilter_free(graph->filters[graph->filter_count - 1]);
500         av_freep(&graph->filters);
501     }
502     avfilter_inout_free(&inputs);
503     avfilter_inout_free(&outputs);
504     avfilter_inout_free(&open_inputs);
505     avfilter_inout_free(&open_outputs);
506     return ret;
507 }