2 * Copyright (c) 2010 Stefano Sabatini
3 * Copyright (c) 2008 Victor Paesa
5 * This file is part of FFmpeg.
7 * FFmpeg 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.
12 * FFmpeg 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * @todo use direct rendering (no allocation of a new frame)
27 * @todo support a PTS correction mechanism
33 #include "libavutil/attributes.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/timestamp.h"
39 #include "libavformat/avformat.h"
47 typedef struct MovieStream {
52 typedef struct MovieContext {
53 /* common A/V fields */
55 int64_t seek_point; ///< seekpoint in microseconds
59 char *stream_specs; /**< user-provided list of streams, separated by + */
60 int stream_index; /**< for compatibility */
63 AVFormatContext *format_ctx;
66 AVFrame *frame; ///< video frame to store the decoded images in
68 int max_stream_index; /**< max stream # actually used for output */
69 MovieStream *st; /**< array of all streams, one per output */
70 int *out_index; /**< stream number -> output number map, or -1 */
73 #define OFFSET(x) offsetof(MovieContext, x)
74 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_VIDEO_PARAM
76 static const AVOption movie_options[]= {
77 { "filename", NULL, OFFSET(file_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
78 { "format_name", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
79 { "f", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
80 { "stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
81 { "si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
82 { "seek_point", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, (INT64_MAX-1) / 1000000, FLAGS },
83 { "sp", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, (INT64_MAX-1) / 1000000, FLAGS },
84 { "streams", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, FLAGS },
85 { "s", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, FLAGS },
86 { "loop", "set loop count", OFFSET(loop_count), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, FLAGS },
90 static int movie_config_output_props(AVFilterLink *outlink);
91 static int movie_request_frame(AVFilterLink *outlink);
93 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
95 int i, ret, already = 0, stream_id = -1;
96 char type_char[2], dummy;
97 AVStream *found = NULL;
98 enum AVMediaType type;
100 ret = sscanf(spec, "d%1[av]%d%c", type_char, &stream_id, &dummy);
101 if (ret >= 1 && ret <= 2) {
102 type = type_char[0] == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
103 ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
105 av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
106 av_get_media_type_string(type), stream_id);
109 return avf->streams[ret];
111 for (i = 0; i < avf->nb_streams; i++) {
112 ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
114 av_log(log, AV_LOG_ERROR,
115 "Invalid stream specifier \"%s\"\n", spec);
120 if (avf->streams[i]->discard != AVDISCARD_ALL) {
125 av_log(log, AV_LOG_WARNING,
126 "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
129 found = avf->streams[i];
132 av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
133 already ? "matched only already used streams" :
134 "did not match any stream");
137 if (found->codec->codec_type != AVMEDIA_TYPE_VIDEO &&
138 found->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
139 av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
140 "currently unsupported by libavfilter\n", spec,
141 av_get_media_type_string(found->codec->codec_type));
147 static int open_stream(void *log, MovieStream *st)
152 codec = avcodec_find_decoder(st->st->codec->codec_id);
154 av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
155 return AVERROR(EINVAL);
158 st->st->codec->refcounted_frames = 1;
160 if ((ret = avcodec_open2(st->st->codec, codec, NULL)) < 0) {
161 av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
168 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
170 AVCodecContext *dec_ctx = st->st->codec;
172 int64_t chl = av_get_default_channel_layout(dec_ctx->channels);
175 av_log(log_ctx, AV_LOG_ERROR,
176 "Channel layout is not set in stream %d, and could not "
177 "be guessed from the number of channels (%d)\n",
178 st_index, dec_ctx->channels);
179 return AVERROR(EINVAL);
182 av_get_channel_layout_string(buf, sizeof(buf), dec_ctx->channels, chl);
183 av_log(log_ctx, AV_LOG_WARNING,
184 "Channel layout is not set in output stream %d, "
185 "guessed channel layout is '%s'\n",
187 dec_ctx->channel_layout = chl;
191 static av_cold int movie_common_init(AVFilterContext *ctx)
193 MovieContext *movie = ctx->priv;
194 AVInputFormat *iformat = NULL;
196 int nb_streams, ret, i;
197 char default_streams[16], *stream_specs, *spec, *cursor;
201 if (!movie->file_name) {
202 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
203 return AVERROR(EINVAL);
206 movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
208 stream_specs = movie->stream_specs;
210 snprintf(default_streams, sizeof(default_streams), "d%c%d",
211 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
212 movie->stream_index);
213 stream_specs = default_streams;
215 for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)
219 if (movie->loop_count != 1 && nb_streams != 1) {
220 av_log(ctx, AV_LOG_ERROR,
221 "Loop with several streams is currently unsupported\n");
222 return AVERROR_PATCHWELCOME;
227 // Try to find the movie format (container)
228 iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
230 movie->format_ctx = NULL;
231 if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
232 av_log(ctx, AV_LOG_ERROR,
233 "Failed to avformat_open_input '%s'\n", movie->file_name);
236 if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
237 av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
239 // if seeking requested, we execute it
240 if (movie->seek_point > 0) {
241 timestamp = movie->seek_point;
242 // add the stream start time, should it exist
243 if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
244 if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
245 av_log(ctx, AV_LOG_ERROR,
246 "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
247 movie->file_name, movie->format_ctx->start_time, movie->seek_point);
248 return AVERROR(EINVAL);
250 timestamp += movie->format_ctx->start_time;
252 if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
253 av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
254 movie->file_name, timestamp);
259 for (i = 0; i < movie->format_ctx->nb_streams; i++)
260 movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
262 movie->st = av_calloc(nb_streams, sizeof(*movie->st));
264 return AVERROR(ENOMEM);
266 for (i = 0; i < nb_streams; i++) {
267 spec = av_strtok(stream_specs, "+", &cursor);
270 stream_specs = NULL; /* for next strtok */
271 st = find_stream(ctx, movie->format_ctx, spec);
273 return AVERROR(EINVAL);
274 st->discard = AVDISCARD_DEFAULT;
275 movie->st[i].st = st;
276 movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
278 if (av_strtok(NULL, "+", &cursor))
281 movie->out_index = av_calloc(movie->max_stream_index + 1,
282 sizeof(*movie->out_index));
283 if (!movie->out_index)
284 return AVERROR(ENOMEM);
285 for (i = 0; i <= movie->max_stream_index; i++)
286 movie->out_index[i] = -1;
287 for (i = 0; i < nb_streams; i++)
288 movie->out_index[movie->st[i].st->index] = i;
290 for (i = 0; i < nb_streams; i++) {
291 AVFilterPad pad = { 0 };
292 snprintf(name, sizeof(name), "out%d", i);
293 pad.type = movie->st[i].st->codec->codec_type;
294 pad.name = av_strdup(name);
295 pad.config_props = movie_config_output_props;
296 pad.request_frame = movie_request_frame;
297 ff_insert_outpad(ctx, i, &pad);
298 ret = open_stream(ctx, &movie->st[i]);
301 if ( movie->st[i].st->codec->codec->type == AVMEDIA_TYPE_AUDIO &&
302 !movie->st[i].st->codec->channel_layout) {
303 ret = guess_channel_layout(&movie->st[i], i, ctx);
309 av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
310 movie->seek_point, movie->format_name, movie->file_name,
311 movie->stream_index);
316 static av_cold void movie_uninit(AVFilterContext *ctx)
318 MovieContext *movie = ctx->priv;
321 for (i = 0; i < ctx->nb_outputs; i++) {
322 av_freep(&ctx->output_pads[i].name);
324 avcodec_close(movie->st[i].st->codec);
326 av_freep(&movie->st);
327 av_freep(&movie->out_index);
328 av_frame_free(&movie->frame);
329 if (movie->format_ctx)
330 avformat_close_input(&movie->format_ctx);
333 static int movie_query_formats(AVFilterContext *ctx)
335 MovieContext *movie = ctx->priv;
336 int list[] = { 0, -1 };
337 int64_t list64[] = { 0, -1 };
340 for (i = 0; i < ctx->nb_outputs; i++) {
341 MovieStream *st = &movie->st[i];
342 AVCodecContext *c = st->st->codec;
343 AVFilterLink *outlink = ctx->outputs[i];
345 switch (c->codec_type) {
346 case AVMEDIA_TYPE_VIDEO:
347 list[0] = c->pix_fmt;
348 ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
350 case AVMEDIA_TYPE_AUDIO:
351 list[0] = c->sample_fmt;
352 ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
353 list[0] = c->sample_rate;
354 ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates);
355 list64[0] = c->channel_layout;
356 ff_channel_layouts_ref(avfilter_make_format64_list(list64),
357 &outlink->in_channel_layouts);
365 static int movie_config_output_props(AVFilterLink *outlink)
367 AVFilterContext *ctx = outlink->src;
368 MovieContext *movie = ctx->priv;
369 unsigned out_id = FF_OUTLINK_IDX(outlink);
370 MovieStream *st = &movie->st[out_id];
371 AVCodecContext *c = st->st->codec;
373 outlink->time_base = st->st->time_base;
375 switch (c->codec_type) {
376 case AVMEDIA_TYPE_VIDEO:
377 outlink->w = c->width;
378 outlink->h = c->height;
379 outlink->frame_rate = st->st->r_frame_rate;
381 case AVMEDIA_TYPE_AUDIO:
388 static char *describe_frame_to_str(char *dst, size_t dst_size,
389 AVFrame *frame, enum AVMediaType frame_type,
392 switch (frame_type) {
393 case AVMEDIA_TYPE_VIDEO:
394 snprintf(dst, dst_size,
395 "video pts:%s time:%s size:%dx%d aspect:%d/%d",
396 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
397 frame->width, frame->height,
398 frame->sample_aspect_ratio.num,
399 frame->sample_aspect_ratio.den);
401 case AVMEDIA_TYPE_AUDIO:
402 snprintf(dst, dst_size,
403 "audio pts:%s time:%s samples:%d",
404 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
408 snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(frame_type));
414 static int rewind_file(AVFilterContext *ctx)
416 MovieContext *movie = ctx->priv;
417 int64_t timestamp = movie->seek_point;
420 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
421 timestamp += movie->format_ctx->start_time;
422 ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
424 av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
425 movie->loop_count = 1; /* do not try again */
429 for (i = 0; i < ctx->nb_outputs; i++) {
430 avcodec_flush_buffers(movie->st[i].st->codec);
431 movie->st[i].done = 0;
438 * Try to push a frame to the requested output.
440 * @param ctx filter context
441 * @param out_id number of output where a frame is wanted;
442 * if the frame is read from file, used to set the return value;
443 * if the codec is being flushed, flush the corresponding stream
444 * @return 1 if a frame was pushed on the requested output,
445 * 0 if another attempt is possible,
448 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
450 MovieContext *movie = ctx->priv;
451 AVPacket *pkt = &movie->pkt;
452 enum AVMediaType frame_type;
454 int ret, got_frame = 0, pkt_out_id;
455 AVFilterLink *outlink;
459 if (movie->st[out_id].done) {
460 if (movie->loop_count != 1) {
461 ret = rewind_file(ctx);
464 movie->loop_count -= movie->loop_count > 1;
465 av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
466 return 0; /* retry */
470 pkt->stream_index = movie->st[out_id].st->index;
471 /* packet is already ready for flushing */
473 ret = av_read_frame(movie->format_ctx, &movie->pkt0);
475 av_init_packet(&movie->pkt0); /* ready for flushing */
477 if (ret == AVERROR_EOF) {
479 return 0; /* start flushing */
487 pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
488 movie->out_index[pkt->stream_index];
489 if (pkt_out_id < 0) {
490 av_free_packet(&movie->pkt0);
491 pkt->size = 0; /* ready for next run */
495 st = &movie->st[pkt_out_id];
496 outlink = ctx->outputs[pkt_out_id];
498 movie->frame = av_frame_alloc();
500 return AVERROR(ENOMEM);
502 frame_type = st->st->codec->codec_type;
503 switch (frame_type) {
504 case AVMEDIA_TYPE_VIDEO:
505 ret = avcodec_decode_video2(st->st->codec, movie->frame, &got_frame, pkt);
507 case AVMEDIA_TYPE_AUDIO:
508 ret = avcodec_decode_audio4(st->st->codec, movie->frame, &got_frame, pkt);
511 ret = AVERROR(ENOSYS);
515 av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
516 av_frame_free(&movie->frame);
517 av_free_packet(&movie->pkt0);
519 movie->pkt.data = NULL;
522 if (!ret || st->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
527 if (pkt->size <= 0) {
528 av_free_packet(&movie->pkt0);
529 pkt->size = 0; /* ready for next run */
535 av_frame_free(&movie->frame);
539 movie->frame->pts = av_frame_get_best_effort_timestamp(movie->frame);
540 av_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
541 describe_frame_to_str((char[1024]){0}, 1024, movie->frame, frame_type, outlink));
543 if (st->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
544 if (movie->frame->format != outlink->format) {
545 av_log(ctx, AV_LOG_ERROR, "Format changed %s -> %s, discarding frame\n",
546 av_get_pix_fmt_name(outlink->format),
547 av_get_pix_fmt_name(movie->frame->format)
549 av_frame_free(&movie->frame);
553 ret = ff_filter_frame(outlink, movie->frame);
558 return pkt_out_id == out_id;
561 static int movie_request_frame(AVFilterLink *outlink)
563 AVFilterContext *ctx = outlink->src;
564 unsigned out_id = FF_OUTLINK_IDX(outlink);
568 ret = movie_push_frame(ctx, out_id);
570 return FFMIN(ret, 0);
574 #if CONFIG_MOVIE_FILTER
576 AVFILTER_DEFINE_CLASS(movie);
578 AVFilter ff_avsrc_movie = {
580 .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
581 .priv_size = sizeof(MovieContext),
582 .priv_class = &movie_class,
583 .init = movie_common_init,
584 .uninit = movie_uninit,
585 .query_formats = movie_query_formats,
589 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
592 #endif /* CONFIG_MOVIE_FILTER */
594 #if CONFIG_AMOVIE_FILTER
596 #define amovie_options movie_options
597 AVFILTER_DEFINE_CLASS(amovie);
599 AVFilter ff_avsrc_amovie = {
601 .description = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
602 .priv_size = sizeof(MovieContext),
603 .init = movie_common_init,
604 .uninit = movie_uninit,
605 .query_formats = movie_query_formats,
609 .priv_class = &amovie_class,
610 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
613 #endif /* CONFIG_AMOVIE_FILTER */