]> git.sesse.net Git - ffmpeg/blob - libavfilter/src_movie.c
examples/filtering_audio: do not stop on decode error.
[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     int loop_count;
50
51     AVFormatContext *format_ctx;
52     AVCodecContext *codec_ctx;
53     int is_done;
54     AVFrame *frame;   ///< video frame to store the decoded images in
55
56     /* video-only fields */
57     int w, h;
58     AVFilterBufferRef *picref;
59
60     /* audio-only fields */
61     int bps;            ///< bytes per sample
62     AVPacket pkt, pkt0;
63     AVFilterBufferRef *samplesref;
64 } MovieContext;
65
66 #define OFFSET(x) offsetof(MovieContext, x)
67
68 static const AVOption movie_options[]= {
69 {"format_name",  "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
70 {"f",            "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING, {.str =  0},  CHAR_MIN, CHAR_MAX },
71 {"stream_index", "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
72 {"si",           "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    {.dbl = -1},  -1,       INT_MAX  },
73 {"seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
74 {"sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl =  0},  0,        (INT64_MAX-1) / 1000000 },
75 {"loop",         "set loop count",          OFFSET(loop_count),   AV_OPT_TYPE_INT,    {.dbl =  1},  0,        INT_MAX  },
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     if (!(movie->frame = avcodec_alloc_frame()) ) {
180         av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
181         return AVERROR(ENOMEM);
182     }
183
184     return 0;
185 }
186
187 static av_cold void movie_common_uninit(AVFilterContext *ctx)
188 {
189     MovieContext *movie = ctx->priv;
190
191     av_free(movie->file_name);
192     av_free(movie->format_name);
193     if (movie->codec_ctx)
194         avcodec_close(movie->codec_ctx);
195     if (movie->format_ctx)
196         avformat_close_input(&movie->format_ctx);
197
198     avfilter_unref_buffer(movie->picref);
199     av_freep(&movie->frame);
200
201     avfilter_unref_buffer(movie->samplesref);
202 }
203
204 #if CONFIG_MOVIE_FILTER
205
206 static av_cold int movie_init(AVFilterContext *ctx, const char *args, void *opaque)
207 {
208     MovieContext *movie = ctx->priv;
209     int ret;
210
211     if ((ret = movie_common_init(ctx, args, opaque, AVMEDIA_TYPE_VIDEO)) < 0)
212         return ret;
213
214     movie->w = movie->codec_ctx->width;
215     movie->h = movie->codec_ctx->height;
216
217     return 0;
218 }
219
220 static int movie_query_formats(AVFilterContext *ctx)
221 {
222     MovieContext *movie = ctx->priv;
223     enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
224
225     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
226     return 0;
227 }
228
229 static int movie_config_output_props(AVFilterLink *outlink)
230 {
231     MovieContext *movie = outlink->src->priv;
232
233     outlink->w = movie->w;
234     outlink->h = movie->h;
235     outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
236
237     return 0;
238 }
239
240 static int movie_get_frame(AVFilterLink *outlink)
241 {
242     MovieContext *movie = outlink->src->priv;
243     AVPacket pkt;
244     int ret, frame_decoded;
245     AVStream *st = movie->format_ctx->streams[movie->stream_index];
246
247     if (movie->is_done == 1)
248         return 0;
249
250     while (1) {
251         ret = av_read_frame(movie->format_ctx, &pkt);
252         if (ret == AVERROR_EOF) {
253             int64_t timestamp;
254             if (movie->loop_count != 1) {
255                 timestamp = movie->seek_point;
256                 if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
257                     timestamp += movie->format_ctx->start_time;
258                 if (av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD) < 0) {
259                     movie->is_done = 1;
260                     break;
261                 } else if (movie->loop_count>1)
262                     movie->loop_count--;
263                 continue;
264             } else {
265                 movie->is_done = 1;
266                 break;
267             }
268         } else if (ret < 0)
269             break;
270
271         // Is this a packet from the video stream?
272         if (pkt.stream_index == movie->stream_index) {
273             avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
274
275             if (frame_decoded) {
276                 /* FIXME: avoid the memcpy */
277                 movie->picref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE | AV_PERM_PRESERVE |
278                                                           AV_PERM_REUSE2, outlink->w, outlink->h);
279                 av_image_copy(movie->picref->data, movie->picref->linesize,
280                               (void*)movie->frame->data,  movie->frame->linesize,
281                               movie->picref->format, outlink->w, outlink->h);
282                 avfilter_copy_frame_props(movie->picref, movie->frame);
283
284                 /* FIXME: use a PTS correction mechanism as that in
285                  * ffplay.c when some API will be available for that */
286                 /* use pkt_dts if pkt_pts is not available */
287                 movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?
288                     movie->frame->pkt_dts : movie->frame->pkt_pts;
289
290                 if (!movie->frame->sample_aspect_ratio.num)
291                     movie->picref->video->sample_aspect_ratio = st->sample_aspect_ratio;
292                 av_dlog(outlink->src,
293                         "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",
294                         movie->file_name, movie->picref->pts,
295                         (double)movie->picref->pts * av_q2d(st->time_base),
296                         movie->picref->pos,
297                         movie->picref->video->sample_aspect_ratio.num,
298                         movie->picref->video->sample_aspect_ratio.den);
299                 // We got it. Free the packet since we are returning
300                 av_free_packet(&pkt);
301
302                 return 0;
303             }
304         }
305         // Free the packet that was allocated by av_read_frame
306         av_free_packet(&pkt);
307     }
308
309     return ret;
310 }
311
312 static int movie_request_frame(AVFilterLink *outlink)
313 {
314     AVFilterBufferRef *outpicref;
315     MovieContext *movie = outlink->src->priv;
316     int ret;
317
318     if (movie->is_done)
319         return AVERROR_EOF;
320     if ((ret = movie_get_frame(outlink)) < 0)
321         return ret;
322
323     outpicref = avfilter_ref_buffer(movie->picref, ~0);
324     avfilter_start_frame(outlink, outpicref);
325     avfilter_draw_slice(outlink, 0, outlink->h, 1);
326     avfilter_end_frame(outlink);
327     avfilter_unref_buffer(movie->picref);
328     movie->picref = NULL;
329
330     return 0;
331 }
332
333 AVFilter avfilter_vsrc_movie = {
334     .name          = "movie",
335     .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
336     .priv_size     = sizeof(MovieContext),
337     .init          = movie_init,
338     .uninit        = movie_common_uninit,
339     .query_formats = movie_query_formats,
340
341     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
342     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
343                                     .type            = AVMEDIA_TYPE_VIDEO,
344                                     .request_frame   = movie_request_frame,
345                                     .config_props    = movie_config_output_props, },
346                                   { .name = NULL}},
347 };
348
349 #endif  /* CONFIG_MOVIE_FILTER */
350
351 #if CONFIG_AMOVIE_FILTER
352
353 static av_cold int amovie_init(AVFilterContext *ctx, const char *args, void *opaque)
354 {
355     MovieContext *movie = ctx->priv;
356     int ret;
357
358     if ((ret = movie_common_init(ctx, args, opaque, AVMEDIA_TYPE_AUDIO)) < 0)
359         return ret;
360
361     movie->bps = av_get_bytes_per_sample(movie->codec_ctx->sample_fmt);
362     return 0;
363 }
364
365 static int amovie_query_formats(AVFilterContext *ctx)
366 {
367     MovieContext *movie = ctx->priv;
368     AVCodecContext *c = movie->codec_ctx;
369
370     enum AVSampleFormat sample_fmts[] = { c->sample_fmt, -1 };
371     int packing_fmts[] = { AVFILTER_PACKED, -1 };
372     int64_t chlayouts[] = { c->channel_layout ? c->channel_layout :
373                             av_get_default_channel_layout(c->channels), -1 };
374
375     avfilter_set_common_sample_formats (ctx, avfilter_make_format_list(sample_fmts));
376     avfilter_set_common_packing_formats(ctx, avfilter_make_format_list(packing_fmts));
377     avfilter_set_common_channel_layouts(ctx, avfilter_make_format64_list(chlayouts));
378
379     return 0;
380 }
381
382 static int amovie_config_output_props(AVFilterLink *outlink)
383 {
384     MovieContext *movie = outlink->src->priv;
385     AVCodecContext *c = movie->codec_ctx;
386
387     outlink->sample_rate = c->sample_rate;
388     outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
389
390     return 0;
391 }
392
393 static int amovie_get_samples(AVFilterLink *outlink)
394 {
395     MovieContext *movie = outlink->src->priv;
396     AVPacket pkt;
397     int ret, got_frame = 0;
398
399     if (!movie->pkt.size && movie->is_done == 1)
400         return AVERROR_EOF;
401
402     /* check for another frame, in case the previous one was completely consumed */
403     if (!movie->pkt.size) {
404         while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
405             // Is this a packet from the selected stream?
406             if (pkt.stream_index != movie->stream_index) {
407                 av_free_packet(&pkt);
408                 continue;
409             } else {
410                 movie->pkt0 = movie->pkt = pkt;
411                 break;
412             }
413         }
414
415         if (ret == AVERROR_EOF) {
416             movie->is_done = 1;
417             return ret;
418         }
419     }
420
421     /* decode and update the movie pkt */
422     avcodec_get_frame_defaults(movie->frame);
423     ret = avcodec_decode_audio4(movie->codec_ctx, movie->frame, &got_frame, &movie->pkt);
424     if (ret < 0) {
425         movie->pkt.size = 0;
426         return ret;
427     }
428     movie->pkt.data += ret;
429     movie->pkt.size -= ret;
430
431     /* wrap the decoded data in a samplesref */
432     if (got_frame) {
433         int nb_samples = movie->frame->nb_samples;
434         int data_size =
435             av_samples_get_buffer_size(NULL, movie->codec_ctx->channels,
436                                        nb_samples, movie->codec_ctx->sample_fmt, 1);
437         if (data_size < 0)
438             return data_size;
439         movie->samplesref =
440             avfilter_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
441         memcpy(movie->samplesref->data[0], movie->frame->data[0], data_size);
442         movie->samplesref->pts = movie->pkt.pts;
443         movie->samplesref->pos = movie->pkt.pos;
444         movie->samplesref->audio->sample_rate = movie->codec_ctx->sample_rate;
445     }
446
447     // We got it. Free the packet since we are returning
448     if (movie->pkt.size <= 0)
449         av_free_packet(&movie->pkt0);
450
451     return 0;
452 }
453
454 static int amovie_request_frame(AVFilterLink *outlink)
455 {
456     MovieContext *movie = outlink->src->priv;
457     int ret;
458
459     if (movie->is_done)
460         return AVERROR_EOF;
461     do {
462         if ((ret = amovie_get_samples(outlink)) < 0)
463             return ret;
464     } while (!movie->samplesref);
465
466     avfilter_filter_samples(outlink, avfilter_ref_buffer(movie->samplesref, ~0));
467     avfilter_unref_buffer(movie->samplesref);
468     movie->samplesref = NULL;
469
470     return 0;
471 }
472
473 AVFilter avfilter_asrc_amovie = {
474     .name          = "amovie",
475     .description   = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
476     .priv_size     = sizeof(MovieContext),
477     .init          = amovie_init,
478     .uninit        = movie_common_uninit,
479     .query_formats = amovie_query_formats,
480
481     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
482     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
483                                     .type            = AVMEDIA_TYPE_AUDIO,
484                                     .request_frame   = amovie_request_frame,
485                                     .config_props    = amovie_config_output_props, },
486                                   { .name = NULL}},
487 };
488
489 #endif /* CONFIG_AMOVIE_FILTER */