]> 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  * @todo support more than one output stream
29  */
30
31 /* #define DEBUG */
32
33 #include <float.h>
34 #include "libavutil/avstring.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/imgutils.h"
37 #include "libavformat/avformat.h"
38 #include "audio.h"
39 #include "avcodec.h"
40 #include "avfilter.h"
41 #include "formats.h"
42 #include "video.h"
43
44 typedef struct {
45     /* common A/V fields */
46     const AVClass *class;
47     int64_t seek_point;   ///< seekpoint in microseconds
48     double seek_point_d;
49     char *format_name;
50     char *file_name;
51     int stream_index;
52     int loop_count;
53
54     AVFormatContext *format_ctx;
55     AVCodecContext *codec_ctx;
56     int is_done;
57     AVFrame *frame;   ///< video frame to store the decoded images in
58
59     /* video-only fields */
60     int w, h;
61     AVFilterBufferRef *picref;
62
63     /* audio-only fields */
64     int bps;            ///< bytes per sample
65     AVPacket pkt, pkt0;
66     AVFilterBufferRef *samplesref;
67 } MovieContext;
68
69 #define OFFSET(x) offsetof(MovieContext, x)
70
71 static const AVOption movie_options[]= {
72 {"format_name",  "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
73 {"f",            "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
74 {"stream_index", "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
75 {"si",           "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
76 {"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
77 {"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
78 {"loop",         "set loop count",          OFFSET(loop_count),   AV_OPT_TYPE_INT,    {.dbl =  1},  0,        INT_MAX  },
79 {NULL},
80 };
81
82 static const AVClass movie_class = {
83     "MovieContext",
84     av_default_item_name,
85     movie_options
86 };
87
88 static av_cold int movie_common_init(AVFilterContext *ctx, const char *args, void *opaque,
89                                      enum AVMediaType type)
90 {
91     MovieContext *movie = ctx->priv;
92     AVInputFormat *iformat = NULL;
93     AVCodec *codec;
94     int64_t timestamp;
95     int ret;
96
97     movie->class = &movie_class;
98     av_opt_set_defaults(movie);
99
100     if (args)
101         movie->file_name = av_get_token(&args, ":");
102     if (!movie->file_name || !*movie->file_name) {
103         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
104         return AVERROR(EINVAL);
105     }
106
107     if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0) {
108         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
109         return ret;
110     }
111
112     movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
113
114     av_register_all();
115
116     // Try to find the movie format (container)
117     iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
118
119     movie->format_ctx = NULL;
120     if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
121         av_log(ctx, AV_LOG_ERROR,
122                "Failed to avformat_open_input '%s'\n", movie->file_name);
123         return ret;
124     }
125     if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
126         av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
127
128     // if seeking requested, we execute it
129     if (movie->seek_point > 0) {
130         timestamp = movie->seek_point;
131         // add the stream start time, should it exist
132         if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
133             if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
134                 av_log(ctx, AV_LOG_ERROR,
135                        "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
136                        movie->file_name, movie->format_ctx->start_time, movie->seek_point);
137                 return AVERROR(EINVAL);
138             }
139             timestamp += movie->format_ctx->start_time;
140         }
141         if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
142             av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
143                    movie->file_name, timestamp);
144             return ret;
145         }
146     }
147
148     /* select the media stream */
149     if ((ret = av_find_best_stream(movie->format_ctx, type,
150                                    movie->stream_index, -1, NULL, 0)) < 0) {
151         av_log(ctx, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
152                av_get_media_type_string(type), movie->stream_index);
153         return ret;
154     }
155     movie->stream_index = ret;
156     movie->codec_ctx = movie->format_ctx->streams[movie->stream_index]->codec;
157
158     /*
159      * So now we've got a pointer to the so-called codec context for our video
160      * stream, but we still have to find the actual codec and open it.
161      */
162     codec = avcodec_find_decoder(movie->codec_ctx->codec_id);
163     if (!codec) {
164         av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
165         return AVERROR(EINVAL);
166     }
167
168     if ((ret = avcodec_open2(movie->codec_ctx, codec, NULL)) < 0) {
169         av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
170         return ret;
171     }
172
173     av_log(ctx, AV_LOG_INFO, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
174            movie->seek_point, movie->format_name, movie->file_name,
175            movie->stream_index);
176
177     if (!(movie->frame = avcodec_alloc_frame()) ) {
178         av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
179         return AVERROR(ENOMEM);
180     }
181
182     return 0;
183 }
184
185 static av_cold void movie_common_uninit(AVFilterContext *ctx)
186 {
187     MovieContext *movie = ctx->priv;
188
189     av_free(movie->file_name);
190     av_free(movie->format_name);
191     if (movie->codec_ctx)
192         avcodec_close(movie->codec_ctx);
193     if (movie->format_ctx)
194         avformat_close_input(&movie->format_ctx);
195
196     avfilter_unref_buffer(movie->picref);
197     av_freep(&movie->frame);
198
199     avfilter_unref_buffer(movie->samplesref);
200 }
201
202 #if CONFIG_MOVIE_FILTER
203
204 static av_cold int movie_init(AVFilterContext *ctx, const char *args, void *opaque)
205 {
206     MovieContext *movie = ctx->priv;
207     int ret;
208
209     if ((ret = movie_common_init(ctx, args, opaque, AVMEDIA_TYPE_VIDEO)) < 0)
210         return ret;
211
212     movie->w = movie->codec_ctx->width;
213     movie->h = movie->codec_ctx->height;
214
215     return 0;
216 }
217
218 static int movie_query_formats(AVFilterContext *ctx)
219 {
220     MovieContext *movie = ctx->priv;
221     enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
222
223     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
224     return 0;
225 }
226
227 static int movie_config_output_props(AVFilterLink *outlink)
228 {
229     MovieContext *movie = outlink->src->priv;
230
231     outlink->w = movie->w;
232     outlink->h = movie->h;
233     outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
234
235     return 0;
236 }
237
238 static int movie_get_frame(AVFilterLink *outlink)
239 {
240     MovieContext *movie = outlink->src->priv;
241     AVPacket pkt;
242     int ret, frame_decoded;
243     AVStream *st = movie->format_ctx->streams[movie->stream_index];
244
245     if (movie->is_done == 1)
246         return 0;
247
248     while (1) {
249         ret = av_read_frame(movie->format_ctx, &pkt);
250         if (ret == AVERROR_EOF) {
251             int64_t timestamp;
252             if (movie->loop_count != 1) {
253                 timestamp = movie->seek_point;
254                 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
255                     timestamp += movie->format_ctx->start_time;
256                 if (av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD) < 0) {
257                     movie->is_done = 1;
258                     break;
259                 } else if (movie->loop_count>1)
260                     movie->loop_count--;
261                 continue;
262             } else {
263                 movie->is_done = 1;
264                 break;
265             }
266         } else if (ret < 0)
267             break;
268
269         // Is this a packet from the video stream?
270         if (pkt.stream_index == movie->stream_index) {
271             avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
272
273             if (frame_decoded) {
274                 /* FIXME: avoid the memcpy */
275                 movie->picref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE | AV_PERM_PRESERVE |
276                                                           AV_PERM_REUSE2, outlink->w, outlink->h);
277                 av_image_copy(movie->picref->data, movie->picref->linesize,
278                               (void*)movie->frame->data,  movie->frame->linesize,
279                               movie->picref->format, outlink->w, outlink->h);
280                 avfilter_copy_frame_props(movie->picref, movie->frame);
281
282                 /* FIXME: use a PTS correction mechanism as that in
283                  * ffplay.c when some API will be available for that */
284                 /* use pkt_dts if pkt_pts is not available */
285                 movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?
286                     movie->frame->pkt_dts : movie->frame->pkt_pts;
287
288                 if (!movie->frame->sample_aspect_ratio.num)
289                     movie->picref->video->sample_aspect_ratio = st->sample_aspect_ratio;
290                 av_dlog(outlink->src,
291                         "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",
292                         movie->file_name, movie->picref->pts,
293                         (double)movie->picref->pts * av_q2d(st->time_base),
294                         movie->picref->pos,
295                         movie->picref->video->sample_aspect_ratio.num,
296                         movie->picref->video->sample_aspect_ratio.den);
297                 // We got it. Free the packet since we are returning
298                 av_free_packet(&pkt);
299
300                 return 0;
301             }
302         }
303         // Free the packet that was allocated by av_read_frame
304         av_free_packet(&pkt);
305     }
306
307     return ret;
308 }
309
310 static int movie_request_frame(AVFilterLink *outlink)
311 {
312     AVFilterBufferRef *outpicref;
313     MovieContext *movie = outlink->src->priv;
314     int ret;
315
316     if (movie->is_done)
317         return AVERROR_EOF;
318     if ((ret = movie_get_frame(outlink)) < 0)
319         return ret;
320
321     outpicref = avfilter_ref_buffer(movie->picref, ~0);
322     ff_start_frame(outlink, outpicref);
323     ff_draw_slice(outlink, 0, outlink->h, 1);
324     ff_end_frame(outlink);
325     avfilter_unref_buffer(movie->picref);
326     movie->picref = NULL;
327
328     return 0;
329 }
330
331 AVFilter avfilter_vsrc_movie = {
332     .name          = "movie",
333     .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
334     .priv_size     = sizeof(MovieContext),
335     .init          = movie_init,
336     .uninit        = movie_common_uninit,
337     .query_formats = movie_query_formats,
338
339     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
340     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
341                                     .type            = AVMEDIA_TYPE_VIDEO,
342                                     .request_frame   = movie_request_frame,
343                                     .config_props    = movie_config_output_props, },
344                                   { .name = NULL}},
345 };
346
347 #endif  /* CONFIG_MOVIE_FILTER */
348
349 #if CONFIG_AMOVIE_FILTER
350
351 static av_cold int amovie_init(AVFilterContext *ctx, const char *args, void *opaque)
352 {
353     MovieContext *movie = ctx->priv;
354     int ret;
355
356     if ((ret = movie_common_init(ctx, args, opaque, AVMEDIA_TYPE_AUDIO)) < 0)
357         return ret;
358
359     movie->bps = av_get_bytes_per_sample(movie->codec_ctx->sample_fmt);
360     return 0;
361 }
362
363 static int amovie_query_formats(AVFilterContext *ctx)
364 {
365     MovieContext *movie = ctx->priv;
366     AVCodecContext *c = movie->codec_ctx;
367
368     enum AVSampleFormat sample_fmts[] = { c->sample_fmt, -1 };
369     int sample_rates[] = { c->sample_rate, -1 };
370     int64_t chlayouts[] = { c->channel_layout ? c->channel_layout :
371                             av_get_default_channel_layout(c->channels), -1 };
372
373     avfilter_set_common_sample_formats (ctx, avfilter_make_format_list(sample_fmts));
374     ff_set_common_samplerates          (ctx, avfilter_make_format_list(sample_rates));
375     ff_set_common_channel_layouts(ctx, avfilter_make_format64_list(chlayouts));
376
377     return 0;
378 }
379
380 static int amovie_config_output_props(AVFilterLink *outlink)
381 {
382     MovieContext *movie = outlink->src->priv;
383     AVCodecContext *c = movie->codec_ctx;
384
385     outlink->sample_rate = c->sample_rate;
386     outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
387
388     return 0;
389 }
390
391 static int amovie_get_samples(AVFilterLink *outlink)
392 {
393     MovieContext *movie = outlink->src->priv;
394     AVPacket pkt;
395     int ret, got_frame = 0;
396
397     if (!movie->pkt.size && movie->is_done == 1)
398         return AVERROR_EOF;
399
400     /* check for another frame, in case the previous one was completely consumed */
401     if (!movie->pkt.size) {
402         while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
403             // Is this a packet from the selected stream?
404             if (pkt.stream_index != movie->stream_index) {
405                 av_free_packet(&pkt);
406                 continue;
407             } else {
408                 movie->pkt0 = movie->pkt = pkt;
409                 break;
410             }
411         }
412
413         if (ret == AVERROR_EOF) {
414             movie->is_done = 1;
415             return ret;
416         }
417     }
418
419     /* decode and update the movie pkt */
420     avcodec_get_frame_defaults(movie->frame);
421     ret = avcodec_decode_audio4(movie->codec_ctx, movie->frame, &got_frame, &movie->pkt);
422     if (ret < 0) {
423         movie->pkt.size = 0;
424         return ret;
425     }
426     movie->pkt.data += ret;
427     movie->pkt.size -= ret;
428
429     /* wrap the decoded data in a samplesref */
430     if (got_frame) {
431         int nb_samples = movie->frame->nb_samples;
432         int data_size =
433             av_samples_get_buffer_size(NULL, movie->codec_ctx->channels,
434                                        nb_samples, movie->codec_ctx->sample_fmt, 1);
435         if (data_size < 0)
436             return data_size;
437         movie->samplesref =
438             ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
439         memcpy(movie->samplesref->data[0], movie->frame->data[0], data_size);
440         movie->samplesref->pts = movie->pkt.pts;
441         movie->samplesref->pos = movie->pkt.pos;
442         movie->samplesref->audio->sample_rate = movie->codec_ctx->sample_rate;
443     }
444
445     // We got it. Free the packet since we are returning
446     if (movie->pkt.size <= 0)
447         av_free_packet(&movie->pkt0);
448
449     return 0;
450 }
451
452 static int amovie_request_frame(AVFilterLink *outlink)
453 {
454     MovieContext *movie = outlink->src->priv;
455     int ret;
456
457     if (movie->is_done)
458         return AVERROR_EOF;
459     do {
460         if ((ret = amovie_get_samples(outlink)) < 0)
461             return ret;
462     } while (!movie->samplesref);
463
464     ff_filter_samples(outlink, avfilter_ref_buffer(movie->samplesref, ~0));
465     avfilter_unref_buffer(movie->samplesref);
466     movie->samplesref = NULL;
467
468     return 0;
469 }
470
471 AVFilter avfilter_asrc_amovie = {
472     .name          = "amovie",
473     .description   = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
474     .priv_size     = sizeof(MovieContext),
475     .init          = amovie_init,
476     .uninit        = movie_common_uninit,
477     .query_formats = amovie_query_formats,
478
479     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
480     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
481                                     .type            = AVMEDIA_TYPE_AUDIO,
482                                     .request_frame   = amovie_request_frame,
483                                     .config_props    = amovie_config_output_props, },
484                                   { .name = NULL}},
485 };
486
487 #endif /* CONFIG_AMOVIE_FILTER */