vsrc_movie.c
Go to the documentation of this file.
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 
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 
40 typedef struct {
41  const AVClass *class;
42  int64_t seek_point;
43  double seek_point_d;
44  char *format_name;
45  char *file_name;
47 
50  int is_done;
52 
53  int w, h;
55 } MovieContext;
56 
57 #define OFFSET(x) offsetof(MovieContext, x)
58 
59 static const AVOption movie_options[]= {
60 {"format_name", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MIN, CHAR_MAX },
61 {"f", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MIN, CHAR_MAX },
62 {"stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, {.dbl = -1}, -1, INT_MAX },
63 {"si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, {.dbl = -1}, -1, INT_MAX },
64 {"seek_point", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, (INT64_MAX-1) / 1000000 },
65 {"sp", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, (INT64_MAX-1) / 1000000 },
66 {NULL},
67 };
68 
69 static const char *movie_get_name(void *ctx)
70 {
71  return "movie";
72 }
73 
74 static const AVClass movie_class = {
75  "MovieContext",
77  movie_options
78 };
79 
80 static int movie_init(AVFilterContext *ctx)
81 {
82  MovieContext *movie = ctx->priv;
84  AVCodec *codec;
85  int ret;
86  int64_t timestamp;
87 
89 
90  // Try to find the movie format (container)
91  iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
92 
93  movie->format_ctx = NULL;
94  if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
95  av_log(ctx, AV_LOG_ERROR,
96  "Failed to avformat_open_input '%s'\n", movie->file_name);
97  return ret;
98  }
99  if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
100  av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
101 
102  // if seeking requested, we execute it
103  if (movie->seek_point > 0) {
104  timestamp = movie->seek_point;
105  // add the stream start time, should it exist
106  if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
107  if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
108  av_log(ctx, AV_LOG_ERROR,
109  "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
110  movie->file_name, movie->format_ctx->start_time, movie->seek_point);
111  return AVERROR(EINVAL);
112  }
113  timestamp += movie->format_ctx->start_time;
114  }
115  if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
116  av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
117  movie->file_name, timestamp);
118  return ret;
119  }
120  }
121 
122  /* select the video stream */
124  movie->stream_index, -1, NULL, 0)) < 0) {
125  av_log(ctx, AV_LOG_ERROR, "No video stream with index '%d' found\n",
126  movie->stream_index);
127  return ret;
128  }
129  movie->stream_index = ret;
130  movie->codec_ctx = movie->format_ctx->streams[movie->stream_index]->codec;
131 
132  /*
133  * So now we've got a pointer to the so-called codec context for our video
134  * stream, but we still have to find the actual codec and open it.
135  */
136  codec = avcodec_find_decoder(movie->codec_ctx->codec_id);
137  if (!codec) {
138  av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
139  return AVERROR(EINVAL);
140  }
141 
142  if ((ret = avcodec_open2(movie->codec_ctx, codec, NULL)) < 0) {
143  av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
144  return ret;
145  }
146 
147  if (!(movie->frame = avcodec_alloc_frame()) ) {
148  av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
149  return AVERROR(ENOMEM);
150  }
151 
152  movie->w = movie->codec_ctx->width;
153  movie->h = movie->codec_ctx->height;
154 
155  av_log(ctx, AV_LOG_INFO, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
156  movie->seek_point, movie->format_name, movie->file_name,
157  movie->stream_index);
158 
159  return 0;
160 }
161 
162 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
163 {
164  MovieContext *movie = ctx->priv;
165  int ret;
166  movie->class = &movie_class;
167  av_opt_set_defaults(movie);
168 
169  if (args)
170  movie->file_name = av_get_token(&args, ":");
171  if (!movie->file_name || !*movie->file_name) {
172  av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
173  return AVERROR(EINVAL);
174  }
175 
176  if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0) {
177  av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
178  return ret;
179  }
180 
181  movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
182 
183  return movie_init(ctx);
184 }
185 
186 static av_cold void uninit(AVFilterContext *ctx)
187 {
188  MovieContext *movie = ctx->priv;
189 
190  av_free(movie->file_name);
191  av_free(movie->format_name);
192  if (movie->codec_ctx)
193  avcodec_close(movie->codec_ctx);
194  if (movie->format_ctx)
197  av_freep(&movie->frame);
198 }
199 
201 {
202  MovieContext *movie = ctx->priv;
203  enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
204 
206  return 0;
207 }
208 
209 static int config_output_props(AVFilterLink *outlink)
210 {
211  MovieContext *movie = outlink->src->priv;
212 
213  outlink->w = movie->w;
214  outlink->h = movie->h;
215  outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
216 
217  return 0;
218 }
219 
220 static int movie_get_frame(AVFilterLink *outlink)
221 {
222  MovieContext *movie = outlink->src->priv;
223  AVPacket pkt;
224  int ret, frame_decoded;
225  AVStream *st = movie->format_ctx->streams[movie->stream_index];
226 
227  if (movie->is_done == 1)
228  return 0;
229 
230  while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
231  // Is this a packet from the video stream?
232  if (pkt.stream_index == movie->stream_index) {
233  movie->codec_ctx->reordered_opaque = pkt.pos;
234  avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
235 
236  if (frame_decoded) {
237  /* FIXME: avoid the memcpy */
239  AV_PERM_REUSE2, outlink->w, outlink->h);
240  av_image_copy(movie->picref->data, movie->picref->linesize,
241  movie->frame->data, movie->frame->linesize,
242  movie->picref->format, outlink->w, outlink->h);
243  avfilter_copy_frame_props(movie->picref, movie->frame);
244 
245  /* FIXME: use a PTS correction mechanism as that in
246  * ffplay.c when some API will be available for that */
247  /* use pkt_dts if pkt_pts is not available */
248  movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?
249  movie->frame->pkt_dts : movie->frame->pkt_pts;
250 
251  movie->picref->pos = movie->frame->reordered_opaque;
252  if (!movie->frame->sample_aspect_ratio.num)
254  av_dlog(outlink->src,
255  "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",
256  movie->file_name, movie->picref->pts,
257  (double)movie->picref->pts * av_q2d(st->time_base),
258  movie->picref->pos,
259  movie->picref->video->pixel_aspect.num, movie->picref->video->pixel_aspect.den);
260  // We got it. Free the packet since we are returning
261  av_free_packet(&pkt);
262 
263  return 0;
264  }
265  }
266  // Free the packet that was allocated by av_read_frame
267  av_free_packet(&pkt);
268  }
269 
270  // On multi-frame source we should stop the mixing process when
271  // the movie source does not have more frames
272  if (ret == AVERROR_EOF)
273  movie->is_done = 1;
274  return ret;
275 }
276 
277 static int request_frame(AVFilterLink *outlink)
278 {
279  AVFilterBufferRef *outpicref;
280  MovieContext *movie = outlink->src->priv;
281  int ret;
282 
283  if (movie->is_done)
284  return AVERROR_EOF;
285  if ((ret = movie_get_frame(outlink)) < 0)
286  return ret;
287 
288  outpicref = avfilter_ref_buffer(movie->picref, ~0);
289  avfilter_start_frame(outlink, outpicref);
290  avfilter_draw_slice(outlink, 0, outlink->h, 1);
291  avfilter_end_frame(outlink);
293  movie->picref = NULL;
294 
295  return 0;
296 }
297 
299  .name = "movie",
300  .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
301  .priv_size = sizeof(MovieContext),
302  .init = init,
303  .uninit = uninit,
305 
306  .inputs = (AVFilterPad[]) {{ .name = NULL }},
307  .outputs = (AVFilterPad[]) {{ .name = "default",
308  .type = AVMEDIA_TYPE_VIDEO,
309  .request_frame = request_frame,
310  .config_props = config_output_props, },
311  { .name = NULL}},
312 };
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:1618
enum PixelFormat pix_fmt
Pixel format, see PIX_FMT_xxx.
Definition: avcodec.h:1426
AVFilterBufferRef * avfilter_get_video_buffer(AVFilterLink *link, int perms, int w, int h)
Request a picture buffer with a specific set of permissions.
Definition: avfilter.c:289
Audio Video Frame.
Definition: avcodec.h:985
AVOption.
Definition: opt.h:244
AVFilterBufferRefVideoProps * video
video buffer specific properties
Definition: avfilter.h:141
int linesize[8]
number of bytes per line
Definition: avfilter.h:127
misc image utilities
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:933
int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, AVPacket *avpkt)
Decode the video frame of size avpkt->size from avpkt->data into picture.
Definition: utils.c:1137
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:606
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:117
void av_opt_set_defaults(void *s)
Set the values of all AVOption fields to their default values.
Definition: opt.c:598
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:716
int num
numerator
Definition: rational.h:44
int av_set_options_string(void *ctx, const char *opts, const char *key_val_sep, const char *pairs_sep)
Parse the key/value pairs list in opts.
Definition: opt.c:698
AVOptions.
AVCodec * avcodec_find_decoder(enum CodecID id)
Find a registered decoder with a matching codec ID.
Definition: utils.c:1357
static int config_output_props(AVFilterLink *outlink)
Definition: vsrc_movie.c:209
AVCodec.
Definition: avcodec.h:3189
char * file_name
Definition: vsrc_movie.c:45
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:147
Format I/O context.
Definition: avformat.h:863
double seek_point_d
Definition: vsrc_movie.c:43
#define av_cold
Definition: attributes.h:71
int avcodec_open2(AVCodecContext *avctx, AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:635
void avfilter_end_frame(AVFilterLink *link)
Notifie the next filter that the current frame has finished.
Definition: avfilter.c:430
static int request_frame(AVFilterLink *outlink)
Definition: vsrc_movie.c:277
AVStream ** streams
Definition: avformat.h:908
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:69
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:151
AVFrame * frame
video frame to store the decoded images in
Definition: vsrc_movie.c:51
#define AVERROR_EOF
End of file.
Definition: error.h:51
AVRational pixel_aspect
pixel aspect ratio
Definition: avfilter.h:109
int64_t pts
presentation timestamp.
Definition: avfilter.h:135
A filter pad used for either input or output.
Definition: avfilter.h:312
int avfilter_copy_frame_props(AVFilterBufferRef *dst, const AVFrame *src)
Copy the frame properties of src to dst, without copying the actual image data.
Definition: avfilter.c:685
int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec **decoder_ret, int flags)
Find the "best" stream in the file.
Definition: utils.c:2619
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:137
void avfilter_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: defaults.c:234
static const AVClass movie_class
Definition: vsrc_movie.c:74
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:191
void * priv
private data for use by the filter
Definition: avfilter.h:553
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:140
AVFilterFormats * avfilter_make_format_list(const int *fmts)
Create a list of supported formats.
Definition: formats.c:90
static int movie_init(AVFilterContext *ctx)
Definition: vsrc_movie.c:80
char * av_get_token(const char **buf, const char *term)
Unescape the given string until a non escaped terminating char, and return the token corresponding to...
Definition: avstring.c:103
AVCodecContext * codec
codec context
Definition: avformat.h:623
AVFrame * avcodec_alloc_frame(void)
Allocate an AVFrame and set its fields to default values.
Definition: utils.c:618
AVInputFormat * av_find_input_format(const char *short_name)
Find AVInputFormat based on the short name of the input format.
Definition: utils.c:258
int width
picture width / height.
Definition: avcodec.h:1408
void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum PixelFormat pix_fmt, int width, int height)
Copy image in src_data to dst_data.
Definition: imgutils.c:237
static av_cold void uninit(AVFilterContext *ctx)
Definition: vsrc_movie.c:186
char * format_name
Definition: vsrc_movie.c:44
int64_t reordered_opaque
opaque 64bit number (generally a PTS) that will be reordered and output in AVFrame.reordered_opaque
Definition: avcodec.h:2856
void avfilter_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
Send a slice to the next filter.
Definition: avfilter.c:447
#define av_dlog(pctx,...)
av_dlog macros Useful to print debug messages that shouldn't get compiled in normally.
Definition: log.h:158
static int query_formats(AVFilterContext *ctx)
Definition: vsrc_movie.c:200
void avfilter_unref_buffer(AVFilterBufferRef *ref)
Remove a reference to a buffer.
Definition: avfilter.c:73
Stream structure.
Definition: avformat.h:620
A reference to an AVFilterBuffer.
Definition: avfilter.h:124
NULL
Definition: eval.c:50
int linesize[AV_NUM_DATA_POINTERS]
Size, in bytes, of the data for each picture/channel plane.
Definition: avcodec.h:1008
main external API structure.
Definition: avcodec.h:1329
AVRational sample_aspect_ratio
sample aspect ratio for the video frame, 0/1 if unknown
Definition: avcodec.h:1292
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:111
#define OFFSET(x)
Definition: vsrc_movie.c:57
AVCodecContext * codec_ctx
Definition: vsrc_movie.c:49
#define INT64_MAX
Definition: internal.h:80
static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
Definition: vsrc_movie.c:162
int64_t reordered_opaque
reordered opaque 64bit (generally an integer or a double precision float PTS but can be anything)...
Definition: avcodec.h:1223
Describe the class of an AVClass context structure.
Definition: log.h:33
Filter definition.
Definition: avfilter.h:497
AVFilterBufferRef * avfilter_ref_buffer(AVFilterBufferRef *ref, int pmask)
Add a new reference to a buffer.
Definition: avfilter.c:47
int64_t seek_point
seekpoint in microseconds
Definition: vsrc_movie.c:42
void avfilter_start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
Notify the next filter of the start of a frame.
Definition: avfilter.c:400
const char * name
filter name
Definition: avfilter.h:498
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1264
int64_t pkt_pts
reordered pts from the last AVPacket that has been input into the decoder
Definition: avcodec.h:1237
int avcodec_close(AVCodecContext *avctx)
Close a given AVCodecContext and free all the data associated with it (but not the AVCodecContext its...
Definition: utils.c:1285
#define AV_PERM_PRESERVE
nobody else can overwrite the buffer
Definition: avfilter.h:83
int64_t start_time
Decoding: position of the first frame of the component, in AV_TIME_BASE fractional seconds...
Definition: avformat.h:935
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: avcodec.h:997
int stream_index
Definition: vsrc_movie.c:46
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Seek to the keyframe at timestamp.
Definition: utils.c:1796
AVFilter avfilter_vsrc_movie
Definition: vsrc_movie.c:298
static const char * movie_get_name(void *ctx)
Definition: vsrc_movie.c:69
int64_t pkt_dts
dts from the last AVPacket that has been input into the decoder
Definition: avcodec.h:1244
PixelFormat
Pixel format.
Definition: pixfmt.h:62
Main libavformat public API header.
static AVInputFormat * iformat
Definition: avprobe.c:49
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:2293
int den
denominator
Definition: rational.h:45
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:2752
#define AV_PERM_REUSE2
can output the buffer multiple times, modified each time
Definition: avfilter.h:85
#define AV_PERM_WRITE
can write to the buffer
Definition: avfilter.h:82
int64_t pos
byte position in stream, -1 if unknown
Definition: avfilter.h:136
static const AVOption movie_options[]
Definition: vsrc_movie.c:59
uint8_t * data[8]
picture/audio data for each plane
Definition: avfilter.h:126
int format
media format
Definition: avfilter.h:128
AVFormatContext * format_ctx
Definition: vsrc_movie.c:48
An instance of a filter.
Definition: avfilter.h:538
const AVClass * class
Definition: vsrc_movie.c:41
#define AV_LOG_INFO
Definition: log.h:119
AVFilterBufferRef * picref
Definition: vsrc_movie.c:54
int stream_index
Definition: avcodec.h:910
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:652
void av_register_all(void)
Initialize libavformat and register all the muxers, demuxers and protocols.
Definition: allformats.c:40
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:271
enum CodecID codec_id
Definition: avcodec.h:1575
static int movie_get_frame(AVFilterLink *outlink)
Definition: vsrc_movie.c:220