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