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