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