]> git.sesse.net Git - ffmpeg/blob - libavfilter/src_movie.c
fc26be15b607f9390a37644b3848169786fdb8a9
[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  */
29
30 #include <float.h>
31 #include <stdint.h>
32
33 #include "libavutil/attributes.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/internal.h"
39 #include "libavutil/timestamp.h"
40
41 #include "libavcodec/avcodec.h"
42
43 #include "libavformat/avformat.h"
44
45 #include "audio.h"
46 #include "avfilter.h"
47 #include "filters.h"
48 #include "formats.h"
49 #include "internal.h"
50 #include "video.h"
51
52 typedef struct MovieStream {
53     AVStream *st;
54     AVCodecContext *codec_ctx;
55     int done;
56     int64_t discontinuity_threshold;
57     int64_t last_pts;
58 } MovieStream;
59
60 typedef struct MovieContext {
61     /* common A/V fields */
62     const AVClass *class;
63     int64_t seek_point;   ///< seekpoint in microseconds
64     double seek_point_d;
65     char *format_name;
66     char *file_name;
67     char *stream_specs; /**< user-provided list of streams, separated by + */
68     int stream_index; /**< for compatibility */
69     int loop_count;
70     int64_t discontinuity_threshold;
71     int64_t ts_offset;
72
73     AVFormatContext *format_ctx;
74     int eof;
75     AVPacket pkt, pkt0;
76
77     int max_stream_index; /**< max stream # actually used for output */
78     MovieStream *st; /**< array of all streams, one per output */
79     int *out_index; /**< stream number -> output number map, or -1 */
80 } MovieContext;
81
82 #define OFFSET(x) offsetof(MovieContext, x)
83 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_VIDEO_PARAM
84
85 static const AVOption movie_options[]= {
86     { "filename",     NULL,                      OFFSET(file_name),    AV_OPT_TYPE_STRING,                                    .flags = FLAGS },
87     { "format_name",  "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING,                                    .flags = FLAGS },
88     { "f",            "set format name",         OFFSET(format_name),  AV_OPT_TYPE_STRING,                                    .flags = FLAGS },
89     { "stream_index", "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1, INT_MAX,                 FLAGS  },
90     { "si",           "set stream index",        OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1, INT_MAX,                 FLAGS  },
91     { "seek_point",   "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl =  0 },  0, (INT64_MAX-1) / 1000000, FLAGS },
92     { "sp",           "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, { .dbl =  0 },  0, (INT64_MAX-1) / 1000000, FLAGS },
93     { "streams",      "set streams",             OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str =  0},  0, 0, FLAGS },
94     { "s",            "set streams",             OFFSET(stream_specs), AV_OPT_TYPE_STRING, {.str =  0},  0, 0, FLAGS },
95     { "loop",         "set loop count",          OFFSET(loop_count),   AV_OPT_TYPE_INT,    {.i64 =  1},  0,        INT_MAX, FLAGS },
96     { "discontinuity", "set discontinuity threshold", OFFSET(discontinuity_threshold), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, FLAGS },
97     { NULL },
98 };
99
100 static int movie_config_output_props(AVFilterLink *outlink);
101
102 static AVStream *find_stream(void *log, AVFormatContext *avf, const char *spec)
103 {
104     int i, ret, already = 0, stream_id = -1;
105     char type_char[2], dummy;
106     AVStream *found = NULL;
107     enum AVMediaType type;
108
109     ret = sscanf(spec, "d%1[av]%d%c", type_char, &stream_id, &dummy);
110     if (ret >= 1 && ret <= 2) {
111         type = type_char[0] == 'v' ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
112         ret = av_find_best_stream(avf, type, stream_id, -1, NULL, 0);
113         if (ret < 0) {
114             av_log(log, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
115                    av_get_media_type_string(type), stream_id);
116             return NULL;
117         }
118         return avf->streams[ret];
119     }
120     for (i = 0; i < avf->nb_streams; i++) {
121         ret = avformat_match_stream_specifier(avf, avf->streams[i], spec);
122         if (ret < 0) {
123             av_log(log, AV_LOG_ERROR,
124                    "Invalid stream specifier \"%s\"\n", spec);
125             return NULL;
126         }
127         if (!ret)
128             continue;
129         if (avf->streams[i]->discard != AVDISCARD_ALL) {
130             already++;
131             continue;
132         }
133         if (found) {
134             av_log(log, AV_LOG_WARNING,
135                    "Ambiguous stream specifier \"%s\", using #%d\n", spec, i);
136             break;
137         }
138         found = avf->streams[i];
139     }
140     if (!found) {
141         av_log(log, AV_LOG_WARNING, "Stream specifier \"%s\" %s\n", spec,
142                already ? "matched only already used streams" :
143                          "did not match any stream");
144         return NULL;
145     }
146     if (found->codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
147         found->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
148         av_log(log, AV_LOG_ERROR, "Stream specifier \"%s\" matched a %s stream,"
149                "currently unsupported by libavfilter\n", spec,
150                av_get_media_type_string(found->codecpar->codec_type));
151         return NULL;
152     }
153     return found;
154 }
155
156 static int open_stream(AVFilterContext *ctx, MovieStream *st)
157 {
158     AVCodec *codec;
159     int ret;
160
161     codec = avcodec_find_decoder(st->st->codecpar->codec_id);
162     if (!codec) {
163         av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
164         return AVERROR(EINVAL);
165     }
166
167     st->codec_ctx = avcodec_alloc_context3(codec);
168     if (!st->codec_ctx)
169         return AVERROR(ENOMEM);
170
171     ret = avcodec_parameters_to_context(st->codec_ctx, st->st->codecpar);
172     if (ret < 0)
173         return ret;
174
175     st->codec_ctx->refcounted_frames = 1;
176     st->codec_ctx->thread_count = ff_filter_get_nb_threads(ctx);
177
178     if ((ret = avcodec_open2(st->codec_ctx, codec, NULL)) < 0) {
179         av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
180         return ret;
181     }
182
183     return 0;
184 }
185
186 static int guess_channel_layout(MovieStream *st, int st_index, void *log_ctx)
187 {
188     AVCodecParameters *dec_par = st->st->codecpar;
189     char buf[256];
190     int64_t chl = av_get_default_channel_layout(dec_par->channels);
191
192     if (!chl) {
193         av_log(log_ctx, AV_LOG_ERROR,
194                "Channel layout is not set in stream %d, and could not "
195                "be guessed from the number of channels (%d)\n",
196                st_index, dec_par->channels);
197         return AVERROR(EINVAL);
198     }
199
200     av_get_channel_layout_string(buf, sizeof(buf), dec_par->channels, chl);
201     av_log(log_ctx, AV_LOG_WARNING,
202            "Channel layout is not set in output stream %d, "
203            "guessed channel layout is '%s'\n",
204            st_index, buf);
205     dec_par->channel_layout = chl;
206     return 0;
207 }
208
209 static av_cold int movie_common_init(AVFilterContext *ctx)
210 {
211     MovieContext *movie = ctx->priv;
212     AVInputFormat *iformat = NULL;
213     int64_t timestamp;
214     int nb_streams = 1, ret, i;
215     char default_streams[16], *stream_specs, *spec, *cursor;
216     AVStream *st;
217
218     if (!movie->file_name) {
219         av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
220         return AVERROR(EINVAL);
221     }
222
223     movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
224
225     stream_specs = movie->stream_specs;
226     if (!stream_specs) {
227         snprintf(default_streams, sizeof(default_streams), "d%c%d",
228                  !strcmp(ctx->filter->name, "amovie") ? 'a' : 'v',
229                  movie->stream_index);
230         stream_specs = default_streams;
231     }
232     for (cursor = stream_specs; *cursor; cursor++)
233         if (*cursor == '+')
234             nb_streams++;
235
236     if (movie->loop_count != 1 && nb_streams != 1) {
237         av_log(ctx, AV_LOG_ERROR,
238                "Loop with several streams is currently unsupported\n");
239         return AVERROR_PATCHWELCOME;
240     }
241
242     // Try to find the movie format (container)
243     iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
244
245     movie->format_ctx = NULL;
246     if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
247         av_log(ctx, AV_LOG_ERROR,
248                "Failed to avformat_open_input '%s'\n", movie->file_name);
249         return ret;
250     }
251     if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
252         av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
253
254     // if seeking requested, we execute it
255     if (movie->seek_point > 0) {
256         timestamp = movie->seek_point;
257         // add the stream start time, should it exist
258         if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
259             if (timestamp > 0 && movie->format_ctx->start_time > INT64_MAX - timestamp) {
260                 av_log(ctx, AV_LOG_ERROR,
261                        "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
262                        movie->file_name, movie->format_ctx->start_time, movie->seek_point);
263                 return AVERROR(EINVAL);
264             }
265             timestamp += movie->format_ctx->start_time;
266         }
267         if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
268             av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
269                    movie->file_name, timestamp);
270             return ret;
271         }
272     }
273
274     for (i = 0; i < movie->format_ctx->nb_streams; i++)
275         movie->format_ctx->streams[i]->discard = AVDISCARD_ALL;
276
277     movie->st = av_calloc(nb_streams, sizeof(*movie->st));
278     if (!movie->st)
279         return AVERROR(ENOMEM);
280
281     for (i = 0; i < nb_streams; i++) {
282         spec = av_strtok(stream_specs, "+", &cursor);
283         if (!spec)
284             return AVERROR_BUG;
285         stream_specs = NULL; /* for next strtok */
286         st = find_stream(ctx, movie->format_ctx, spec);
287         if (!st)
288             return AVERROR(EINVAL);
289         st->discard = AVDISCARD_DEFAULT;
290         movie->st[i].st = st;
291         movie->max_stream_index = FFMAX(movie->max_stream_index, st->index);
292         movie->st[i].discontinuity_threshold =
293             av_rescale_q(movie->discontinuity_threshold, AV_TIME_BASE_Q, st->time_base);
294     }
295     if (av_strtok(NULL, "+", &cursor))
296         return AVERROR_BUG;
297
298     movie->out_index = av_calloc(movie->max_stream_index + 1,
299                                  sizeof(*movie->out_index));
300     if (!movie->out_index)
301         return AVERROR(ENOMEM);
302     for (i = 0; i <= movie->max_stream_index; i++)
303         movie->out_index[i] = -1;
304     for (i = 0; i < nb_streams; i++) {
305         AVFilterPad pad = { 0 };
306         movie->out_index[movie->st[i].st->index] = i;
307         pad.type          = movie->st[i].st->codecpar->codec_type;
308         pad.name          = av_asprintf("out%d", i);
309         if (!pad.name)
310             return AVERROR(ENOMEM);
311         pad.config_props  = movie_config_output_props;
312         if ((ret = ff_insert_outpad(ctx, i, &pad)) < 0) {
313             av_freep(&pad.name);
314             return ret;
315         }
316         if ( movie->st[i].st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
317             !movie->st[i].st->codecpar->channel_layout) {
318             ret = guess_channel_layout(&movie->st[i], i, ctx);
319             if (ret < 0)
320                 return ret;
321         }
322         ret = open_stream(ctx, &movie->st[i]);
323         if (ret < 0)
324             return ret;
325     }
326
327     av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
328            movie->seek_point, movie->format_name, movie->file_name,
329            movie->stream_index);
330
331     return 0;
332 }
333
334 static av_cold void movie_uninit(AVFilterContext *ctx)
335 {
336     MovieContext *movie = ctx->priv;
337     int i;
338
339     for (i = 0; i < ctx->nb_outputs; i++) {
340         av_freep(&ctx->output_pads[i].name);
341         if (movie->st[i].st)
342             avcodec_free_context(&movie->st[i].codec_ctx);
343     }
344     av_freep(&movie->st);
345     av_freep(&movie->out_index);
346     if (movie->format_ctx)
347         avformat_close_input(&movie->format_ctx);
348 }
349
350 static int movie_query_formats(AVFilterContext *ctx)
351 {
352     MovieContext *movie = ctx->priv;
353     int list[] = { 0, -1 };
354     int64_t list64[] = { 0, -1 };
355     int i, ret;
356
357     for (i = 0; i < ctx->nb_outputs; i++) {
358         MovieStream *st = &movie->st[i];
359         AVCodecParameters *c = st->st->codecpar;
360         AVFilterLink *outlink = ctx->outputs[i];
361
362         switch (c->codec_type) {
363         case AVMEDIA_TYPE_VIDEO:
364             list[0] = c->format;
365             if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
366                 return ret;
367             break;
368         case AVMEDIA_TYPE_AUDIO:
369             list[0] = c->format;
370             if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_formats)) < 0)
371                 return ret;
372             list[0] = c->sample_rate;
373             if ((ret = ff_formats_ref(ff_make_format_list(list), &outlink->in_samplerates)) < 0)
374                 return ret;
375             list64[0] = c->channel_layout;
376             if ((ret = ff_channel_layouts_ref(ff_make_format64_list(list64),
377                                    &outlink->in_channel_layouts)) < 0)
378                 return ret;
379             break;
380         }
381     }
382
383     return 0;
384 }
385
386 static int movie_config_output_props(AVFilterLink *outlink)
387 {
388     AVFilterContext *ctx = outlink->src;
389     MovieContext *movie  = ctx->priv;
390     unsigned out_id = FF_OUTLINK_IDX(outlink);
391     MovieStream *st = &movie->st[out_id];
392     AVCodecParameters *c = st->st->codecpar;
393
394     outlink->time_base = st->st->time_base;
395
396     switch (c->codec_type) {
397     case AVMEDIA_TYPE_VIDEO:
398         outlink->w          = c->width;
399         outlink->h          = c->height;
400         outlink->frame_rate = st->st->r_frame_rate;
401         break;
402     case AVMEDIA_TYPE_AUDIO:
403         break;
404     }
405
406     return 0;
407 }
408
409 static char *describe_frame_to_str(char *dst, size_t dst_size,
410                                    AVFrame *frame, enum AVMediaType frame_type,
411                                    AVFilterLink *link)
412 {
413     switch (frame_type) {
414     case AVMEDIA_TYPE_VIDEO:
415         snprintf(dst, dst_size,
416                  "video pts:%s time:%s size:%dx%d aspect:%d/%d",
417                  av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
418                  frame->width, frame->height,
419                  frame->sample_aspect_ratio.num,
420                  frame->sample_aspect_ratio.den);
421                  break;
422     case AVMEDIA_TYPE_AUDIO:
423         snprintf(dst, dst_size,
424                  "audio pts:%s time:%s samples:%d",
425                  av_ts2str(frame->pts), av_ts2timestr(frame->pts, &link->time_base),
426                  frame->nb_samples);
427                  break;
428     default:
429         snprintf(dst, dst_size, "%s BUG", av_get_media_type_string(frame_type));
430         break;
431     }
432     return dst;
433 }
434
435 static int rewind_file(AVFilterContext *ctx)
436 {
437     MovieContext *movie = ctx->priv;
438     int64_t timestamp = movie->seek_point;
439     int ret, i;
440
441     if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
442         timestamp += movie->format_ctx->start_time;
443     ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD);
444     if (ret < 0) {
445         av_log(ctx, AV_LOG_ERROR, "Unable to loop: %s\n", av_err2str(ret));
446         movie->loop_count = 1; /* do not try again */
447         return ret;
448     }
449
450     for (i = 0; i < ctx->nb_outputs; i++) {
451         avcodec_flush_buffers(movie->st[i].codec_ctx);
452         movie->st[i].done = 0;
453     }
454     movie->eof = 0;
455     return 0;
456 }
457
458 /**
459  * Try to push a frame to the requested output.
460  *
461  * @param ctx     filter context
462  * @param out_id  number of output where a frame is wanted;
463  *                if the frame is read from file, used to set the return value;
464  *                if the codec is being flushed, flush the corresponding stream
465  * @return  1 if a frame was pushed on the requested output,
466  *          0 if another attempt is possible,
467  *          <0 AVERROR code
468  */
469 static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)
470 {
471     MovieContext *movie = ctx->priv;
472     AVPacket *pkt = &movie->pkt;
473     enum AVMediaType frame_type;
474     MovieStream *st;
475     int ret, got_frame = 0, pkt_out_id;
476     AVFilterLink *outlink;
477     AVFrame *frame;
478
479     if (!pkt->size) {
480         if (movie->eof) {
481             if (movie->st[out_id].done) {
482                 if (movie->loop_count != 1) {
483                     ret = rewind_file(ctx);
484                     if (ret < 0)
485                         return ret;
486                     movie->loop_count -= movie->loop_count > 1;
487                     av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");
488                     return 0; /* retry */
489                 }
490                 return AVERROR_EOF;
491             }
492             pkt->stream_index = movie->st[out_id].st->index;
493             /* packet is already ready for flushing */
494         } else {
495             ret = av_read_frame(movie->format_ctx, &movie->pkt0);
496             if (ret < 0) {
497                 av_init_packet(&movie->pkt0); /* ready for flushing */
498                 *pkt = movie->pkt0;
499                 if (ret == AVERROR_EOF) {
500                     movie->eof = 1;
501                     return 0; /* start flushing */
502                 }
503                 return ret;
504             }
505             *pkt = movie->pkt0;
506         }
507     }
508
509     pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :
510                  movie->out_index[pkt->stream_index];
511     if (pkt_out_id < 0) {
512         av_packet_unref(&movie->pkt0);
513         pkt->size = 0; /* ready for next run */
514         pkt->data = NULL;
515         return 0;
516     }
517     st = &movie->st[pkt_out_id];
518     outlink = ctx->outputs[pkt_out_id];
519
520     frame = av_frame_alloc();
521     if (!frame)
522         return AVERROR(ENOMEM);
523
524     frame_type = st->st->codecpar->codec_type;
525     switch (frame_type) {
526     case AVMEDIA_TYPE_VIDEO:
527         ret = avcodec_decode_video2(st->codec_ctx, frame, &got_frame, pkt);
528         break;
529     case AVMEDIA_TYPE_AUDIO:
530         ret = avcodec_decode_audio4(st->codec_ctx, frame, &got_frame, pkt);
531         break;
532     default:
533         ret = AVERROR(ENOSYS);
534         break;
535     }
536     if (ret < 0) {
537         av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));
538         av_frame_free(&frame);
539         av_packet_unref(&movie->pkt0);
540         movie->pkt.size = 0;
541         movie->pkt.data = NULL;
542         return 0;
543     }
544     if (!ret || st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
545         ret = pkt->size;
546
547     pkt->data += ret;
548     pkt->size -= ret;
549     if (pkt->size <= 0) {
550         av_packet_unref(&movie->pkt0);
551         pkt->size = 0; /* ready for next run */
552         pkt->data = NULL;
553     }
554     if (!got_frame) {
555         if (!ret)
556             st->done = 1;
557         av_frame_free(&frame);
558         return 0;
559     }
560
561     frame->pts = frame->best_effort_timestamp;
562     if (frame->pts != AV_NOPTS_VALUE) {
563         if (movie->ts_offset)
564             frame->pts += av_rescale_q_rnd(movie->ts_offset, AV_TIME_BASE_Q, outlink->time_base, AV_ROUND_UP);
565         if (st->discontinuity_threshold) {
566             if (st->last_pts != AV_NOPTS_VALUE) {
567                 int64_t diff = frame->pts - st->last_pts;
568                 if (diff < 0 || diff > st->discontinuity_threshold) {
569                     av_log(ctx, AV_LOG_VERBOSE, "Discontinuity in stream:%d diff:%"PRId64"\n", pkt_out_id, diff);
570                     movie->ts_offset += av_rescale_q_rnd(-diff, outlink->time_base, AV_TIME_BASE_Q, AV_ROUND_UP);
571                     frame->pts -= diff;
572                 }
573             }
574         }
575         st->last_pts = frame->pts;
576     }
577     ff_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,
578             describe_frame_to_str((char[1024]){0}, 1024, frame, frame_type, outlink));
579
580     if (st->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
581         if (frame->format != outlink->format) {
582             av_log(ctx, AV_LOG_ERROR, "Format changed %s -> %s, discarding frame\n",
583                 av_get_pix_fmt_name(outlink->format),
584                 av_get_pix_fmt_name(frame->format)
585                 );
586             av_frame_free(&frame);
587             return 0;
588         }
589     }
590     ret = ff_filter_frame(outlink, frame);
591
592     if (ret < 0)
593         return ret;
594     return pkt_out_id == out_id;
595 }
596
597 static int activate(AVFilterContext *ctx)
598 {
599     MovieContext *movie = ctx->priv;
600     int nb_eofs = 0;
601
602     for (int i = 0; i < ctx->nb_outputs; i++) {
603         AVFilterLink *outlink = ctx->outputs[i];
604
605         nb_eofs += !!ff_outlink_get_status(outlink);
606         if (ff_outlink_frame_wanted(outlink)) {
607             int ret = movie_push_frame(ctx, i);
608
609             if (ret == AVERROR_EOF) {
610                 ff_outlink_set_status(outlink, AVERROR_EOF, movie->st[i].last_pts);
611                 return 0;
612             } else if (ret) {
613                 return FFMIN(ret, 0);
614             }
615         }
616     }
617
618     if (nb_eofs != ctx->nb_outputs) {
619         ff_filter_set_ready(ctx, 100);
620         return 0;
621     }
622
623     return FFERROR_NOT_READY;
624 }
625
626 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
627                            char *res, int res_len, int flags)
628 {
629     MovieContext *movie = ctx->priv;
630     int ret = AVERROR(ENOSYS);
631
632     if (!strcmp(cmd, "seek")) {
633         int idx, flags, i;
634         int64_t ts;
635         char tail[2];
636
637         if (sscanf(args, "%i|%"SCNi64"|%i %1s", &idx, &ts, &flags, tail) != 3)
638             return AVERROR(EINVAL);
639
640         ret = av_seek_frame(movie->format_ctx, idx, ts, flags);
641         if (ret < 0)
642             return ret;
643
644         for (i = 0; i < ctx->nb_outputs; i++) {
645             avcodec_flush_buffers(movie->st[i].codec_ctx);
646             movie->st[i].done = 0;
647         }
648         return ret;
649     } else if (!strcmp(cmd, "get_duration")) {
650         int print_len;
651         char tail[2];
652
653         if (!res || res_len <= 0)
654             return AVERROR(EINVAL);
655
656         if (args && sscanf(args, "%1s", tail) == 1)
657             return AVERROR(EINVAL);
658
659         print_len = snprintf(res, res_len, "%"PRId64, movie->format_ctx->duration);
660         if (print_len < 0 || print_len >= res_len)
661             return AVERROR(EINVAL);
662
663         return 0;
664     }
665
666     return ret;
667 }
668
669 #if CONFIG_MOVIE_FILTER
670
671 AVFILTER_DEFINE_CLASS(movie);
672
673 AVFilter ff_avsrc_movie = {
674     .name          = "movie",
675     .description   = NULL_IF_CONFIG_SMALL("Read from a movie source."),
676     .priv_size     = sizeof(MovieContext),
677     .priv_class    = &movie_class,
678     .init          = movie_common_init,
679     .uninit        = movie_uninit,
680     .query_formats = movie_query_formats,
681
682     .inputs    = NULL,
683     .outputs   = NULL,
684     .activate  = activate,
685     .flags     = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
686     .process_command = process_command
687 };
688
689 #endif  /* CONFIG_MOVIE_FILTER */
690
691 #if CONFIG_AMOVIE_FILTER
692
693 #define amovie_options movie_options
694 AVFILTER_DEFINE_CLASS(amovie);
695
696 AVFilter ff_avsrc_amovie = {
697     .name          = "amovie",
698     .description   = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
699     .priv_size     = sizeof(MovieContext),
700     .init          = movie_common_init,
701     .uninit        = movie_uninit,
702     .query_formats = movie_query_formats,
703
704     .inputs     = NULL,
705     .outputs    = NULL,
706     .activate   = activate,
707     .priv_class = &amovie_class,
708     .flags      = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
709     .process_command = process_command,
710 };
711
712 #endif /* CONFIG_AMOVIE_FILTER */