]> git.sesse.net Git - ffmpeg/blob - libavfilter/vsrc_movie.c
lavfi: make avfilter_get_video_buffer() private on next bump.
[ffmpeg] / libavfilter / vsrc_movie.c
1 /*
2  * Copyright (c) 2010 Stefano Sabatini
3  * Copyright (c) 2008 Victor Paesa
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * movie video source
25  *
26  * @todo use direct rendering (no allocation of a new frame)
27  * @todo support a PTS correction mechanism
28  * @todo support more than one output stream
29  */
30
31 /* #define DEBUG */
32
33 #include <float.h>
34 #include "libavutil/avstring.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/imgutils.h"
37 #include "libavformat/avformat.h"
38 #include "avfilter.h"
39 #include "formats.h"
40 #include "video.h"
41
42 typedef struct {
43     const AVClass *class;
44     int64_t seek_point;   ///< seekpoint in microseconds
45     double seek_point_d;
46     char *format_name;
47     char *file_name;
48     int stream_index;
49
50     AVFormatContext *format_ctx;
51     AVCodecContext *codec_ctx;
52     int is_done;
53     AVFrame *frame;   ///< video frame to store the decoded images in
54
55     int w, h;
56     AVFilterBufferRef *picref;
57 } MovieContext;
58
59 #define OFFSET(x) offsetof(MovieContext, x)
60
61 static const AVOption movie_options[]= {
62 {"format_name",  "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
63 {"f",            "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
64 {"stream_index", "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
65 {"si",           "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
66 {"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
67 {"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
68 {NULL},
69 };
70
71 static const char *movie_get_name(void *ctx)
72 {
73     return "movie";
74 }
75
76 static const AVClass movie_class = {
77     "MovieContext",
78     movie_get_name,
79     movie_options
80 };
81
82 static int movie_init(AVFilterContext *ctx)
83 {
84     MovieContext *movie = ctx->priv;
85     AVInputFormat *iformat = NULL;
86     AVCodec *codec;
87     int ret;
88     int64_t timestamp;
89
90     av_register_all();
91
92     // Try to find the movie format (container)
93     iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
94
95     movie->format_ctx = NULL;
96     if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
97         av_log(ctx, AV_LOG_ERROR,
98                "Failed to avformat_open_input '%s'\n", movie->file_name);
99         return ret;
100     }
101     if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
102         av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
103
104     // if seeking requested, we execute it
105     if (movie->seek_point > 0) {
106         timestamp = movie->seek_point;
107         // add the stream start time, should it exist
108         if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
109             if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
110                 av_log(ctx, AV_LOG_ERROR,
111                        "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
112                        movie->file_name, movie->format_ctx->start_time, movie->seek_point);
113                 return AVERROR(EINVAL);
114             }
115             timestamp += movie->format_ctx->start_time;
116         }
117         if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
118             av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
119                    movie->file_name, timestamp);
120             return ret;
121         }
122     }
123
124     /* select the video stream */
125     if ((ret = av_find_best_stream(movie->format_ctx, AVMEDIA_TYPE_VIDEO,
126                                    movie->stream_index, -1, NULL, 0)) < 0) {
127         av_log(ctx, AV_LOG_ERROR, "No video stream with index '%d' found\n",
128                movie->stream_index);
129         return ret;
130     }
131     movie->stream_index = ret;
132     movie->codec_ctx = movie->format_ctx->streams[movie->stream_index]->codec;
133
134     /*
135      * So now we've got a pointer to the so-called codec context for our video
136      * stream, but we still have to find the actual codec and open it.
137      */
138     codec = avcodec_find_decoder(movie->codec_ctx->codec_id);
139     if (!codec) {
140         av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
141         return AVERROR(EINVAL);
142     }
143
144     if ((ret = avcodec_open2(movie->codec_ctx, codec, NULL)) < 0) {
145         av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
146         return ret;
147     }
148
149     if (!(movie->frame = avcodec_alloc_frame()) ) {
150         av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
151         return AVERROR(ENOMEM);
152     }
153
154     movie->w = movie->codec_ctx->width;
155     movie->h = movie->codec_ctx->height;
156
157     av_log(ctx, AV_LOG_INFO, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
158            movie->seek_point, movie->format_name, movie->file_name,
159            movie->stream_index);
160
161     return 0;
162 }
163
164 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
165 {
166     MovieContext *movie = ctx->priv;
167     int ret;
168     movie->class = &movie_class;
169     av_opt_set_defaults(movie);
170
171     if (args)
172         movie->file_name = av_get_token(&args, ":");
173     if (!movie->file_name || !*movie->file_name) {
174         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
175         return AVERROR(EINVAL);
176     }
177
178     if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0) {
179         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
180         return ret;
181     }
182
183     movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
184
185     return movie_init(ctx);
186 }
187
188 static av_cold void uninit(AVFilterContext *ctx)
189 {
190     MovieContext *movie = ctx->priv;
191
192     av_free(movie->file_name);
193     av_free(movie->format_name);
194     if (movie->codec_ctx)
195         avcodec_close(movie->codec_ctx);
196     if (movie->format_ctx)
197         avformat_close_input(&movie->format_ctx);
198     avfilter_unref_buffer(movie->picref);
199     av_freep(&movie->frame);
200 }
201
202 static int query_formats(AVFilterContext *ctx)
203 {
204     MovieContext *movie = ctx->priv;
205     enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
206
207     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
208     return 0;
209 }
210
211 static int config_output_props(AVFilterLink *outlink)
212 {
213     MovieContext *movie = outlink->src->priv;
214
215     outlink->w = movie->w;
216     outlink->h = movie->h;
217     outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
218
219     return 0;
220 }
221
222 static int movie_get_frame(AVFilterLink *outlink)
223 {
224     MovieContext *movie = outlink->src->priv;
225     AVPacket pkt;
226     int ret, frame_decoded;
227     AVStream *st = movie->format_ctx->streams[movie->stream_index];
228
229     if (movie->is_done == 1)
230         return 0;
231
232     while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
233         // Is this a packet from the video stream?
234         if (pkt.stream_index == movie->stream_index) {
235             movie->codec_ctx->reordered_opaque = pkt.pos;
236             avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
237
238             if (frame_decoded) {
239                 /* FIXME: avoid the memcpy */
240                 movie->picref = ff_get_video_buffer(outlink, AV_PERM_WRITE | AV_PERM_PRESERVE |
241                                                     AV_PERM_REUSE2, outlink->w, outlink->h);
242                 av_image_copy(movie->picref->data, movie->picref->linesize,
243                               movie->frame->data,  movie->frame->linesize,
244                               movie->picref->format, outlink->w, outlink->h);
245                 avfilter_copy_frame_props(movie->picref, movie->frame);
246
247                 /* FIXME: use a PTS correction mechanism as that in
248                  * ffplay.c when some API will be available for that */
249                 /* use pkt_dts if pkt_pts is not available */
250                 movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?
251                     movie->frame->pkt_dts : movie->frame->pkt_pts;
252
253                 movie->picref->pos                    = movie->frame->reordered_opaque;
254                 if (!movie->frame->sample_aspect_ratio.num)
255                     movie->picref->video->pixel_aspect = st->sample_aspect_ratio;
256                 av_dlog(outlink->src,
257                         "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",
258                         movie->file_name, movie->picref->pts,
259                         (double)movie->picref->pts * av_q2d(st->time_base),
260                         movie->picref->pos,
261                         movie->picref->video->pixel_aspect.num, movie->picref->video->pixel_aspect.den);
262                 // We got it. Free the packet since we are returning
263                 av_free_packet(&pkt);
264
265                 return 0;
266             }
267         }
268         // Free the packet that was allocated by av_read_frame
269         av_free_packet(&pkt);
270     }
271
272     // On multi-frame source we should stop the mixing process when
273     // the movie source does not have more frames
274     if (ret == AVERROR_EOF)
275         movie->is_done = 1;
276     return ret;
277 }
278
279 static int request_frame(AVFilterLink *outlink)
280 {
281     AVFilterBufferRef *outpicref;
282     MovieContext *movie = outlink->src->priv;
283     int ret;
284
285     if (movie->is_done)
286         return AVERROR_EOF;
287     if ((ret = movie_get_frame(outlink)) < 0)
288         return ret;
289
290     outpicref = avfilter_ref_buffer(movie->picref, ~0);
291     ff_start_frame(outlink, outpicref);
292     ff_draw_slice(outlink, 0, outlink->h, 1);
293     ff_end_frame(outlink);
294     avfilter_unref_buffer(movie->picref);
295     movie->picref = NULL;
296
297     return 0;
298 }
299
300 AVFilter avfilter_vsrc_movie = {
301     .name          = "movie",
302     .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
303     .priv_size     = sizeof(MovieContext),
304     .init          = init,
305     .uninit        = uninit,
306     .query_formats = query_formats,
307
308     .inputs    = (AVFilterPad[]) {{ .name = NULL }},
309     .outputs   = (AVFilterPad[]) {{ .name            = "default",
310                                     .type            = AVMEDIA_TYPE_VIDEO,
311                                     .request_frame   = request_frame,
312                                     .config_props    = config_output_props, },
313                                   { .name = NULL}},
314 };