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/avstring.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/timestamp.h"
38 #include "libavformat/avformat.h"
52 /* common A/V fields */
54 int64_t seek_point; ///< seekpoint in microseconds
58 char *stream_specs; /**< user-provided list of streams, separated by + */
59 int stream_index; /**< for compatibility */
62 AVFormatContext *format_ctx;
65 AVFrame *frame; ///< video frame to store the decoded images in
67 int max_stream_index; /**< max stream # actually used for output */
68 MovieStream *st; /**< array of all streams, one per output */
69 int *out_index; /**< stream number -> output number map, or -1 */
72 #define OFFSET(x) offsetof(MovieContext, x)
73 #define F AV_OPT_FLAG_FILTERING_PARAM
75 static const AVOption movie_options[]= {
76 {"format_name", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MIN, CHAR_MAX, F },
77 {"f", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MIN, CHAR_MAX, F },
78 {"streams", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, F },
79 {"s", "set streams", OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MAX, CHAR_MAX, F },
80 {"si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, F },
81 {"stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, F },
82 {"seek_point", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, (INT64_MAX-1) / 1000000, F },
83 {"sp", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, (INT64_MAX-1) / 1000000, F },
84 {"loop", "set loop count", OFFSET(loop_count), AV_OPT_TYPE_INT, {.i64 = 1}, 0, INT_MAX, F },
88 static int movie_config_output_props(AVFilterLink *outlink);
89 static int movie_request_frame(AVFilterLink *outlink);
91 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
93 int i, ret, already = 0, stream_id = -1;
94 char type_char, dummy;
95 AVStream *found = NULL;
96 enum AVMediaType type;
98 ret = sscanf(spec, "d%[av]%d%c", &type_char, &stream_id, &dummy);
99 if (ret >= 1 && ret <= 2) {
100 type = type_char == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
101 ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
103 av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
104 av_get_media_type_string(type), stream_id);
107 return avf->streams[ret];
109 for (i = 0; i < avf->nb_streams; i++) {
110 ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
112 av_log(log, AV_LOG_ERROR,
113 "Invalid stream specifier \"%s\"\n", spec);
118 if (avf->streams[i]->discard != AVDISCARD_ALL) {
123 av_log(log, AV_LOG_WARNING,
124 "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
127 found = avf->streams[i];
130 av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
131 already ? "matched only already used streams" :
132 "did not match any stream");
135 if (found->codec->codec_type != AVMEDIA_TYPE_VIDEO &&
136 found->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
137 av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
138 "currently unsupported by libavfilter\n", spec,
139 av_get_media_type_string(found->codec->codec_type));
145 static int open_stream(void *log, MovieStream *st)
150 codec = avcodec_find_decoder(st->st->codec->codec_id);
152 av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
153 return AVERROR(EINVAL);
156 if ((ret = avcodec_open2(st->st->codec, codec, NULL)) < 0) {
157 av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
164 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
166 AVCodecContext *dec_ctx = st->st->codec;
168 int64_t chl = av_get_default_channel_layout(dec_ctx->channels);
171 av_log(log_ctx, AV_LOG_ERROR,
172 "Channel layout is not set in stream %d, and could not "
173 "be guessed from the number of channels (%d)\n",
174 st_index, dec_ctx->channels);
175 return AVERROR(EINVAL);
178 av_get_channel_layout_string(buf, sizeof(buf), dec_ctx->channels, chl);
179 av_log(log_ctx, AV_LOG_WARNING,
180 "Channel layout is not set in output stream %d, "
181 "guessed channel layout is '%s'\n",
183 dec_ctx->channel_layout = chl;
187 static av_cold int movie_common_init(AVFilterContext *ctx, const char *args, const AVClass *class)
189 MovieContext *movie = ctx->priv;
190 AVInputFormat *iformat = NULL;
192 int nb_streams, ret, i;
193 char default_streams[16], *stream_specs, *spec, *cursor;
197 movie->class = class;
198 av_opt_set_defaults(movie);
201 movie->file_name = av_get_token(&args, ":");
202 if (!movie->file_name || !*movie->file_name) {
203 av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
204 return AVERROR(EINVAL);
207 if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0)
210 movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
212 stream_specs = movie->stream_specs;
214 snprintf(default_streams, sizeof(default_streams), "d%c%d",
215 !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
216 movie->stream_index);
217 stream_specs = default_streams;
219 for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)
223 if (movie->loop_count != 1 && nb_streams != 1) {
224 av_log(ctx, AV_LOG_ERROR,
225 "Loop with several streams is currently unsupported\n");
226 return AVERROR_PATCHWELCOME;
231 // Try to find the movie format (container)
232 iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
234 movie->format_ctx = NULL;
235 if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
236 av_log(ctx, AV_LOG_ERROR,
237 "Failed to avformat_open_input '%s'\n", movie->file_name);
240 if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
241 av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
243 // if seeking requested, we execute it
244 if (movie->seek_point > 0) {
245 timestamp = movie->seek_point;
246 // add the stream start time, should it exist
247 if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
248 if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
249 av_log(ctx, AV_LOG_ERROR,
250 "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
251 movie->file_name, movie->format_ctx->start_time, movie->seek_point);
252 return AVERROR(EINVAL);
254 timestamp += movie->format_ctx->start_time;
256 if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
257 av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
258 movie->file_name, timestamp);
263 for (i = 0; i < movie->format_ctx->nb_streams; i++)
264 movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
266 movie->st = av_calloc(nb_streams, sizeof(*movie->st));
268 return AVERROR(ENOMEM);
270 for (i = 0; i < nb_streams; i++) {
271 spec = av_strtok(stream_specs, "+", &cursor);
274 stream_specs = NULL; /* for next strtok */
275 st = find_stream(ctx, movie->format_ctx, spec);
277 return AVERROR(EINVAL);
278 st->discard = AVDISCARD_DEFAULT;
279 movie->st[i].st = st;
280 movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
282 if (av_strtok(NULL, "+", &cursor))
285 movie->out_index = av_calloc(movie->max_stream_index + 1,
286 sizeof(*movie->out_index));
287 if (!movie->out_index)
288 return AVERROR(ENOMEM);
289 for (i = 0; i <= movie->max_stream_index; i++)
290 movie->out_index[i] = -1;
291 for (i = 0; i < nb_streams; i++)
292 movie->out_index[movie->st[i].st->index] = i;
294 for (i = 0; i < nb_streams; i++) {
295 AVFilterPad pad = { 0 };
296 snprintf(name, sizeof(name), "out%d", i);
297 pad.type = movie->st[i].st->codec->codec_type;
298 pad.name = av_strdup(name);
299 pad.config_props = movie_config_output_props;
300 pad.request_frame = movie_request_frame;
301 ff_insert_outpad(ctx, i, &pad);
302 ret = open_stream(ctx, &movie->st[i]);
305 if ( movie->st[i].st->codec->codec->type == AVMEDIA_TYPE_AUDIO &&
306 !movie->st[i].st->codec->channel_layout) {
307 ret = guess_channel_layout(&movie->st[i], i, ctx);
313 if (!(movie->frame = avcodec_alloc_frame()) ) {
314 av_log(log, AV_LOG_ERROR, "Failed to alloc frame\n");
315 return AVERROR(ENOMEM);
318 av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
319 movie->seek_point, movie->format_name, movie->file_name,
320 movie->stream_index);
325 static av_cold void movie_uninit(AVFilterContext *ctx)
327 MovieContext *movie = ctx->priv;
330 for (i = 0; i < ctx->nb_outputs; i++) {
331 av_freep(&ctx->output_pads[i].name);
333 avcodec_close(movie->st[i].st->codec);
336 av_freep(&movie->file_name);
337 av_freep(&movie->st);
338 av_freep(&movie->out_index);
339 avcodec_free_frame(&movie->frame);
340 if (movie->format_ctx)
341 avformat_close_input(&movie->format_ctx);
344 static int movie_query_formats(AVFilterContext *ctx)
346 MovieContext *movie = ctx->priv;
347 int list[] = { 0, -1 };
348 int64_t list64[] = { 0, -1 };
351 for (i = 0; i < ctx->nb_outputs; i++) {
352 MovieStream *st = &movie->st[i];
353 AVCodecContext *c = st->st->codec;
354 AVFilterLink *outlink = ctx->outputs[i];
356 switch (c->codec_type) {
357 case AVMEDIA_TYPE_VIDEO:
358 list[0] = c->pix_fmt;
359 ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
361 case AVMEDIA_TYPE_AUDIO:
362 list[0] = c->sample_fmt;
363 ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
364 list[0] = c->sample_rate;
365 ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates);
366 list64[0] = c->channel_layout;
367 ff_channel_layouts_ref(avfilter_make_format64_list(list64),
368 &outlink->in_channel_layouts);
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 AVCodecContext *c = st->st->codec;
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 AVFilterBufferRef *frame_to_buf(enum AVMediaType type, AVFrame *frame,
400 AVFilterLink *outlink)
402 AVFilterBufferRef *buf, *copy;
404 buf = avfilter_get_buffer_ref_from_frame(type, frame,
410 buf->pts = av_frame_get_best_effort_timestamp(frame);
411 copy = ff_copy_buffer_ref(outlink, buf);
414 buf->buf->data[0] = NULL; /* it belongs to the frame */
415 avfilter_unref_buffer(buf);
419 static char *describe_bufref_to_str(char *dst, size_t dst_size,
420 AVFilterBufferRef *buf,
424 case AVMEDIA_TYPE_VIDEO:
425 snprintf(dst, dst_size,
426 "video pts:%s time:%s pos:%"PRId64" size:%dx%d aspect:%d/%d",
427 av_ts2str(buf->pts), av_ts2timestr(buf->pts, &link->time_base),
428 buf->pos, buf->video->w, buf->video->h,
429 buf->video->sample_aspect_ratio.num,
430 buf->video->sample_aspect_ratio.den);
432 case AVMEDIA_TYPE_AUDIO:
433 snprintf(dst, dst_size,
434 "audio pts:%s time:%s pos:%"PRId64" samples:%d",
435 av_ts2str(buf->pts), av_ts2timestr(buf->pts, &link->time_base),
436 buf->pos, buf->audio->nb_samples);
439 snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(buf->type));
445 #define describe_bufref(buf, link) \
446 describe_bufref_to_str((char[1024]){0}, 1024, buf, link)
448 static int rewind_file(AVFilterContext *ctx)
450 MovieContext *movie = ctx->priv;
451 int64_t timestamp = movie->seek_point;
454 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
455 timestamp += movie->format_ctx->start_time;
456 ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
458 av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
459 movie->loop_count = 1; /* do not try again */
463 for (i = 0; i < ctx->nb_outputs; i++) {
464 avcodec_flush_buffers(movie->st[i].st->codec);
465 movie->st[i].done = 0;
472 * Try to push a frame to the requested output.
474 * @param ctx filter context
475 * @param out_id number of output where a frame is wanted;
476 * if the frame is read from file, used to set the return value;
477 * if the codec is being flushed, flush the corresponding stream
478 * @return 1 if a frame was pushed on the requested output,
479 * 0 if another attempt is possible,
482 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
484 MovieContext *movie = ctx->priv;
485 AVPacket *pkt = &movie->pkt;
487 int ret, got_frame = 0, pkt_out_id;
488 AVFilterLink *outlink;
489 AVFilterBufferRef *buf;
493 if (movie->st[out_id].done) {
494 if (movie->loop_count != 1) {
495 ret = rewind_file(ctx);
498 movie->loop_count -= movie->loop_count > 1;
499 av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
500 return 0; /* retry */
504 pkt->stream_index = movie->st[out_id].st->index;
505 /* packet is already ready for flushing */
507 ret = av_read_frame(movie->format_ctx, &movie->pkt0);
509 av_init_packet(&movie->pkt0); /* ready for flushing */
511 if (ret == AVERROR_EOF) {
513 return 0; /* start flushing */
521 pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
522 movie->out_index[pkt->stream_index];
523 if (pkt_out_id < 0) {
524 av_free_packet(&movie->pkt0);
525 pkt->size = 0; /* ready for next run */
529 st = &movie->st[pkt_out_id];
530 outlink = ctx->outputs[pkt_out_id];
532 switch (st->st->codec->codec_type) {
533 case AVMEDIA_TYPE_VIDEO:
534 ret = avcodec_decode_video2(st->st->codec, movie->frame, &got_frame, pkt);
536 case AVMEDIA_TYPE_AUDIO:
537 ret = avcodec_decode_audio4(st->st->codec, movie->frame, &got_frame, pkt);
540 ret = AVERROR(ENOSYS);
544 av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
552 if (pkt->size <= 0) {
553 av_free_packet(&movie->pkt0);
554 pkt->size = 0; /* ready for next run */
563 buf = frame_to_buf(st->st->codec->codec_type, movie->frame, outlink);
565 return AVERROR(ENOMEM);
566 av_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
567 describe_bufref(buf, outlink));
568 switch (st->st->codec->codec_type) {
569 case AVMEDIA_TYPE_VIDEO:
570 if (!movie->frame->sample_aspect_ratio.num)
571 buf->video->sample_aspect_ratio = st->st->sample_aspect_ratio;
572 ff_start_frame(outlink, buf);
573 ff_draw_slice(outlink, 0, outlink->h, 1);
574 ff_end_frame(outlink);
576 case AVMEDIA_TYPE_AUDIO:
577 ff_filter_samples(outlink, buf);
581 return pkt_out_id == out_id;
584 static int movie_request_frame(AVFilterLink *outlink)
586 AVFilterContext *ctx = outlink->src;
587 unsigned out_id = FF_OUTLINK_IDX(outlink);
591 ret = movie_push_frame(ctx, out_id);
593 return FFMIN(ret, 0);
597 #if CONFIG_MOVIE_FILTER
599 AVFILTER_DEFINE_CLASS(movie);
601 static av_cold int movie_init(AVFilterContext *ctx, const char *args)
603 return movie_common_init(ctx, args, &movie_class);
606 AVFilter avfilter_avsrc_movie = {
608 .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
609 .priv_size = sizeof(MovieContext),
611 .uninit = movie_uninit,
612 .query_formats = movie_query_formats,
615 .outputs = (const AVFilterPad[]) {{ .name = NULL }},
616 .priv_class = &movie_class,
619 #endif /* CONFIG_MOVIE_FILTER */
621 #if CONFIG_AMOVIE_FILTER
623 #define amovie_options movie_options
624 AVFILTER_DEFINE_CLASS(amovie);
626 static av_cold int amovie_init(AVFilterContext *ctx, const char *args)
628 return movie_common_init(ctx, args, &amovie_class);
631 AVFilter avfilter_avsrc_amovie = {
633 .description = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
634 .priv_size = sizeof(MovieContext),
636 .uninit = movie_uninit,
637 .query_formats = movie_query_formats,
639 .inputs = (const AVFilterPad[]) {{ .name = NULL }},
640 .outputs = (const AVFilterPad[]) {{ .name = NULL }},
641 .priv_class = &amovie_class,
644 #endif /* CONFIG_AMOVIE_FILTER */