]> 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 <string.h>
24 #include <stdio.h>
25
26 #include "libavutil/avstring.h"
27 #include "libavutil/mem.h"
28 #include "avfilter.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 = NULL;
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     *filt_ctx = avfilter_graph_alloc_filter(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 AVERROR(ENOMEM);
117     }
118
119     if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags") &&
120         ctx->scale_sws_opts) {
121         tmp_args = av_asprintf("%s:%s",
122                  args, ctx->scale_sws_opts);
123         if (!tmp_args)
124             return AVERROR(ENOMEM);
125         args = tmp_args;
126     }
127
128     ret = avfilter_init_str(*filt_ctx, args);
129     if (ret < 0) {
130         av_log(log_ctx, AV_LOG_ERROR,
131                "Error initializing filter '%s'", filt_name);
132         if (args)
133             av_log(log_ctx, AV_LOG_ERROR, " with args '%s'", args);
134         av_log(log_ctx, AV_LOG_ERROR, "\n");
135     }
136
137     av_free(tmp_args);
138     return ret;
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             ret = link_filter(p->filter_ctx, p->pad_idx, filt_ctx, pad, log_ctx);
242             av_free(p->name);
243             av_free(p);
244             if (ret < 0)
245                 return ret;
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                 av_free(name);
295                 return AVERROR(ENOMEM);
296             }
297             match->name    = name;
298             match->pad_idx = pad;
299         }
300
301         append_inout(&parsed_inputs, &match);
302
303         *buf += strspn(*buf, WHITESPACES);
304         pad++;
305     }
306
307     append_inout(&parsed_inputs, curr_inputs);
308     *curr_inputs = parsed_inputs;
309
310     return pad;
311 }
312
313 static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,
314                          AVFilterInOut **open_inputs,
315                          AVFilterInOut **open_outputs, void *log_ctx)
316 {
317     int ret, pad = 0;
318
319     while (**buf == '[') {
320         char *name = parse_link_name(buf, log_ctx);
321         AVFilterInOut *match;
322
323         AVFilterInOut *input = *curr_inputs;
324
325         if (!name)
326             return AVERROR(EINVAL);
327
328         if (!input) {
329             av_log(log_ctx, AV_LOG_ERROR,
330                    "No output pad can be associated to link label '%s'.\n", name);
331             av_free(name);
332             return AVERROR(EINVAL);
333         }
334         *curr_inputs = (*curr_inputs)->next;
335
336         /* First check if the label is not in the open_inputs list */
337         match = extract_inout(name, open_inputs);
338
339         if (match) {
340             if ((ret = link_filter(input->filter_ctx, input->pad_idx,
341                                    match->filter_ctx, match->pad_idx, log_ctx)) < 0) {
342                 av_free(name);
343                 return ret;
344             }
345             av_free(match->name);
346             av_free(name);
347             av_free(match);
348             av_free(input);
349         } else {
350             /* Not in the list, so add the first input as a open_output */
351             input->name = name;
352             insert_inout(open_outputs, input);
353         }
354         *buf += strspn(*buf, WHITESPACES);
355         pad++;
356     }
357
358     return pad;
359 }
360
361 static int parse_sws_flags(const char **buf, AVFilterGraph *graph)
362 {
363     char *p = strchr(*buf, ';');
364
365     if (strncmp(*buf, "sws_flags=", 10))
366         return 0;
367
368     if (!p) {
369         av_log(graph, AV_LOG_ERROR, "sws_flags not terminated with ';'.\n");
370         return AVERROR(EINVAL);
371     }
372
373     *buf += 4;  // keep the 'flags=' part
374
375     av_freep(&graph->scale_sws_opts);
376     if (!(graph->scale_sws_opts = av_mallocz(p - *buf + 1)))
377         return AVERROR(ENOMEM);
378     av_strlcpy(graph->scale_sws_opts, *buf, p - *buf + 1);
379
380     *buf = p + 1;
381     return 0;
382 }
383
384 int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters,
385                           AVFilterInOut **inputs,
386                           AVFilterInOut **outputs)
387 {
388     int index = 0, ret = 0;
389     char chr = 0;
390
391     AVFilterInOut *curr_inputs = NULL, *open_inputs = NULL, *open_outputs = NULL;
392
393     filters += strspn(filters, WHITESPACES);
394
395     if ((ret = parse_sws_flags(&filters, graph)) < 0)
396         goto fail;
397
398     do {
399         AVFilterContext *filter;
400         filters += strspn(filters, WHITESPACES);
401
402         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, graph)) < 0)
403             goto end;
404         if ((ret = parse_filter(&filter, &filters, graph, index, graph)) < 0)
405             goto end;
406
407
408         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, graph)) < 0)
409             goto end;
410
411         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
412                                  graph)) < 0)
413             goto end;
414
415         filters += strspn(filters, WHITESPACES);
416         chr = *filters++;
417
418         if (chr == ';' && curr_inputs)
419             append_inout(&open_outputs, &curr_inputs);
420         index++;
421     } while (chr == ',' || chr == ';');
422
423     if (chr) {
424         av_log(graph, AV_LOG_ERROR,
425                "Unable to parse graph description substring: \"%s\"\n",
426                filters - 1);
427         ret = AVERROR(EINVAL);
428         goto end;
429     }
430
431     append_inout(&open_outputs, &curr_inputs);
432
433
434     *inputs  = open_inputs;
435     *outputs = open_outputs;
436     return 0;
437
438  fail:end:
439     while (graph->nb_filters)
440         avfilter_free(graph->filters[0]);
441     av_freep(&graph->filters);
442     avfilter_inout_free(&open_inputs);
443     avfilter_inout_free(&open_outputs);
444     avfilter_inout_free(&curr_inputs);
445
446     *inputs  = NULL;
447     *outputs = NULL;
448
449     return ret;
450 }
451
452 #if HAVE_INCOMPATIBLE_LIBAV_ABI || !FF_API_OLD_GRAPH_PARSE
453 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
454                          AVFilterInOut *open_inputs,
455                          AVFilterInOut *open_outputs, void *log_ctx)
456 {
457     int ret;
458     AVFilterInOut *cur, *match, *inputs = NULL, *outputs = NULL;
459
460     if ((ret = avfilter_graph_parse2(graph, filters, &inputs, &outputs)) < 0)
461         goto fail;
462
463     /* First input can be omitted if it is "[in]" */
464     if (inputs && !inputs->name)
465         inputs->name = av_strdup("in");
466     for (cur = inputs; cur; cur = cur->next) {
467         if (!cur->name) {
468               av_log(log_ctx, AV_LOG_ERROR,
469                      "Not enough inputs specified for the \"%s\" filter.\n",
470                      cur->filter_ctx->filter->name);
471               ret = AVERROR(EINVAL);
472               goto fail;
473         }
474         if (!(match = extract_inout(cur->name, &open_outputs)))
475             continue;
476         ret = avfilter_link(match->filter_ctx, match->pad_idx,
477                             cur->filter_ctx,   cur->pad_idx);
478         avfilter_inout_free(&match);
479         if (ret < 0)
480             goto fail;
481     }
482
483     /* Last output can be omitted if it is "[out]" */
484     if (outputs && !outputs->name)
485         outputs->name = av_strdup("out");
486     for (cur = outputs; cur; cur = cur->next) {
487         if (!cur->name) {
488             av_log(log_ctx, AV_LOG_ERROR,
489                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
490                    filters);
491             ret = AVERROR(EINVAL);
492             goto fail;
493         }
494         if (!(match = extract_inout(cur->name, &open_inputs)))
495             continue;
496         ret = avfilter_link(cur->filter_ctx,   cur->pad_idx,
497                             match->filter_ctx, match->pad_idx);
498         avfilter_inout_free(&match);
499         if (ret < 0)
500             goto fail;
501     }
502
503  fail:
504     if (ret < 0) {
505         while (graph->nb_filters)
506             avfilter_free(graph->filters[0]);
507         av_freep(&graph->filters);
508     }
509     avfilter_inout_free(&inputs);
510     avfilter_inout_free(&outputs);
511     avfilter_inout_free(&open_inputs);
512     avfilter_inout_free(&open_outputs);
513     return ret;
514 #else
515 int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,
516                          AVFilterInOut **inputs, AVFilterInOut **outputs,
517                          void *log_ctx)
518 {
519     return avfilter_graph_parse_ptr(graph, filters, inputs, outputs, log_ctx);
520 #endif
521 }
522
523 int avfilter_graph_parse_ptr(AVFilterGraph *graph, const char *filters,
524                          AVFilterInOut **open_inputs_ptr, AVFilterInOut **open_outputs_ptr,
525                          void *log_ctx)
526 {
527     int index = 0, ret = 0;
528     char chr = 0;
529
530     AVFilterInOut *curr_inputs = NULL;
531     AVFilterInOut *open_inputs  = open_inputs_ptr  ? *open_inputs_ptr  : NULL;
532     AVFilterInOut *open_outputs = open_outputs_ptr ? *open_outputs_ptr : NULL;
533
534     if ((ret = parse_sws_flags(&filters, graph)) < 0)
535         goto end;
536
537     do {
538         AVFilterContext *filter;
539         const char *filterchain = filters;
540         filters += strspn(filters, WHITESPACES);
541
542         if ((ret = parse_inputs(&filters, &curr_inputs, &open_outputs, log_ctx)) < 0)
543             goto end;
544
545         if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)
546             goto end;
547
548         if (filter->nb_inputs == 1 && !curr_inputs && !index) {
549             /* First input pad, assume it is "[in]" if not specified */
550             const char *tmp = "[in]";
551             if ((ret = parse_inputs(&tmp, &curr_inputs, &open_outputs, log_ctx)) < 0)
552                 goto end;
553         }
554
555         if ((ret = link_filter_inouts(filter, &curr_inputs, &open_inputs, log_ctx)) < 0)
556             goto end;
557
558         if ((ret = parse_outputs(&filters, &curr_inputs, &open_inputs, &open_outputs,
559                                  log_ctx)) < 0)
560             goto end;
561
562         filters += strspn(filters, WHITESPACES);
563         chr = *filters++;
564
565         if (chr == ';' && curr_inputs) {
566             av_log(log_ctx, AV_LOG_ERROR,
567                    "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",
568                    filterchain);
569             ret = AVERROR(EINVAL);
570             goto end;
571         }
572         index++;
573     } while (chr == ',' || chr == ';');
574
575     if (chr) {
576         av_log(log_ctx, AV_LOG_ERROR,
577                "Unable to parse graph description substring: \"%s\"\n",
578                filters - 1);
579         ret = AVERROR(EINVAL);
580         goto end;
581     }
582
583     if (curr_inputs) {
584         /* Last output pad, assume it is "[out]" if not specified */
585         const char *tmp = "[out]";
586         if ((ret = parse_outputs(&tmp, &curr_inputs, &open_inputs, &open_outputs,
587                                  log_ctx)) < 0)
588             goto end;
589     }
590
591 end:
592     /* clear open_in/outputs only if not passed as parameters */
593     if (open_inputs_ptr) *open_inputs_ptr = open_inputs;
594     else avfilter_inout_free(&open_inputs);
595     if (open_outputs_ptr) *open_outputs_ptr = open_outputs;
596     else avfilter_inout_free(&open_outputs);
597     avfilter_inout_free(&curr_inputs);
598
599     if (ret < 0) {
600         while (graph->nb_filters)
601             avfilter_free(graph->filters[0]);
602         av_freep(&graph->filters);
603     }
604     return ret;
605 }