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"
41 #include "libavcodec/avcodec.h"
43 #include "libavformat/avformat.h"
51 typedef struct MovieStream {
53 AVCodecContext *codec_ctx;
55 int64_t discontinuity_threshold;
59 typedef struct MovieContext {
60 /* common A/V fields */
62 int64_t seek_point; ///< seekpoint in microseconds
66 char *stream_specs; /**< user-provided list of streams, separated by + */
67 int stream_index; /**< for compatibility */
69 int64_t discontinuity_threshold;
72 AVFormatContext *format_ctx;
76 int max_stream_index; /**< max stream # actually used for output */
77 MovieStream *st; /**< array of all streams, one per output */
78 int *out_index; /**< stream number -> output number map, or -1 */
81 #define OFFSET(x) offsetof(MovieContext, x)
82 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_VIDEO_PARAM
84 static const AVOption movie_options[]= {
85 { "filename", NULL, OFFSET(file_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
86 { "format_name", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
87 { "f", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
88 { "stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
89 { "si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
90 { "seek_point", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, (INT64_MAX-1) / 1000000, FLAGS },
91 { "sp", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, (INT64_MAX-1) / 1000000, FLAGS },
92 { "streams", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, FLAGS },
93 { "s", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, FLAGS },
94 { "loop", "set loop count", OFFSET(loop_count), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, FLAGS },
95 { "discontinuity", "set discontinuity threshold", OFFSET(discontinuity_threshold), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, FLAGS },
99 static int movie_config_output_props(AVFilterLink *outlink);
100 static int movie_request_frame(AVFilterLink *outlink);
102 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
104 int i, ret, already = 0, stream_id = -1;
105 char type_char[2], dummy;
106 AVStream *found = NULL;
107 enum AVMediaType type;
109 ret = sscanf(spec, "d%1[av]%d%c", type_char, &stream_id, &dummy);
110 if (ret >= 1 && ret <= 2) {
111 type = type_char[0] == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
112 ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
114 av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
115 av_get_media_type_string(type), stream_id);
118 return avf->streams[ret];
120 for (i = 0; i < avf->nb_streams; i++) {
121 ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
123 av_log(log, AV_LOG_ERROR,
124 "Invalid stream specifier \"%s\"\n", spec);
129 if (avf->streams[i]->discard != AVDISCARD_ALL) {
134 av_log(log, AV_LOG_WARNING,
135 "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
138 found = avf->streams[i];
141 av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
142 already ? "matched only already used streams" :
143 "did not match any stream");
146 if (found->codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
147 found->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
148 av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
149 "currently unsupported by libavfilter\n", spec,
150 av_get_media_type_string(found->codecpar->codec_type));
156 static int open_stream(void *log, MovieStream *st)
161 codec = avcodec_find_decoder(st->st->codecpar->codec_id);
163 av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
164 return AVERROR(EINVAL);
167 st->codec_ctx = avcodec_alloc_context3(codec);
169 return AVERROR(ENOMEM);
171 ret = avcodec_parameters_to_context(st->codec_ctx, st->st->codecpar);
175 st->codec_ctx->refcounted_frames = 1;
177 if ((ret = avcodec_open2(st->codec_ctx, codec, NULL)) < 0) {
178 av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
185 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
187 AVCodecParameters *dec_par = st->st->codecpar;
189 int64_t chl = av_get_default_channel_layout(dec_par->channels);
192 av_log(log_ctx, AV_LOG_ERROR,
193 "Channel layout is not set in stream %d, and could not "
194 "be guessed from the number of channels (%d)\n",
195 st_index, dec_par->channels);
196 return AVERROR(EINVAL);
199 av_get_channel_layout_string(buf, sizeof(buf), dec_par->channels, chl);
200 av_log(log_ctx, AV_LOG_WARNING,
201 "Channel layout is not set in output stream %d, "
202 "guessed channel layout is '%s'\n",
204 dec_par->channel_layout = chl;
208 static av_cold int movie_common_init(AVFilterContext *ctx)
210 MovieContext *movie = ctx->priv;
211 AVInputFormat *iformat = NULL;
213 int nb_streams = 1, ret, i;
214 char default_streams[16], *stream_specs, *spec, *cursor;
218 if (!movie->file_name) {
219 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
220 return AVERROR(EINVAL);
223 movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
225 stream_specs = movie->stream_specs;
227 snprintf(default_streams, sizeof(default_streams), "d%c%d",
228 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
229 movie->stream_index);
230 stream_specs = default_streams;
232 for (cursor = stream_specs; *cursor; cursor++)
236 if (movie->loop_count != 1 && nb_streams != 1) {
237 av_log(ctx, AV_LOG_ERROR,
238 "Loop with several streams is currently unsupported\n");
239 return AVERROR_PATCHWELCOME;
242 // Try to find the movie format (container)
243 iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
245 movie->format_ctx = NULL;
246 if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
247 av_log(ctx, AV_LOG_ERROR,
248 "Failed to avformat_open_input '%s'\n", movie->file_name);
251 if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
252 av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
254 // if seeking requested, we execute it
255 if (movie->seek_point > 0) {
256 timestamp = movie->seek_point;
257 // add the stream start time, should it exist
258 if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
259 if (timestamp > 0 && movie->format_ctx->start_time > INT64_MAX - timestamp) {
260 av_log(ctx, AV_LOG_ERROR,
261 "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
262 movie->file_name, movie->format_ctx->start_time, movie->seek_point);
263 return AVERROR(EINVAL);
265 timestamp += movie->format_ctx->start_time;
267 if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
268 av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
269 movie->file_name, timestamp);
274 for (i = 0; i < movie->format_ctx->nb_streams; i++)
275 movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
277 movie->st = av_calloc(nb_streams, sizeof(*movie->st));
279 return AVERROR(ENOMEM);
281 for (i = 0; i < nb_streams; i++) {
282 spec = av_strtok(stream_specs, "+", &cursor);
285 stream_specs = NULL; /* for next strtok */
286 st = find_stream(ctx, movie->format_ctx, spec);
288 return AVERROR(EINVAL);
289 st->discard = AVDISCARD_DEFAULT;
290 movie->st[i].st = st;
291 movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
292 movie->st[i].discontinuity_threshold =
293 av_rescale_q(movie->discontinuity_threshold, AV_TIME_BASE_Q, st->time_base);
295 if (av_strtok(NULL, "+", &cursor))
298 movie->out_index = av_calloc(movie->max_stream_index + 1,
299 sizeof(*movie->out_index));
300 if (!movie->out_index)
301 return AVERROR(ENOMEM);
302 for (i = 0; i <= movie->max_stream_index; i++)
303 movie->out_index[i] = -1;
304 for (i = 0; i < nb_streams; i++) {
305 AVFilterPad pad = { 0 };
306 movie->out_index[movie->st[i].st->index] = i;
307 snprintf(name, sizeof(name), "out%d", i);
308 pad.type = movie->st[i].st->codecpar->codec_type;
309 pad.name = av_strdup(name);
311 return AVERROR(ENOMEM);
312 pad.config_props = movie_config_output_props;
313 pad.request_frame = movie_request_frame;
314 if ((ret = ff_insert_outpad(ctx, i, &pad)) < 0) {
318 if ( movie->st[i].st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
319 !movie->st[i].st->codecpar->channel_layout) {
320 ret = guess_channel_layout(&movie->st[i], i, ctx);
324 ret = open_stream(ctx, &movie->st[i]);
329 av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
330 movie->seek_point, movie->format_name, movie->file_name,
331 movie->stream_index);
336 static av_cold void movie_uninit(AVFilterContext *ctx)
338 MovieContext *movie = ctx->priv;
341 for (i = 0; i < ctx->nb_outputs; i++) {
342 av_freep(&ctx->output_pads[i].name);
344 avcodec_free_context(&movie->st[i].codec_ctx);
346 av_freep(&movie->st);
347 av_freep(&movie->out_index);
348 if (movie->format_ctx)
349 avformat_close_input(&movie->format_ctx);
352 static int movie_query_formats(AVFilterContext *ctx)
354 MovieContext *movie = ctx->priv;
355 int list[] = { 0, -1 };
356 int64_t list64[] = { 0, -1 };
359 for (i = 0; i < ctx->nb_outputs; i++) {
360 MovieStream *st = &movie->st[i];
361 AVCodecParameters *c = st->st->codecpar;
362 AVFilterLink *outlink = ctx->outputs[i];
364 switch (c->codec_type) {
365 case AVMEDIA_TYPE_VIDEO:
367 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
370 case AVMEDIA_TYPE_AUDIO:
372 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
374 list[0] = c->sample_rate;
375 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates)) < 0)
377 list64[0] = c->channel_layout;
378 if ((ret = ff_channel_layouts_ref(avfilter_make_format64_list(list64),
379 &outlink->in_channel_layouts)) < 0)
388 static int movie_config_output_props(AVFilterLink *outlink)
390 AVFilterContext *ctx = outlink->src;
391 MovieContext *movie = ctx->priv;
392 unsigned out_id = FF_OUTLINK_IDX(outlink);
393 MovieStream *st = &movie->st[out_id];
394 AVCodecParameters *c = st->st->codecpar;
396 outlink->time_base = st->st->time_base;
398 switch (c->codec_type) {
399 case AVMEDIA_TYPE_VIDEO:
400 outlink->w = c->width;
401 outlink->h = c->height;
402 outlink->frame_rate = st->st->r_frame_rate;
404 case AVMEDIA_TYPE_AUDIO:
411 static char *describe_frame_to_str(char *dst, size_t dst_size,
412 AVFrame *frame, enum AVMediaType frame_type,
415 switch (frame_type) {
416 case AVMEDIA_TYPE_VIDEO:
417 snprintf(dst, dst_size,
418 "video pts:%s time:%s size:%dx%d aspect:%d/%d",
419 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
420 frame->width, frame->height,
421 frame->sample_aspect_ratio.num,
422 frame->sample_aspect_ratio.den);
424 case AVMEDIA_TYPE_AUDIO:
425 snprintf(dst, dst_size,
426 "audio pts:%s time:%s samples:%d",
427 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
431 snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(frame_type));
437 static int rewind_file(AVFilterContext *ctx)
439 MovieContext *movie = ctx->priv;
440 int64_t timestamp = movie->seek_point;
443 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
444 timestamp += movie->format_ctx->start_time;
445 ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
447 av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
448 movie->loop_count = 1; /* do not try again */
452 for (i = 0; i < ctx->nb_outputs; i++) {
453 avcodec_flush_buffers(movie->st[i].codec_ctx);
454 movie->st[i].done = 0;
461 * Try to push a frame to the requested output.
463 * @param ctx filter context
464 * @param out_id number of output where a frame is wanted;
465 * if the frame is read from file, used to set the return value;
466 * if the codec is being flushed, flush the corresponding stream
467 * @return 1 if a frame was pushed on the requested output,
468 * 0 if another attempt is possible,
471 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
473 MovieContext *movie = ctx->priv;
474 AVPacket *pkt = &movie->pkt;
475 enum AVMediaType frame_type;
477 int ret, got_frame = 0, pkt_out_id;
478 AVFilterLink *outlink;
483 if (movie->st[out_id].done) {
484 if (movie->loop_count != 1) {
485 ret = rewind_file(ctx);
488 movie->loop_count -= movie->loop_count > 1;
489 av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
490 return 0; /* retry */
494 pkt->stream_index = movie->st[out_id].st->index;
495 /* packet is already ready for flushing */
497 ret = av_read_frame(movie->format_ctx, &movie->pkt0);
499 av_init_packet(&movie->pkt0); /* ready for flushing */
501 if (ret == AVERROR_EOF) {
503 return 0; /* start flushing */
511 pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
512 movie->out_index[pkt->stream_index];
513 if (pkt_out_id < 0) {
514 av_packet_unref(&movie->pkt0);
515 pkt->size = 0; /* ready for next run */
519 st = &movie->st[pkt_out_id];
520 outlink = ctx->outputs[pkt_out_id];
522 frame = av_frame_alloc();
524 return AVERROR(ENOMEM);
526 frame_type = st->st->codecpar->codec_type;
527 switch (frame_type) {
528 case AVMEDIA_TYPE_VIDEO:
529 ret = avcodec_decode_video2(st->codec_ctx, frame, &got_frame, pkt);
531 case AVMEDIA_TYPE_AUDIO:
532 ret = avcodec_decode_audio4(st->codec_ctx, frame, &got_frame, pkt);
535 ret = AVERROR(ENOSYS);
539 av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
540 av_frame_free(&frame);
541 av_packet_unref(&movie->pkt0);
543 movie->pkt.data = NULL;
546 if (!ret || st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
551 if (pkt->size <= 0) {
552 av_packet_unref(&movie->pkt0);
553 pkt->size = 0; /* ready for next run */
559 av_frame_free(&frame);
563 frame->pts = frame->best_effort_timestamp;
564 if (frame->pts != AV_NOPTS_VALUE) {
565 if (movie->ts_offset)
566 frame->pts += av_rescale_q_rnd(movie->ts_offset, AV_TIME_BASE_Q, outlink->time_base, AV_ROUND_UP);
567 if (st->discontinuity_threshold) {
568 if (st->last_pts != AV_NOPTS_VALUE) {
569 int64_t diff = frame->pts - st->last_pts;
570 if (diff < 0 || diff > st->discontinuity_threshold) {
571 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity in stream:%d diff:%"PRId64"\n", pkt_out_id, diff);
572 movie->ts_offset += av_rescale_q_rnd(-diff, outlink->time_base, AV_TIME_BASE_Q, AV_ROUND_UP);
577 st->last_pts = frame->pts;
579 ff_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
580 describe_frame_to_str((char[1024]){0}, 1024, frame, frame_type, outlink));
582 if (st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
583 if (frame->format != outlink->format) {
584 av_log(ctx, AV_LOG_ERROR, "Format changed %s -> %s, discarding frame\n",
585 av_get_pix_fmt_name(outlink->format),
586 av_get_pix_fmt_name(frame->format)
588 av_frame_free(&frame);
592 ret = ff_filter_frame(outlink, frame);
596 return pkt_out_id == out_id;
599 static int movie_request_frame(AVFilterLink *outlink)
601 AVFilterContext *ctx = outlink->src;
602 unsigned out_id = FF_OUTLINK_IDX(outlink);
606 ret = movie_push_frame(ctx, out_id);
608 return FFMIN(ret, 0);
612 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
613 char *res, int res_len, int flags)
615 MovieContext *movie = ctx->priv;
616 int ret = AVERROR(ENOSYS);
618 if (!strcmp(cmd, "seek")) {
623 if (sscanf(args, "%i|%"SCNi64"|%i %1s", &idx, &ts, &flags, tail) != 3)
624 return AVERROR(EINVAL);
626 ret = av_seek_frame(movie->format_ctx, idx, ts, flags);
630 for (i = 0; i < ctx->nb_outputs; i++) {
631 avcodec_flush_buffers(movie->st[i].codec_ctx);
632 movie->st[i].done = 0;
635 } else if (!strcmp(cmd, "get_duration")) {
639 if (!res || res_len <= 0)
640 return AVERROR(EINVAL);
642 if (args && sscanf(args, "%1s", tail) == 1)
643 return AVERROR(EINVAL);
645 print_len = snprintf(res, res_len, "%"PRId64, movie->format_ctx->duration);
646 if (print_len < 0 || print_len >= res_len)
647 return AVERROR(EINVAL);
655 #if CONFIG_MOVIE_FILTER
657 AVFILTER_DEFINE_CLASS(movie);
659 AVFilter ff_avsrc_movie = {
661 .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
662 .priv_size = sizeof(MovieContext),
663 .priv_class = &movie_class,
664 .init = movie_common_init,
665 .uninit = movie_uninit,
666 .query_formats = movie_query_formats,
670 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
671 .process_command = process_command
674 #endif /* CONFIG_MOVIE_FILTER */
676 #if CONFIG_AMOVIE_FILTER
678 #define amovie_options movie_options
679 AVFILTER_DEFINE_CLASS(amovie);
681 AVFilter ff_avsrc_amovie = {
683 .description = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
684 .priv_size = sizeof(MovieContext),
685 .init = movie_common_init,
686 .uninit = movie_uninit,
687 .query_formats = movie_query_formats,
691 .priv_class = &amovie_class,
692 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
693 .process_command = process_command,
696 #endif /* CONFIG_AMOVIE_FILTER */