]> git.sesse.net Git - ffmpeg/blob - libavfilter/graphparser.c
Merge commit 'c68317ebbe4915035df0b08c23eea7a0b80ab881'
[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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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_%s_%d", filt_name, index);
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         && ctx->scale_sws_opts) {
128         snprintf(tmp_args, sizeof(tmp_args), "%s:%s",
129                  args, ctx->scale_sws_opts);
130         args = tmp_args;
131     }
132
133     if ((ret = avfilter_init_filter(*filt_ctx, args, NULL)) < 0) {
134         av_log(log_ctx, AV_LOG_ERROR,
135                "Error initializing filter '%s' with args '%s'\n", filt_name, args);
136         return ret;
137     }
138
139     return 0;
140 }
141
142 /**
143  * Parse a string of the form FILTER_NAME[=PARAMS], and create a
144  * corresponding filter instance which is added to graph with
145  * create_filter().
146  *
147  * @param filt_ctx Pointer that is set to the created and configured filter
148  *                 context on success, set to NULL on failure.
149  * @param filt_ctx put here a pointer to the created filter context on
150  * success, NULL otherwise
151  * @param buf pointer to the buffer to parse, *buf will be updated to
152  * point to the char next after the parsed string
153  * @param index an index which is assigned to the created filter
154  * instance, and which is supposed to be unique for each filter
155  * instance added to the filtergraph
156  * @return 0 in case of success, a negative AVERROR code otherwise
157  */
158 static int parse_filter(AVFilterContext **filt_ctx, const char **buf, AVFilterGraph *graph,
159                         int index, void *log_ctx)
160 {
161     char *opts = NULL;
162     char *name = av_get_token(buf, "=,;[\n");
163     int ret;
164
165     if (**buf == '=') {
166         (*buf)++;
167         opts = av_get_token(buf, "[],;\n");
168     }
169
170     ret = create_filter(filt_ctx, graph, index, name, opts, log_ctx);
171     av_free(name);
172     av_free(opts);
173     return ret;
174 }
175
176 AVFilterInOut *avfilter_inout_alloc(void)
177 {
178     return av_mallocz(sizeof(AVFilterInOut));
179 }
180
181 void avfilter_inout_free(AVFilterInOut **inout)
182 {
183     while (*inout) {
184         AVFilterInOut *next = (*inout)->next;
185         av_freep(&(*inout)->name);
186         av_freep(inout);
187         *inout = next;
188     }
189 }
190
191 static AVFilterInOut *extract_inout(const char *label, AVFilterInOut **links)
192 {
193     AVFilterInOut *ret;
194
195     while (*links && (!(*links)->name || strcmp((*links)->name, label)))
196         links = &((*links)->next);
197
198     ret = *links;
199
200     if (ret) {
201         *links = ret->next;
202         ret->next = NULL;
203     }
204
205     return ret;
206 }
207
208 static void insert_inout(AVFilterInOut **inouts, AVFilterInOut *element)
209 {
210     element->next = *inouts;
211     *inouts = element;
212 }
213
214 static void append_inout(AVFilterInOut **inouts, AVFilterInOut **element)
215 {
216     while (*inouts && (*inouts)->next)
217         inouts = &((*inouts)->next);
218
219     if (!*inouts)
220         *inouts = *element;
221     else
222         (*inouts)->next = *element;
223     *element = NULL;
224 }
225
226 static int link_filter_inouts(AVFilterContext *filt_ctx,
227                               AVFilterInOut **curr_inputs,
228                               AVFilterInOut **open_inputs, void *log_ctx)
229 {
230     int pad, ret;
231
232     for (pad = 0; pad < filt_ctx->nb_inputs; pad++) {
233         AVFilterInOut *p = *curr_inputs;
234
235         if (p) {
236             *curr_inputs = (*curr_inputs)->next;
237             p->next = NULL;
238         } else if (!(p = av_mallocz(sizeof(*p))))
239             return AVERROR(ENOMEM);
240
241         if (p->filter_ctx) {
242             if ((ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx)) < 0)
243                 return ret;
244             av_free(p->name);
245             av_free(p);
246         } else {
247             p->filter_ctx = filt_ctx;
248             p->pad_idx = pad;
249             append_inout(open_inputs, &p);
250         }
251     }
252
253     if (*curr_inputs) {
254         av_log(log_ctx, AV_LOG_ERROR,
255                "Too many inputs specified for the \"%s\" filter.\n",
256                filt_ctx->filter->name);
257         return AVERROR(EINVAL);
258     }
259
260     pad = filt_ctx->nb_outputs;
261     while (pad--) {
262         AVFilterInOut *currlinkn = av_mallocz(sizeof(AVFilterInOut));
263         if (!currlinkn)
264             return AVERROR(ENOMEM);
265         currlinkn->filter_ctx  = filt_ctx;
266         currlinkn->pad_idx = pad;
267         insert_inout(curr_inputs, currlinkn);
268     }
269
270     return 0;
271 }
272
273 static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,
274                         AVFilterInOut **open_outputs, void *log_ctx)
275 {
276     AVFilterInOut *parsed_inputs = NULL;
277     int pad = 0;
278
279     while (**buf == '[') {
280         char *name = parse_link_name(buf, log_ctx);
281         AVFilterInOut *match;
282
283         if (!name)
284             return AVERROR(EINVAL);
285
286         /* First check if the label is not in the open_outputs list */
287         match = extract_inout(name, open_outputs);
288
289         if (match) {
290             av_free(name);
291         } else {
292             /* Not in the list, so add it as an input */
293             if (!(match = av_mallocz(sizeof(AVFilterInOut))))
294                 return AVERROR(ENOMEM);
295             match->name    = name;
296             match->pad_idx = pad;
297         }
298
299         append_inout(&parsed_inputs, &match);
300
301         *buf += strspn(*buf, WHITESPACES);
302         pad++;
303     }
304
305     append_inout(&parsed_inputs, curr_inputs);
306     *curr_inputs = parsed_inputs;
307
308     return pad;
309 }
310
311 static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,
312                          AVFilterInOut **open_inputs,
313                          AVFilterInOut **open_outputs, void *log_ctx)
314 {
315     int ret, pad = 0;
316
317     while (**buf == '[') {
318         char *name = parse_link_name(buf, log_ctx);
319         AVFilterInOut *match;
320
321         AVFilterInOut *input = *curr_inputs;
322         if (!input) {
323             av_log(log_ctx, AV_LOG_ERROR,
324                    "No output pad can be associated to link label '%s'.\n",
325                    name);
326             return AVERROR(EINVAL);
327         }
328         *curr_inputs = (*curr_inputs)->next;
329
330         if (!name)
331             return AVERROR(EINVAL);
332
333         /* First check if the label is not in the open_inputs list */
334         match = extract_inout(name, open_inputs);
335
336         if (match) {
337             if ((ret = link_filter(input->filter_ctx, input->pad_idx,
338                                    match->filter_ctx, match->pad_idx, log_ctx)) < 0)
339                 return ret;
340             av_free(match->name);
341             av_free(name);
342             av_free(match);
343             av_free(input);
344         } else {
345             /* Not in the list, so add the first input as a open_output */
346             input->name = name;
347             insert_inout(open_outputs, input);
348         }
349         *buf += strspn(*buf, WHITESPACES);
350         pad++;
351     }
352
353     return pad;
354 }
355
356 static int parse_sws_flags(const char **buf, AVFilterGraph *graph)
357 {
358     char *p = strchr(*buf, ';');
359
360     if (strncmp(*buf, "sws_flags=", 10))
361         return 0;
362
363     if (!p) {
364         av_log(graph, AV_LOG_ERROR, "sws_flags not terminated with ';'.\n");
365         return AVERROR(EINVAL);
366     }
367
368     *buf += 4;  // keep the 'flags=' part
369
370     av_freep(&graph->scale_sws_opts);
371     if (!(graph->scale_sws_opts = av_mallocz(p - *buf + 1)))
372         return AVERROR(ENOMEM);
373     av_strlcpy(graph->scale_sws_opts, *buf, p - *buf + 1);
374
375     *buf = p + 1;
376     return 0;
377 }
378
379 int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters,
380                           AVFilterInOut **inputs,
381                           AVFilterInOut **outputs)
382 {
383     int index = 0, ret = 0;
384     char chr = 0;
385
386     AVFilterInOut *curr_inputs = NULL, *open_inputs = NULL, *open_outputs = NULL;
387
388     filters += strspn(filters, WHITESPACES);
389
390     if ((ret = parse_sws_flags(&filters, graph)) < 0)
391         goto fail;
392
393     do {
394         AVFilterContext *filter;
395         filters += strspn(filters, WHITESPACES);
396
397         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, graph)) < 0)
398             goto end;
399         if ((ret = parse_filter(&filter, &filters, graph, index, graph)) < 0)
400             goto end;
401
402
403         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, graph)) < 0)
404             goto end;
405
406         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
407                                  graph)) < 0)
408             goto end;
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 end;
424     }
425
426     append_inout(&open_outputs, &curr_inputs);
427
428
429     *inputs  = open_inputs;
430     *outputs = open_outputs;
431     return 0;
432
433  fail:end:
434     for (; graph->filter_count > 0; graph->filter_count--)
435         avfilter_free(graph->filters[graph->filter_count - 1]);
436     av_freep(&graph->filters);
437     avfilter_inout_free(&open_inputs);
438     avfilter_inout_free(&open_outputs);
439     avfilter_inout_free(&curr_inputs);
440
441     *inputs  = NULL;
442     *outputs = NULL;
443
444     return ret;
445 }
446
447 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
448                          AVFilterInOut **open_inputs_ptr, AVFilterInOut **open_outputs_ptr,
449                          void *log_ctx)
450 {
451 #if 0
452     int ret;
453     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
454     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
455     AVFilterInOut *cur, *match, *inputs = NULL, *outputs = NULL;
456
457     if ((ret = avfilter_graph_parse2(graph, filters, &inputs, &outputs)) < 0)
458         goto fail;
459
460     /* First input can be omitted if it is "[in]" */
461     if (inputs && !inputs->name)
462         inputs->name = av_strdup("in");
463     for (cur = inputs; cur; cur = cur->next) {
464         if (!cur->name) {
465               av_log(log_ctx, AV_LOG_ERROR,
466                      "Not enough inputs specified for the \"%s\" filter.\n",
467                      cur->filter_ctx->filter->name);
468               ret = AVERROR(EINVAL);
469               goto fail;
470         }
471         if (!(match = extract_inout(cur->name, &open_outputs)))
472             continue;
473         ret = avfilter_link(match->filter_ctx, match->pad_idx,
474                             cur->filter_ctx,   cur->pad_idx);
475         avfilter_inout_free(&match);
476         if (ret < 0)
477             goto fail;
478     }
479
480     /* Last output can be omitted if it is "[out]" */
481     if (outputs && !outputs->name)
482         outputs->name = av_strdup("out");
483     for (cur = outputs; cur; cur = cur->next) {
484         if (!cur->name) {
485             av_log(log_ctx, AV_LOG_ERROR,
486                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
487                    filters);
488             ret = AVERROR(EINVAL);
489             goto fail;
490         }
491         if (!(match = extract_inout(cur->name, &open_inputs)))
492             continue;
493         ret = avfilter_link(cur->filter_ctx,   cur->pad_idx,
494                             match->filter_ctx, match->pad_idx);
495         avfilter_inout_free(&match);
496         if (ret < 0)
497             goto fail;
498     }
499
500  fail:
501     if (ret < 0) {
502         for (; graph->filter_count > 0; graph->filter_count--)
503             avfilter_free(graph->filters[graph->filter_count - 1]);
504         av_freep(&graph->filters);
505     }
506     avfilter_inout_free(&inputs);
507     avfilter_inout_free(&outputs);
508     /* clear open_in/outputs only if not passed as parameters */
509     if (open_inputs_ptr) *open_inputs_ptr = open_inputs;
510     else avfilter_inout_free(&open_inputs);
511     if (open_outputs_ptr) *open_outputs_ptr = open_outputs;
512     else avfilter_inout_free(&open_outputs);
513     return ret;
514 }
515 #else
516     int index = 0, ret = 0;
517     char chr = 0;
518
519     AVFilterInOut *curr_inputs = NULL;
520     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
521     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
522
523     if ((ret = parse_sws_flags(&filters, graph)) < 0)
524         goto end;
525
526     do {
527         AVFilterContext *filter;
528         const char *filterchain = filters;
529         filters += strspn(filters, WHITESPACES);
530
531         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)
532             goto end;
533
534         if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)
535             goto end;
536
537         if (filter->input_count == 1 && !curr_inputs && !index) {
538             /* First input pad, assume it is "[in]" if not specified */
539             const char *tmp = "[in]";
540             if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)
541                 goto end;
542         }
543
544         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)
545             goto end;
546
547         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
548                                  log_ctx)) < 0)
549             goto end;
550
551         filters += strspn(filters, WHITESPACES);
552         chr = *filters++;
553
554         if (chr == ';' && curr_inputs) {
555             av_log(log_ctx, AV_LOG_ERROR,
556                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
557                    filterchain);
558             ret = AVERROR(EINVAL);
559             goto end;
560         }
561         index++;
562     } while (chr == ',' || chr == ';');
563
564     if (chr) {
565         av_log(log_ctx, AV_LOG_ERROR,
566                "Unable to parse graph description substring: \"%s\"\n",
567                filters - 1);
568         ret = AVERROR(EINVAL);
569         goto end;
570     }
571
572     if (curr_inputs) {
573         /* Last output pad, assume it is "[out]" if not specified */
574         const char *tmp = "[out]";
575         if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,
576                                  log_ctx)) < 0)
577             goto end;
578     }
579
580 end:
581     /* clear open_in/outputs only if not passed as parameters */
582     if (open_inputs_ptr) *open_inputs_ptr = open_inputs;
583     else avfilter_inout_free(&open_inputs);
584     if (open_outputs_ptr) *open_outputs_ptr = open_outputs;
585     else avfilter_inout_free(&open_outputs);
586     avfilter_inout_free(&curr_inputs);
587
588     if (ret < 0) {
589         for (; graph->filter_count > 0; graph->filter_count--)
590             avfilter_free(graph->filters[graph->filter_count - 1]);
591         av_freep(&graph->filters);
592     }
593     return ret;
594 }
595
596 #endif