]> git.sesse.net Git - ffmpeg/blob - libavfilter/src_movie.c
Merge remote-tracking branch 'qatar/master'
[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
74 static const AVOption movie_options[]= {
75 {"format_name",  "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
76 {"f",            "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
77 {"streams",      "set streams",             OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MAX, CHAR_MAX },
78 {"s",            "set streams",             OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MAX, CHAR_MAX },
79 {"si",           "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
80 {"stream_index", "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
81 {"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
82 {"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
83 {"loop",         "set loop count",          OFFSET(loop_count),   AV_OPT_TYPE_INT,    {.dbl =  1},  0,        INT_MAX  },
84 {NULL},
85 };
86
87 AVFILTER_DEFINE_CLASS(movie);
88
89 static int movie_config_output_props(AVFilterLink *outlink);
90 static int movie_request_frame(AVFilterLink *outlink);
91
92 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
93 {
94     int i, ret, already = 0, stream_id = -1;
95     char type_char, dummy;
96     AVStream *found = NULL;
97     enum AVMediaType type;
98
99     ret = sscanf(spec, "d%[av]%d%c", &type_char, &stream_id, &dummy);
100     if (ret >= 1 && ret <= 2) {
101         type = type_char == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
102         ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
103         if (ret < 0) {
104             av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
105                    av_get_media_type_string(type), stream_id);
106             return NULL;
107         }
108         return avf->streams[ret];
109     }
110     for (i = 0; i < avf->nb_streams; i++) {
111         ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
112         if (ret < 0) {
113             av_log(log, AV_LOG_ERROR,
114                    "Invalid stream specifier \"%s\"\n", spec);
115             return NULL;
116         }
117         if (!ret)
118             continue;
119         if (avf->streams[i]->discard != AVDISCARD_ALL) {
120             already++;
121             continue;
122         }
123         if (found) {
124             av_log(log, AV_LOG_WARNING,
125                    "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
126             break;
127         }
128         found = avf->streams[i];
129     }
130     if (!found) {
131         av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
132                already ? "matched only already used streams" :
133                          "did not match any stream");
134         return NULL;
135     }
136     if (found->codec->codec_type != AVMEDIA_TYPE_VIDEO &&
137         found->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
138         av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
139                "currently unsupported by libavfilter\n", spec,
140                av_get_media_type_string(found->codec->codec_type));
141         return NULL;
142     }
143     return found;
144 }
145
146 static int open_stream(void *log, MovieStream *st)
147 {
148     AVCodec *codec;
149     int ret;
150
151     codec = avcodec_find_decoder(st->st->codec->codec_id);
152     if (!codec) {
153         av_log(log, AV_LOG_ERROR, "Failed to find any codec\n");
154         return AVERROR(EINVAL);
155     }
156
157     if ((ret = avcodec_open2(st->st->codec, codec, NULL)) < 0) {
158         av_log(log, AV_LOG_ERROR, "Failed to open codec\n");
159         return ret;
160     }
161
162     return 0;
163 }
164
165 static av_cold int movie_init(AVFilterContext *ctx, const char *args)
166 {
167     MovieContext *movie = ctx->priv;
168     AVInputFormat *iformat = NULL;
169     int64_t timestamp;
170     int nb_streams, ret, i;
171     char default_streams[16], *stream_specs, *spec, *cursor;
172     char name[16];
173     AVStream *st;
174
175     movie->class = &movie_class;
176     av_opt_set_defaults(movie);
177
178     if (args)
179         movie->file_name = av_get_token(&args, ":");
180     if (!movie->file_name || !*movie->file_name) {
181         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
182         return AVERROR(EINVAL);
183     }
184
185     if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0) {
186         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
187         return ret;
188     }
189
190     movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
191
192     stream_specs = movie->stream_specs;
193     if (!stream_specs) {
194         snprintf(default_streams, sizeof(default_streams), "d%c%d",
195                  !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
196                  movie->stream_index);
197         stream_specs = default_streams;
198     }
199     for (cursor = stream_specs, nb_streams = 1; *cursor; cursor++)
200         if (*cursor == '+')
201             nb_streams++;
202
203     if (movie->loop_count != 1 && nb_streams != 1) {
204         av_log(ctx, AV_LOG_ERROR,
205                "Loop with several streams is currently unsupported\n");
206         return AVERROR_PATCHWELCOME;
207     }
208
209     av_register_all();
210
211     // Try to find the movie format (container)
212     iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
213
214     movie->format_ctx = NULL;
215     if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
216         av_log(ctx, AV_LOG_ERROR,
217                "Failed to avformat_open_input '%s'\n", movie->file_name);
218         return ret;
219     }
220     if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
221         av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
222
223     // if seeking requested, we execute it
224     if (movie->seek_point > 0) {
225         timestamp = movie->seek_point;
226         // add the stream start time, should it exist
227         if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
228             if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
229                 av_log(ctx, AV_LOG_ERROR,
230                        "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
231                        movie->file_name, movie->format_ctx->start_time, movie->seek_point);
232                 return AVERROR(EINVAL);
233             }
234             timestamp += movie->format_ctx->start_time;
235         }
236         if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
237             av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
238                    movie->file_name, timestamp);
239             return ret;
240         }
241     }
242
243     for (i = 0; i < movie->format_ctx->nb_streams; i++)
244         movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
245
246     movie->st = av_calloc(nb_streams, sizeof(*movie->st));
247     if (!movie->st)
248         return AVERROR(ENOMEM);
249
250     for (i = 0; i < nb_streams; i++) {
251         spec = av_strtok(stream_specs, "+", &cursor);
252         if (!spec)
253             return AVERROR_BUG;
254         stream_specs = NULL; /* for next strtok */
255         st = find_stream(ctx, movie->format_ctx, spec);
256         if (!st)
257             return AVERROR(EINVAL);
258         st->discard = AVDISCARD_DEFAULT;
259         movie->st[i].st = st;
260         movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
261     }
262     if (av_strtok(NULL, "+", &cursor))
263         return AVERROR_BUG;
264
265     movie->out_index = av_calloc(movie->max_stream_index + 1,
266                                  sizeof(*movie->out_index));
267     if (!movie->out_index)
268         return AVERROR(ENOMEM);
269     for (i = 0; i <= movie->max_stream_index; i++)
270         movie->out_index[i] = -1;
271     for (i = 0; i < nb_streams; i++)
272         movie->out_index[movie->st[i].st->index] = i;
273
274     for (i = 0; i < nb_streams; i++) {
275         AVFilterPad pad = { 0 };
276         snprintf(name, sizeof(name), "out%d", i);
277         pad.type          = movie->st[i].st->codec->codec_type;
278         pad.name          = av_strdup(name);
279         pad.config_props  = movie_config_output_props;
280         pad.request_frame = movie_request_frame;
281         ff_insert_outpad(ctx, i, &pad);
282         ret = open_stream(ctx, &movie->st[i]);
283         if (ret < 0)
284             return ret;
285     }
286
287     if (!(movie->frame = avcodec_alloc_frame()) ) {
288         av_log(log, AV_LOG_ERROR, "Failed to alloc frame\n");
289         return AVERROR(ENOMEM);
290     }
291
292     av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
293            movie->seek_point, movie->format_name, movie->file_name,
294            movie->stream_index);
295
296     return 0;
297 }
298
299 static av_cold void movie_uninit(AVFilterContext *ctx)
300 {
301     MovieContext *movie = ctx->priv;
302     int i;
303
304     for (i = 0; i < ctx->nb_outputs; i++) {
305         av_freep(&ctx->output_pads[i].name);
306         if (movie->st[i].st)
307             avcodec_close(movie->st[i].st->codec);
308     }
309     av_opt_free(movie);
310     av_freep(&movie->file_name);
311     av_freep(&movie->st);
312     av_freep(&movie->out_index);
313     av_freep(&movie->frame);
314     if (movie->format_ctx)
315         avformat_close_input(&movie->format_ctx);
316 }
317
318 static int movie_query_formats(AVFilterContext *ctx)
319 {
320     MovieContext *movie = ctx->priv;
321     int list[] = { 0, -1 };
322     int64_t list64[] = { 0, -1 };
323     int i;
324
325     for (i = 0; i < ctx->nb_outputs; i++) {
326         MovieStream *st = &movie->st[i];
327         AVCodecContext *c = st->st->codec;
328         AVFilterLink *outlink = ctx->outputs[i];
329
330         switch (c->codec_type) {
331         case AVMEDIA_TYPE_VIDEO:
332             list[0] = c->pix_fmt;
333             ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
334             break;
335         case AVMEDIA_TYPE_AUDIO:
336             list[0] = c->sample_fmt;
337             ff_formats_ref(ff_make_format_list(list), &outlink->in_formats);
338             list[0] = c->sample_rate;
339             ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates);
340             list64[0] = c->channel_layout ? c->channel_layout :
341                         av_get_default_channel_layout(c->channels);
342             ff_channel_layouts_ref(avfilter_make_format64_list(list64),
343                                    &outlink->in_channel_layouts);
344             break;
345         }
346     }
347
348     return 0;
349 }
350
351 static int movie_config_output_props(AVFilterLink *outlink)
352 {
353     AVFilterContext *ctx = outlink->src;
354     MovieContext *movie  = ctx->priv;
355     unsigned out_id = FF_OUTLINK_IDX(outlink);
356     MovieStream *st = &movie->st[out_id];
357     AVCodecContext *c = st->st->codec;
358
359     outlink->time_base = st->st->time_base;
360
361     switch (c->codec_type) {
362     case AVMEDIA_TYPE_VIDEO:
363         outlink->w          = c->width;
364         outlink->h          = c->height;
365         outlink->frame_rate = st->st->r_frame_rate;
366         break;
367     case AVMEDIA_TYPE_AUDIO:
368         break;
369     }
370
371     return 0;
372 }
373
374 static AVFilterBufferRef *frame_to_buf(enum AVMediaType type, AVFrame *frame,
375                                        AVFilterLink *outlink)
376 {
377     AVFilterBufferRef *buf, *copy;
378
379     buf = avfilter_get_buffer_ref_from_frame(type, frame,
380                                              AV_PERM_WRITE |
381                                              AV_PERM_PRESERVE |
382                                              AV_PERM_REUSE2);
383     if (!buf)
384         return NULL;
385     buf->pts = av_frame_get_best_effort_timestamp(frame);
386     copy = ff_copy_buffer_ref(outlink, buf);
387     if (!copy)
388         return NULL;
389     buf->buf->data[0] = NULL; /* it belongs to the frame */
390     avfilter_unref_buffer(buf);
391     return copy;
392 }
393
394 static char *describe_bufref_to_str(char *dst, size_t dst_size,
395                                     AVFilterBufferRef *buf,
396                                     AVFilterLink *link)
397 {
398     switch (buf->type) {
399     case AVMEDIA_TYPE_VIDEO:
400         snprintf(dst, dst_size,
401                  "video pts:%s time:%s pos:%"PRId64" size:%dx%d aspect:%d/%d",
402                  av_ts2str(buf->pts), av_ts2timestr(buf->pts, &link->time_base),
403                  buf->pos, buf->video->w, buf->video->h,
404                  buf->video->sample_aspect_ratio.num,
405                  buf->video->sample_aspect_ratio.den);
406                  break;
407     case AVMEDIA_TYPE_AUDIO:
408         snprintf(dst, dst_size,
409                  "audio pts:%s time:%s pos:%"PRId64" samples:%d",
410                  av_ts2str(buf->pts), av_ts2timestr(buf->pts, &link->time_base),
411                  buf->pos, buf->audio->nb_samples);
412                  break;
413     default:
414         snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(buf->type));
415         break;
416     }
417     return dst;
418 }
419
420 #define describe_bufref(buf, link) \
421     describe_bufref_to_str((char[1024]){0}, 1024, buf, link)
422
423 static int rewind_file(AVFilterContext *ctx)
424 {
425     MovieContext *movie = ctx->priv;
426     int64_t timestamp = movie->seek_point;
427     int ret, i;
428
429     if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
430         timestamp += movie->format_ctx->start_time;
431     ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
432     if (ret < 0) {
433         av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
434         movie->loop_count = 1; /* do not try again */
435         return ret;
436     }
437
438     for (i = 0; i < ctx->nb_outputs; i++) {
439         avcodec_flush_buffers(movie->st[i].st->codec);
440         movie->st[i].done = 0;
441     }
442     movie->eof = 0;
443     return 0;
444 }
445
446 /**
447  * Try to push a frame to the requested output.
448  *
449  * @return  1 if a frame was pushed on the requested output,
450  *          0 if another attempt is possible,
451  *          <0 AVERROR code
452  */
453 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
454 {
455     MovieContext *movie = ctx->priv;
456     AVPacket *pkt = &movie->pkt;
457     MovieStream *st;
458     int ret, got_frame = 0, pkt_out_id;
459     AVFilterLink *outlink;
460     AVFilterBufferRef *buf;
461
462     if (!pkt->size) {
463         if (movie->eof) {
464             if (movie->st[out_id].done) {
465                 if (movie->loop_count != 1) {
466                     ret = rewind_file(ctx);
467                     if (ret < 0)
468                         return ret;
469                     movie->loop_count -= movie->loop_count > 1;
470                     av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
471                     return 0; /* retry */
472                 }
473                 return AVERROR_EOF;
474             }
475             /* packet is already ready for flushing */
476         } else {
477             ret = av_read_frame(movie->format_ctx, &movie->pkt0);
478             if (ret < 0) {
479                 av_init_packet(&movie->pkt0); /* ready for flushing */
480                 *pkt = movie->pkt0;
481                 if (ret == AVERROR_EOF) {
482                     movie->eof = 1;
483                     return 0; /* start flushing */
484                 }
485                 return ret;
486             }
487             *pkt = movie->pkt0;
488         }
489     }
490
491     pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
492                  movie->out_index[pkt->stream_index];
493     if (pkt_out_id < 0) {
494         av_free_packet(&movie->pkt0);
495         pkt->size = 0; /* ready for next run */
496         pkt->data = NULL;
497         return 0;
498     }
499     st = &movie->st[pkt_out_id];
500     outlink = ctx->outputs[pkt_out_id];
501
502     switch (st->st->codec->codec_type) {
503     case AVMEDIA_TYPE_VIDEO:
504         ret = avcodec_decode_video2(st->st->codec, movie->frame, &got_frame, pkt);
505         break;
506     case AVMEDIA_TYPE_AUDIO:
507         ret = avcodec_decode_audio4(st->st->codec, movie->frame, &got_frame, pkt);
508         break;
509     default:
510         ret = AVERROR(ENOSYS);
511         break;
512     }
513     if (ret < 0) {
514         av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
515         return 0;
516     }
517     if (!ret)
518         ret = pkt->size;
519
520     pkt->data += ret;
521     pkt->size -= ret;
522     if (pkt->size <= 0) {
523         av_free_packet(&movie->pkt0);
524         pkt->size = 0; /* ready for next run */
525         pkt->data = NULL;
526     }
527     if (!got_frame) {
528         if (!ret)
529             st->done = 1;
530         return 0;
531     }
532
533     buf = frame_to_buf(st->st->codec->codec_type, movie->frame, outlink);
534     if (!buf)
535         return AVERROR(ENOMEM);
536     av_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
537             describe_bufref(buf, outlink));
538     switch (st->st->codec->codec_type) {
539     case AVMEDIA_TYPE_VIDEO:
540         if (!movie->frame->sample_aspect_ratio.num)
541             buf->video->sample_aspect_ratio = st->st->sample_aspect_ratio;
542         ff_start_frame(outlink, buf);
543         ff_draw_slice(outlink, 0, outlink->h, 1);
544         ff_end_frame(outlink);
545         break;
546     case AVMEDIA_TYPE_AUDIO:
547         ff_filter_samples(outlink, buf);
548         break;
549     }
550
551     return pkt_out_id == out_id;
552 }
553
554 static int movie_request_frame(AVFilterLink *outlink)
555 {
556     AVFilterContext *ctx = outlink->src;
557     unsigned out_id = FF_OUTLINK_IDX(outlink);
558     int ret;
559
560     while (1) {
561         ret = movie_push_frame(ctx, out_id);
562         if (ret)
563             return FFMIN(ret, 0);
564     }
565 }
566
567 #if CONFIG_MOVIE_FILTER
568
569 AVFilter avfilter_avsrc_movie = {
570     .name          = "movie",
571     .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
572     .priv_size     = sizeof(MovieContext),
573     .init          = movie_init,
574     .uninit        = movie_uninit,
575     .query_formats = movie_query_formats,
576
577     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
578     .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
579 };
580
581 #endif  /* CONFIG_MOVIE_FILTER */
582
583 #if CONFIG_AMOVIE_FILTER
584
585 AVFilter avfilter_avsrc_amovie = {
586     .name          = "amovie",
587     .description   = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
588     .priv_size     = sizeof(MovieContext),
589     .init          = movie_init,
590     .uninit        = movie_uninit,
591     .query_formats = movie_query_formats,
592
593     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
594     .outputs   = (const AVFilterPad[]) {{ .name = NULL }},
595 };
596
597 #endif /* CONFIG_AMOVIE_FILTER */