[PATCH] Add movie video source.

Stefano Sabatini stefano.sabatini-lala
Sun Oct 31 17:37:10 CET 2010


---
 doc/filters.texi         |   39 +++++
 libavfilter/Makefile     |    2 +
 libavfilter/allfilters.c |    1 +
 libavfilter/vsrc_movie.c |  351 ++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 393 insertions(+), 0 deletions(-)
 create mode 100644 libavfilter/vsrc_movie.c

diff --git a/doc/filters.texi b/doc/filters.texi
index 3842886..16ca163 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -1088,6 +1088,45 @@ to the pad with identifier "in".
 "color=red@@0.2:qcif:10 [color]; [in][color] overlay [out]"
 @end example
 
+ at section movie
+
+Read a video stream from a movie container.
+
+It accepts the syntax:
+ at example
+ at var{seekpoint}:@var{format}:@var{filename}[:@var{stream_index}]
+ at end example
+
+ at var{seekpoint} specifies the seek point in seconds, the frames will
+be output starting from this seek point, the parameter is evaluated
+with @code{av_strtod} so the numerical value may be suffixed by an SI
+postfix.
+
+ at var{format} specifies the assumed format for the input file, and can
+be either the name of a container or an input device.
+
+ at var{filename} specifies the name of the input file.
+
+ at var{stream_index} is optional and specifies the index of the video
+stream to read. If the value is negative, the best suited video stream
+will be automatically selected. Default value is "-1".
+
+It is possible to overlay a second movie on top of another source as
+shown in this graph:
+ at example
+input -----------> deltapts0 --> overlay --> output
+                                    ^
+                                    |
+movie --> scale--> deltapts1 -------+
+ at end example
+
+Some examples follow:
+ at example
+# skip 3.2 seconds from the start of the avi file in.avi, and overlay it
+# on top of the input labelled as "in".
+"movie=3.2:avi:in.avi, scale=180:-1, setpts=PTS-STARTPTS [movie]; [in] setpts=PTS-START_PTS, [movie] overlay=16:16 [out]"
+ at end example
+
 @section nullsrc
 
 Null video source, never return images. It is mainly useful as a
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index fdb181e..ce1caa5 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -2,6 +2,7 @@ include $(SUBDIR)../config.mak
 
 NAME = avfilter
 FFLIBS = avcore avutil
+FFLIBS-$(CONFIG_MOVIE_FILTER) += avformat avcodec
 FFLIBS-$(CONFIG_SCALE_FILTER) += swscale
 
 HEADERS = avfilter.h avfiltergraph.h
@@ -50,6 +51,7 @@ OBJS-$(CONFIG_YADIF_FILTER)                  += vf_yadif.o
 OBJS-$(CONFIG_BUFFER_FILTER)                 += vsrc_buffer.o
 OBJS-$(CONFIG_COLOR_FILTER)                  += vf_pad.o
 OBJS-$(CONFIG_FREI0R_SRC_FILTER)             += vf_frei0r.o
+OBJS-$(CONFIG_MOVIE_FILTER)                  += vsrc_movie.o
 OBJS-$(CONFIG_NULLSRC_FILTER)                += vsrc_nullsrc.o
 
 OBJS-$(CONFIG_NULLSINK_FILTER)               += vsink_nullsink.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 1dffb80..cb29c2f 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -71,6 +71,7 @@ void avfilter_register_all(void)
     REGISTER_FILTER (BUFFER,      buffer,      vsrc);
     REGISTER_FILTER (COLOR,       color,       vsrc);
     REGISTER_FILTER (FREI0R,      frei0r_src,  vsrc);
+    REGISTER_FILTER (MOVIE,       movie,       vsrc);
     REGISTER_FILTER (NULLSRC,     nullsrc,     vsrc);
 
     REGISTER_FILTER (NULLSINK,    nullsink,    vsink);
diff --git a/libavfilter/vsrc_movie.c b/libavfilter/vsrc_movie.c
new file mode 100644
index 0000000..72bbcc2
--- /dev/null
+++ b/libavfilter/vsrc_movie.c
@@ -0,0 +1,351 @@
+/*
+ * Copyright (c) 2010 Stefano Sabatini
+ * Copyright (c) 2008 Victor Paesa
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * movie file video source filter
+ *
+ * @todo use direct rendering (no allocation of a new frame)
+ * @todo support more than one output stream
+ */
+
+/* #define DEBUG */
+
+#include <float.h>
+#include "libavutil/avstring.h"
+#include "libavutil/opt.h"
+#include "libavcore/imgutils.h"
+#include "libavformat/avformat.h"
+#include "avfilter.h"
+
+typedef struct {
+    int64_t num_faulty_pts;  /// number of incorrect PTS values so far
+    int64_t num_faulty_dts;  /// number of incorrect DTS values so far
+    int64_t last_pts;        /// PTS of the last frame
+    int64_t last_dts;        /// DTS of the last frame
+} PtsCorrectionContext;
+
+static void init_pts_correction(PtsCorrectionContext *ctx)
+{
+    ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
+    ctx->last_pts = ctx->last_dts = INT64_MIN;
+}
+
+static int64_t guess_correct_pts(PtsCorrectionContext *ctx,
+                                 int64_t reordered_pts, int64_t dts)
+{
+    int64_t pts = AV_NOPTS_VALUE;
+
+    if (dts != AV_NOPTS_VALUE) {
+        ctx->num_faulty_dts += dts <= ctx->last_dts;
+        ctx->last_dts = dts;
+    }
+    if (reordered_pts != AV_NOPTS_VALUE) {
+        ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
+        ctx->last_pts = reordered_pts;
+    }
+    if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
+       && reordered_pts != AV_NOPTS_VALUE)
+        pts = reordered_pts;
+    else
+        pts = dts;
+
+    return pts;
+}
+
+typedef struct {
+    const AVClass *class;
+    int64_t seek_point;   ///< seekpoint in microseconds
+    double seek_point_d;
+    char *format_name;
+    char *file_name;
+    int stream_index;
+
+    AVFormatContext *format_ctx;
+    AVCodecContext *codec_ctx;
+    int is_done;
+    AVFrame *frame;   ///< video frame to store the decoded images in
+
+    int w, h;
+    AVFilterBufferRef *picref;
+    int decoder_reorder_pts;
+    PtsCorrectionContext pts_correction_ctx;
+} MovieContext;
+
+#define OFFSET(x) offsetof(MovieContext, x)
+
+static const AVOption movie_options[]= {
+{"format_name",  "set format name",         OFFSET(format_name),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
+{"f",            "set format name",         OFFSET(format_name),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
+{"stream_index", "set stream index",        OFFSET(stream_index), FF_OPT_TYPE_INT,   -1,        -1, INT_MAX  },
+{"si",           "set stream index",        OFFSET(stream_index), FF_OPT_TYPE_INT,   -1,        -1, INT_MAX  },
+{"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), FF_OPT_TYPE_DOUBLE, 0,         0, DBL_MAX  },
+{"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), FF_OPT_TYPE_DOUBLE, 0,         0, DBL_MAX  },
+{"decoder_reorder_pts", "let the decoder reorder the PTS", OFFSET(decoder_reorder_pts), FF_OPT_TYPE_INT, -1, -1, 1 },
+{"drp",          "let the decoder reorder the PTS", OFFSET(decoder_reorder_pts), FF_OPT_TYPE_INT, -1, -1, 1 },
+{NULL},
+};
+
+static const char *movie_get_name(void *ctx)
+{
+    return "movie";
+}
+
+static const AVClass movie_class = {
+    "MovieContext",
+    movie_get_name,
+    movie_options
+};
+
+static int movie_init(AVFilterContext *ctx)
+{
+    MovieContext *movie = ctx->priv;
+    AVInputFormat *iformat = NULL;
+    AVCodec *codec;
+    int ret;
+    int64_t timestamp;
+
+    av_register_all();
+
+    // Try to find the movie format (container)
+    iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
+
+    movie->format_ctx = NULL;
+    if ((ret = av_open_input_file(&movie->format_ctx, movie->file_name, iformat, 0, NULL)) < 0) {
+        av_log(ctx, AV_LOG_ERROR,
+               "Failed to av_open_input_file '%s'\n", movie->file_name);
+        return ret;
+    }
+    if ((ret = av_find_stream_info(movie->format_ctx)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to find stream info\n");
+        return ret;
+    }
+
+    // if seeking requested, we execute it
+    if (movie->seek_point > 0) {
+        timestamp = movie->seek_point;
+        // add the stream start time, should it exist
+        if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
+            timestamp += movie->format_ctx->start_time;
+        if (av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD) < 0) {
+            av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
+                   movie->file_name, timestamp);
+        }
+    }
+
+    /* select the video stream */
+    if ((ret = av_find_best_stream(movie->format_ctx, AVMEDIA_TYPE_VIDEO,
+                                   movie->stream_index, -1, NULL, 0)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "No video stream with index '%d' found\n",
+               movie->stream_index);
+        return ret;
+    }
+    movie->stream_index = ret;
+    movie->codec_ctx = movie->format_ctx->streams[movie->stream_index]->codec;
+
+    /*
+     * So now we've got a pointer to the so-called codec context for our video
+     * stream, but we still have to find the actual codec and open it.
+     */
+    codec = avcodec_find_decoder(movie->codec_ctx->codec_id);
+    if (!codec) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
+        return AVERROR(EINVAL);
+    }
+
+    if ((ret = avcodec_open(movie->codec_ctx, codec)) < 0) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
+        return ret;
+    }
+
+    if (!(movie->frame = avcodec_alloc_frame()) ) {
+        av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
+        return AVERROR(ENOMEM);
+    }
+
+    movie->w = movie->codec_ctx->width;
+    movie->h = movie->codec_ctx->height;
+
+    av_log(ctx, AV_LOG_INFO, "seek_point:%lld format_name:%s file_name:%s stream_index:%d\n",
+           movie->seek_point, movie->format_name, movie->file_name,
+           movie->stream_index);
+
+    return 0;
+}
+
+static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
+{
+    MovieContext *movie = ctx->priv;
+    int ret;
+    movie->class = &movie_class;
+    av_opt_set_defaults2(movie, 0, 0);
+
+    if (args) {
+        movie->file_name = av_get_token(&args, ":");
+        args++;
+        if ((ret = (av_set_options_string(movie, args, "=", ":"))) < 0) {
+            av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
+            return ret;
+        }
+    }
+    if (!movie->file_name) {
+        av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
+        return AVERROR(EINVAL);
+    }
+
+    if (movie->seek_point_d > (INT64_MAX-0.5) / 1000000) {
+        av_log(ctx, AV_LOG_ERROR, "Value for seek point is too big\n");
+        return AVERROR(EINVAL);
+    }
+    movie->seek_point = (int64_t)(movie->seek_point_d * 1000000 + 0.5);
+
+    init_pts_correction(&movie->pts_correction_ctx);
+
+    return movie_init(ctx);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    MovieContext *movie = ctx->priv;
+
+    av_free(movie->file_name);
+    av_free(movie->format_name);
+    if (movie->codec_ctx)
+        avcodec_close(movie->codec_ctx);
+    if (movie->format_ctx)
+        av_close_input_file(movie->format_ctx);
+    if (movie->picref) {
+        av_free(movie->picref->video);
+        av_freep(&movie->picref);
+    }
+    av_freep(&movie->frame);
+}
+
+static int query_formats(AVFilterContext *ctx)
+{
+    MovieContext *movie = ctx->priv;
+    enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
+
+    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
+    return 0;
+}
+
+static int config_output_props(AVFilterLink *outlink)
+{
+    MovieContext *movie = outlink->src->priv;
+
+    outlink->w = movie->w;
+    outlink->h = movie->h;
+    outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
+
+    return 0;
+}
+
+static int movie_get_frame(AVFilterLink *outlink)
+{
+    MovieContext *movie = outlink->src->priv;
+    AVPacket pkt;
+    int ret, frame_decoded;
+
+    if (movie->is_done == 1)
+        return 0;
+
+    while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
+        // Is this a packet from the video stream?
+        if (pkt.stream_index == movie->stream_index) {
+            movie->codec_ctx->reordered_opaque = pkt.pos;
+            avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
+
+            if (frame_decoded) {
+                movie->picref =
+                    avfilter_get_video_buffer_ref_from_arrays(movie->frame->data, movie->frame->linesize,
+                                                              AV_PERM_READ,
+                                                              outlink->format, outlink->w, outlink->h);
+
+                if (movie->decoder_reorder_pts == -1) {
+                    movie->picref->pts = guess_correct_pts(&movie->pts_correction_ctx, movie->frame->pkt_pts, pkt.dts);
+                } else if (movie->decoder_reorder_pts == 1) {
+                    movie->picref->pts = movie->frame->pkt_pts;
+                } else {
+                    movie->picref->pts = pkt.dts;
+                }
+                movie->picref->pos                    = movie->frame->reordered_opaque;
+                movie->picref->video->pixel_aspect    = movie->codec_ctx->sample_aspect_ratio;
+                movie->picref->video->interlaced      = movie->frame->interlaced_frame;
+                movie->picref->video->top_field_first = movie->frame->top_field_first;
+#ifdef DEBUG
+                av_log(outlink->src, AV_LOG_DEBUG,
+                       "movie_get_frame(): file:'%s' pkt.pts:%"PRId64" t:%lf pts:%"PRId64"\n",
+                       movie->file_name, packet.pts,
+                       (double)packet.pts * av_q2d(movie->format_ctx->streams[movie->stream_index]->time_base),
+                       movie->picref->pts);
+#endif
+                // We got it. Free the packet since we are returning
+                av_free_packet(&pkt);
+
+                return 0;
+            }
+        }
+        // Free the packet that was allocated by av_read_frame
+        av_free_packet(&pkt);
+    }
+
+    // On multi-frame source we should stop the mixing process when
+    // the movie source does not have more frames
+    if (ret == AVERROR_EOF)
+        movie->is_done = 1;
+    return ret;
+}
+
+static int request_frame(AVFilterLink *outlink)
+{
+    AVFilterBufferRef *outpicref;
+    MovieContext *movie = outlink->src->priv;
+    int ret;
+
+    if (movie->is_done)
+        return AVERROR_EOF;
+    if ((ret = movie_get_frame(outlink)) < 0)
+        return ret;
+
+    outpicref = avfilter_ref_buffer(movie->picref, ~0);
+    avfilter_start_frame(outlink, outpicref);
+    avfilter_draw_slice(outlink, 0, outlink->h, 1);
+    avfilter_end_frame(outlink);
+
+    return 0;
+}
+
+AVFilter avfilter_vsrc_movie = {
+    .name          = "movie",
+    .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
+    .priv_size     = sizeof(MovieContext),
+    .init          = init,
+    .uninit        = uninit,
+    .query_formats = query_formats,
+
+    .inputs    = (AVFilterPad[]) {{ .name = NULL }},
+    .outputs   = (AVFilterPad[]) {{ .name            = "default",
+                                    .type            = AVMEDIA_TYPE_VIDEO,
+                                    .request_frame   = request_frame,
+                                    .config_props    = config_output_props, },
+                                  { .name = NULL}},
+};
-- 
1.7.2.3


--h31gzZEtNLTqOjlF--



More information about the ffmpeg-devel mailing list