]> git.sesse.net Git - ffmpeg/blob - libavfilter/graphparser.c
Merge remote-tracking branch 'qatar/master'
[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
26 #include "libavutil/avstring.h"
27 #include "avfilter.h"
28 #include "avfiltergraph.h"
29
30 #define WHITESPACES " \n\t"
31
32 /**
33  * Link two filters together.
34  *
35  * @see avfilter_link()
36  */
37 static int link_filter(AVFilterContext *src, int srcpad,
38                        AVFilterContext *dst, int dstpad,
39                        void *log_ctx)
40 {
41     int ret;
42     if ((ret = avfilter_link(src, srcpad, dst, dstpad))) {
43         av_log(log_ctx, AV_LOG_ERROR,
44                "Cannot create the link %s:%d -> %s:%d\n",
45                src->filter->name, srcpad, dst->filter->name, dstpad);
46         return ret;
47     }
48
49     return 0;
50 }
51
52 /**
53  * Parse the name of a link, which has the format "[linkname]".
54  *
55  * @return a pointer (that need to be freed after use) to the name
56  * between parenthesis
57  */
58 static char *parse_link_name(const char **buf, void *log_ctx)
59 {
60     const char *start = *buf;
61     char *name;
62     (*buf)++;
63
64     name = av_get_token(buf, "]");
65
66     if (!name[0]) {
67         av_log(log_ctx, AV_LOG_ERROR,
68                "Bad (empty?) label found in the following: \"%s\".\n", start);
69         goto fail;
70     }
71
72     if (*(*buf)++ != ']') {
73         av_log(log_ctx, AV_LOG_ERROR,
74                "Mismatched '[' found in the following: \"%s\".\n", start);
75     fail:
76         av_freep(&name);
77     }
78
79     return name;
80 }
81
82 /**
83  * Create an instance of a filter, initialize and insert it in the
84  * filtergraph in *ctx.
85  *
86  * @param filt_ctx put here a filter context in case of successful creation and configuration, NULL otherwise.
87  * @param ctx the filtergraph context
88  * @param index an index which is supposed to be unique for each filter instance added to the filtergraph
89  * @param filt_name the name of the filter to create
90  * @param args the arguments provided to the filter during its initialization
91  * @param log_ctx the log context to use
92  * @return 0 in case of success, a negative AVERROR code otherwise
93  */
94 static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index,
95                          const char *filt_name, const char *args, void *log_ctx)
96 {
97     AVFilter *filt;
98     char inst_name[30];
99     char tmp_args[256];
100     int ret;
101
102     snprintf(inst_name, sizeof(inst_name), "Parsed_%s_%d", filt_name, index);
103
104     filt = avfilter_get_by_name(filt_name);
105
106     if (!filt) {
107         av_log(log_ctx, AV_LOG_ERROR,
108                "No such filter: '%s'\n", filt_name);
109         return AVERROR(EINVAL);
110     }
111
112     ret = avfilter_open(filt_ctx, filt, inst_name);
113     if (!*filt_ctx) {
114         av_log(log_ctx, AV_LOG_ERROR,
115                "Error creating filter '%s'\n", filt_name);
116         return ret;
117     }
118
119     if ((ret = avfilter_graph_add_filter(ctx, *filt_ctx)) < 0) {
120         avfilter_free(*filt_ctx);
121         return ret;
122     }
123
124     if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags")) {
125         snprintf(tmp_args, sizeof(tmp_args), "%s:%s",
126                  args, ctx->scale_sws_opts);
127         args = tmp_args;
128     }
129
130     if ((ret = avfilter_init_filter(*filt_ctx, args, NULL)) < 0) {
131         av_log(log_ctx, AV_LOG_ERROR,
132                "Error initializing filter '%s' with args '%s'\n", filt_name, args);
133         return ret;
134     }
135
136     return 0;
137 }
138
139 /**
140  * Parse a string of the form FILTER_NAME[=PARAMS], and create a
141  * corresponding filter instance which is added to graph with
142  * create_filter().
143  *
144  * @param filt_ctx Pointer that is set to the created and configured filter
145  *                 context on success, set to NULL on failure.
146  * @param filt_ctx put here a pointer to the created filter context on
147  * success, NULL otherwise
148  * @param buf pointer to the buffer to parse, *buf will be updated to
149  * point to the char next after the parsed string
150  * @param index an index which is assigned to the created filter
151  * instance, and which is supposed to be unique for each filter
152  * instance added to the filtergraph
153  * @return 0 in case of success, a negative AVERROR code otherwise
154  */
155 static int parse_filter(AVFilterContext **filt_ctx, const char **buf, AVFilterGraph *graph,
156                         int index, void *log_ctx)
157 {
158     char *opts = NULL;
159     char *name = av_get_token(buf, "=,;[\n");
160     int ret;
161
162     if (**buf == '=') {
163         (*buf)++;
164         opts = av_get_token(buf, "[],;\n");
165     }
166
167     ret = create_filter(filt_ctx, graph, index, name, opts, log_ctx);
168     av_free(name);
169     av_free(opts);
170     return ret;
171 }
172
173 AVFilterInOut *avfilter_inout_alloc(void)
174 {
175     return av_mallocz(sizeof(AVFilterInOut));
176 }
177
178 void avfilter_inout_free(AVFilterInOut **inout)
179 {
180     while (*inout) {
181         AVFilterInOut *next = (*inout)->next;
182         av_freep(&(*inout)->name);
183         av_freep(inout);
184         *inout = next;
185     }
186 }
187
188 static AVFilterInOut *extract_inout(const char *label, AVFilterInOut **links)
189 {
190     AVFilterInOut *ret;
191
192     while (*links && (!(*links)->name || strcmp((*links)->name, label)))
193         links = &((*links)->next);
194
195     ret = *links;
196
197     if (ret) {
198         *links = ret->next;
199         ret->next = NULL;
200     }
201
202     return ret;
203 }
204
205 static void insert_inout(AVFilterInOut **inouts, AVFilterInOut *element)
206 {
207     element->next = *inouts;
208     *inouts = element;
209 }
210
211 static void append_inout(AVFilterInOut **inouts, AVFilterInOut **element)
212 {
213     while (*inouts && (*inouts)->next)
214         inouts = &((*inouts)->next);
215
216     if (!*inouts)
217         *inouts = *element;
218     else
219         (*inouts)->next = *element;
220     *element = NULL;
221 }
222
223 static int link_filter_inouts(AVFilterContext *filt_ctx,
224                               AVFilterInOut **curr_inputs,
225                               AVFilterInOut **open_inputs, void *log_ctx)
226 {
227     int pad, ret;
228
229     for (pad = 0; pad < filt_ctx->nb_inputs; pad++) {
230         AVFilterInOut *p = *curr_inputs;
231
232         if (p) {
233             *curr_inputs = (*curr_inputs)->next;
234             p->next = NULL;
235         } else if (!(p = av_mallocz(sizeof(*p))))
236             return AVERROR(ENOMEM);
237
238         if (p->filter_ctx) {
239             if ((ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx)) < 0)
240                 return ret;
241             av_free(p->name);
242             av_free(p);
243         } else {
244             p->filter_ctx = filt_ctx;
245             p->pad_idx = pad;
246             append_inout(open_inputs, &p);
247         }
248     }
249
250     if (*curr_inputs) {
251         av_log(log_ctx, AV_LOG_ERROR,
252                "Too many inputs specified for the \"%s\" filter.\n",
253                filt_ctx->filter->name);
254         return AVERROR(EINVAL);
255     }
256
257     pad = filt_ctx->nb_outputs;
258     while (pad--) {
259         AVFilterInOut *currlinkn = av_mallocz(sizeof(AVFilterInOut));
260         if (!currlinkn)
261             return AVERROR(ENOMEM);
262         currlinkn->filter_ctx  = filt_ctx;
263         currlinkn->pad_idx = pad;
264         insert_inout(curr_inputs, currlinkn);
265     }
266
267     return 0;
268 }
269
270 static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,
271                         AVFilterInOut **open_outputs, void *log_ctx)
272 {
273     AVFilterInOut *parsed_inputs = NULL;
274     int pad = 0;
275
276     while (**buf == '[') {
277         char *name = parse_link_name(buf, log_ctx);
278         AVFilterInOut *match;
279
280         if (!name)
281             return AVERROR(EINVAL);
282
283         /* First check if the label is not in the open_outputs list */
284         match = extract_inout(name, open_outputs);
285
286         if (match) {
287             av_free(name);
288         } else {
289             /* Not in the list, so add it as an input */
290             if (!(match = av_mallocz(sizeof(AVFilterInOut))))
291                 return AVERROR(ENOMEM);
292             match->name    = name;
293             match->pad_idx = pad;
294         }
295
296         append_inout(&parsed_inputs, &match);
297
298         *buf += strspn(*buf, WHITESPACES);
299         pad++;
300     }
301
302     append_inout(&parsed_inputs, curr_inputs);
303     *curr_inputs = parsed_inputs;
304
305     return pad;
306 }
307
308 static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,
309                          AVFilterInOut **open_inputs,
310                          AVFilterInOut **open_outputs, void *log_ctx)
311 {
312     int ret, pad = 0;
313
314     while (**buf == '[') {
315         char *name = parse_link_name(buf, log_ctx);
316         AVFilterInOut *match;
317
318         AVFilterInOut *input = *curr_inputs;
319         if (!input) {
320             av_log(log_ctx, AV_LOG_ERROR,
321                    "No output pad can be associated to link label '%s'.\n",
322                    name);
323             return AVERROR(EINVAL);
324         }
325         *curr_inputs = (*curr_inputs)->next;
326
327         if (!name)
328             return AVERROR(EINVAL);
329
330         /* First check if the label is not in the open_inputs list */
331         match = extract_inout(name, open_inputs);
332
333         if (match) {
334             if ((ret = link_filter(input->filter_ctx, input->pad_idx,
335                                    match->filter_ctx, match->pad_idx, log_ctx)) < 0)
336                 return ret;
337             av_free(match->name);
338             av_free(name);
339             av_free(match);
340             av_free(input);
341         } else {
342             /* Not in the list, so add the first input as a open_output */
343             input->name = name;
344             insert_inout(open_outputs, input);
345         }
346         *buf += strspn(*buf, WHITESPACES);
347         pad++;
348     }
349
350     return pad;
351 }
352
353 static int parse_sws_flags(const char **buf, AVFilterGraph *graph)
354 {
355     char *p = strchr(*buf, ';');
356
357     if (strncmp(*buf, "sws_flags=", 10))
358         return 0;
359
360     if (!p) {
361         av_log(graph, AV_LOG_ERROR, "sws_flags not terminated with ';'.\n");
362         return AVERROR(EINVAL);
363     }
364
365     *buf += 4;  // keep the 'flags=' part
366
367     av_freep(&graph->scale_sws_opts);
368     if (!(graph->scale_sws_opts = av_mallocz(p - *buf + 1)))
369         return AVERROR(ENOMEM);
370     av_strlcpy(graph->scale_sws_opts, *buf, p - *buf + 1);
371
372     *buf = p + 1;
373     return 0;
374 }
375
376 int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters,
377                           AVFilterInOut **inputs,
378                           AVFilterInOut **outputs)
379 {
380     int index = 0, ret = 0;
381     char chr = 0;
382
383     AVFilterInOut *curr_inputs = NULL, *open_inputs = NULL, *open_outputs = NULL;
384
385     filters += strspn(filters, WHITESPACES);
386
387     if ((ret = parse_sws_flags(&filters, graph)) < 0)
388         goto fail;
389
390     do {
391         AVFilterContext *filter;
392         filters += strspn(filters, WHITESPACES);
393
394         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, graph)) < 0)
395             goto end;
396         if ((ret = parse_filter(&filter, &filters, graph, index, graph)) < 0)
397             goto end;
398
399
400         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, graph)) < 0)
401             goto end;
402
403         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
404                                  graph)) < 0)
405             goto end;
406
407         filters += strspn(filters, WHITESPACES);
408         chr = *filters++;
409
410         if (chr == ';' && curr_inputs)
411             append_inout(&open_outputs, &curr_inputs);
412         index++;
413     } while (chr == ',' || chr == ';');
414
415     if (chr) {
416         av_log(graph, AV_LOG_ERROR,
417                "Unable to parse graph description substring: \"%s\"\n",
418                filters - 1);
419         ret = AVERROR(EINVAL);
420         goto end;
421     }
422
423     append_inout(&open_outputs, &curr_inputs);
424
425
426     *inputs  = open_inputs;
427     *outputs = open_outputs;
428     return 0;
429
430  fail:end:
431     for (; graph->filter_count > 0; graph->filter_count--)
432         avfilter_free(graph->filters[graph->filter_count - 1]);
433     av_freep(&graph->filters);
434     avfilter_inout_free(&open_inputs);
435     avfilter_inout_free(&open_outputs);
436     avfilter_inout_free(&curr_inputs);
437
438     *inputs  = NULL;
439     *outputs = NULL;
440
441     return ret;
442 }
443
444 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
445                          AVFilterInOut **open_inputs_ptr, AVFilterInOut **open_outputs_ptr,
446                          void *log_ctx)
447 {
448 #if 0
449     int ret;
450     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
451     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
452     AVFilterInOut *cur, *match, *inputs = NULL, *outputs = NULL;
453
454     if ((ret = avfilter_graph_parse2(graph, filters, &inputs, &outputs)) < 0)
455         goto fail;
456
457     /* First input can be omitted if it is "[in]" */
458     if (inputs && !inputs->name)
459         inputs->name = av_strdup("in");
460     for (cur = inputs; cur; cur = cur->next) {
461         if (!cur->name) {
462               av_log(log_ctx, AV_LOG_ERROR,
463                      "Not enough inputs specified for the \"%s\" filter.\n",
464                      cur->filter_ctx->filter->name);
465               ret = AVERROR(EINVAL);
466               goto fail;
467         }
468         if (!(match = extract_inout(cur->name, &open_outputs)))
469             continue;
470         ret = avfilter_link(match->filter_ctx, match->pad_idx,
471                             cur->filter_ctx,   cur->pad_idx);
472         avfilter_inout_free(&match);
473         if (ret < 0)
474             goto fail;
475     }
476
477     /* Last output can be omitted if it is "[out]" */
478     if (outputs && !outputs->name)
479         outputs->name = av_strdup("out");
480     for (cur = outputs; cur; cur = cur->next) {
481         if (!cur->name) {
482             av_log(log_ctx, AV_LOG_ERROR,
483                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
484                    filters);
485             ret = AVERROR(EINVAL);
486             goto fail;
487         }
488         if (!(match = extract_inout(cur->name, &open_inputs)))
489             continue;
490         ret = avfilter_link(cur->filter_ctx,   cur->pad_idx,
491                             match->filter_ctx, match->pad_idx);
492         avfilter_inout_free(&match);
493         if (ret < 0)
494             goto fail;
495     }
496
497  fail:
498     if (ret < 0) {
499         for (; graph->filter_count > 0; graph->filter_count--)
500             avfilter_free(graph->filters[graph->filter_count - 1]);
501         av_freep(&graph->filters);
502     }
503     avfilter_inout_free(&inputs);
504     avfilter_inout_free(&outputs);
505     /* clear open_in/outputs only if not passed as parameters */
506     if (open_inputs_ptr) *open_inputs_ptr = open_inputs;
507     else avfilter_inout_free(&open_inputs);
508     if (open_outputs_ptr) *open_outputs_ptr = open_outputs;
509     else avfilter_inout_free(&open_outputs);
510     return ret;
511 }
512 #else
513     int index = 0, ret = 0;
514     char chr = 0;
515
516     AVFilterInOut *curr_inputs = NULL;
517     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
518     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
519
520     do {
521         AVFilterContext *filter;
522         const char *filterchain = filters;
523         filters += strspn(filters, WHITESPACES);
524
525         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)
526             goto end;
527
528         if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)
529             goto end;
530
531         if (filter->input_count == 1 && !curr_inputs && !index) {
532             /* First input pad, assume it is "[in]" if not specified */
533             const char *tmp = "[in]";
534             if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)
535                 goto end;
536         }
537
538         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)
539             goto end;
540
541         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
542                                  log_ctx)) < 0)
543             goto end;
544
545         filters += strspn(filters, WHITESPACES);
546         chr = *filters++;
547
548         if (chr == ';' && curr_inputs) {
549             av_log(log_ctx, AV_LOG_ERROR,
550                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
551                    filterchain);
552             ret = AVERROR(EINVAL);
553             goto end;
554         }
555         index++;
556     } while (chr == ',' || chr == ';');
557
558     if (chr) {
559         av_log(log_ctx, AV_LOG_ERROR,
560                "Unable to parse graph description substring: \"%s\"\n",
561                filters - 1);
562         ret = AVERROR(EINVAL);
563         goto end;
564     }
565
566     if (curr_inputs) {
567         /* Last output pad, assume it is "[out]" if not specified */
568         const char *tmp = "[out]";
569         if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,
570                                  log_ctx)) < 0)
571             goto end;
572     }
573
574 end:
575     /* clear open_in/outputs only if not passed as parameters */
576     if (open_inputs_ptr) *open_inputs_ptr = open_inputs;
577     else avfilter_inout_free(&open_inputs);
578     if (open_outputs_ptr) *open_outputs_ptr = open_outputs;
579     else avfilter_inout_free(&open_outputs);
580     avfilter_inout_free(&curr_inputs);
581
582     if (ret < 0) {
583         for (; graph->filter_count > 0; graph->filter_count--)
584             avfilter_free(graph->filters[graph->filter_count - 1]);
585         av_freep(&graph->filters);
586     }
587     return ret;
588 }
589
590 #endif