]> git.sesse.net Git - ffmpeg/blob - libavfilter/src_movie.c
Merge commit 'b83e9efc53e5491716625aa31c69006b1119b280'
[ffmpeg] / libavfilter / src_movie.c
1 /*
2  * Copyright (c) 2010 Stefano Sabatini
3  * Copyright (c) 2008 Victor Paesa
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * movie video source
25  *
26  * @todo use direct rendering (no allocation of a new frame)
27  * @todo support a PTS correction mechanism
28  */
29
30 /* #define DEBUG */
31
32 #include <float.h>
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"
39 #include "audio.h"
40 #include "avcodec.h"
41 #include "avfilter.h"
42 #include "formats.h"
43 #include "internal.h"
44 #include "video.h"
45
46 typedef struct {
47     AVStream *st;
48     int done;
49 } MovieStream;
50
51 typedef struct {
52     /* common A/V fields */
53     const AVClass *class;
54     int64_t seek_point;   ///< seekpoint in microseconds
55     double seek_point_d;
56     char *format_name;
57     char *file_name;
58     char *stream_specs; /**< user-provided list of streams, separated by + */
59     int stream_index; /**< for compatibility */
60     int loop_count;
61
62     AVFormatContext *format_ctx;
63     int eof;
64     AVPacket pkt, pkt0;
65     AVFrame *frame;   ///< video frame to store the decoded images in
66
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 */
70 } MovieContext;
71
72 #define OFFSET(x) offsetof(MovieContext, x)
73 #define F AV_OPT_FLAG_FILTERING_PARAM
74
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 },
85 {NULL},
86 };
87
88 static int movie_config_output_props(AVFilterLink *outlink);
89 static int movie_request_frame(AVFilterLink *outlink);
90
91 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
92 {
93     int i, ret, already = 0, stream_id = -1;
94     char type_char, dummy;
95     AVStream *found = NULL;
96     enum AVMediaType type;
97
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);
102         if (ret < 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);
105             return NULL;
106         }
107         return avf->streams[ret];
108     }
109     for (i = 0; i < avf->nb_streams; i++) {
110         ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
111         if (ret < 0) {
112             av_log(log, AV_LOG_ERROR,
113                    "Invalid stream specifier \"%s\"\n", spec);
114             return NULL;
115         }
116         if (!ret)
117             continue;
118         if (avf->streams[i]->discard != AVDISCARD_ALL) {
119             already++;
120             continue;
121         }
122         if (found) {
123             av_log(log, AV_LOG_WARNING,
124                    "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
125             break;
126         }
127         found = avf->streams[i];
128     }
129     if (!found) {
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");
133         return NULL;
134     }
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));
140         return NULL;
141     }
142     return found;
143 }
144
145 static int open_stream(void *log, MovieStream *st)
146 {
147     AVCodec *codec;
148     int ret;
149
150     codec = avcodec_find_decoder(st->st->codec->codec_id);
151     if (!codec) {
152         av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
153         return AVERROR(EINVAL);
154     }
155
156     st->st->codec->refcounted_frames = 1;
157
158     if ((ret = avcodec_open2(st->st->codec, codec, NULL)) < 0) {
159         av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
160         return ret;
161     }
162
163     return 0;
164 }
165
166 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
167 {
168     AVCodecContext *dec_ctx = st->st->codec;
169     char buf[256];
170     int64_t chl = av_get_default_channel_layout(dec_ctx->channels);
171
172     if (!chl) {
173         av_log(log_ctx, AV_LOG_ERROR,
174                "Channel layout is not set in stream %d, and could not "
175                "be guessed from the number of channels (%d)\n",
176                st_index, dec_ctx->channels);
177         return AVERROR(EINVAL);
178     }
179
180     av_get_channel_layout_string(buf, sizeof(buf), dec_ctx->channels, chl);
181     av_log(log_ctx, AV_LOG_WARNING,
182            "Channel layout is not set in output stream %d, "
183            "guessed channel layout is '%s'\n",
184            st_index, buf);
185     dec_ctx->channel_layout = chl;
186     return 0;
187 }
188
189 static av_cold int movie_common_init(AVFilterContext *ctx, const char *args, const AVClass *class)
190 {
191     MovieContext *movie = ctx->priv;
192     AVInputFormat *iformat = NULL;
193     int64_t timestamp;
194     int nb_streams, ret, i;
195     char default_streams[16], *stream_specs, *spec, *cursor;
196     char name[16];
197     AVStream *st;
198
199     movie->class = class;
200     av_opt_set_defaults(movie);
201
202     if (args) {
203         movie->file_name = av_get_token(&args, ":");
204         if (!movie->file_name)
205             return AVERROR(ENOMEM);
206     }
207     if (!args || !*movie->file_name) {
208         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
209         return AVERROR(EINVAL);
210     }
211
212     if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0)
213         return ret;
214
215     movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
216
217     stream_specs = movie->stream_specs;
218     if (!stream_specs) {
219         snprintf(default_streams, sizeof(default_streams), "d%c%d",
220                  !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
221                  movie->stream_index);
222         stream_specs = default_streams;
223     }
224     for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)
225         if (*cursor == '+')
226             nb_streams++;
227
228     if (movie->loop_count != 1 && nb_streams != 1) {
229         av_log(ctx, AV_LOG_ERROR,
230                "Loop with several streams is currently unsupported\n");
231         return AVERROR_PATCHWELCOME;
232     }
233
234     av_register_all();
235
236     // Try to find the movie format (container)
237     iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
238
239     movie->format_ctx = NULL;
240     if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
241         av_log(ctx, AV_LOG_ERROR,
242                "Failed to avformat_open_input '%s'\n", movie->file_name);
243         return ret;
244     }
245     if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
246         av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
247
248     // if seeking requested, we execute it
249     if (movie->seek_point > 0) {
250         timestamp = movie->seek_point;
251         // add the stream start time, should it exist
252         if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
253             if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
254                 av_log(ctx, AV_LOG_ERROR,
255                        "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
256                        movie->file_name, movie->format_ctx->start_time, movie->seek_point);
257                 return AVERROR(EINVAL);
258             }
259             timestamp += movie->format_ctx->start_time;
260         }
261         if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
262             av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
263                    movie->file_name, timestamp);
264             return ret;
265         }
266     }
267
268     for (i = 0; i < movie->format_ctx->nb_streams; i++)
269         movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
270
271     movie->st = av_calloc(nb_streams, sizeof(*movie->st));
272     if (!movie->st)
273         return AVERROR(ENOMEM);
274
275     for (i = 0; i < nb_streams; i++) {
276         spec = av_strtok(stream_specs, "+", &cursor);
277         if (!spec)
278             return AVERROR_BUG;
279         stream_specs = NULL; /* for next strtok */
280         st = find_stream(ctx, movie->format_ctx, spec);
281         if (!st)
282             return AVERROR(EINVAL);
283         st->discard = AVDISCARD_DEFAULT;
284         movie->st[i].st = st;
285         movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
286     }
287     if (av_strtok(NULL, "+", &cursor))
288         return AVERROR_BUG;
289
290     movie->out_index = av_calloc(movie->max_stream_index + 1,
291                                  sizeof(*movie->out_index));
292     if (!movie->out_index)
293         return AVERROR(ENOMEM);
294     for (i = 0; i <= movie->max_stream_index; i++)
295         movie->out_index[i] = -1;
296     for (i = 0; i < nb_streams; i++)
297         movie->out_index[movie->st[i].st->index] = i;
298
299     for (i = 0; i < nb_streams; i++) {
300         AVFilterPad pad = { 0 };
301         snprintf(name, sizeof(name), "out%d", i);
302         pad.type          = movie->st[i].st->codec->codec_type;
303         pad.name          = av_strdup(name);
304         pad.config_props  = movie_config_output_props;
305         pad.request_frame = movie_request_frame;
306         ff_insert_outpad(ctx, i, &pad);
307         ret = open_stream(ctx, &movie->st[i]);
308         if (ret < 0)
309             return ret;
310         if ( movie->st[i].st->codec->codec->type == AVMEDIA_TYPE_AUDIO &&
311             !movie->st[i].st->codec->channel_layout) {
312             ret = guess_channel_layout(&movie->st[i], i, ctx);
313             if (ret < 0)
314                 return ret;
315         }
316     }
317
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);
321
322     return 0;
323 }
324
325 static av_cold void movie_uninit(AVFilterContext *ctx)
326 {
327     MovieContext *movie = ctx->priv;
328     int i;
329
330     for (i = 0; i < ctx->nb_outputs; i++) {
331         av_freep(&ctx->output_pads[i].name);
332         if (movie->st[i].st)
333             avcodec_close(movie->st[i].st->codec);
334     }
335     av_opt_free(movie);
336     av_freep(&movie->file_name);
337     av_freep(&movie->st);
338     av_freep(&movie->out_index);
339     av_frame_free(&movie->frame);
340     if (movie->format_ctx)
341         avformat_close_input(&movie->format_ctx);
342 }
343
344 static int movie_query_formats(AVFilterContext *ctx)
345 {
346     MovieContext *movie = ctx->priv;
347     int list[] = { 0, -1 };
348     int64_t list64[] = { 0, -1 };
349     int i;
350
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];
355
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);
360             break;
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);
369             break;
370         }
371     }
372
373     return 0;
374 }
375
376 static int movie_config_output_props(AVFilterLink *outlink)
377 {
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;
383
384     outlink->time_base = st->st->time_base;
385
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;
391         break;
392     case AVMEDIA_TYPE_AUDIO:
393         break;
394     }
395
396     return 0;
397 }
398
399 static char *describe_frame_to_str(char *dst, size_t dst_size,
400                                     AVFrame *frame,
401                                     AVFilterLink *link)
402 {
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);
411                  break;
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),
416                  frame->nb_samples);
417                  break;
418     default:
419         snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(frame->type));
420         break;
421     }
422     return dst;
423 }
424
425 #define describe_frameref(f, link) \
426     describe_frame_to_str((char[1024]){0}, 1024, f, link)
427
428 static int rewind_file(AVFilterContext *ctx)
429 {
430     MovieContext *movie = ctx->priv;
431     int64_t timestamp = movie->seek_point;
432     int ret, i;
433
434     if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
435         timestamp += movie->format_ctx->start_time;
436     ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
437     if (ret < 0) {
438         av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
439         movie->loop_count = 1; /* do not try again */
440         return ret;
441     }
442
443     for (i = 0; i < ctx->nb_outputs; i++) {
444         avcodec_flush_buffers(movie->st[i].st->codec);
445         movie->st[i].done = 0;
446     }
447     movie->eof = 0;
448     return 0;
449 }
450
451 /**
452  * Try to push a frame to the requested output.
453  *
454  * @param ctx     filter context
455  * @param out_id  number of output where a frame is wanted;
456  *                if the frame is read from file, used to set the return value;
457  *                if the codec is being flushed, flush the corresponding stream
458  * @return  1 if a frame was pushed on the requested output,
459  *          0 if another attempt is possible,
460  *          <0 AVERROR code
461  */
462 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
463 {
464     MovieContext *movie = ctx->priv;
465     AVPacket *pkt = &movie->pkt;
466     MovieStream *st;
467     int ret, got_frame = 0, pkt_out_id;
468     AVFilterLink *outlink;
469
470     if (!pkt->size) {
471         if (movie->eof) {
472             if (movie->st[out_id].done) {
473                 if (movie->loop_count != 1) {
474                     ret = rewind_file(ctx);
475                     if (ret < 0)
476                         return ret;
477                     movie->loop_count -= movie->loop_count > 1;
478                     av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
479                     return 0; /* retry */
480                 }
481                 return AVERROR_EOF;
482             }
483             pkt->stream_index = movie->st[out_id].st->index;
484             /* packet is already ready for flushing */
485         } else {
486             ret = av_read_frame(movie->format_ctx, &movie->pkt0);
487             if (ret < 0) {
488                 av_init_packet(&movie->pkt0); /* ready for flushing */
489                 *pkt = movie->pkt0;
490                 if (ret == AVERROR_EOF) {
491                     movie->eof = 1;
492                     return 0; /* start flushing */
493                 }
494                 return ret;
495             }
496             *pkt = movie->pkt0;
497         }
498     }
499
500     pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
501                  movie->out_index[pkt->stream_index];
502     if (pkt_out_id < 0) {
503         av_free_packet(&movie->pkt0);
504         pkt->size = 0; /* ready for next run */
505         pkt->data = NULL;
506         return 0;
507     }
508     st = &movie->st[pkt_out_id];
509     outlink = ctx->outputs[pkt_out_id];
510
511     movie->frame = av_frame_alloc();
512     if (!movie->frame)
513         return AVERROR(ENOMEM);
514
515     switch (st->st->codec->codec_type) {
516     case AVMEDIA_TYPE_VIDEO:
517         ret = avcodec_decode_video2(st->st->codec, movie->frame, &got_frame, pkt);
518         break;
519     case AVMEDIA_TYPE_AUDIO:
520         ret = avcodec_decode_audio4(st->st->codec, movie->frame, &got_frame, pkt);
521         break;
522     default:
523         ret = AVERROR(ENOSYS);
524         break;
525     }
526     if (ret < 0) {
527         av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
528         av_frame_free(&movie->frame);
529         return 0;
530     }
531     if (!ret)
532         ret = pkt->size;
533
534     pkt->data += ret;
535     pkt->size -= ret;
536     if (pkt->size <= 0) {
537         av_free_packet(&movie->pkt0);
538         pkt->size = 0; /* ready for next run */
539         pkt->data = NULL;
540     }
541     if (!got_frame) {
542         if (!ret)
543             st->done = 1;
544         av_frame_free(&movie->frame);
545         return 0;
546     }
547
548     av_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
549             describe_frameref(movie->frame, outlink));
550
551     movie->frame->pts = av_frame_get_best_effort_timestamp(movie->frame);
552     ret = ff_filter_frame(outlink, movie->frame);
553     movie->frame = NULL;
554
555     if (ret < 0)
556         return ret;
557     return pkt_out_id == out_id;
558 }
559
560 static int movie_request_frame(AVFilterLink *outlink)
561 {
562     AVFilterContext *ctx = outlink->src;
563     unsigned out_id = FF_OUTLINK_IDX(outlink);
564     int ret;
565
566     while (1) {
567         ret = movie_push_frame(ctx, out_id);
568         if (ret)
569             return FFMIN(ret, 0);
570     }
571 }
572
573 #if CONFIG_MOVIE_FILTER
574
575 AVFILTER_DEFINE_CLASS(movie);
576
577 static av_cold int movie_init(AVFilterContext *ctx, const char *args)
578 {
579     return movie_common_init(ctx, args, &movie_class);
580 }
581
582 AVFilter avfilter_avsrc_movie = {
583     .name          = "movie",
584     .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
585     .priv_size     = sizeof(MovieContext),
586     .init          = movie_init,
587     .uninit        = movie_uninit,
588     .query_formats = movie_query_formats,
589
590     .inputs    = NULL,
591     .outputs   = NULL,
592     .priv_class = &movie_class,
593 };
594
595 #endif  /* CONFIG_MOVIE_FILTER */
596
597 #if CONFIG_AMOVIE_FILTER
598
599 #define amovie_options movie_options
600 AVFILTER_DEFINE_CLASS(amovie);
601
602 static av_cold int amovie_init(AVFilterContext *ctx, const char *args)
603 {
604     return movie_common_init(ctx, args, &amovie_class);
605 }
606
607 AVFilter avfilter_avsrc_amovie = {
608     .name          = "amovie",
609     .description   = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
610     .priv_size     = sizeof(MovieContext),
611     .init          = amovie_init,
612     .uninit        = movie_uninit,
613     .query_formats = movie_query_formats,
614
615     .inputs     = NULL,
616     .outputs    = NULL,
617     .priv_class = &amovie_class,
618 };
619
620 #endif /* CONFIG_AMOVIE_FILTER */