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;
51 int64_t discontinuity_threshold;
55 typedef struct MovieContext {
56 /* common A/V fields */
58 int64_t seek_point; ///< seekpoint in microseconds
62 char *stream_specs; /**< user-provided list of streams, separated by + */
63 int stream_index; /**< for compatibility */
65 int64_t discontinuity_threshold;
68 AVFormatContext *format_ctx;
72 int max_stream_index; /**< max stream # actually used for output */
73 MovieStream *st; /**< array of all streams, one per output */
74 int *out_index; /**< stream number -> output number map, or -1 */
77 #define OFFSET(x) offsetof(MovieContext, x)
78 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_VIDEO_PARAM
80 static const AVOption movie_options[]= {
81 { "filename", NULL, OFFSET(file_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
82 { "format_name", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
83 { "f", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, .flags = FLAGS },
84 { "stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
85 { "si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, FLAGS },
86 { "seek_point", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, (INT64_MAX-1) / 1000000, FLAGS },
87 { "sp", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl = 0 }, 0, (INT64_MAX-1) / 1000000, FLAGS },
88 { "streams", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, FLAGS },
89 { "s", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, FLAGS },
90 { "loop", "set loop count", OFFSET(loop_count), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, FLAGS },
91 { "discontinuity", "set discontinuity threshold", OFFSET(discontinuity_threshold), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, FLAGS },
95 static int movie_config_output_props(AVFilterLink *outlink);
96 static int movie_request_frame(AVFilterLink *outlink);
98 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
100 int i, ret, already = 0, stream_id = -1;
101 char type_char[2], dummy;
102 AVStream *found = NULL;
103 enum AVMediaType type;
105 ret = sscanf(spec, "d%1[av]%d%c", type_char, &stream_id, &dummy);
106 if (ret >= 1 && ret <= 2) {
107 type = type_char[0] == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
108 ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
110 av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
111 av_get_media_type_string(type), stream_id);
114 return avf->streams[ret];
116 for (i = 0; i < avf->nb_streams; i++) {
117 ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
119 av_log(log, AV_LOG_ERROR,
120 "Invalid stream specifier \"%s\"\n", spec);
125 if (avf->streams[i]->discard != AVDISCARD_ALL) {
130 av_log(log, AV_LOG_WARNING,
131 "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
134 found = avf->streams[i];
137 av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
138 already ? "matched only already used streams" :
139 "did not match any stream");
142 if (found->codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
143 found->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
144 av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
145 "currently unsupported by libavfilter\n", spec,
146 av_get_media_type_string(found->codecpar->codec_type));
152 static int open_stream(void *log, MovieStream *st)
157 codec = avcodec_find_decoder(st->st->codecpar->codec_id);
159 av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
160 return AVERROR(EINVAL);
163 st->codec_ctx = avcodec_alloc_context3(codec);
165 return AVERROR(ENOMEM);
167 ret = avcodec_parameters_to_context(st->codec_ctx, st->st->codecpar);
171 st->codec_ctx->refcounted_frames = 1;
173 if ((ret = avcodec_open2(st->codec_ctx, codec, NULL)) < 0) {
174 av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
181 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
183 AVCodecParameters *dec_par = st->st->codecpar;
185 int64_t chl = av_get_default_channel_layout(dec_par->channels);
188 av_log(log_ctx, AV_LOG_ERROR,
189 "Channel layout is not set in stream %d, and could not "
190 "be guessed from the number of channels (%d)\n",
191 st_index, dec_par->channels);
192 return AVERROR(EINVAL);
195 av_get_channel_layout_string(buf, sizeof(buf), dec_par->channels, chl);
196 av_log(log_ctx, AV_LOG_WARNING,
197 "Channel layout is not set in output stream %d, "
198 "guessed channel layout is '%s'\n",
200 dec_par->channel_layout = chl;
204 static av_cold int movie_common_init(AVFilterContext *ctx)
206 MovieContext *movie = ctx->priv;
207 AVInputFormat *iformat = NULL;
209 int nb_streams = 1, ret, i;
210 char default_streams[16], *stream_specs, *spec, *cursor;
214 if (!movie->file_name) {
215 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
216 return AVERROR(EINVAL);
219 movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
221 stream_specs = movie->stream_specs;
223 snprintf(default_streams, sizeof(default_streams), "d%c%d",
224 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
225 movie->stream_index);
226 stream_specs = default_streams;
228 for (cursor = stream_specs; *cursor; cursor++)
232 if (movie->loop_count != 1 && nb_streams != 1) {
233 av_log(ctx, AV_LOG_ERROR,
234 "Loop with several streams is currently unsupported\n");
235 return AVERROR_PATCHWELCOME;
240 // Try to find the movie format (container)
241 iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
243 movie->format_ctx = NULL;
244 if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
245 av_log(ctx, AV_LOG_ERROR,
246 "Failed to avformat_open_input '%s'\n", movie->file_name);
249 if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
250 av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
252 // if seeking requested, we execute it
253 if (movie->seek_point > 0) {
254 timestamp = movie->seek_point;
255 // add the stream start time, should it exist
256 if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
257 if (timestamp > 0 && movie->format_ctx->start_time > INT64_MAX - timestamp) {
258 av_log(ctx, AV_LOG_ERROR,
259 "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
260 movie->file_name, movie->format_ctx->start_time, movie->seek_point);
261 return AVERROR(EINVAL);
263 timestamp += movie->format_ctx->start_time;
265 if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
266 av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
267 movie->file_name, timestamp);
272 for (i = 0; i < movie->format_ctx->nb_streams; i++)
273 movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
275 movie->st = av_calloc(nb_streams, sizeof(*movie->st));
277 return AVERROR(ENOMEM);
279 for (i = 0; i < nb_streams; i++) {
280 spec = av_strtok(stream_specs, "+", &cursor);
283 stream_specs = NULL; /* for next strtok */
284 st = find_stream(ctx, movie->format_ctx, spec);
286 return AVERROR(EINVAL);
287 st->discard = AVDISCARD_DEFAULT;
288 movie->st[i].st = st;
289 movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
290 movie->st[i].discontinuity_threshold =
291 av_rescale_q(movie->discontinuity_threshold, AV_TIME_BASE_Q, st->time_base);
293 if (av_strtok(NULL, "+", &cursor))
296 movie->out_index = av_calloc(movie->max_stream_index + 1,
297 sizeof(*movie->out_index));
298 if (!movie->out_index)
299 return AVERROR(ENOMEM);
300 for (i = 0; i <= movie->max_stream_index; i++)
301 movie->out_index[i] = -1;
302 for (i = 0; i < nb_streams; i++) {
303 AVFilterPad pad = { 0 };
304 movie->out_index[movie->st[i].st->index] = i;
305 snprintf(name, sizeof(name), "out%d", i);
306 pad.type = movie->st[i].st->codecpar->codec_type;
307 pad.name = av_strdup(name);
309 return AVERROR(ENOMEM);
310 pad.config_props = movie_config_output_props;
311 pad.request_frame = movie_request_frame;
312 ff_insert_outpad(ctx, i, &pad);
313 if ( movie->st[i].st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
314 !movie->st[i].st->codecpar->channel_layout) {
315 ret = guess_channel_layout(&movie->st[i], i, ctx);
319 ret = open_stream(ctx, &movie->st[i]);
324 av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
325 movie->seek_point, movie->format_name, movie->file_name,
326 movie->stream_index);
331 static av_cold void movie_uninit(AVFilterContext *ctx)
333 MovieContext *movie = ctx->priv;
336 for (i = 0; i < ctx->nb_outputs; i++) {
337 av_freep(&ctx->output_pads[i].name);
339 avcodec_free_context(&movie->st[i].codec_ctx);
341 av_freep(&movie->st);
342 av_freep(&movie->out_index);
343 if (movie->format_ctx)
344 avformat_close_input(&movie->format_ctx);
347 static int movie_query_formats(AVFilterContext *ctx)
349 MovieContext *movie = ctx->priv;
350 int list[] = { 0, -1 };
351 int64_t list64[] = { 0, -1 };
354 for (i = 0; i < ctx->nb_outputs; i++) {
355 MovieStream *st = &movie->st[i];
356 AVCodecParameters *c = st->st->codecpar;
357 AVFilterLink *outlink = ctx->outputs[i];
359 switch (c->codec_type) {
360 case AVMEDIA_TYPE_VIDEO:
362 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
365 case AVMEDIA_TYPE_AUDIO:
367 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
369 list[0] = c->sample_rate;
370 if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates)) < 0)
372 list64[0] = c->channel_layout;
373 if ((ret = ff_channel_layouts_ref(avfilter_make_format64_list(list64),
374 &outlink->in_channel_layouts)) < 0)
383 static int movie_config_output_props(AVFilterLink *outlink)
385 AVFilterContext *ctx = outlink->src;
386 MovieContext *movie = ctx->priv;
387 unsigned out_id = FF_OUTLINK_IDX(outlink);
388 MovieStream *st = &movie->st[out_id];
389 AVCodecParameters *c = st->st->codecpar;
391 outlink->time_base = st->st->time_base;
393 switch (c->codec_type) {
394 case AVMEDIA_TYPE_VIDEO:
395 outlink->w = c->width;
396 outlink->h = c->height;
397 outlink->frame_rate = st->st->r_frame_rate;
399 case AVMEDIA_TYPE_AUDIO:
406 static char *describe_frame_to_str(char *dst, size_t dst_size,
407 AVFrame *frame, enum AVMediaType frame_type,
410 switch (frame_type) {
411 case AVMEDIA_TYPE_VIDEO:
412 snprintf(dst, dst_size,
413 "video pts:%s time:%s size:%dx%d aspect:%d/%d",
414 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
415 frame->width, frame->height,
416 frame->sample_aspect_ratio.num,
417 frame->sample_aspect_ratio.den);
419 case AVMEDIA_TYPE_AUDIO:
420 snprintf(dst, dst_size,
421 "audio pts:%s time:%s samples:%d",
422 av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
426 snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(frame_type));
432 static int rewind_file(AVFilterContext *ctx)
434 MovieContext *movie = ctx->priv;
435 int64_t timestamp = movie->seek_point;
438 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
439 timestamp += movie->format_ctx->start_time;
440 ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
442 av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
443 movie->loop_count = 1; /* do not try again */
447 for (i = 0; i < ctx->nb_outputs; i++) {
448 avcodec_flush_buffers(movie->st[i].codec_ctx);
449 movie->st[i].done = 0;
456 * Try to push a frame to the requested output.
458 * @param ctx filter context
459 * @param out_id number of output where a frame is wanted;
460 * if the frame is read from file, used to set the return value;
461 * if the codec is being flushed, flush the corresponding stream
462 * @return 1 if a frame was pushed on the requested output,
463 * 0 if another attempt is possible,
466 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
468 MovieContext *movie = ctx->priv;
469 AVPacket *pkt = &movie->pkt;
470 enum AVMediaType frame_type;
472 int ret, got_frame = 0, pkt_out_id;
473 AVFilterLink *outlink;
478 if (movie->st[out_id].done) {
479 if (movie->loop_count != 1) {
480 ret = rewind_file(ctx);
483 movie->loop_count -= movie->loop_count > 1;
484 av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
485 return 0; /* retry */
489 pkt->stream_index = movie->st[out_id].st->index;
490 /* packet is already ready for flushing */
492 ret = av_read_frame(movie->format_ctx, &movie->pkt0);
494 av_init_packet(&movie->pkt0); /* ready for flushing */
496 if (ret == AVERROR_EOF) {
498 return 0; /* start flushing */
506 pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
507 movie->out_index[pkt->stream_index];
508 if (pkt_out_id < 0) {
509 av_packet_unref(&movie->pkt0);
510 pkt->size = 0; /* ready for next run */
514 st = &movie->st[pkt_out_id];
515 outlink = ctx->outputs[pkt_out_id];
517 frame = av_frame_alloc();
519 return AVERROR(ENOMEM);
521 frame_type = st->st->codecpar->codec_type;
522 switch (frame_type) {
523 case AVMEDIA_TYPE_VIDEO:
524 ret = avcodec_decode_video2(st->codec_ctx, frame, &got_frame, pkt);
526 case AVMEDIA_TYPE_AUDIO:
527 ret = avcodec_decode_audio4(st->codec_ctx, frame, &got_frame, pkt);
530 ret = AVERROR(ENOSYS);
534 av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
535 av_frame_free(&frame);
536 av_packet_unref(&movie->pkt0);
538 movie->pkt.data = NULL;
541 if (!ret || st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
546 if (pkt->size <= 0) {
547 av_packet_unref(&movie->pkt0);
548 pkt->size = 0; /* ready for next run */
554 av_frame_free(&frame);
558 frame->pts = av_frame_get_best_effort_timestamp(frame);
559 if (frame->pts != AV_NOPTS_VALUE) {
560 if (movie->ts_offset)
561 frame->pts += av_rescale_q_rnd(movie->ts_offset, AV_TIME_BASE_Q, outlink->time_base, AV_ROUND_UP);
562 if (st->discontinuity_threshold) {
563 if (st->last_pts != AV_NOPTS_VALUE) {
564 int64_t diff = frame->pts - st->last_pts;
565 if (diff < 0 || diff > st->discontinuity_threshold) {
566 av_log(ctx, AV_LOG_VERBOSE, "Discontinuity in stream:%d diff:%"PRId64"\n", pkt_out_id, diff);
567 movie->ts_offset += av_rescale_q_rnd(-diff, outlink->time_base, AV_TIME_BASE_Q, AV_ROUND_UP);
572 st->last_pts = frame->pts;
574 ff_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
575 describe_frame_to_str((char[1024]){0}, 1024, frame, frame_type, outlink));
577 if (st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
578 if (frame->format != outlink->format) {
579 av_log(ctx, AV_LOG_ERROR, "Format changed %s -> %s, discarding frame\n",
580 av_get_pix_fmt_name(outlink->format),
581 av_get_pix_fmt_name(frame->format)
583 av_frame_free(&frame);
587 ret = ff_filter_frame(outlink, frame);
591 return pkt_out_id == out_id;
594 static int movie_request_frame(AVFilterLink *outlink)
596 AVFilterContext *ctx = outlink->src;
597 unsigned out_id = FF_OUTLINK_IDX(outlink);
601 ret = movie_push_frame(ctx, out_id);
603 return FFMIN(ret, 0);
607 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
608 char *res, int res_len, int flags)
610 MovieContext *movie = ctx->priv;
611 int ret = AVERROR(ENOSYS);
613 if (!strcmp(cmd, "seek")) {
618 if (sscanf(args, "%i|%"SCNi64"|%i %1s", &idx, &ts, &flags, tail) != 3)
619 return AVERROR(EINVAL);
621 ret = av_seek_frame(movie->format_ctx, idx, ts, flags);
625 for (i = 0; i < ctx->nb_outputs; i++) {
626 avcodec_flush_buffers(movie->st[i].codec_ctx);
627 movie->st[i].done = 0;
630 } else if (!strcmp(cmd, "get_duration")) {
634 if (!res || res_len <= 0)
635 return AVERROR(EINVAL);
637 if (args && sscanf(args, "%1s", tail) == 1)
638 return AVERROR(EINVAL);
640 print_len = snprintf(res, res_len, "%"PRId64, movie->format_ctx->duration);
641 if (print_len < 0 || print_len >= res_len)
642 return AVERROR(EINVAL);
650 #if CONFIG_MOVIE_FILTER
652 AVFILTER_DEFINE_CLASS(movie);
654 AVFilter ff_avsrc_movie = {
656 .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
657 .priv_size = sizeof(MovieContext),
658 .priv_class = &movie_class,
659 .init = movie_common_init,
660 .uninit = movie_uninit,
661 .query_formats = movie_query_formats,
665 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
666 .process_command = process_command
669 #endif /* CONFIG_MOVIE_FILTER */
671 #if CONFIG_AMOVIE_FILTER
673 #define amovie_options movie_options
674 AVFILTER_DEFINE_CLASS(amovie);
676 AVFilter ff_avsrc_amovie = {
678 .description = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
679 .priv_size = sizeof(MovieContext),
680 .init = movie_common_init,
681 .uninit = movie_uninit,
682 .query_formats = movie_query_formats,
686 .priv_class = &amovie_class,
687 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
688 .process_command = process_command,
691 #endif /* CONFIG_AMOVIE_FILTER */