libavdevice/lavfi.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 2011 Stefano Sabatini
00003  *
00004  * This file is part of FFmpeg.
00005  *
00006  * FFmpeg is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU Lesser General Public
00008  * License as published by the Free Software Foundation; either
00009  * version 2.1 of the License, or (at your option) any later version.
00010  *
00011  * FFmpeg is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * Lesser General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU Lesser General Public
00017  * License along with FFmpeg; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00026 /* #define DEBUG */
00027 
00028 #include "float.h"              /* DBL_MIN, DBL_MAX */
00029 
00030 #include "libavutil/log.h"
00031 #include "libavutil/mem.h"
00032 #include "libavutil/opt.h"
00033 #include "libavutil/parseutils.h"
00034 #include "libavutil/pixdesc.h"
00035 #include "libavfilter/avfilter.h"
00036 #include "libavfilter/avfiltergraph.h"
00037 #include "libavfilter/buffersink.h"
00038 #include "libavformat/internal.h"
00039 #include "avdevice.h"
00040 
00041 typedef struct {
00042     AVClass *class;          
00043     char          *graph_str;
00044     char          *dump_graph;
00045     AVFilterGraph *graph;
00046     AVFilterContext **sinks;
00047     int *sink_stream_map;
00048     int *stream_sink_map;
00049 } LavfiContext;
00050 
00051 static int *create_all_formats(int n)
00052 {
00053     int i, j, *fmts, count = 0;
00054 
00055     for (i = 0; i < n; i++)
00056         if (!(av_pix_fmt_descriptors[i].flags & PIX_FMT_HWACCEL))
00057             count++;
00058 
00059     if (!(fmts = av_malloc((count+1) * sizeof(int))))
00060         return NULL;
00061     for (j = 0, i = 0; i < n; i++) {
00062         if (!(av_pix_fmt_descriptors[i].flags & PIX_FMT_HWACCEL))
00063             fmts[j++] = i;
00064     }
00065     fmts[j] = -1;
00066     return fmts;
00067 }
00068 
00069 av_cold static int lavfi_read_close(AVFormatContext *avctx)
00070 {
00071     LavfiContext *lavfi = avctx->priv_data;
00072 
00073     av_freep(&lavfi->sink_stream_map);
00074     av_freep(&lavfi->stream_sink_map);
00075     av_freep(&lavfi->sinks);
00076     avfilter_graph_free(&lavfi->graph);
00077 
00078     return 0;
00079 }
00080 
00081 av_cold static int lavfi_read_header(AVFormatContext *avctx,
00082                                      AVFormatParameters *ap)
00083 {
00084     LavfiContext *lavfi = avctx->priv_data;
00085     AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;
00086     AVFilter *buffersink, *abuffersink;
00087     int *pix_fmts = create_all_formats(PIX_FMT_NB);
00088     enum AVMediaType type;
00089     int ret = 0, i, n;
00090 
00091 #define FAIL(ERR) { ret = ERR; goto end; }
00092 
00093     if (!pix_fmts)
00094         FAIL(AVERROR(ENOMEM));
00095 
00096     avfilter_register_all();
00097 
00098     buffersink = avfilter_get_by_name("buffersink");
00099     abuffersink = avfilter_get_by_name("abuffersink");
00100 
00101     if (!lavfi->graph_str)
00102         lavfi->graph_str = av_strdup(avctx->filename);
00103 
00104     /* parse the graph, create a stream for each open output */
00105     if (!(lavfi->graph = avfilter_graph_alloc()))
00106         FAIL(AVERROR(ENOMEM));
00107 
00108     if ((ret = avfilter_graph_parse(lavfi->graph, lavfi->graph_str,
00109                                     &input_links, &output_links, avctx)) < 0)
00110         FAIL(ret);
00111 
00112     if (input_links) {
00113         av_log(avctx, AV_LOG_ERROR,
00114                "Open inputs in the filtergraph are not acceptable\n");
00115         FAIL(AVERROR(EINVAL));
00116     }
00117 
00118     /* count the outputs */
00119     for (n = 0, inout = output_links; inout; n++, inout = inout->next);
00120 
00121     if (!(lavfi->sink_stream_map = av_malloc(sizeof(int) * n)))
00122         FAIL(AVERROR(ENOMEM));
00123     if (!(lavfi->stream_sink_map = av_malloc(sizeof(int) * n)))
00124         FAIL(AVERROR(ENOMEM));
00125 
00126     for (i = 0; i < n; i++)
00127         lavfi->stream_sink_map[i] = -1;
00128 
00129     /* parse the output link names - they need to be of the form out0, out1, ...
00130      * create a mapping between them and the streams */
00131     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
00132         int stream_idx;
00133         if (!strcmp(inout->name, "out"))
00134             stream_idx = 0;
00135         else if (sscanf(inout->name, "out%d\n", &stream_idx) != 1) {
00136             av_log(avctx,  AV_LOG_ERROR,
00137                    "Invalid outpad name '%s'\n", inout->name);
00138             FAIL(AVERROR(EINVAL));
00139         }
00140 
00141         if ((unsigned)stream_idx >= n) {
00142             av_log(avctx, AV_LOG_ERROR,
00143                    "Invalid index was specified in output '%s', "
00144                    "must be a non-negative value < %d\n",
00145                    inout->name, n);
00146             FAIL(AVERROR(EINVAL));
00147         }
00148 
00149         /* is an audio or video output? */
00150         type = inout->filter_ctx->output_pads[inout->pad_idx].type;
00151         if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
00152             av_log(avctx,  AV_LOG_ERROR,
00153                    "Output '%s' is not a video or audio output, not yet supported\n", inout->name);
00154             FAIL(AVERROR(EINVAL));
00155         }
00156 
00157         if (lavfi->stream_sink_map[stream_idx] != -1) {
00158             av_log(avctx,  AV_LOG_ERROR,
00159                    "An output with stream index %d was already specified\n",
00160                    stream_idx);
00161             FAIL(AVERROR(EINVAL));
00162         }
00163         lavfi->sink_stream_map[i] = stream_idx;
00164         lavfi->stream_sink_map[stream_idx] = i;
00165     }
00166 
00167     /* for each open output create a corresponding stream */
00168     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
00169         AVStream *st;
00170         if (!(st = avformat_new_stream(avctx, NULL)))
00171             FAIL(AVERROR(ENOMEM));
00172         st->id = i;
00173     }
00174 
00175     /* create a sink for each output and connect them to the graph */
00176     lavfi->sinks = av_malloc(sizeof(AVFilterContext *) * avctx->nb_streams);
00177     if (!lavfi->sinks)
00178         FAIL(AVERROR(ENOMEM));
00179 
00180     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
00181         AVFilterContext *sink;
00182 
00183         type = inout->filter_ctx->output_pads[inout->pad_idx].type;
00184 
00185         if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||
00186             type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {
00187                 av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");
00188                 FAIL(AVERROR_FILTER_NOT_FOUND);
00189         }
00190 
00191         if (type == AVMEDIA_TYPE_VIDEO) {
00192             AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
00193 
00194 #if FF_API_OLD_VSINK_API
00195             ret = avfilter_graph_create_filter(&sink, buffersink,
00196                                                inout->name, NULL,
00197                                                pix_fmts, lavfi->graph);
00198 #else
00199             buffersink_params->pixel_fmts = pix_fmts;
00200             ret = avfilter_graph_create_filter(&sink, buffersink,
00201                                                inout->name, NULL,
00202                                                buffersink_params, lavfi->graph);
00203 #endif
00204             av_freep(&buffersink_params);
00205 
00206             if (ret < 0)
00207                 goto end;
00208         } else if (type == AVMEDIA_TYPE_AUDIO) {
00209             enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, -1 };
00210             const int packing_fmts[] = { AVFILTER_PACKED, -1 };
00211             const int64_t *chlayouts = avfilter_all_channel_layouts;
00212             AVABufferSinkParams *abuffersink_params = av_abuffersink_params_alloc();
00213             abuffersink_params->sample_fmts = sample_fmts;
00214             abuffersink_params->packing_fmts = packing_fmts;
00215             abuffersink_params->channel_layouts = chlayouts;
00216 
00217             ret = avfilter_graph_create_filter(&sink, abuffersink,
00218                                                inout->name, NULL,
00219                                                abuffersink_params, lavfi->graph);
00220             av_free(abuffersink_params);
00221             if (ret < 0)
00222                 goto end;
00223         }
00224 
00225         lavfi->sinks[i] = sink;
00226         if ((ret = avfilter_link(inout->filter_ctx, inout->pad_idx, sink, 0)) < 0)
00227             FAIL(ret);
00228     }
00229 
00230     /* configure the graph */
00231     if ((ret = avfilter_graph_config(lavfi->graph, avctx)) < 0)
00232         FAIL(ret);
00233 
00234     if (lavfi->dump_graph) {
00235         char *dump = avfilter_graph_dump(lavfi->graph, lavfi->dump_graph);
00236         fputs(dump, stderr);
00237         fflush(stderr);
00238         av_free(dump);
00239     }
00240 
00241     /* fill each stream with the information in the corresponding sink */
00242     for (i = 0; i < avctx->nb_streams; i++) {
00243         AVFilterLink *link = lavfi->sinks[lavfi->stream_sink_map[i]]->inputs[0];
00244         AVStream *st = avctx->streams[i];
00245         st->codec->codec_type = link->type;
00246         avpriv_set_pts_info(st, 64, link->time_base.num, link->time_base.den);
00247         if (link->type == AVMEDIA_TYPE_VIDEO) {
00248             st->codec->codec_id   = CODEC_ID_RAWVIDEO;
00249             st->codec->pix_fmt    = link->format;
00250             st->codec->time_base  = link->time_base;
00251             st->codec->width      = link->w;
00252             st->codec->height     = link->h;
00253             st       ->sample_aspect_ratio =
00254             st->codec->sample_aspect_ratio = link->sample_aspect_ratio;
00255         } else if (link->type == AVMEDIA_TYPE_AUDIO) {
00256             st->codec->codec_id    = CODEC_ID_PCM_S16LE;
00257             st->codec->channels    = av_get_channel_layout_nb_channels(link->channel_layout);
00258             st->codec->sample_fmt  = link->format;
00259             st->codec->sample_rate = link->sample_rate;
00260             st->codec->time_base   = link->time_base;
00261             st->codec->channel_layout = link->channel_layout;
00262         }
00263     }
00264 
00265 end:
00266     av_free(pix_fmts);
00267     avfilter_inout_free(&input_links);
00268     avfilter_inout_free(&output_links);
00269     if (ret < 0)
00270         lavfi_read_close(avctx);
00271     return ret;
00272 }
00273 
00274 static int lavfi_read_packet(AVFormatContext *avctx, AVPacket *pkt)
00275 {
00276     LavfiContext *lavfi = avctx->priv_data;
00277     double min_pts = DBL_MAX;
00278     int stream_idx, min_pts_sink_idx = 0;
00279     AVFilterBufferRef *ref;
00280     AVPicture pict;
00281     int ret, i;
00282     int size = 0;
00283 
00284     /* iterate through all the graph sinks. Select the sink with the
00285      * minimum PTS */
00286     for (i = 0; i < avctx->nb_streams; i++) {
00287         AVRational tb = lavfi->sinks[i]->inputs[0]->time_base;
00288         double d;
00289         int ret = av_buffersink_get_buffer_ref(lavfi->sinks[i],
00290                                                &ref, AV_BUFFERSINK_FLAG_PEEK);
00291         if (ret < 0)
00292             return ret;
00293         d = av_rescale_q(ref->pts, tb, AV_TIME_BASE_Q);
00294         av_dlog(avctx, "sink_idx:%d time:%f\n", i, d);
00295 
00296         if (d < min_pts) {
00297             min_pts = d;
00298             min_pts_sink_idx = i;
00299         }
00300     }
00301     av_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);
00302 
00303     av_buffersink_get_buffer_ref(lavfi->sinks[min_pts_sink_idx], &ref, 0);
00304     stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];
00305 
00306     if (ref->video) {
00307         size = avpicture_get_size(ref->format, ref->video->w, ref->video->h);
00308         if ((ret = av_new_packet(pkt, size)) < 0)
00309             return ret;
00310 
00311         memcpy(pict.data,     ref->data,     4*sizeof(ref->data[0]));
00312         memcpy(pict.linesize, ref->linesize, 4*sizeof(ref->linesize[0]));
00313 
00314         avpicture_layout(&pict, ref->format, ref->video->w,
00315                          ref->video->h, pkt->data, size);
00316     } else if (ref->audio) {
00317         size = ref->audio->nb_samples *
00318             av_get_bytes_per_sample(ref->format) *
00319             av_get_channel_layout_nb_channels(ref->audio->channel_layout);
00320         if ((ret = av_new_packet(pkt, size)) < 0)
00321             return ret;
00322         memcpy(pkt->data, ref->data[0], size);
00323     }
00324 
00325     pkt->stream_index = stream_idx;
00326     pkt->pts = ref->pts;
00327     pkt->pos = ref->pos;
00328     pkt->size = size;
00329     avfilter_unref_buffer(ref);
00330 
00331     return size;
00332 }
00333 
00334 #define OFFSET(x) offsetof(LavfiContext, x)
00335 
00336 #define DEC AV_OPT_FLAG_DECODING_PARAM
00337 
00338 static const AVOption options[] = {
00339     { "graph", "Libavfilter graph", OFFSET(graph_str),  AV_OPT_TYPE_STRING, {.str = NULL }, 0,  0, DEC },
00340     { "dumpgraph", "Dump graph to stderr", OFFSET(dump_graph), AV_OPT_TYPE_STRING, {.str = NULL}, 0,  0, DEC },
00341     { NULL },
00342 };
00343 
00344 static const AVClass lavfi_class = {
00345     .class_name = "lavfi indev",
00346     .item_name  = av_default_item_name,
00347     .option     = options,
00348     .version    = LIBAVUTIL_VERSION_INT,
00349 };
00350 
00351 AVInputFormat ff_lavfi_demuxer = {
00352     .name           = "lavfi",
00353     .long_name      = NULL_IF_CONFIG_SMALL("Libavfilter virtual input device"),
00354     .priv_data_size = sizeof(LavfiContext),
00355     .read_header    = lavfi_read_header,
00356     .read_packet    = lavfi_read_packet,
00357     .read_close     = lavfi_read_close,
00358     .flags          = AVFMT_NOFILE,
00359     .priv_class     = &lavfi_class,
00360 };