Imported Upstream version 6.1
[platform/upstream/ffmpeg.git] / fftools / ffmpeg.h
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #ifndef FFTOOLS_FFMPEG_H
20 #define FFTOOLS_FFMPEG_H
21
22 #include "config.h"
23
24 #include <stdatomic.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <signal.h>
28
29 #include "cmdutils.h"
30 #include "sync_queue.h"
31
32 #include "libavformat/avformat.h"
33 #include "libavformat/avio.h"
34
35 #include "libavcodec/avcodec.h"
36 #include "libavcodec/bsf.h"
37
38 #include "libavfilter/avfilter.h"
39
40 #include "libavutil/avutil.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/eval.h"
43 #include "libavutil/fifo.h"
44 #include "libavutil/hwcontext.h"
45 #include "libavutil/pixfmt.h"
46 #include "libavutil/rational.h"
47 #include "libavutil/thread.h"
48 #include "libavutil/threadmessage.h"
49
50 #include "libswresample/swresample.h"
51
52 // deprecated features
53 #define FFMPEG_OPT_PSNR 1
54 #define FFMPEG_OPT_MAP_CHANNEL 1
55 #define FFMPEG_OPT_MAP_SYNC 1
56 #define FFMPEG_ROTATION_METADATA 1
57 #define FFMPEG_OPT_QPHIST 1
58 #define FFMPEG_OPT_ADRIFT_THRESHOLD 1
59 #define FFMPEG_OPT_ENC_TIME_BASE_NUM 1
60 #define FFMPEG_OPT_TOP 1
61 #define FFMPEG_OPT_FORCE_KF_SOURCE_NO_DROP 1
62
63 enum VideoSyncMethod {
64     VSYNC_AUTO = -1,
65     VSYNC_PASSTHROUGH,
66     VSYNC_CFR,
67     VSYNC_VFR,
68     VSYNC_VSCFR,
69     VSYNC_DROP,
70 };
71
72 enum EncTimeBase {
73     ENC_TIME_BASE_DEMUX  = -1,
74     ENC_TIME_BASE_FILTER = -2,
75 };
76
77 enum HWAccelID {
78     HWACCEL_NONE = 0,
79     HWACCEL_AUTO,
80     HWACCEL_GENERIC,
81 };
82
83 typedef struct HWDevice {
84     const char *name;
85     enum AVHWDeviceType type;
86     AVBufferRef *device_ref;
87 } HWDevice;
88
89 /* select an input stream for an output stream */
90 typedef struct StreamMap {
91     int disabled;           /* 1 is this mapping is disabled by a negative map */
92     int file_index;
93     int stream_index;
94     char *linklabel;       /* name of an output link, for mapping lavfi outputs */
95 } StreamMap;
96
97 #if FFMPEG_OPT_MAP_CHANNEL
98 typedef struct {
99     int  file_idx,  stream_idx,  channel_idx; // input
100     int ofile_idx, ostream_idx;               // output
101 } AudioChannelMap;
102 #endif
103
104 typedef struct DemuxPktData {
105     // estimated dts in AV_TIME_BASE_Q,
106     // to be used when real dts is missing
107     int64_t dts_est;
108 } DemuxPktData;
109
110 typedef struct OptionsContext {
111     OptionGroup *g;
112
113     /* input/output options */
114     int64_t start_time;
115     int64_t start_time_eof;
116     int seek_timestamp;
117     const char *format;
118
119     SpecifierOpt *codec_names;
120     int        nb_codec_names;
121     SpecifierOpt *audio_ch_layouts;
122     int        nb_audio_ch_layouts;
123     SpecifierOpt *audio_channels;
124     int        nb_audio_channels;
125     SpecifierOpt *audio_sample_rate;
126     int        nb_audio_sample_rate;
127     SpecifierOpt *frame_rates;
128     int        nb_frame_rates;
129     SpecifierOpt *max_frame_rates;
130     int        nb_max_frame_rates;
131     SpecifierOpt *frame_sizes;
132     int        nb_frame_sizes;
133     SpecifierOpt *frame_pix_fmts;
134     int        nb_frame_pix_fmts;
135
136     /* input options */
137     int64_t input_ts_offset;
138     int loop;
139     int rate_emu;
140     float readrate;
141     double readrate_initial_burst;
142     int accurate_seek;
143     int thread_queue_size;
144     int input_sync_ref;
145     int find_stream_info;
146
147     SpecifierOpt *ts_scale;
148     int        nb_ts_scale;
149     SpecifierOpt *dump_attachment;
150     int        nb_dump_attachment;
151     SpecifierOpt *hwaccels;
152     int        nb_hwaccels;
153     SpecifierOpt *hwaccel_devices;
154     int        nb_hwaccel_devices;
155     SpecifierOpt *hwaccel_output_formats;
156     int        nb_hwaccel_output_formats;
157     SpecifierOpt *autorotate;
158     int        nb_autorotate;
159
160     /* output options */
161     StreamMap *stream_maps;
162     int     nb_stream_maps;
163 #if FFMPEG_OPT_MAP_CHANNEL
164     AudioChannelMap *audio_channel_maps; /* one info entry per -map_channel */
165     int           nb_audio_channel_maps; /* number of (valid) -map_channel settings */
166 #endif
167     const char **attachments;
168     int       nb_attachments;
169
170     int chapters_input_file;
171
172     int64_t recording_time;
173     int64_t stop_time;
174     int64_t limit_filesize;
175     float mux_preload;
176     float mux_max_delay;
177     float shortest_buf_duration;
178     int shortest;
179     int bitexact;
180
181     int video_disable;
182     int audio_disable;
183     int subtitle_disable;
184     int data_disable;
185
186     // keys are stream indices
187     AVDictionary *streamid;
188
189     SpecifierOpt *metadata;
190     int        nb_metadata;
191     SpecifierOpt *max_frames;
192     int        nb_max_frames;
193     SpecifierOpt *bitstream_filters;
194     int        nb_bitstream_filters;
195     SpecifierOpt *codec_tags;
196     int        nb_codec_tags;
197     SpecifierOpt *sample_fmts;
198     int        nb_sample_fmts;
199     SpecifierOpt *qscale;
200     int        nb_qscale;
201     SpecifierOpt *forced_key_frames;
202     int        nb_forced_key_frames;
203     SpecifierOpt *fps_mode;
204     int        nb_fps_mode;
205     SpecifierOpt *force_fps;
206     int        nb_force_fps;
207     SpecifierOpt *frame_aspect_ratios;
208     int        nb_frame_aspect_ratios;
209     SpecifierOpt *display_rotations;
210     int        nb_display_rotations;
211     SpecifierOpt *display_hflips;
212     int        nb_display_hflips;
213     SpecifierOpt *display_vflips;
214     int        nb_display_vflips;
215     SpecifierOpt *rc_overrides;
216     int        nb_rc_overrides;
217     SpecifierOpt *intra_matrices;
218     int        nb_intra_matrices;
219     SpecifierOpt *inter_matrices;
220     int        nb_inter_matrices;
221     SpecifierOpt *chroma_intra_matrices;
222     int        nb_chroma_intra_matrices;
223 #if FFMPEG_OPT_TOP
224     SpecifierOpt *top_field_first;
225     int        nb_top_field_first;
226 #endif
227     SpecifierOpt *metadata_map;
228     int        nb_metadata_map;
229     SpecifierOpt *presets;
230     int        nb_presets;
231     SpecifierOpt *copy_initial_nonkeyframes;
232     int        nb_copy_initial_nonkeyframes;
233     SpecifierOpt *copy_prior_start;
234     int        nb_copy_prior_start;
235     SpecifierOpt *filters;
236     int        nb_filters;
237     SpecifierOpt *filter_scripts;
238     int        nb_filter_scripts;
239     SpecifierOpt *reinit_filters;
240     int        nb_reinit_filters;
241     SpecifierOpt *fix_sub_duration;
242     int        nb_fix_sub_duration;
243     SpecifierOpt *fix_sub_duration_heartbeat;
244     int        nb_fix_sub_duration_heartbeat;
245     SpecifierOpt *canvas_sizes;
246     int        nb_canvas_sizes;
247     SpecifierOpt *pass;
248     int        nb_pass;
249     SpecifierOpt *passlogfiles;
250     int        nb_passlogfiles;
251     SpecifierOpt *max_muxing_queue_size;
252     int        nb_max_muxing_queue_size;
253     SpecifierOpt *muxing_queue_data_threshold;
254     int        nb_muxing_queue_data_threshold;
255     SpecifierOpt *guess_layout_max;
256     int        nb_guess_layout_max;
257     SpecifierOpt *apad;
258     int        nb_apad;
259     SpecifierOpt *discard;
260     int        nb_discard;
261     SpecifierOpt *disposition;
262     int        nb_disposition;
263     SpecifierOpt *program;
264     int        nb_program;
265     SpecifierOpt *time_bases;
266     int        nb_time_bases;
267     SpecifierOpt *enc_time_bases;
268     int        nb_enc_time_bases;
269     SpecifierOpt *autoscale;
270     int        nb_autoscale;
271     SpecifierOpt *bits_per_raw_sample;
272     int        nb_bits_per_raw_sample;
273     SpecifierOpt *enc_stats_pre;
274     int        nb_enc_stats_pre;
275     SpecifierOpt *enc_stats_post;
276     int        nb_enc_stats_post;
277     SpecifierOpt *mux_stats;
278     int        nb_mux_stats;
279     SpecifierOpt *enc_stats_pre_fmt;
280     int        nb_enc_stats_pre_fmt;
281     SpecifierOpt *enc_stats_post_fmt;
282     int        nb_enc_stats_post_fmt;
283     SpecifierOpt *mux_stats_fmt;
284     int        nb_mux_stats_fmt;
285 } OptionsContext;
286
287 typedef struct InputFilter {
288     struct FilterGraph *graph;
289     uint8_t            *name;
290 } InputFilter;
291
292 typedef struct OutputFilter {
293     struct OutputStream *ost;
294     struct FilterGraph  *graph;
295     uint8_t             *name;
296
297     /* for filters that are not yet bound to an output stream,
298      * this stores the output linklabel, if any */
299     uint8_t             *linklabel;
300
301     enum AVMediaType     type;
302
303     /* pts of the last frame received from this filter, in AV_TIME_BASE_Q */
304     int64_t last_pts;
305
306     uint64_t nb_frames_dup;
307     uint64_t nb_frames_drop;
308 } OutputFilter;
309
310 typedef struct FilterGraph {
311     const AVClass *class;
312     int            index;
313
314     AVFilterGraph *graph;
315
316     InputFilter   **inputs;
317     int          nb_inputs;
318     OutputFilter **outputs;
319     int         nb_outputs;
320 } FilterGraph;
321
322 typedef struct Decoder Decoder;
323
324 typedef struct InputStream {
325     const AVClass *class;
326
327     int file_index;
328     int index;
329
330     AVStream *st;
331     int discard;             /* true if stream data should be discarded */
332     int user_set_discard;
333     int decoding_needed;     /* non zero if the packets must be decoded in 'raw_fifo', see DECODING_FOR_* */
334 #define DECODING_FOR_OST    1
335 #define DECODING_FOR_FILTER 2
336
337     /**
338      * Codec parameters - to be used by the decoding/streamcopy code.
339      * st->codecpar should not be accessed, because it may be modified
340      * concurrently by the demuxing thread.
341      */
342     AVCodecParameters *par;
343     Decoder *decoder;
344     AVCodecContext *dec_ctx;
345     const AVCodec *dec;
346     const AVCodecDescriptor *codec_desc;
347
348     AVRational framerate_guessed;
349
350     int64_t nb_samples; /* number of samples in the last decoded audio frame before looping */
351
352     AVDictionary *decoder_opts;
353     AVRational framerate;               /* framerate forced with -r */
354 #if FFMPEG_OPT_TOP
355     int top_field_first;
356 #endif
357
358     int autorotate;
359
360     int fix_sub_duration;
361
362     struct sub2video {
363         int w, h;
364     } sub2video;
365
366     /* decoded data from this stream goes into all those filters
367      * currently video and audio only */
368     InputFilter **filters;
369     int        nb_filters;
370
371     /*
372      * Output targets that do not go through lavfi, i.e. subtitles or
373      * streamcopy. Those two cases are distinguished by the OutputStream
374      * having an encoder or not.
375      */
376     struct OutputStream **outputs;
377     int                nb_outputs;
378
379     int reinit_filters;
380
381     /* hwaccel options */
382     enum HWAccelID hwaccel_id;
383     enum AVHWDeviceType hwaccel_device_type;
384     char  *hwaccel_device;
385     enum AVPixelFormat hwaccel_output_format;
386
387     /* stats */
388     // number of frames/samples retrieved from the decoder
389     uint64_t frames_decoded;
390     uint64_t samples_decoded;
391     uint64_t decode_errors;
392 } InputStream;
393
394 typedef struct LastFrameDuration {
395     int     stream_idx;
396     int64_t duration;
397 } LastFrameDuration;
398
399 typedef struct InputFile {
400     const AVClass *class;
401
402     int index;
403
404     // input format has no timestamps
405     int format_nots;
406
407     AVFormatContext *ctx;
408     int eof_reached;      /* true if eof reached */
409     int eagain;           /* true if last read attempt returned EAGAIN */
410     int64_t input_ts_offset;
411     int input_sync_ref;
412     /**
413      * Effective format start time based on enabled streams.
414      */
415     int64_t start_time_effective;
416     int64_t ts_offset;
417     int64_t start_time;   /* user-specified start time in AV_TIME_BASE or AV_NOPTS_VALUE */
418     int64_t recording_time;
419
420     /* streams that ffmpeg is aware of;
421      * there may be extra streams in ctx that are not mapped to an InputStream
422      * if new streams appear dynamically during demuxing */
423     InputStream **streams;
424     int        nb_streams;
425
426     float readrate;
427     int accurate_seek;
428
429     /* when looping the input file, this queue is used by decoders to report
430      * the last frame duration back to the demuxer thread */
431     AVThreadMessageQueue *audio_duration_queue;
432     int                   audio_duration_queue_size;
433 } InputFile;
434
435 enum forced_keyframes_const {
436     FKF_N,
437     FKF_N_FORCED,
438     FKF_PREV_FORCED_N,
439     FKF_PREV_FORCED_T,
440     FKF_T,
441     FKF_NB
442 };
443
444 #define ABORT_ON_FLAG_EMPTY_OUTPUT        (1 <<  0)
445 #define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM (1 <<  1)
446
447 enum EncStatsType {
448     ENC_STATS_LITERAL = 0,
449     ENC_STATS_FILE_IDX,
450     ENC_STATS_STREAM_IDX,
451     ENC_STATS_FRAME_NUM,
452     ENC_STATS_FRAME_NUM_IN,
453     ENC_STATS_TIMEBASE,
454     ENC_STATS_TIMEBASE_IN,
455     ENC_STATS_PTS,
456     ENC_STATS_PTS_TIME,
457     ENC_STATS_PTS_IN,
458     ENC_STATS_PTS_TIME_IN,
459     ENC_STATS_DTS,
460     ENC_STATS_DTS_TIME,
461     ENC_STATS_SAMPLE_NUM,
462     ENC_STATS_NB_SAMPLES,
463     ENC_STATS_PKT_SIZE,
464     ENC_STATS_BITRATE,
465     ENC_STATS_AVG_BITRATE,
466 };
467
468 typedef struct EncStatsComponent {
469     enum EncStatsType type;
470
471     uint8_t *str;
472     size_t   str_len;
473 } EncStatsComponent;
474
475 typedef struct EncStats {
476     EncStatsComponent  *components;
477     int              nb_components;
478
479     AVIOContext        *io;
480 } EncStats;
481
482 extern const char *const forced_keyframes_const_names[];
483
484 typedef enum {
485     ENCODER_FINISHED = 1,
486     MUXER_FINISHED = 2,
487 } OSTFinished ;
488
489 enum {
490     KF_FORCE_SOURCE         = 1,
491 #if FFMPEG_OPT_FORCE_KF_SOURCE_NO_DROP
492     KF_FORCE_SOURCE_NO_DROP = 2,
493 #endif
494 };
495
496 typedef struct KeyframeForceCtx {
497     int          type;
498
499     int64_t      ref_pts;
500
501     // timestamps of the forced keyframes, in AV_TIME_BASE_Q
502     int64_t     *pts;
503     int       nb_pts;
504     int          index;
505
506     AVExpr      *pexpr;
507     double       expr_const_values[FKF_NB];
508
509     int          dropped_keyframe;
510 } KeyframeForceCtx;
511
512 typedef struct Encoder Encoder;
513
514 typedef struct OutputStream {
515     const AVClass *class;
516
517     enum AVMediaType type;
518
519     int file_index;          /* file index */
520     int index;               /* stream index in the output file */
521
522     /**
523      * Codec parameters for packets submitted to the muxer (i.e. before
524      * bitstream filtering, if any).
525      */
526     AVCodecParameters *par_in;
527
528     /* input stream that is the source for this output stream;
529      * may be NULL for streams with no well-defined source, e.g.
530      * attachments or outputs from complex filtergraphs */
531     InputStream *ist;
532
533     AVStream *st;            /* stream in the output file */
534     /* dts of the last packet sent to the muxing queue, in AV_TIME_BASE_Q */
535     int64_t last_mux_dts;
536
537     AVRational enc_timebase;
538
539     Encoder *enc;
540     AVCodecContext *enc_ctx;
541
542     /* video only */
543     AVRational frame_rate;
544     AVRational max_frame_rate;
545     enum VideoSyncMethod vsync_method;
546     int is_cfr;
547     int force_fps;
548 #if FFMPEG_OPT_TOP
549     int top_field_first;
550 #endif
551 #if FFMPEG_ROTATION_METADATA
552     int rotate_overridden;
553 #endif
554     int autoscale;
555     int bitexact;
556     int bits_per_raw_sample;
557 #if FFMPEG_ROTATION_METADATA
558     double rotate_override_value;
559 #endif
560
561     AVRational frame_aspect_ratio;
562
563     KeyframeForceCtx kf;
564
565     /* audio only */
566 #if FFMPEG_OPT_MAP_CHANNEL
567     int *audio_channels_map;             /* list of the channels id to pick from the source stream */
568     int audio_channels_mapped;           /* number of channels in audio_channels_map */
569 #endif
570
571     char *logfile_prefix;
572     FILE *logfile;
573
574     OutputFilter *filter;
575
576     AVDictionary *encoder_opts;
577     AVDictionary *sws_dict;
578     AVDictionary *swr_opts;
579     char *apad;
580     OSTFinished finished;        /* no more packets should be written for this stream */
581     int unavailable;                     /* true if the steram is unavailable (possibly temporarily) */
582
583     // init_output_stream() has been called for this stream
584     // The encoder and the bitstream filters have been initialized and the stream
585     // parameters are set in the AVStream.
586     int initialized;
587
588     const char *attachment_filename;
589
590     int keep_pix_fmt;
591
592     /* stats */
593     // number of packets send to the muxer
594     atomic_uint_least64_t packets_written;
595     // number of frames/samples sent to the encoder
596     uint64_t frames_encoded;
597     uint64_t samples_encoded;
598
599     /* packet quality factor */
600     int quality;
601
602     int sq_idx_encode;
603     int sq_idx_mux;
604
605     EncStats enc_stats_pre;
606     EncStats enc_stats_post;
607
608     /*
609      * bool on whether this stream should be utilized for splitting
610      * subtitles utilizing fix_sub_duration at random access points.
611      */
612     unsigned int fix_sub_duration_heartbeat;
613 } OutputStream;
614
615 typedef struct OutputFile {
616     const AVClass *class;
617
618     int index;
619
620     const AVOutputFormat *format;
621     const char           *url;
622
623     OutputStream **streams;
624     int         nb_streams;
625
626     SyncQueue *sq_encode;
627
628     int64_t recording_time;  ///< desired length of the resulting file in microseconds == AV_TIME_BASE units
629     int64_t start_time;      ///< start time in microseconds == AV_TIME_BASE units
630
631     int shortest;
632     int bitexact;
633 } OutputFile;
634
635 // optionally attached as opaque_ref to decoded AVFrames
636 typedef struct FrameData {
637     // properties that come from the decoder
638     struct {
639         uint64_t   frame_num;
640
641         int64_t    pts;
642         AVRational tb;
643     } dec;
644
645     AVRational frame_rate_filter;
646
647     int        bits_per_raw_sample;
648 } FrameData;
649
650 extern InputFile   **input_files;
651 extern int        nb_input_files;
652
653 extern OutputFile   **output_files;
654 extern int         nb_output_files;
655
656 extern FilterGraph **filtergraphs;
657 extern int        nb_filtergraphs;
658
659 extern char *vstats_filename;
660 extern char *sdp_filename;
661
662 extern float dts_delta_threshold;
663 extern float dts_error_threshold;
664
665 extern enum VideoSyncMethod video_sync_method;
666 extern float frame_drop_threshold;
667 extern int do_benchmark;
668 extern int do_benchmark_all;
669 extern int do_hex_dump;
670 extern int do_pkt_dump;
671 extern int copy_ts;
672 extern int start_at_zero;
673 extern int copy_tb;
674 extern int debug_ts;
675 extern int exit_on_error;
676 extern int abort_on_flags;
677 extern int print_stats;
678 extern int64_t stats_period;
679 extern int stdin_interaction;
680 extern AVIOContext *progress_avio;
681 extern float max_error_rate;
682
683 extern char *filter_nbthreads;
684 extern int filter_complex_nbthreads;
685 extern int vstats_version;
686 extern int auto_conversion_filters;
687
688 extern const AVIOInterruptCB int_cb;
689
690 extern const OptionDef options[];
691 extern HWDevice *filter_hw_device;
692
693 extern unsigned nb_output_dumped;
694
695 extern int ignore_unknown_streams;
696 extern int copy_unknown_streams;
697
698 extern int recast_media;
699
700 extern FILE *vstats_file;
701
702 #if FFMPEG_OPT_PSNR
703 extern int do_psnr;
704 #endif
705
706 void term_init(void);
707 void term_exit(void);
708
709 void show_usage(void);
710
711 void remove_avoptions(AVDictionary **a, AVDictionary *b);
712 int check_avoptions(AVDictionary *m);
713
714 int assert_file_overwrite(const char *filename);
715 char *file_read(const char *filename);
716 AVDictionary *strip_specifiers(const AVDictionary *dict);
717 int find_codec(void *logctx, const char *name,
718                enum AVMediaType type, int encoder, const AVCodec **codec);
719 int parse_and_set_vsync(const char *arg, int *vsync_var, int file_idx, int st_idx, int is_global);
720
721 int check_filter_outputs(void);
722 int filtergraph_is_simple(const FilterGraph *fg);
723 int init_simple_filtergraph(InputStream *ist, OutputStream *ost,
724                             char *graph_desc);
725 int init_complex_filtergraph(FilterGraph *fg);
726
727 int copy_av_subtitle(AVSubtitle *dst, const AVSubtitle *src);
728 int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy);
729
730 /**
731  * Get our axiliary frame data attached to the frame, allocating it
732  * if needed.
733  */
734 FrameData *frame_data(AVFrame *frame);
735
736 int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame, int keep_reference);
737 int ifilter_send_eof(InputFilter *ifilter, int64_t pts, AVRational tb);
738 int ifilter_sub2video(InputFilter *ifilter, const AVFrame *frame);
739 void ifilter_sub2video_heartbeat(InputFilter *ifilter, int64_t pts, AVRational tb);
740
741 /**
742  * Set up fallback filtering parameters from a decoder context. They will only
743  * be used if no frames are ever sent on this input, otherwise the actual
744  * parameters are taken from the frame.
745  */
746 int ifilter_parameters_from_dec(InputFilter *ifilter, const AVCodecContext *dec);
747
748 int ofilter_bind_ost(OutputFilter *ofilter, OutputStream *ost);
749
750 /**
751  * Create a new filtergraph in the global filtergraph list.
752  *
753  * @param graph_desc Graph description; an av_malloc()ed string, filtergraph
754  *                   takes ownership of it.
755  */
756 int fg_create(FilterGraph **pfg, char *graph_desc);
757
758 void fg_free(FilterGraph **pfg);
759
760 /**
761  * Perform a step of transcoding for the specified filter graph.
762  *
763  * @param[in]  graph     filter graph to consider
764  * @param[out] best_ist  input stream where a frame would allow to continue
765  * @return  0 for success, <0 for error
766  */
767 int fg_transcode_step(FilterGraph *graph, InputStream **best_ist);
768
769 void fg_send_command(FilterGraph *fg, double time, const char *target,
770                      const char *command, const char *arg, int all_filters);
771
772 /**
773  * Get and encode new output from specified filtergraph, without causing
774  * activity.
775  *
776  * @return  0 for success, <0 for severe errors
777  */
778 int reap_filters(FilterGraph *fg, int flush);
779
780 int ffmpeg_parse_options(int argc, char **argv);
781
782 void enc_stats_write(OutputStream *ost, EncStats *es,
783                      const AVFrame *frame, const AVPacket *pkt,
784                      uint64_t frame_num);
785
786 HWDevice *hw_device_get_by_name(const char *name);
787 HWDevice *hw_device_get_by_type(enum AVHWDeviceType type);
788 int hw_device_init_from_string(const char *arg, HWDevice **dev);
789 int hw_device_init_from_type(enum AVHWDeviceType type,
790                              const char *device,
791                              HWDevice **dev_out);
792 void hw_device_free_all(void);
793
794 /**
795  * Get a hardware device to be used with this filtergraph.
796  * The returned reference is owned by the callee, the caller
797  * must ref it explicitly for long-term use.
798  */
799 AVBufferRef *hw_device_for_filter(void);
800
801 int hwaccel_retrieve_data(AVCodecContext *avctx, AVFrame *input);
802
803 int dec_open(InputStream *ist);
804 void dec_free(Decoder **pdec);
805
806 /**
807  * Submit a packet for decoding
808  *
809  * When pkt==NULL and no_eof=0, there will be no more input. Flush decoders and
810  * mark all downstreams as finished.
811  *
812  * When pkt==NULL and no_eof=1, the stream was reset (e.g. after a seek). Flush
813  * decoders and await further input.
814  */
815 int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof);
816
817 int enc_alloc(Encoder **penc, const AVCodec *codec);
818 void enc_free(Encoder **penc);
819
820 int enc_open(OutputStream *ost, const AVFrame *frame);
821 int enc_subtitle(OutputFile *of, OutputStream *ost, const AVSubtitle *sub);
822 int enc_frame(OutputStream *ost, AVFrame *frame);
823 int enc_flush(void);
824
825 /*
826  * Initialize muxing state for the given stream, should be called
827  * after the codec/streamcopy setup has been done.
828  *
829  * Open the muxer once all the streams have been initialized.
830  */
831 int of_stream_init(OutputFile *of, OutputStream *ost);
832 int of_write_trailer(OutputFile *of);
833 int of_open(const OptionsContext *o, const char *filename);
834 void of_free(OutputFile **pof);
835
836 void of_enc_stats_close(void);
837
838 int of_output_packet(OutputFile *of, OutputStream *ost, AVPacket *pkt);
839
840 /**
841  * @param dts predicted packet dts in AV_TIME_BASE_Q
842  */
843 int of_streamcopy(OutputStream *ost, const AVPacket *pkt, int64_t dts);
844
845 int64_t of_filesize(OutputFile *of);
846
847 int ifile_open(const OptionsContext *o, const char *filename);
848 void ifile_close(InputFile **f);
849
850 /**
851  * Get next input packet from the demuxer.
852  *
853  * @param pkt the packet is written here when this function returns 0
854  * @return
855  * - 0 when a packet has been read successfully
856  * - 1 when stream end was reached, but the stream is looped;
857  *     caller should flush decoders and read from this demuxer again
858  * - a negative error code on failure
859  */
860 int ifile_get_packet(InputFile *f, AVPacket **pkt);
861
862 int ist_output_add(InputStream *ist, OutputStream *ost);
863 int ist_filter_add(InputStream *ist, InputFilter *ifilter, int is_simple);
864
865 /**
866  * Find an unused input stream of given type.
867  */
868 InputStream *ist_find_unused(enum AVMediaType type);
869
870 /* iterate over all input streams in all input files;
871  * pass NULL to start iteration */
872 InputStream *ist_iter(InputStream *prev);
873
874 /* iterate over all output streams in all output files;
875  * pass NULL to start iteration */
876 OutputStream *ost_iter(OutputStream *prev);
877
878 void close_output_stream(OutputStream *ost);
879 int trigger_fix_sub_duration_heartbeat(OutputStream *ost, const AVPacket *pkt);
880 int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts);
881 void update_benchmark(const char *fmt, ...);
882
883 /**
884  * Merge two return codes - return one of the error codes if at least one of
885  * them was negative, 0 otherwise.
886  * Currently just picks the first one, eventually we might want to do something
887  * more sophisticated, like sorting them by priority.
888  */
889 static inline int err_merge(int err0, int err1)
890 {
891     return (err0 < 0) ? err0 : FFMIN(err1, 0);
892 }
893
894 #define SPECIFIER_OPT_FMT_str  "%s"
895 #define SPECIFIER_OPT_FMT_i    "%i"
896 #define SPECIFIER_OPT_FMT_i64  "%"PRId64
897 #define SPECIFIER_OPT_FMT_ui64 "%"PRIu64
898 #define SPECIFIER_OPT_FMT_f    "%f"
899 #define SPECIFIER_OPT_FMT_dbl  "%lf"
900
901 #define WARN_MULTIPLE_OPT_USAGE(name, type, so, st)\
902 {\
903     char namestr[128] = "";\
904     const char *spec = so->specifier && so->specifier[0] ? so->specifier : "";\
905     for (int _i = 0; opt_name_##name[_i]; _i++)\
906         av_strlcatf(namestr, sizeof(namestr), "-%s%s", opt_name_##name[_i], opt_name_##name[_i+1] ? (opt_name_##name[_i+2] ? ", " : " or ") : "");\
907     av_log(NULL, AV_LOG_WARNING, "Multiple %s options specified for stream %d, only the last option '-%s%s%s "SPECIFIER_OPT_FMT_##type"' will be used.\n",\
908            namestr, st->index, opt_name_##name[0], spec[0] ? ":" : "", spec, so->u.type);\
909 }
910
911 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
912 {\
913     int _ret, _matches = 0;\
914     SpecifierOpt *so;\
915     for (int _i = 0; _i < o->nb_ ## name; _i++) {\
916         char *spec = o->name[_i].specifier;\
917         if ((_ret = check_stream_specifier(fmtctx, st, spec)) > 0) {\
918             outvar = o->name[_i].u.type;\
919             so = &o->name[_i];\
920             _matches++;\
921         } else if (_ret < 0)\
922             return _ret;\
923     }\
924     if (_matches > 1)\
925        WARN_MULTIPLE_OPT_USAGE(name, type, so, st);\
926 }
927
928 #define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)\
929 {\
930     int i;\
931     for (i = 0; i < o->nb_ ## name; i++) {\
932         char *spec = o->name[i].specifier;\
933         if (!strcmp(spec, mediatype))\
934             outvar = o->name[i].u.type;\
935     }\
936 }
937
938 extern const char * const opt_name_codec_names[];
939 extern const char * const opt_name_codec_tags[];
940 extern const char * const opt_name_frame_rates[];
941 #if FFMPEG_OPT_TOP
942 extern const char * const opt_name_top_field_first[];
943 #endif
944
945 static inline void pkt_move(void *dst, void *src)
946 {
947     av_packet_move_ref(dst, src);
948 }
949
950 static inline void frame_move(void *dst, void *src)
951 {
952     av_frame_move_ref(dst, src);
953 }
954
955 #endif /* FFTOOLS_FFMPEG_H */