]> git.sesse.net Git - ffmpeg/blob - libavfilter/avfilter.c
Merge commit 'b047c68783aa4042b322af7af043b643d5daf09c'
[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/avassert.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/common.h"
26 #include "libavutil/imgutils.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/rational.h"
29 #include "libavutil/samplefmt.h"
30
31 #include "audio.h"
32 #include "avfilter.h"
33 #include "formats.h"
34 #include "internal.h"
35 #include "audio.h"
36
37 char *ff_get_ref_perms_string(char *buf, size_t buf_size, int perms)
38 {
39     snprintf(buf, buf_size, "%s%s%s%s%s%s",
40              perms & AV_PERM_READ      ? "r" : "",
41              perms & AV_PERM_WRITE     ? "w" : "",
42              perms & AV_PERM_PRESERVE  ? "p" : "",
43              perms & AV_PERM_REUSE     ? "u" : "",
44              perms & AV_PERM_REUSE2    ? "U" : "",
45              perms & AV_PERM_NEG_LINESIZES ? "n" : "");
46     return buf;
47 }
48
49 void ff_tlog_ref(void *ctx, AVFilterBufferRef *ref, int end)
50 {
51     av_unused char buf[16];
52     ff_tlog(ctx,
53             "ref[%p buf:%p refcount:%d perms:%s data:%p linesize[%d, %d, %d, %d] pts:%"PRId64" pos:%"PRId64,
54             ref, ref->buf, ref->buf->refcount, ff_get_ref_perms_string(buf, sizeof(buf), ref->perms), ref->data[0],
55             ref->linesize[0], ref->linesize[1], ref->linesize[2], ref->linesize[3],
56             ref->pts, ref->pos);
57
58     if (ref->video) {
59         ff_tlog(ctx, " a:%d/%d s:%dx%d i:%c iskey:%d type:%c",
60                 ref->video->sample_aspect_ratio.num, ref->video->sample_aspect_ratio.den,
61                 ref->video->w, ref->video->h,
62                 !ref->video->interlaced     ? 'P' :         /* Progressive  */
63                 ref->video->top_field_first ? 'T' : 'B',    /* Top / Bottom */
64                 ref->video->key_frame,
65                 av_get_picture_type_char(ref->video->pict_type));
66     }
67     if (ref->audio) {
68         ff_tlog(ctx, " cl:%"PRId64"d n:%d r:%d",
69                 ref->audio->channel_layout,
70                 ref->audio->nb_samples,
71                 ref->audio->sample_rate);
72     }
73
74     ff_tlog(ctx, "]%s", end ? "\n" : "");
75 }
76
77 unsigned avfilter_version(void) {
78     av_assert0(LIBAVFILTER_VERSION_MICRO >= 100);
79     return LIBAVFILTER_VERSION_INT;
80 }
81
82 const char *avfilter_configuration(void)
83 {
84     return FFMPEG_CONFIGURATION;
85 }
86
87 const char *avfilter_license(void)
88 {
89 #define LICENSE_PREFIX "libavfilter license: "
90     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
91 }
92
93 void ff_command_queue_pop(AVFilterContext *filter)
94 {
95     AVFilterCommand *c= filter->command_queue;
96     av_freep(&c->arg);
97     av_freep(&c->command);
98     filter->command_queue= c->next;
99     av_free(c);
100 }
101
102 void ff_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,
103                    AVFilterPad **pads, AVFilterLink ***links,
104                    AVFilterPad *newpad)
105 {
106     unsigned i;
107
108     idx = FFMIN(idx, *count);
109
110     *pads  = av_realloc(*pads,  sizeof(AVFilterPad)   * (*count + 1));
111     *links = av_realloc(*links, sizeof(AVFilterLink*) * (*count + 1));
112     memmove(*pads +idx+1, *pads +idx, sizeof(AVFilterPad)   * (*count-idx));
113     memmove(*links+idx+1, *links+idx, sizeof(AVFilterLink*) * (*count-idx));
114     memcpy(*pads+idx, newpad, sizeof(AVFilterPad));
115     (*links)[idx] = NULL;
116
117     (*count)++;
118     for (i = idx+1; i < *count; i++)
119         if (*links[i])
120             (*(unsigned *)((uint8_t *) *links[i] + padidx_off))++;
121 }
122
123 int avfilter_link(AVFilterContext *src, unsigned srcpad,
124                   AVFilterContext *dst, unsigned dstpad)
125 {
126     AVFilterLink *link;
127
128     if (src->nb_outputs <= srcpad || dst->nb_inputs <= dstpad ||
129         src->outputs[srcpad]      || dst->inputs[dstpad])
130         return -1;
131
132     if (src->output_pads[srcpad].type != dst->input_pads[dstpad].type) {
133         av_log(src, AV_LOG_ERROR,
134                "Media type mismatch between the '%s' filter output pad %d (%s) and the '%s' filter input pad %d (%s)\n",
135                src->name, srcpad, (char *)av_x_if_null(av_get_media_type_string(src->output_pads[srcpad].type), "?"),
136                dst->name, dstpad, (char *)av_x_if_null(av_get_media_type_string(dst-> input_pads[dstpad].type), "?"));
137         return AVERROR(EINVAL);
138     }
139
140     src->outputs[srcpad] =
141     dst-> inputs[dstpad] = link = av_mallocz(sizeof(AVFilterLink));
142
143     link->src     = src;
144     link->dst     = dst;
145     link->srcpad  = &src->output_pads[srcpad];
146     link->dstpad  = &dst->input_pads[dstpad];
147     link->type    = src->output_pads[srcpad].type;
148     av_assert0(AV_PIX_FMT_NONE == -1 && AV_SAMPLE_FMT_NONE == -1);
149     link->format  = -1;
150
151     return 0;
152 }
153
154 void avfilter_link_free(AVFilterLink **link)
155 {
156     if (!*link)
157         return;
158
159     if ((*link)->pool)
160         ff_free_pool((*link)->pool);
161
162     avfilter_unref_bufferp(&(*link)->partial_buf);
163
164     av_freep(link);
165 }
166
167 int avfilter_link_get_channels(AVFilterLink *link)
168 {
169     return link->channels;
170 }
171
172 void avfilter_link_set_closed(AVFilterLink *link, int closed)
173 {
174     link->closed = closed;
175 }
176
177 int avfilter_insert_filter(AVFilterLink *link, AVFilterContext *filt,
178                            unsigned filt_srcpad_idx, unsigned filt_dstpad_idx)
179 {
180     int ret;
181     unsigned dstpad_idx = link->dstpad - link->dst->input_pads;
182
183     av_log(link->dst, AV_LOG_VERBOSE, "auto-inserting filter '%s' "
184            "between the filter '%s' and the filter '%s'\n",
185            filt->name, link->src->name, link->dst->name);
186
187     link->dst->inputs[dstpad_idx] = NULL;
188     if ((ret = avfilter_link(filt, filt_dstpad_idx, link->dst, dstpad_idx)) < 0) {
189         /* failed to link output filter to new filter */
190         link->dst->inputs[dstpad_idx] = link;
191         return ret;
192     }
193
194     /* re-hookup the link to the new destination filter we inserted */
195     link->dst = filt;
196     link->dstpad = &filt->input_pads[filt_srcpad_idx];
197     filt->inputs[filt_srcpad_idx] = link;
198
199     /* if any information on supported media formats already exists on the
200      * link, we need to preserve that */
201     if (link->out_formats)
202         ff_formats_changeref(&link->out_formats,
203                                    &filt->outputs[filt_dstpad_idx]->out_formats);
204
205     if (link->out_samplerates)
206         ff_formats_changeref(&link->out_samplerates,
207                                    &filt->outputs[filt_dstpad_idx]->out_samplerates);
208     if (link->out_channel_layouts)
209         ff_channel_layouts_changeref(&link->out_channel_layouts,
210                                      &filt->outputs[filt_dstpad_idx]->out_channel_layouts);
211
212     return 0;
213 }
214
215 int avfilter_config_links(AVFilterContext *filter)
216 {
217     int (*config_link)(AVFilterLink *);
218     unsigned i;
219     int ret;
220
221     for (i = 0; i < filter->nb_inputs; i ++) {
222         AVFilterLink *link = filter->inputs[i];
223         AVFilterLink *inlink = link->src->nb_inputs ?
224             link->src->inputs[0] : NULL;
225
226         if (!link) continue;
227
228         link->current_pts = AV_NOPTS_VALUE;
229
230         switch (link->init_state) {
231         case AVLINK_INIT:
232             continue;
233         case AVLINK_STARTINIT:
234             av_log(filter, AV_LOG_INFO, "circular filter chain detected\n");
235             return 0;
236         case AVLINK_UNINIT:
237             link->init_state = AVLINK_STARTINIT;
238
239             if ((ret = avfilter_config_links(link->src)) < 0)
240                 return ret;
241
242             if (!(config_link = link->srcpad->config_props)) {
243                 if (link->src->nb_inputs != 1) {
244                     av_log(link->src, AV_LOG_ERROR, "Source filters and filters "
245                                                     "with more than one input "
246                                                     "must set config_props() "
247                                                     "callbacks on all outputs\n");
248                     return AVERROR(EINVAL);
249                 }
250             } else if ((ret = config_link(link)) < 0) {
251                 av_log(link->src, AV_LOG_ERROR,
252                        "Failed to configure output pad on %s\n",
253                        link->src->name);
254                 return ret;
255             }
256
257             switch (link->type) {
258             case AVMEDIA_TYPE_VIDEO:
259                 if (!link->time_base.num && !link->time_base.den)
260                     link->time_base = inlink ? inlink->time_base : AV_TIME_BASE_Q;
261
262                 if (!link->sample_aspect_ratio.num && !link->sample_aspect_ratio.den)
263                     link->sample_aspect_ratio = inlink ?
264                         inlink->sample_aspect_ratio : (AVRational){1,1};
265
266                 if (inlink && !link->frame_rate.num && !link->frame_rate.den)
267                     link->frame_rate = inlink->frame_rate;
268
269                 if (inlink) {
270                     if (!link->w)
271                         link->w = inlink->w;
272                     if (!link->h)
273                         link->h = inlink->h;
274                 } else if (!link->w || !link->h) {
275                     av_log(link->src, AV_LOG_ERROR,
276                            "Video source filters must set their output link's "
277                            "width and height\n");
278                     return AVERROR(EINVAL);
279                 }
280                 break;
281
282             case AVMEDIA_TYPE_AUDIO:
283                 if (inlink) {
284                     if (!link->time_base.num && !link->time_base.den)
285                         link->time_base = inlink->time_base;
286                 }
287
288                 if (!link->time_base.num && !link->time_base.den)
289                     link->time_base = (AVRational) {1, link->sample_rate};
290             }
291
292             if ((config_link = link->dstpad->config_props))
293                 if ((ret = config_link(link)) < 0) {
294                     av_log(link->src, AV_LOG_ERROR,
295                            "Failed to configure input pad on %s\n",
296                            link->dst->name);
297                     return ret;
298                 }
299
300             link->init_state = AVLINK_INIT;
301         }
302     }
303
304     return 0;
305 }
306
307 void ff_tlog_link(void *ctx, AVFilterLink *link, int end)
308 {
309     if (link->type == AVMEDIA_TYPE_VIDEO) {
310         ff_tlog(ctx,
311                 "link[%p s:%dx%d fmt:%s %s->%s]%s",
312                 link, link->w, link->h,
313                 av_get_pix_fmt_name(link->format),
314                 link->src ? link->src->filter->name : "",
315                 link->dst ? link->dst->filter->name : "",
316                 end ? "\n" : "");
317     } else {
318         char buf[128];
319         av_get_channel_layout_string(buf, sizeof(buf), -1, link->channel_layout);
320
321         ff_tlog(ctx,
322                 "link[%p r:%d cl:%s fmt:%s %s->%s]%s",
323                 link, (int)link->sample_rate, buf,
324                 av_get_sample_fmt_name(link->format),
325                 link->src ? link->src->filter->name : "",
326                 link->dst ? link->dst->filter->name : "",
327                 end ? "\n" : "");
328     }
329 }
330
331 int ff_request_frame(AVFilterLink *link)
332 {
333     int ret = -1;
334     FF_TPRINTF_START(NULL, request_frame); ff_tlog_link(NULL, link, 1);
335
336     if (link->closed)
337         return AVERROR_EOF;
338     if (link->srcpad->request_frame)
339         ret = link->srcpad->request_frame(link);
340     else if (link->src->inputs[0])
341         ret = ff_request_frame(link->src->inputs[0]);
342     if (ret == AVERROR_EOF && link->partial_buf) {
343         AVFilterBufferRef *pbuf = link->partial_buf;
344         link->partial_buf = NULL;
345         ff_filter_samples_framed(link, pbuf);
346         return 0;
347     }
348     if (ret == AVERROR_EOF)
349         link->closed = 1;
350     return ret;
351 }
352
353 int ff_poll_frame(AVFilterLink *link)
354 {
355     int i, min = INT_MAX;
356
357     if (link->srcpad->poll_frame)
358         return link->srcpad->poll_frame(link);
359
360     for (i = 0; i < link->src->nb_inputs; i++) {
361         int val;
362         if (!link->src->inputs[i])
363             return -1;
364         val = ff_poll_frame(link->src->inputs[i]);
365         min = FFMIN(min, val);
366     }
367
368     return min;
369 }
370
371 void ff_update_link_current_pts(AVFilterLink *link, int64_t pts)
372 {
373     if (pts == AV_NOPTS_VALUE)
374         return;
375     link->current_pts = av_rescale_q(pts, link->time_base, AV_TIME_BASE_Q);
376     /* TODO use duration */
377     if (link->graph && link->age_index >= 0)
378         ff_avfilter_graph_update_heap(link->graph, link);
379 }
380
381 int avfilter_process_command(AVFilterContext *filter, const char *cmd, const char *arg, char *res, int res_len, int flags)
382 {
383     if(!strcmp(cmd, "ping")){
384         av_strlcatf(res, res_len, "pong from:%s %s\n", filter->filter->name, filter->name);
385         return 0;
386     }else if(filter->filter->process_command) {
387         return filter->filter->process_command(filter, cmd, arg, res, res_len, flags);
388     }
389     return AVERROR(ENOSYS);
390 }
391
392 #define MAX_REGISTERED_AVFILTERS_NB 128
393
394 static AVFilter *registered_avfilters[MAX_REGISTERED_AVFILTERS_NB + 1];
395
396 static int next_registered_avfilter_idx = 0;
397
398 AVFilter *avfilter_get_by_name(const char *name)
399 {
400     int i;
401
402     for (i = 0; registered_avfilters[i]; i++)
403         if (!strcmp(registered_avfilters[i]->name, name))
404             return registered_avfilters[i];
405
406     return NULL;
407 }
408
409 int avfilter_register(AVFilter *filter)
410 {
411     int i;
412
413     if (next_registered_avfilter_idx == MAX_REGISTERED_AVFILTERS_NB) {
414         av_log(NULL, AV_LOG_ERROR,
415                "Maximum number of registered filters %d reached, "
416                "impossible to register filter with name '%s'\n",
417                MAX_REGISTERED_AVFILTERS_NB, filter->name);
418         return AVERROR(ENOMEM);
419     }
420
421     for(i=0; filter->inputs && filter->inputs[i].name; i++) {
422         const AVFilterPad *input = &filter->inputs[i];
423         av_assert0(     !input->filter_frame
424                     || (!input->start_frame && !input->end_frame && !input->draw_slice));
425     }
426
427     registered_avfilters[next_registered_avfilter_idx++] = filter;
428     return 0;
429 }
430
431 AVFilter **av_filter_next(AVFilter **filter)
432 {
433     return filter ? ++filter : &registered_avfilters[0];
434 }
435
436 void avfilter_uninit(void)
437 {
438     memset(registered_avfilters, 0, sizeof(registered_avfilters));
439     next_registered_avfilter_idx = 0;
440 }
441
442 static int pad_count(const AVFilterPad *pads)
443 {
444     int count;
445
446     if (!pads)
447         return 0;
448
449     for(count = 0; pads->name; count ++) pads ++;
450     return count;
451 }
452
453 static const char *default_filter_name(void *filter_ctx)
454 {
455     AVFilterContext *ctx = filter_ctx;
456     return ctx->name ? ctx->name : ctx->filter->name;
457 }
458
459 static void *filter_child_next(void *obj, void *prev)
460 {
461     AVFilterContext *ctx = obj;
462     if (!prev && ctx->filter && ctx->filter->priv_class)
463         return ctx->priv;
464     return NULL;
465 }
466
467 static const AVClass *filter_child_class_next(const AVClass *prev)
468 {
469     AVFilter **filter_ptr = NULL;
470
471     /* find the filter that corresponds to prev */
472     while (prev && *(filter_ptr = av_filter_next(filter_ptr)))
473         if ((*filter_ptr)->priv_class == prev)
474             break;
475
476     /* could not find filter corresponding to prev */
477     if (prev && !(*filter_ptr))
478         return NULL;
479
480     /* find next filter with specific options */
481     while (*(filter_ptr = av_filter_next(filter_ptr)))
482         if ((*filter_ptr)->priv_class)
483             return (*filter_ptr)->priv_class;
484     return NULL;
485 }
486
487 static const AVClass avfilter_class = {
488     .class_name = "AVFilter",
489     .item_name  = default_filter_name,
490     .version    = LIBAVUTIL_VERSION_INT,
491     .category   = AV_CLASS_CATEGORY_FILTER,
492     .child_next = filter_child_next,
493     .child_class_next = filter_child_class_next,
494 };
495
496 const AVClass *avfilter_get_class(void)
497 {
498     return &avfilter_class;
499 }
500
501 int avfilter_open(AVFilterContext **filter_ctx, AVFilter *filter, const char *inst_name)
502 {
503     AVFilterContext *ret;
504     *filter_ctx = NULL;
505
506     if (!filter)
507         return AVERROR(EINVAL);
508
509     ret = av_mallocz(sizeof(AVFilterContext));
510     if (!ret)
511         return AVERROR(ENOMEM);
512
513     ret->av_class = &avfilter_class;
514     ret->filter   = filter;
515     ret->name     = inst_name ? av_strdup(inst_name) : NULL;
516     if (filter->priv_size) {
517         ret->priv     = av_mallocz(filter->priv_size);
518         if (!ret->priv)
519             goto err;
520     }
521
522     ret->nb_inputs = pad_count(filter->inputs);
523     if (ret->nb_inputs ) {
524         ret->input_pads   = av_malloc(sizeof(AVFilterPad) * ret->nb_inputs);
525         if (!ret->input_pads)
526             goto err;
527         memcpy(ret->input_pads, filter->inputs, sizeof(AVFilterPad) * ret->nb_inputs);
528         ret->inputs       = av_mallocz(sizeof(AVFilterLink*) * ret->nb_inputs);
529         if (!ret->inputs)
530             goto err;
531     }
532
533     ret->nb_outputs = pad_count(filter->outputs);
534     if (ret->nb_outputs) {
535         ret->output_pads  = av_malloc(sizeof(AVFilterPad) * ret->nb_outputs);
536         if (!ret->output_pads)
537             goto err;
538         memcpy(ret->output_pads, filter->outputs, sizeof(AVFilterPad) * ret->nb_outputs);
539         ret->outputs      = av_mallocz(sizeof(AVFilterLink*) * ret->nb_outputs);
540         if (!ret->outputs)
541             goto err;
542     }
543 #if FF_API_FOO_COUNT
544     ret->output_count = ret->nb_outputs;
545     ret->input_count  = ret->nb_inputs;
546 #endif
547
548     *filter_ctx = ret;
549     return 0;
550
551 err:
552     av_freep(&ret->inputs);
553     av_freep(&ret->input_pads);
554     ret->nb_inputs = 0;
555     av_freep(&ret->outputs);
556     av_freep(&ret->output_pads);
557     ret->nb_outputs = 0;
558     av_freep(&ret->priv);
559     av_free(ret);
560     return AVERROR(ENOMEM);
561 }
562
563 void avfilter_free(AVFilterContext *filter)
564 {
565     int i;
566     AVFilterLink *link;
567
568     if (!filter)
569         return;
570
571     if (filter->filter->uninit)
572         filter->filter->uninit(filter);
573
574     for (i = 0; i < filter->nb_inputs; i++) {
575         if ((link = filter->inputs[i])) {
576             if (link->src)
577                 link->src->outputs[link->srcpad - link->src->output_pads] = NULL;
578             ff_formats_unref(&link->in_formats);
579             ff_formats_unref(&link->out_formats);
580             ff_formats_unref(&link->in_samplerates);
581             ff_formats_unref(&link->out_samplerates);
582             ff_channel_layouts_unref(&link->in_channel_layouts);
583             ff_channel_layouts_unref(&link->out_channel_layouts);
584         }
585         avfilter_link_free(&link);
586     }
587     for (i = 0; i < filter->nb_outputs; i++) {
588         if ((link = filter->outputs[i])) {
589             if (link->dst)
590                 link->dst->inputs[link->dstpad - link->dst->input_pads] = NULL;
591             ff_formats_unref(&link->in_formats);
592             ff_formats_unref(&link->out_formats);
593             ff_formats_unref(&link->in_samplerates);
594             ff_formats_unref(&link->out_samplerates);
595             ff_channel_layouts_unref(&link->in_channel_layouts);
596             ff_channel_layouts_unref(&link->out_channel_layouts);
597         }
598         avfilter_link_free(&link);
599     }
600
601     av_freep(&filter->name);
602     av_freep(&filter->input_pads);
603     av_freep(&filter->output_pads);
604     av_freep(&filter->inputs);
605     av_freep(&filter->outputs);
606     av_freep(&filter->priv);
607     while(filter->command_queue){
608         ff_command_queue_pop(filter);
609     }
610     av_free(filter);
611 }
612
613 int avfilter_init_filter(AVFilterContext *filter, const char *args, void *opaque)
614 {
615     int ret=0;
616
617     if (filter->filter->init_opaque)
618         ret = filter->filter->init_opaque(filter, args, opaque);
619     else if (filter->filter->init)
620         ret = filter->filter->init(filter, args);
621     return ret;
622 }
623
624 const char *avfilter_pad_get_name(AVFilterPad *pads, int pad_idx)
625 {
626     return pads[pad_idx].name;
627 }
628
629 enum AVMediaType avfilter_pad_get_type(AVFilterPad *pads, int pad_idx)
630 {
631     return pads[pad_idx].type;
632 }
633
634 int ff_filter_frame(AVFilterLink *link, AVFilterBufferRef *frame)
635 {
636     int ret;
637     FF_TPRINTF_START(NULL, filter_frame); ff_tlog_link(NULL, link, 1); ff_tlog(NULL, " "); ff_tlog_ref(NULL, frame, 1);
638
639     switch (link->type) {
640     case AVMEDIA_TYPE_VIDEO:
641         if((ret = ff_start_frame(link, frame)) < 0)
642             return ret;
643         if((ret = ff_draw_slice(link, 0, frame->video->h, 1)) < 0)
644             return ret;
645         if((ret = ff_end_frame(link)) < 0)
646             return ret;
647         return ret;
648     case AVMEDIA_TYPE_AUDIO:
649         return ff_filter_samples(link, frame);
650     default: return AVERROR(EINVAL);
651     }
652 }