]> git.sesse.net Git - ffmpeg/blob - libavfilter/avfilter.c
Merge commit '310cc4bf82824f09bdd0b9147ed725cdbeaf9bdd'
[ffmpeg] / libavfilter / avfilter.c
1 /*
2  * filter layer
3  * Copyright (c) 2007 Bobby Bingham
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/atomic.h"
23 #include "libavutil/avassert.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/channel_layout.h"
26 #include "libavutil/common.h"
27 #include "libavutil/eval.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/internal.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/rational.h"
33 #include "libavutil/samplefmt.h"
34
35 #include "audio.h"
36 #include "avfilter.h"
37 #include "formats.h"
38 #include "internal.h"
39 #include "audio.h"
40
41 static int ff_filter_frame_framed(AVFilterLink *link, AVFrame *frame);
42
43 void ff_tlog_ref(void *ctx, AVFrame *ref, int end)
44 {
45     av_unused char buf[16];
46     ff_tlog(ctx,
47             "ref[%p buf:%p data:%p linesize[%d, %d, %d, %d] pts:%"PRId64" pos:%"PRId64,
48             ref, ref->buf, ref->data[0],
49             ref->linesize[0], ref->linesize[1], ref->linesize[2], ref->linesize[3],
50             ref->pts, av_frame_get_pkt_pos(ref));
51
52     if (ref->width) {
53         ff_tlog(ctx, " a:%d/%d s:%dx%d i:%c iskey:%d type:%c",
54                 ref->sample_aspect_ratio.num, ref->sample_aspect_ratio.den,
55                 ref->width, ref->height,
56                 !ref->interlaced_frame     ? 'P' :         /* Progressive  */
57                 ref->top_field_first ? 'T' : 'B',    /* Top / Bottom */
58                 ref->key_frame,
59                 av_get_picture_type_char(ref->pict_type));
60     }
61     if (ref->nb_samples) {
62         ff_tlog(ctx, " cl:%"PRId64"d n:%d r:%d",
63                 ref->channel_layout,
64                 ref->nb_samples,
65                 ref->sample_rate);
66     }
67
68     ff_tlog(ctx, "]%s", end ? "\n" : "");
69 }
70
71 unsigned avfilter_version(void)
72 {
73     av_assert0(LIBAVFILTER_VERSION_MICRO >= 100);
74     return LIBAVFILTER_VERSION_INT;
75 }
76
77 const char *avfilter_configuration(void)
78 {
79     return FFMPEG_CONFIGURATION;
80 }
81
82 const char *avfilter_license(void)
83 {
84 #define LICENSE_PREFIX "libavfilter license: "
85     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
86 }
87
88 void ff_command_queue_pop(AVFilterContext *filter)
89 {
90     AVFilterCommand *c= filter->command_queue;
91     av_freep(&c->arg);
92     av_freep(&c->command);
93     filter->command_queue= c->next;
94     av_free(c);
95 }
96
97 void ff_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,
98                    AVFilterPad **pads, AVFilterLink ***links,
99                    AVFilterPad *newpad)
100 {
101     unsigned i;
102
103     idx = FFMIN(idx, *count);
104
105     *pads  = av_realloc(*pads,  sizeof(AVFilterPad)   * (*count + 1));
106     *links = av_realloc(*links, sizeof(AVFilterLink*) * (*count + 1));
107     memmove(*pads  + idx + 1, *pads  + idx, sizeof(AVFilterPad)   * (*count - idx));
108     memmove(*links + idx + 1, *links + idx, sizeof(AVFilterLink*) * (*count - idx));
109     memcpy(*pads + idx, newpad, sizeof(AVFilterPad));
110     (*links)[idx] = NULL;
111
112     (*count)++;
113     for (i = idx + 1; i < *count; i++)
114         if (*links[i])
115             (*(unsigned *)((uint8_t *) *links[i] + padidx_off))++;
116 }
117
118 int avfilter_link(AVFilterContext *src, unsigned srcpad,
119                   AVFilterContext *dst, unsigned dstpad)
120 {
121     AVFilterLink *link;
122
123     if (src->nb_outputs <= srcpad || dst->nb_inputs <= dstpad ||
124         src->outputs[srcpad]      || dst->inputs[dstpad])
125         return -1;
126
127     if (src->output_pads[srcpad].type != dst->input_pads[dstpad].type) {
128         av_log(src, AV_LOG_ERROR,
129                "Media type mismatch between the '%s' filter output pad %d (%s) and the '%s' filter input pad %d (%s)\n",
130                src->name, srcpad, (char *)av_x_if_null(av_get_media_type_string(src->output_pads[srcpad].type), "?"),
131                dst->name, dstpad, (char *)av_x_if_null(av_get_media_type_string(dst-> input_pads[dstpad].type), "?"));
132         return AVERROR(EINVAL);
133     }
134
135     link = av_mallocz(sizeof(*link));
136     if (!link)
137         return AVERROR(ENOMEM);
138
139     src->outputs[srcpad] = dst->inputs[dstpad] = link;
140
141     link->src     = src;
142     link->dst     = dst;
143     link->srcpad  = &src->output_pads[srcpad];
144     link->dstpad  = &dst->input_pads[dstpad];
145     link->type    = src->output_pads[srcpad].type;
146     av_assert0(AV_PIX_FMT_NONE == -1 && AV_SAMPLE_FMT_NONE == -1);
147     link->format  = -1;
148
149     return 0;
150 }
151
152 void avfilter_link_free(AVFilterLink **link)
153 {
154     if (!*link)
155         return;
156
157     av_frame_free(&(*link)->partial_buf);
158
159     av_freep(link);
160 }
161
162 int avfilter_link_get_channels(AVFilterLink *link)
163 {
164     return link->channels;
165 }
166
167 void avfilter_link_set_closed(AVFilterLink *link, int closed)
168 {
169     link->closed = closed;
170 }
171
172 int avfilter_insert_filter(AVFilterLink *link, AVFilterContext *filt,
173                            unsigned filt_srcpad_idx, unsigned filt_dstpad_idx)
174 {
175     int ret;
176     unsigned dstpad_idx = link->dstpad - link->dst->input_pads;
177
178     av_log(link->dst, AV_LOG_VERBOSE, "auto-inserting filter '%s' "
179            "between the filter '%s' and the filter '%s'\n",
180            filt->name, link->src->name, link->dst->name);
181
182     link->dst->inputs[dstpad_idx] = NULL;
183     if ((ret = avfilter_link(filt, filt_dstpad_idx, link->dst, dstpad_idx)) < 0) {
184         /* failed to link output filter to new filter */
185         link->dst->inputs[dstpad_idx] = link;
186         return ret;
187     }
188
189     /* re-hookup the link to the new destination filter we inserted */
190     link->dst                     = filt;
191     link->dstpad                  = &filt->input_pads[filt_srcpad_idx];
192     filt->inputs[filt_srcpad_idx] = link;
193
194     /* if any information on supported media formats already exists on the
195      * link, we need to preserve that */
196     if (link->out_formats)
197         ff_formats_changeref(&link->out_formats,
198                              &filt->outputs[filt_dstpad_idx]->out_formats);
199     if (link->out_samplerates)
200         ff_formats_changeref(&link->out_samplerates,
201                              &filt->outputs[filt_dstpad_idx]->out_samplerates);
202     if (link->out_channel_layouts)
203         ff_channel_layouts_changeref(&link->out_channel_layouts,
204                                      &filt->outputs[filt_dstpad_idx]->out_channel_layouts);
205
206     return 0;
207 }
208
209 int avfilter_config_links(AVFilterContext *filter)
210 {
211     int (*config_link)(AVFilterLink *);
212     unsigned i;
213     int ret;
214
215     for (i = 0; i < filter->nb_inputs; i ++) {
216         AVFilterLink *link = filter->inputs[i];
217         AVFilterLink *inlink;
218
219         if (!link) continue;
220
221         inlink = link->src->nb_inputs ? link->src->inputs[0] : NULL;
222         link->current_pts = AV_NOPTS_VALUE;
223
224         switch (link->init_state) {
225         case AVLINK_INIT:
226             continue;
227         case AVLINK_STARTINIT:
228             av_log(filter, AV_LOG_INFO, "circular filter chain detected\n");
229             return 0;
230         case AVLINK_UNINIT:
231             link->init_state = AVLINK_STARTINIT;
232
233             if ((ret = avfilter_config_links(link->src)) < 0)
234                 return ret;
235
236             if (!(config_link = link->srcpad->config_props)) {
237                 if (link->src->nb_inputs != 1) {
238                     av_log(link->src, AV_LOG_ERROR, "Source filters and filters "
239                                                     "with more than one input "
240                                                     "must set config_props() "
241                                                     "callbacks on all outputs\n");
242                     return AVERROR(EINVAL);
243                 }
244             } else if ((ret = config_link(link)) < 0) {
245                 av_log(link->src, AV_LOG_ERROR,
246                        "Failed to configure output pad on %s\n",
247                        link->src->name);
248                 return ret;
249             }
250
251             switch (link->type) {
252             case AVMEDIA_TYPE_VIDEO:
253                 if (!link->time_base.num && !link->time_base.den)
254                     link->time_base = inlink ? inlink->time_base : AV_TIME_BASE_Q;
255
256                 if (!link->sample_aspect_ratio.num && !link->sample_aspect_ratio.den)
257                     link->sample_aspect_ratio = inlink ?
258                         inlink->sample_aspect_ratio : (AVRational){1,1};
259
260                 if (inlink && !link->frame_rate.num && !link->frame_rate.den)
261                     link->frame_rate = inlink->frame_rate;
262
263                 if (inlink) {
264                     if (!link->w)
265                         link->w = inlink->w;
266                     if (!link->h)
267                         link->h = inlink->h;
268                 } else if (!link->w || !link->h) {
269                     av_log(link->src, AV_LOG_ERROR,
270                            "Video source filters must set their output link's "
271                            "width and height\n");
272                     return AVERROR(EINVAL);
273                 }
274                 break;
275
276             case AVMEDIA_TYPE_AUDIO:
277                 if (inlink) {
278                     if (!link->time_base.num && !link->time_base.den)
279                         link->time_base = inlink->time_base;
280                 }
281
282                 if (!link->time_base.num && !link->time_base.den)
283                     link->time_base = (AVRational) {1, link->sample_rate};
284             }
285
286             if ((config_link = link->dstpad->config_props))
287                 if ((ret = config_link(link)) < 0) {
288                     av_log(link->src, AV_LOG_ERROR,
289                            "Failed to configure input pad on %s\n",
290                            link->dst->name);
291                     return ret;
292                 }
293
294             link->init_state = AVLINK_INIT;
295         }
296     }
297
298     return 0;
299 }
300
301 void ff_tlog_link(void *ctx, AVFilterLink *link, int end)
302 {
303     if (link->type == AVMEDIA_TYPE_VIDEO) {
304         ff_tlog(ctx,
305                 "link[%p s:%dx%d fmt:%s %s->%s]%s",
306                 link, link->w, link->h,
307                 av_get_pix_fmt_name(link->format),
308                 link->src ? link->src->filter->name : "",
309                 link->dst ? link->dst->filter->name : "",
310                 end ? "\n" : "");
311     } else {
312         char buf[128];
313         av_get_channel_layout_string(buf, sizeof(buf), -1, link->channel_layout);
314
315         ff_tlog(ctx,
316                 "link[%p r:%d cl:%s fmt:%s %s->%s]%s",
317                 link, (int)link->sample_rate, buf,
318                 av_get_sample_fmt_name(link->format),
319                 link->src ? link->src->filter->name : "",
320                 link->dst ? link->dst->filter->name : "",
321                 end ? "\n" : "");
322     }
323 }
324
325 int ff_request_frame(AVFilterLink *link)
326 {
327     int ret = -1;
328     FF_TPRINTF_START(NULL, request_frame); ff_tlog_link(NULL, link, 1);
329
330     if (link->closed)
331         return AVERROR_EOF;
332     av_assert0(!link->frame_requested);
333     link->frame_requested = 1;
334     while (link->frame_requested) {
335         if (link->srcpad->request_frame)
336             ret = link->srcpad->request_frame(link);
337         else if (link->src->inputs[0])
338             ret = ff_request_frame(link->src->inputs[0]);
339         if (ret == AVERROR_EOF && link->partial_buf) {
340             AVFrame *pbuf = link->partial_buf;
341             link->partial_buf = NULL;
342             ret = ff_filter_frame_framed(link, pbuf);
343         }
344         if (ret < 0) {
345             link->frame_requested = 0;
346             if (ret == AVERROR_EOF)
347                 link->closed = 1;
348         } else {
349             av_assert0(!link->frame_requested ||
350                        link->flags & FF_LINK_FLAG_REQUEST_LOOP);
351         }
352     }
353     return ret;
354 }
355
356 int ff_poll_frame(AVFilterLink *link)
357 {
358     int i, min = INT_MAX;
359
360     if (link->srcpad->poll_frame)
361         return link->srcpad->poll_frame(link);
362
363     for (i = 0; i < link->src->nb_inputs; i++) {
364         int val;
365         if (!link->src->inputs[i])
366             return -1;
367         val = ff_poll_frame(link->src->inputs[i]);
368         min = FFMIN(min, val);
369     }
370
371     return min;
372 }
373
374 static const char *const var_names[] = {   "t",   "n",   "pos",        NULL };
375 enum                                   { VAR_T, VAR_N, VAR_POS, VAR_VARS_NB };
376
377 static int set_enable_expr(AVFilterContext *ctx, const char *expr)
378 {
379     int ret;
380     char *expr_dup;
381     AVExpr *old = ctx->enable;
382
383     if (!(ctx->filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE)) {
384         av_log(ctx, AV_LOG_ERROR, "Timeline ('enable' option) not supported "
385                "with filter '%s'\n", ctx->filter->name);
386         return AVERROR_PATCHWELCOME;
387     }
388
389     expr_dup = av_strdup(expr);
390     if (!expr_dup)
391         return AVERROR(ENOMEM);
392
393     if (!ctx->var_values) {
394         ctx->var_values = av_calloc(VAR_VARS_NB, sizeof(*ctx->var_values));
395         if (!ctx->var_values) {
396             av_free(expr_dup);
397             return AVERROR(ENOMEM);
398         }
399     }
400
401     ret = av_expr_parse((AVExpr**)&ctx->enable, expr_dup, var_names,
402                         NULL, NULL, NULL, NULL, 0, ctx->priv);
403     if (ret < 0) {
404         av_log(ctx->priv, AV_LOG_ERROR,
405                "Error when evaluating the expression '%s' for enable\n",
406                expr_dup);
407         av_free(expr_dup);
408         return ret;
409     }
410
411     av_expr_free(old);
412     av_free(ctx->enable_str);
413     ctx->enable_str = expr_dup;
414     return 0;
415 }
416
417 void ff_update_link_current_pts(AVFilterLink *link, int64_t pts)
418 {
419     if (pts == AV_NOPTS_VALUE)
420         return;
421     link->current_pts = av_rescale_q(pts, link->time_base, AV_TIME_BASE_Q);
422     /* TODO use duration */
423     if (link->graph && link->age_index >= 0)
424         ff_avfilter_graph_update_heap(link->graph, link);
425 }
426
427 int avfilter_process_command(AVFilterContext *filter, const char *cmd, const char *arg, char *res, int res_len, int flags)
428 {
429     if(!strcmp(cmd, "ping")){
430         av_strlcatf(res, res_len, "pong from:%s %s\n", filter->filter->name, filter->name);
431         return 0;
432     }else if(!strcmp(cmd, "enable")) {
433         return set_enable_expr(filter, arg);
434     }else if(filter->filter->process_command) {
435         return filter->filter->process_command(filter, cmd, arg, res, res_len, flags);
436     }
437     return AVERROR(ENOSYS);
438 }
439
440 static AVFilter *first_filter;
441
442 AVFilter *avfilter_get_by_name(const char *name)
443 {
444     const AVFilter *f = NULL;
445
446     if (!name)
447         return NULL;
448
449     while ((f = avfilter_next(f)))
450         if (!strcmp(f->name, name))
451             return (AVFilter *)f;
452
453     return NULL;
454 }
455
456 int avfilter_register(AVFilter *filter)
457 {
458     AVFilter **f = &first_filter;
459     int i;
460
461     /* the filter must select generic or internal exclusively */
462     av_assert0((filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE) != AVFILTER_FLAG_SUPPORT_TIMELINE);
463
464     for(i=0; filter->inputs && filter->inputs[i].name; i++) {
465         const AVFilterPad *input = &filter->inputs[i];
466         av_assert0(     !input->filter_frame
467                     || (!input->start_frame && !input->end_frame));
468     }
469
470     filter->next = NULL;
471
472     while(avpriv_atomic_ptr_cas((void * volatile *)f, NULL, filter))
473         f = &(*f)->next;
474
475     return 0;
476 }
477
478 const AVFilter *avfilter_next(const AVFilter *prev)
479 {
480     return prev ? prev->next : first_filter;
481 }
482
483 #if FF_API_OLD_FILTER_REGISTER
484 AVFilter **av_filter_next(AVFilter **filter)
485 {
486     return filter ? &(*filter)->next : &first_filter;
487 }
488
489 void avfilter_uninit(void)
490 {
491 }
492 #endif
493
494 int avfilter_pad_count(const AVFilterPad *pads)
495 {
496     int count;
497
498     if (!pads)
499         return 0;
500
501     for (count = 0; pads->name; count++)
502         pads++;
503     return count;
504 }
505
506 static const char *default_filter_name(void *filter_ctx)
507 {
508     AVFilterContext *ctx = filter_ctx;
509     return ctx->name ? ctx->name : ctx->filter->name;
510 }
511
512 static void *filter_child_next(void *obj, void *prev)
513 {
514     AVFilterContext *ctx = obj;
515     if (!prev && ctx->filter && ctx->filter->priv_class && ctx->priv)
516         return ctx->priv;
517     return NULL;
518 }
519
520 static const AVClass *filter_child_class_next(const AVClass *prev)
521 {
522     const AVFilter *f = NULL;
523
524     /* find the filter that corresponds to prev */
525     while (prev && (f = avfilter_next(f)))
526         if (f->priv_class == prev)
527             break;
528
529     /* could not find filter corresponding to prev */
530     if (prev && !f)
531         return NULL;
532
533     /* find next filter with specific options */
534     while ((f = avfilter_next(f)))
535         if (f->priv_class)
536             return f->priv_class;
537
538     return NULL;
539 }
540
541 #define OFFSET(x) offsetof(AVFilterContext, x)
542 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM
543 static const AVOption avfilter_options[] = {
544     { "thread_type", "Allowed thread types", OFFSET(thread_type), AV_OPT_TYPE_FLAGS,
545         { .i64 = AVFILTER_THREAD_SLICE }, 0, INT_MAX, FLAGS, "thread_type" },
546         { "slice", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AVFILTER_THREAD_SLICE }, .unit = "thread_type" },
547     { "enable", "set enable expression", OFFSET(enable_str), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
548     { NULL },
549 };
550
551 static const AVClass avfilter_class = {
552     .class_name = "AVFilter",
553     .item_name  = default_filter_name,
554     .version    = LIBAVUTIL_VERSION_INT,
555     .category   = AV_CLASS_CATEGORY_FILTER,
556     .child_next = filter_child_next,
557     .child_class_next = filter_child_class_next,
558     .option           = avfilter_options,
559 };
560
561 static int default_execute(AVFilterContext *ctx, action_func *func, void *arg,
562                            int *ret, int nb_jobs)
563 {
564     int i;
565
566     for (i = 0; i < nb_jobs; i++) {
567         int r = func(ctx, arg, i, nb_jobs);
568         if (ret)
569             ret[i] = r;
570     }
571     return 0;
572 }
573
574 AVFilterContext *ff_filter_alloc(const AVFilter *filter, const char *inst_name)
575 {
576     AVFilterContext *ret;
577
578     if (!filter)
579         return NULL;
580
581     ret = av_mallocz(sizeof(AVFilterContext));
582     if (!ret)
583         return NULL;
584
585     ret->av_class = &avfilter_class;
586     ret->filter   = filter;
587     ret->name     = inst_name ? av_strdup(inst_name) : NULL;
588     if (filter->priv_size) {
589         ret->priv     = av_mallocz(filter->priv_size);
590         if (!ret->priv)
591             goto err;
592     }
593
594     av_opt_set_defaults(ret);
595     if (filter->priv_class) {
596         *(const AVClass**)ret->priv = filter->priv_class;
597         av_opt_set_defaults(ret->priv);
598     }
599
600     ret->internal = av_mallocz(sizeof(*ret->internal));
601     if (!ret->internal)
602         goto err;
603     ret->internal->execute = default_execute;
604
605     ret->nb_inputs = avfilter_pad_count(filter->inputs);
606     if (ret->nb_inputs ) {
607         ret->input_pads   = av_malloc(sizeof(AVFilterPad) * ret->nb_inputs);
608         if (!ret->input_pads)
609             goto err;
610         memcpy(ret->input_pads, filter->inputs, sizeof(AVFilterPad) * ret->nb_inputs);
611         ret->inputs       = av_mallocz(sizeof(AVFilterLink*) * ret->nb_inputs);
612         if (!ret->inputs)
613             goto err;
614     }
615
616     ret->nb_outputs = avfilter_pad_count(filter->outputs);
617     if (ret->nb_outputs) {
618         ret->output_pads  = av_malloc(sizeof(AVFilterPad) * ret->nb_outputs);
619         if (!ret->output_pads)
620             goto err;
621         memcpy(ret->output_pads, filter->outputs, sizeof(AVFilterPad) * ret->nb_outputs);
622         ret->outputs      = av_mallocz(sizeof(AVFilterLink*) * ret->nb_outputs);
623         if (!ret->outputs)
624             goto err;
625     }
626 #if FF_API_FOO_COUNT
627 FF_DISABLE_DEPRECATION_WARNINGS
628     ret->output_count = ret->nb_outputs;
629     ret->input_count  = ret->nb_inputs;
630 FF_ENABLE_DEPRECATION_WARNINGS
631 #endif
632
633     return ret;
634
635 err:
636     av_freep(&ret->inputs);
637     av_freep(&ret->input_pads);
638     ret->nb_inputs = 0;
639     av_freep(&ret->outputs);
640     av_freep(&ret->output_pads);
641     ret->nb_outputs = 0;
642     av_freep(&ret->priv);
643     av_freep(&ret->internal);
644     av_free(ret);
645     return NULL;
646 }
647
648 #if FF_API_AVFILTER_OPEN
649 int avfilter_open(AVFilterContext **filter_ctx, AVFilter *filter, const char *inst_name)
650 {
651     *filter_ctx = ff_filter_alloc(filter, inst_name);
652     return *filter_ctx ? 0 : AVERROR(ENOMEM);
653 }
654 #endif
655
656 static void free_link(AVFilterLink *link)
657 {
658     if (!link)
659         return;
660
661     if (link->src)
662         link->src->outputs[link->srcpad - link->src->output_pads] = NULL;
663     if (link->dst)
664         link->dst->inputs[link->dstpad - link->dst->input_pads] = NULL;
665
666     ff_formats_unref(&link->in_formats);
667     ff_formats_unref(&link->out_formats);
668     ff_formats_unref(&link->in_samplerates);
669     ff_formats_unref(&link->out_samplerates);
670     ff_channel_layouts_unref(&link->in_channel_layouts);
671     ff_channel_layouts_unref(&link->out_channel_layouts);
672     avfilter_link_free(&link);
673 }
674
675 void avfilter_free(AVFilterContext *filter)
676 {
677     int i;
678
679     if (!filter)
680         return;
681
682     if (filter->graph)
683         ff_filter_graph_remove_filter(filter->graph, filter);
684
685     if (filter->filter->uninit)
686         filter->filter->uninit(filter);
687
688     for (i = 0; i < filter->nb_inputs; i++) {
689         free_link(filter->inputs[i]);
690     }
691     for (i = 0; i < filter->nb_outputs; i++) {
692         free_link(filter->outputs[i]);
693     }
694
695     if (filter->filter->priv_class)
696         av_opt_free(filter->priv);
697
698     av_freep(&filter->name);
699     av_freep(&filter->input_pads);
700     av_freep(&filter->output_pads);
701     av_freep(&filter->inputs);
702     av_freep(&filter->outputs);
703     av_freep(&filter->priv);
704     while(filter->command_queue){
705         ff_command_queue_pop(filter);
706     }
707     av_opt_free(filter);
708     av_expr_free(filter->enable);
709     filter->enable = NULL;
710     av_freep(&filter->var_values);
711     av_freep(&filter->internal);
712     av_free(filter);
713 }
714
715 static int process_options(AVFilterContext *ctx, AVDictionary **options,
716                            const char *args)
717 {
718     const AVOption *o = NULL;
719     int ret, count = 0;
720     char *av_uninit(parsed_key), *av_uninit(value);
721     const char *key;
722     int offset= -1;
723
724     if (!args)
725         return 0;
726
727     while (*args) {
728         const char *shorthand = NULL;
729
730         o = av_opt_next(ctx->priv, o);
731         if (o) {
732             if (o->type == AV_OPT_TYPE_CONST || o->offset == offset)
733                 continue;
734             offset = o->offset;
735             shorthand = o->name;
736         }
737
738         ret = av_opt_get_key_value(&args, "=", ":",
739                                    shorthand ? AV_OPT_FLAG_IMPLICIT_KEY : 0,
740                                    &parsed_key, &value);
741         if (ret < 0) {
742             if (ret == AVERROR(EINVAL))
743                 av_log(ctx, AV_LOG_ERROR, "No option name near '%s'\n", args);
744             else
745                 av_log(ctx, AV_LOG_ERROR, "Unable to parse '%s': %s\n", args,
746                        av_err2str(ret));
747             return ret;
748         }
749         if (*args)
750             args++;
751         if (parsed_key) {
752             key = parsed_key;
753             while ((o = av_opt_next(ctx->priv, o))); /* discard all remaining shorthand */
754         } else {
755             key = shorthand;
756         }
757
758         av_log(ctx, AV_LOG_DEBUG, "Setting '%s' to value '%s'\n", key, value);
759
760         if (av_opt_find(ctx, key, NULL, 0, 0)) {
761             ret = av_opt_set(ctx, key, value, 0);
762             if (ret < 0) {
763                 av_free(value);
764                 av_free(parsed_key);
765                 return ret;
766             }
767         } else {
768         av_dict_set(options, key, value, 0);
769         if ((ret = av_opt_set(ctx->priv, key, value, 0)) < 0) {
770             if (!av_opt_find(ctx->priv, key, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
771             if (ret == AVERROR_OPTION_NOT_FOUND)
772                 av_log(ctx, AV_LOG_ERROR, "Option '%s' not found\n", key);
773             av_free(value);
774             av_free(parsed_key);
775             return ret;
776             }
777         }
778         }
779
780         av_free(value);
781         av_free(parsed_key);
782         count++;
783     }
784
785     if (ctx->enable_str) {
786         ret = set_enable_expr(ctx, ctx->enable_str);
787         if (ret < 0)
788             return ret;
789     }
790     return count;
791 }
792
793 #if FF_API_AVFILTER_INIT_FILTER
794 int avfilter_init_filter(AVFilterContext *filter, const char *args, void *opaque)
795 {
796     return avfilter_init_str(filter, args);
797 }
798 #endif
799
800 int avfilter_init_dict(AVFilterContext *ctx, AVDictionary **options)
801 {
802     int ret = 0;
803
804     ret = av_opt_set_dict(ctx, options);
805     if (ret < 0) {
806         av_log(ctx, AV_LOG_ERROR, "Error applying generic filter options.\n");
807         return ret;
808     }
809
810     if (ctx->filter->flags & AVFILTER_FLAG_SLICE_THREADS &&
811         ctx->thread_type & ctx->graph->thread_type & AVFILTER_THREAD_SLICE &&
812         ctx->graph->internal->thread_execute) {
813         ctx->thread_type       = AVFILTER_THREAD_SLICE;
814         ctx->internal->execute = ctx->graph->internal->thread_execute;
815     } else {
816         ctx->thread_type = 0;
817     }
818
819     if (ctx->filter->priv_class) {
820         ret = av_opt_set_dict(ctx->priv, options);
821         if (ret < 0) {
822             av_log(ctx, AV_LOG_ERROR, "Error applying options to the filter.\n");
823             return ret;
824         }
825     }
826
827     if (ctx->filter->init_opaque)
828         ret = ctx->filter->init_opaque(ctx, NULL);
829     else if (ctx->filter->init)
830         ret = ctx->filter->init(ctx);
831     else if (ctx->filter->init_dict)
832         ret = ctx->filter->init_dict(ctx, options);
833
834     return ret;
835 }
836
837 int avfilter_init_str(AVFilterContext *filter, const char *args)
838 {
839     AVDictionary *options = NULL;
840     AVDictionaryEntry *e;
841     int ret = 0;
842
843     if (args && *args) {
844         if (!filter->filter->priv_class) {
845             av_log(filter, AV_LOG_ERROR, "This filter does not take any "
846                    "options, but options were provided: %s.\n", args);
847             return AVERROR(EINVAL);
848         }
849
850 #if FF_API_OLD_FILTER_OPTS
851             if (   !strcmp(filter->filter->name, "format")     ||
852                    !strcmp(filter->filter->name, "noformat")   ||
853                    !strcmp(filter->filter->name, "frei0r")     ||
854                    !strcmp(filter->filter->name, "frei0r_src") ||
855                    !strcmp(filter->filter->name, "ocv")        ||
856                    !strcmp(filter->filter->name, "pan")        ||
857                    !strcmp(filter->filter->name, "pp")         ||
858                    !strcmp(filter->filter->name, "aevalsrc")) {
859             /* a hack for compatibility with the old syntax
860              * replace colons with |s */
861             char *copy = av_strdup(args);
862             char *p    = copy;
863             int nb_leading = 0; // number of leading colons to skip
864             int deprecated = 0;
865
866             if (!copy) {
867                 ret = AVERROR(ENOMEM);
868                 goto fail;
869             }
870
871             if (!strcmp(filter->filter->name, "frei0r") ||
872                 !strcmp(filter->filter->name, "ocv"))
873                 nb_leading = 1;
874             else if (!strcmp(filter->filter->name, "frei0r_src"))
875                 nb_leading = 3;
876
877             while (nb_leading--) {
878                 p = strchr(p, ':');
879                 if (!p) {
880                     p = copy + strlen(copy);
881                     break;
882                 }
883                 p++;
884             }
885
886             deprecated = strchr(p, ':') != NULL;
887
888             if (!strcmp(filter->filter->name, "aevalsrc")) {
889                 deprecated = 0;
890                 while ((p = strchr(p, ':')) && p[1] != ':') {
891                     const char *epos = strchr(p + 1, '=');
892                     const char *spos = strchr(p + 1, ':');
893                     const int next_token_is_opt = epos && (!spos || epos < spos);
894                     if (next_token_is_opt) {
895                         p++;
896                         break;
897                     }
898                     /* next token does not contain a '=', assume a channel expression */
899                     deprecated = 1;
900                     *p++ = '|';
901                 }
902                 if (p && *p == ':') { // double sep '::' found
903                     deprecated = 1;
904                     memmove(p, p + 1, strlen(p));
905                 }
906             } else
907             while ((p = strchr(p, ':')))
908                 *p++ = '|';
909
910             if (deprecated)
911                 av_log(filter, AV_LOG_WARNING, "This syntax is deprecated. Use "
912                        "'|' to separate the list items.\n");
913
914             av_log(filter, AV_LOG_DEBUG, "compat: called with args=[%s]\n", copy);
915             ret = process_options(filter, &options, copy);
916             av_freep(&copy);
917
918             if (ret < 0)
919                 goto fail;
920 #endif
921         } else {
922 #if CONFIG_MP_FILTER
923             if (!strcmp(filter->filter->name, "mp")) {
924                 char *escaped;
925
926                 if (!strncmp(args, "filter=", 7))
927                     args += 7;
928                 ret = av_escape(&escaped, args, ":=", AV_ESCAPE_MODE_BACKSLASH, 0);
929                 if (ret < 0) {
930                     av_log(filter, AV_LOG_ERROR, "Unable to escape MPlayer filters arg '%s'\n", args);
931                     goto fail;
932                 }
933                 ret = process_options(filter, &options, escaped);
934                 av_free(escaped);
935             } else
936 #endif
937             ret = process_options(filter, &options, args);
938             if (ret < 0)
939                 goto fail;
940         }
941     }
942
943     ret = avfilter_init_dict(filter, &options);
944     if (ret < 0)
945         goto fail;
946
947     if ((e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
948         av_log(filter, AV_LOG_ERROR, "No such option: %s.\n", e->key);
949         ret = AVERROR_OPTION_NOT_FOUND;
950         goto fail;
951     }
952
953 fail:
954     av_dict_free(&options);
955
956     return ret;
957 }
958
959 const char *avfilter_pad_get_name(const AVFilterPad *pads, int pad_idx)
960 {
961     return pads[pad_idx].name;
962 }
963
964 enum AVMediaType avfilter_pad_get_type(const AVFilterPad *pads, int pad_idx)
965 {
966     return pads[pad_idx].type;
967 }
968
969 static int default_filter_frame(AVFilterLink *link, AVFrame *frame)
970 {
971     return ff_filter_frame(link->dst->outputs[0], frame);
972 }
973
974 static int ff_filter_frame_framed(AVFilterLink *link, AVFrame *frame)
975 {
976     int (*filter_frame)(AVFilterLink *, AVFrame *);
977     AVFilterContext *dstctx = link->dst;
978     AVFilterPad *dst = link->dstpad;
979     AVFrame *out;
980     int ret;
981     AVFilterCommand *cmd= link->dst->command_queue;
982     int64_t pts;
983
984     if (link->closed) {
985         av_frame_free(&frame);
986         return AVERROR_EOF;
987     }
988
989     if (!(filter_frame = dst->filter_frame))
990         filter_frame = default_filter_frame;
991
992     /* copy the frame if needed */
993     if (dst->needs_writable && !av_frame_is_writable(frame)) {
994         av_log(link->dst, AV_LOG_DEBUG, "Copying data in avfilter.\n");
995
996         /* Maybe use ff_copy_buffer_ref instead? */
997         switch (link->type) {
998         case AVMEDIA_TYPE_VIDEO:
999             out = ff_get_video_buffer(link, link->w, link->h);
1000             break;
1001         case AVMEDIA_TYPE_AUDIO:
1002             out = ff_get_audio_buffer(link, frame->nb_samples);
1003             break;
1004         default: return AVERROR(EINVAL);
1005         }
1006         if (!out) {
1007             av_frame_free(&frame);
1008             return AVERROR(ENOMEM);
1009         }
1010         av_frame_copy_props(out, frame);
1011
1012         switch (link->type) {
1013         case AVMEDIA_TYPE_VIDEO:
1014             av_image_copy(out->data, out->linesize, (const uint8_t **)frame->data, frame->linesize,
1015                           frame->format, frame->width, frame->height);
1016             break;
1017         case AVMEDIA_TYPE_AUDIO:
1018             av_samples_copy(out->extended_data, frame->extended_data,
1019                             0, 0, frame->nb_samples,
1020                             av_get_channel_layout_nb_channels(frame->channel_layout),
1021                             frame->format);
1022             break;
1023         default: return AVERROR(EINVAL);
1024         }
1025
1026         av_frame_free(&frame);
1027     } else
1028         out = frame;
1029
1030     while(cmd && cmd->time <= out->pts * av_q2d(link->time_base)){
1031         av_log(link->dst, AV_LOG_DEBUG,
1032                "Processing command time:%f command:%s arg:%s\n",
1033                cmd->time, cmd->command, cmd->arg);
1034         avfilter_process_command(link->dst, cmd->command, cmd->arg, 0, 0, cmd->flags);
1035         ff_command_queue_pop(link->dst);
1036         cmd= link->dst->command_queue;
1037     }
1038
1039     pts = out->pts;
1040     if (dstctx->enable_str) {
1041         int64_t pos = av_frame_get_pkt_pos(out);
1042         dstctx->var_values[VAR_N] = link->frame_count;
1043         dstctx->var_values[VAR_T] = pts == AV_NOPTS_VALUE ? NAN : pts * av_q2d(link->time_base);
1044         dstctx->var_values[VAR_POS] = pos == -1 ? NAN : pos;
1045
1046         dstctx->is_disabled = !av_expr_eval(dstctx->enable, dstctx->var_values, NULL);
1047         if (dstctx->is_disabled &&
1048             (dstctx->filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC))
1049             filter_frame = default_filter_frame;
1050     }
1051     ret = filter_frame(link, out);
1052     link->frame_count++;
1053     link->frame_requested = 0;
1054     ff_update_link_current_pts(link, pts);
1055     return ret;
1056 }
1057
1058 static int ff_filter_frame_needs_framing(AVFilterLink *link, AVFrame *frame)
1059 {
1060     int insamples = frame->nb_samples, inpos = 0, nb_samples;
1061     AVFrame *pbuf = link->partial_buf;
1062     int nb_channels = av_frame_get_channels(frame);
1063     int ret = 0;
1064
1065     link->flags |= FF_LINK_FLAG_REQUEST_LOOP;
1066     /* Handle framing (min_samples, max_samples) */
1067     while (insamples) {
1068         if (!pbuf) {
1069             AVRational samples_tb = { 1, link->sample_rate };
1070             pbuf = ff_get_audio_buffer(link, link->partial_buf_size);
1071             if (!pbuf) {
1072                 av_log(link->dst, AV_LOG_WARNING,
1073                        "Samples dropped due to memory allocation failure.\n");
1074                 return 0;
1075             }
1076             av_frame_copy_props(pbuf, frame);
1077             pbuf->pts = frame->pts +
1078                         av_rescale_q(inpos, samples_tb, link->time_base);
1079             pbuf->nb_samples = 0;
1080         }
1081         nb_samples = FFMIN(insamples,
1082                            link->partial_buf_size - pbuf->nb_samples);
1083         av_samples_copy(pbuf->extended_data, frame->extended_data,
1084                         pbuf->nb_samples, inpos,
1085                         nb_samples, nb_channels, link->format);
1086         inpos                   += nb_samples;
1087         insamples               -= nb_samples;
1088         pbuf->nb_samples += nb_samples;
1089         if (pbuf->nb_samples >= link->min_samples) {
1090             ret = ff_filter_frame_framed(link, pbuf);
1091             pbuf = NULL;
1092         }
1093     }
1094     av_frame_free(&frame);
1095     link->partial_buf = pbuf;
1096     return ret;
1097 }
1098
1099 int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
1100 {
1101     FF_TPRINTF_START(NULL, filter_frame); ff_tlog_link(NULL, link, 1); ff_tlog(NULL, " "); ff_tlog_ref(NULL, frame, 1);
1102
1103     /* Consistency checks */
1104     if (link->type == AVMEDIA_TYPE_VIDEO) {
1105         if (strcmp(link->dst->filter->name, "scale")) {
1106             av_assert1(frame->format                 == link->format);
1107             av_assert1(frame->width               == link->w);
1108             av_assert1(frame->height               == link->h);
1109         }
1110     } else {
1111         av_assert1(frame->format                == link->format);
1112         av_assert1(av_frame_get_channels(frame) == link->channels);
1113         av_assert1(frame->channel_layout        == link->channel_layout);
1114         av_assert1(frame->sample_rate           == link->sample_rate);
1115     }
1116
1117     /* Go directly to actual filtering if possible */
1118     if (link->type == AVMEDIA_TYPE_AUDIO &&
1119         link->min_samples &&
1120         (link->partial_buf ||
1121          frame->nb_samples < link->min_samples ||
1122          frame->nb_samples > link->max_samples)) {
1123         return ff_filter_frame_needs_framing(link, frame);
1124     } else {
1125         return ff_filter_frame_framed(link, frame);
1126     }
1127 }
1128
1129 const AVClass *avfilter_get_class(void)
1130 {
1131     return &avfilter_class;
1132 }