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