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