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/internal.h"
39 #include "libavutil/timestamp.h"
40 #include "libavformat/avformat.h"
47 typedef struct MovieStream {
49 AVCodecContext *codec_ctx;
53 typedef struct MovieContext {
54 /* common A/V fields */
56 int64_t seek_point; ///< seekpoint in microseconds
60 char *stream_specs; /**< user-provided list of streams, separated by + */
61 int stream_index; /**< for compatibility */
64 AVFormatContext *format_ctx;
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->codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
138 found->codecpar->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->codecpar->codec_type));
147 static int open_stream(void *log, MovieStream *st)
152 codec = avcodec_find_decoder(st->st->codecpar->codec_id);
154 av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
155 return AVERROR(EINVAL);
158 st->codec_ctx = avcodec_alloc_context3(codec);
160 return AVERROR(ENOMEM);
162 ret = avcodec_parameters_to_context(st->codec_ctx, st->st->codecpar);
166 st->codec_ctx->refcounted_frames = 1;
168 if ((ret = avcodec_open2(st->codec_ctx, codec, NULL)) < 0) {
169 av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
176 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
178 AVCodecParameters *dec_par = st->st->codecpar;
180 int64_t chl = av_get_default_channel_layout(dec_par->channels);
183 av_log(log_ctx, AV_LOG_ERROR,
184 "Channel layout is not set in stream %d, and could not "
185 "be guessed from the number of channels (%d)\n",
186 st_index, dec_par->channels);
187 return AVERROR(EINVAL);
190 av_get_channel_layout_string(buf, sizeof(buf), dec_par->channels, chl);
191 av_log(log_ctx, AV_LOG_WARNING,
192 "Channel layout is not set in output stream %d, "
193 "guessed channel layout is '%s'\n",
195 dec_par->channel_layout = chl;
199 static av_cold int movie_common_init(AVFilterContext *ctx)
201 MovieContext *movie = ctx->priv;
202 AVInputFormat *iformat = NULL;
204 int nb_streams = 1, ret, i;
205 char default_streams[16], *stream_specs, *spec, *cursor;
209 if (!movie->file_name) {
210 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
211 return AVERROR(EINVAL);
214 movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
216 stream_specs = movie->stream_specs;
218 snprintf(default_streams, sizeof(default_streams), "d%c%d",
219 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
220 movie->stream_index);
221 stream_specs = default_streams;
223 for (cursor = stream_specs; *cursor; cursor++)
227 if (movie->loop_count != 1 && nb_streams != 1) {
228 av_log(ctx, AV_LOG_ERROR,
229 "Loop with several streams is currently unsupported\n");
230 return AVERROR_PATCHWELCOME;
235 // Try to find the movie format (container)
236 iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
238 movie->format_ctx = NULL;
239 if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
240 av_log(ctx, AV_LOG_ERROR,
241 "Failed to avformat_open_input '%s'\n", movie->file_name);
244 if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
245 av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
247 // if seeking requested, we execute it
248 if (movie->seek_point > 0) {
249 timestamp = movie->seek_point;
250 // add the stream start time, should it exist
251 if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
252 if (timestamp > 0 && movie->format_ctx->start_time > INT64_MAX - timestamp) {
253 av_log(ctx, AV_LOG_ERROR,
254 "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
255 movie->file_name, movie->format_ctx->start_time, movie->seek_point);
256 return AVERROR(EINVAL);
258 timestamp += movie->format_ctx->start_time;
260 if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
261 av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
262 movie->file_name, timestamp);
267 for (i = 0; i < movie->format_ctx->nb_streams; i++)
268 movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
270 movie->st = av_calloc(nb_streams, sizeof(*movie->st));
272 return AVERROR(ENOMEM);
274 for (i = 0; i < nb_streams; i++) {
275 spec = av_strtok(stream_specs, "+", &cursor);
278 stream_specs = NULL; /* for next strtok */
279 st = find_stream(ctx, movie->format_ctx, spec);
281 return AVERROR(EINVAL);
282 st->discard = AVDISCARD_DEFAULT;
283 movie->st[i].st = st;
284 movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
286 if (av_strtok(NULL, "+", &cursor))
289 movie->out_index = av_calloc(movie->max_stream_index + 1,
290 sizeof(*movie->out_index));
291 if (!movie->out_index)
292 return AVERROR(ENOMEM);
293 for (i = 0; i <= movie->max_stream_index; i++)
294 movie->out_index[i] = -1;
295 for (i = 0; i < nb_streams; i++) {
296 AVFilterPad pad = { 0 };
297 movie->out_index[movie->st[i].st->index] = i;
298 snprintf(name, sizeof(name), "out%d", i);
299 pad.type = movie->st[i].st->codecpar->codec_type;
300 pad.name = av_strdup(name);
302 return AVERROR(ENOMEM);
303 pad.config_props = movie_config_output_props;
304 pad.request_frame = movie_request_frame;
305 ff_insert_outpad(ctx, i, &pad);
306 ret = open_stream(ctx, &movie->st[i]);
309 if ( movie->st[i].st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
310 !movie->st[i].st->codecpar->channel_layout) {
311 ret = guess_channel_layout(&movie->st[i], i, ctx);
317 av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
318 movie->seek_point, movie->format_name, movie->file_name,
319 movie->stream_index);
324 static av_cold void movie_uninit(AVFilterContext *ctx)
326 MovieContext *movie = ctx->priv;
329 for (i = 0; i < ctx->nb_outputs; i++) {
330 av_freep(&ctx->output_pads[i].name);
332 avcodec_free_context(&movie->st[i].codec_ctx);
334 av_freep(&movie->st);
335 av_freep(&movie->out_index);
336 if (movie->format_ctx)
337 avformat_close_input(&movie->format_ctx);
340 static int movie_query_formats(AVFilterContext *ctx)
342 MovieContext *movie = ctx->priv;
343 int list[] = { 0, -1 };
344 int64_t list64[] = { 0, -1 };
347 for (i = 0; i < ctx->nb_outputs; i++) {
348 MovieStream *st = &movie->st[i];
349 AVCodecParameters *c = st->st->codecpar;
350 AVFilterLink *outlink = ctx->outputs[i];
352 switch (c->codec_type) {
353 case AVMEDIA_TYPE_VIDEO:
355 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
358 case AVMEDIA_TYPE_AUDIO:
360 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
362 list[0] = c->sample_rate;
363 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates)) < 0)
365 list64[0] = c->channel_layout;
366 if ((ret = ff_channel_layouts_ref(avfilter_make_format64_list(list64),
367 &outlink->in_channel_layouts)) < 0)
376 static int movie_config_output_props(AVFilterLink *outlink)
378 AVFilterContext *ctx = outlink->src;
379 MovieContext *movie = ctx->priv;
380 unsigned out_id = FF_OUTLINK_IDX(outlink);
381 MovieStream *st = &movie->st[out_id];
382 AVCodecParameters *c = st->st->codecpar;
384 outlink->time_base = st->st->time_base;
386 switch (c->codec_type) {
387 case AVMEDIA_TYPE_VIDEO:
388 outlink->w = c->width;
389 outlink->h = c->height;
390 outlink->frame_rate = st->st->r_frame_rate;
392 case AVMEDIA_TYPE_AUDIO:
399 static char *describe_frame_to_str(char *dst, size_t dst_size,
400 AVFrame *frame, enum AVMediaType frame_type,
403 switch (frame_type) {
404 case AVMEDIA_TYPE_VIDEO:
405 snprintf(dst, dst_size,
406 "video pts:%s time:%s size:%dx%d aspect:%d/%d",
407 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
408 frame->width, frame->height,
409 frame->sample_aspect_ratio.num,
410 frame->sample_aspect_ratio.den);
412 case AVMEDIA_TYPE_AUDIO:
413 snprintf(dst, dst_size,
414 "audio pts:%s time:%s samples:%d",
415 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
419 snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(frame_type));
425 static int rewind_file(AVFilterContext *ctx)
427 MovieContext *movie = ctx->priv;
428 int64_t timestamp = movie->seek_point;
431 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
432 timestamp += movie->format_ctx->start_time;
433 ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
435 av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
436 movie->loop_count = 1; /* do not try again */
440 for (i = 0; i < ctx->nb_outputs; i++) {
441 avcodec_flush_buffers(movie->st[i].codec_ctx);
442 movie->st[i].done = 0;
449 * Try to push a frame to the requested output.
451 * @param ctx filter context
452 * @param out_id number of output where a frame is wanted;
453 * if the frame is read from file, used to set the return value;
454 * if the codec is being flushed, flush the corresponding stream
455 * @return 1 if a frame was pushed on the requested output,
456 * 0 if another attempt is possible,
459 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
461 MovieContext *movie = ctx->priv;
462 AVPacket *pkt = &movie->pkt;
463 enum AVMediaType frame_type;
465 int ret, got_frame = 0, pkt_out_id;
466 AVFilterLink *outlink;
471 if (movie->st[out_id].done) {
472 if (movie->loop_count != 1) {
473 ret = rewind_file(ctx);
476 movie->loop_count -= movie->loop_count > 1;
477 av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
478 return 0; /* retry */
482 pkt->stream_index = movie->st[out_id].st->index;
483 /* packet is already ready for flushing */
485 ret = av_read_frame(movie->format_ctx, &movie->pkt0);
487 av_init_packet(&movie->pkt0); /* ready for flushing */
489 if (ret == AVERROR_EOF) {
491 return 0; /* start flushing */
499 pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
500 movie->out_index[pkt->stream_index];
501 if (pkt_out_id < 0) {
502 av_packet_unref(&movie->pkt0);
503 pkt->size = 0; /* ready for next run */
507 st = &movie->st[pkt_out_id];
508 outlink = ctx->outputs[pkt_out_id];
510 frame = av_frame_alloc();
512 return AVERROR(ENOMEM);
514 frame_type = st->st->codecpar->codec_type;
515 switch (frame_type) {
516 case AVMEDIA_TYPE_VIDEO:
517 ret = avcodec_decode_video2(st->codec_ctx, frame, &got_frame, pkt);
519 case AVMEDIA_TYPE_AUDIO:
520 ret = avcodec_decode_audio4(st->codec_ctx, frame, &got_frame, pkt);
523 ret = AVERROR(ENOSYS);
527 av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
528 av_frame_free(&frame);
529 av_packet_unref(&movie->pkt0);
531 movie->pkt.data = NULL;
534 if (!ret || st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
539 if (pkt->size <= 0) {
540 av_packet_unref(&movie->pkt0);
541 pkt->size = 0; /* ready for next run */
547 av_frame_free(&frame);
551 frame->pts = av_frame_get_best_effort_timestamp(frame);
552 ff_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
553 describe_frame_to_str((char[1024]){0}, 1024, frame, frame_type, outlink));
555 if (st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
556 if (frame->format != outlink->format) {
557 av_log(ctx, AV_LOG_ERROR, "Format changed %s -> %s, discarding frame\n",
558 av_get_pix_fmt_name(outlink->format),
559 av_get_pix_fmt_name(frame->format)
561 av_frame_free(&frame);
565 ret = ff_filter_frame(outlink, frame);
569 return pkt_out_id == out_id;
572 static int movie_request_frame(AVFilterLink *outlink)
574 AVFilterContext *ctx = outlink->src;
575 unsigned out_id = FF_OUTLINK_IDX(outlink);
579 ret = movie_push_frame(ctx, out_id);
581 return FFMIN(ret, 0);
585 #if CONFIG_MOVIE_FILTER
587 AVFILTER_DEFINE_CLASS(movie);
589 AVFilter ff_avsrc_movie = {
591 .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
592 .priv_size = sizeof(MovieContext),
593 .priv_class = &movie_class,
594 .init = movie_common_init,
595 .uninit = movie_uninit,
596 .query_formats = movie_query_formats,
600 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
603 #endif /* CONFIG_MOVIE_FILTER */
605 #if CONFIG_AMOVIE_FILTER
607 #define amovie_options movie_options
608 AVFILTER_DEFINE_CLASS(amovie);
610 AVFilter ff_avsrc_amovie = {
612 .description = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
613 .priv_size = sizeof(MovieContext),
614 .init = movie_common_init,
615 .uninit = movie_uninit,
616 .query_formats = movie_query_formats,
620 .priv_class = &amovie_class,
621 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
624 #endif /* CONFIG_AMOVIE_FILTER */