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