]> git.sesse.net Git - ffmpeg/blob - fftools/ffmpeg.h
ffmpeg: add option stats_period
[ffmpeg] / 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 <stdint.h>
25 #include <stdio.h>
26 #include <signal.h>
27
28 #include "cmdutils.h"
29
30 #include "libavformat/avformat.h"
31 #include "libavformat/avio.h"
32
33 #include "libavcodec/avcodec.h"
34
35 #include "libavfilter/avfilter.h"
36
37 #include "libavutil/avutil.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/eval.h"
40 #include "libavutil/fifo.h"
41 #include "libavutil/hwcontext.h"
42 #include "libavutil/pixfmt.h"
43 #include "libavutil/rational.h"
44 #include "libavutil/thread.h"
45 #include "libavutil/threadmessage.h"
46
47 #include "libswresample/swresample.h"
48
49 #define VSYNC_AUTO       -1
50 #define VSYNC_PASSTHROUGH 0
51 #define VSYNC_CFR         1
52 #define VSYNC_VFR         2
53 #define VSYNC_VSCFR       0xfe
54 #define VSYNC_DROP        0xff
55
56 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
57
58 enum HWAccelID {
59     HWACCEL_NONE = 0,
60     HWACCEL_AUTO,
61     HWACCEL_GENERIC,
62     HWACCEL_VIDEOTOOLBOX,
63     HWACCEL_QSV,
64 };
65
66 typedef struct HWAccel {
67     const char *name;
68     int (*init)(AVCodecContext *s);
69     enum HWAccelID id;
70     enum AVPixelFormat pix_fmt;
71 } HWAccel;
72
73 typedef struct HWDevice {
74     const char *name;
75     enum AVHWDeviceType type;
76     AVBufferRef *device_ref;
77 } HWDevice;
78
79 /* select an input stream for an output stream */
80 typedef struct StreamMap {
81     int disabled;           /* 1 is this mapping is disabled by a negative map */
82     int file_index;
83     int stream_index;
84     int sync_file_index;
85     int sync_stream_index;
86     char *linklabel;       /* name of an output link, for mapping lavfi outputs */
87 } StreamMap;
88
89 typedef struct {
90     int  file_idx,  stream_idx,  channel_idx; // input
91     int ofile_idx, ostream_idx;               // output
92 } AudioChannelMap;
93
94 typedef struct OptionsContext {
95     OptionGroup *g;
96
97     /* input/output options */
98     int64_t start_time;
99     int64_t start_time_eof;
100     int seek_timestamp;
101     const char *format;
102
103     SpecifierOpt *codec_names;
104     int        nb_codec_names;
105     SpecifierOpt *audio_channels;
106     int        nb_audio_channels;
107     SpecifierOpt *audio_sample_rate;
108     int        nb_audio_sample_rate;
109     SpecifierOpt *frame_rates;
110     int        nb_frame_rates;
111     SpecifierOpt *frame_sizes;
112     int        nb_frame_sizes;
113     SpecifierOpt *frame_pix_fmts;
114     int        nb_frame_pix_fmts;
115
116     /* input options */
117     int64_t input_ts_offset;
118     int loop;
119     int rate_emu;
120     int accurate_seek;
121     int thread_queue_size;
122
123     SpecifierOpt *ts_scale;
124     int        nb_ts_scale;
125     SpecifierOpt *dump_attachment;
126     int        nb_dump_attachment;
127     SpecifierOpt *hwaccels;
128     int        nb_hwaccels;
129     SpecifierOpt *hwaccel_devices;
130     int        nb_hwaccel_devices;
131     SpecifierOpt *hwaccel_output_formats;
132     int        nb_hwaccel_output_formats;
133     SpecifierOpt *autorotate;
134     int        nb_autorotate;
135
136     /* output options */
137     StreamMap *stream_maps;
138     int     nb_stream_maps;
139     AudioChannelMap *audio_channel_maps; /* one info entry per -map_channel */
140     int           nb_audio_channel_maps; /* number of (valid) -map_channel settings */
141     int metadata_global_manual;
142     int metadata_streams_manual;
143     int metadata_chapters_manual;
144     const char **attachments;
145     int       nb_attachments;
146
147     int chapters_input_file;
148
149     int64_t recording_time;
150     int64_t stop_time;
151     uint64_t limit_filesize;
152     float mux_preload;
153     float mux_max_delay;
154     int shortest;
155     int bitexact;
156
157     int video_disable;
158     int audio_disable;
159     int subtitle_disable;
160     int data_disable;
161
162     /* indexed by output file stream index */
163     int   *streamid_map;
164     int nb_streamid_map;
165
166     SpecifierOpt *metadata;
167     int        nb_metadata;
168     SpecifierOpt *max_frames;
169     int        nb_max_frames;
170     SpecifierOpt *bitstream_filters;
171     int        nb_bitstream_filters;
172     SpecifierOpt *codec_tags;
173     int        nb_codec_tags;
174     SpecifierOpt *sample_fmts;
175     int        nb_sample_fmts;
176     SpecifierOpt *qscale;
177     int        nb_qscale;
178     SpecifierOpt *forced_key_frames;
179     int        nb_forced_key_frames;
180     SpecifierOpt *force_fps;
181     int        nb_force_fps;
182     SpecifierOpt *frame_aspect_ratios;
183     int        nb_frame_aspect_ratios;
184     SpecifierOpt *rc_overrides;
185     int        nb_rc_overrides;
186     SpecifierOpt *intra_matrices;
187     int        nb_intra_matrices;
188     SpecifierOpt *inter_matrices;
189     int        nb_inter_matrices;
190     SpecifierOpt *chroma_intra_matrices;
191     int        nb_chroma_intra_matrices;
192     SpecifierOpt *top_field_first;
193     int        nb_top_field_first;
194     SpecifierOpt *metadata_map;
195     int        nb_metadata_map;
196     SpecifierOpt *presets;
197     int        nb_presets;
198     SpecifierOpt *copy_initial_nonkeyframes;
199     int        nb_copy_initial_nonkeyframes;
200     SpecifierOpt *copy_prior_start;
201     int        nb_copy_prior_start;
202     SpecifierOpt *filters;
203     int        nb_filters;
204     SpecifierOpt *filter_scripts;
205     int        nb_filter_scripts;
206     SpecifierOpt *reinit_filters;
207     int        nb_reinit_filters;
208     SpecifierOpt *fix_sub_duration;
209     int        nb_fix_sub_duration;
210     SpecifierOpt *canvas_sizes;
211     int        nb_canvas_sizes;
212     SpecifierOpt *pass;
213     int        nb_pass;
214     SpecifierOpt *passlogfiles;
215     int        nb_passlogfiles;
216     SpecifierOpt *max_muxing_queue_size;
217     int        nb_max_muxing_queue_size;
218     SpecifierOpt *muxing_queue_data_threshold;
219     int        nb_muxing_queue_data_threshold;
220     SpecifierOpt *guess_layout_max;
221     int        nb_guess_layout_max;
222     SpecifierOpt *apad;
223     int        nb_apad;
224     SpecifierOpt *discard;
225     int        nb_discard;
226     SpecifierOpt *disposition;
227     int        nb_disposition;
228     SpecifierOpt *program;
229     int        nb_program;
230     SpecifierOpt *time_bases;
231     int        nb_time_bases;
232     SpecifierOpt *enc_time_bases;
233     int        nb_enc_time_bases;
234     SpecifierOpt *autoscale;
235     int        nb_autoscale;
236 } OptionsContext;
237
238 typedef struct InputFilter {
239     AVFilterContext    *filter;
240     struct InputStream *ist;
241     struct FilterGraph *graph;
242     uint8_t            *name;
243     enum AVMediaType    type;   // AVMEDIA_TYPE_SUBTITLE for sub2video
244
245     AVFifoBuffer *frame_queue;
246
247     // parameters configured for this input
248     int format;
249
250     int width, height;
251     AVRational sample_aspect_ratio;
252
253     int sample_rate;
254     int channels;
255     uint64_t channel_layout;
256
257     AVBufferRef *hw_frames_ctx;
258
259     int eof;
260 } InputFilter;
261
262 typedef struct OutputFilter {
263     AVFilterContext     *filter;
264     struct OutputStream *ost;
265     struct FilterGraph  *graph;
266     uint8_t             *name;
267
268     /* temporary storage until stream maps are processed */
269     AVFilterInOut       *out_tmp;
270     enum AVMediaType     type;
271
272     /* desired output stream properties */
273     int width, height;
274     AVRational frame_rate;
275     int format;
276     int sample_rate;
277     uint64_t channel_layout;
278
279     // those are only set if no format is specified and the encoder gives us multiple options
280     int *formats;
281     uint64_t *channel_layouts;
282     int *sample_rates;
283 } OutputFilter;
284
285 typedef struct FilterGraph {
286     int            index;
287     const char    *graph_desc;
288
289     AVFilterGraph *graph;
290     int reconfiguration;
291
292     InputFilter   **inputs;
293     int          nb_inputs;
294     OutputFilter **outputs;
295     int         nb_outputs;
296 } FilterGraph;
297
298 typedef struct InputStream {
299     int file_index;
300     AVStream *st;
301     int discard;             /* true if stream data should be discarded */
302     int user_set_discard;
303     int decoding_needed;     /* non zero if the packets must be decoded in 'raw_fifo', see DECODING_FOR_* */
304 #define DECODING_FOR_OST    1
305 #define DECODING_FOR_FILTER 2
306
307     AVCodecContext *dec_ctx;
308     AVCodec *dec;
309     AVFrame *decoded_frame;
310     AVFrame *filter_frame; /* a ref of decoded_frame, to be sent to filters */
311
312     int64_t       start;     /* time when read started */
313     /* predicted dts of the next packet read for this stream or (when there are
314      * several frames in a packet) of the next frame in current packet (in AV_TIME_BASE units) */
315     int64_t       next_dts;
316     int64_t       dts;       ///< dts of the last packet read for this stream (in AV_TIME_BASE units)
317
318     int64_t       next_pts;  ///< synthetic pts for the next decode frame (in AV_TIME_BASE units)
319     int64_t       pts;       ///< current pts of the decoded frame  (in AV_TIME_BASE units)
320     int           wrap_correction_done;
321
322     int64_t filter_in_rescale_delta_last;
323
324     int64_t min_pts; /* pts with the smallest value in a current stream */
325     int64_t max_pts; /* pts with the higher value in a current stream */
326
327     // when forcing constant input framerate through -r,
328     // this contains the pts that will be given to the next decoded frame
329     int64_t cfr_next_pts;
330
331     int64_t nb_samples; /* number of samples in the last decoded audio frame before looping */
332
333     double ts_scale;
334     int saw_first_ts;
335     AVDictionary *decoder_opts;
336     AVRational framerate;               /* framerate forced with -r */
337     int top_field_first;
338     int guess_layout_max;
339
340     int autorotate;
341
342     int fix_sub_duration;
343     struct { /* previous decoded subtitle and related variables */
344         int got_output;
345         int ret;
346         AVSubtitle subtitle;
347     } prev_sub;
348
349     struct sub2video {
350         int64_t last_pts;
351         int64_t end_pts;
352         AVFifoBuffer *sub_queue;    ///< queue of AVSubtitle* before filter init
353         AVFrame *frame;
354         int w, h;
355         unsigned int initialize; ///< marks if sub2video_update should force an initialization
356     } sub2video;
357
358     int dr1;
359
360     /* decoded data from this stream goes into all those filters
361      * currently video and audio only */
362     InputFilter **filters;
363     int        nb_filters;
364
365     int reinit_filters;
366
367     /* hwaccel options */
368     enum HWAccelID hwaccel_id;
369     enum AVHWDeviceType hwaccel_device_type;
370     char  *hwaccel_device;
371     enum AVPixelFormat hwaccel_output_format;
372
373     /* hwaccel context */
374     void  *hwaccel_ctx;
375     void (*hwaccel_uninit)(AVCodecContext *s);
376     int  (*hwaccel_get_buffer)(AVCodecContext *s, AVFrame *frame, int flags);
377     int  (*hwaccel_retrieve_data)(AVCodecContext *s, AVFrame *frame);
378     enum AVPixelFormat hwaccel_pix_fmt;
379     enum AVPixelFormat hwaccel_retrieved_pix_fmt;
380     AVBufferRef *hw_frames_ctx;
381
382     /* stats */
383     // combined size of all the packets read
384     uint64_t data_size;
385     /* number of packets successfully read for this stream */
386     uint64_t nb_packets;
387     // number of frames/samples retrieved from the decoder
388     uint64_t frames_decoded;
389     uint64_t samples_decoded;
390
391     int64_t *dts_buffer;
392     int nb_dts_buffer;
393
394     int got_output;
395 } InputStream;
396
397 typedef struct InputFile {
398     AVFormatContext *ctx;
399     int eof_reached;      /* true if eof reached */
400     int eagain;           /* true if last read attempt returned EAGAIN */
401     int ist_index;        /* index of first stream in input_streams */
402     int loop;             /* set number of times input stream should be looped */
403     int64_t duration;     /* actual duration of the longest stream in a file
404                              at the moment when looping happens */
405     AVRational time_base; /* time base of the duration */
406     int64_t input_ts_offset;
407
408     int64_t ts_offset;
409     int64_t last_ts;
410     int64_t start_time;   /* user-specified start time in AV_TIME_BASE or AV_NOPTS_VALUE */
411     int seek_timestamp;
412     int64_t recording_time;
413     int nb_streams;       /* number of stream that ffmpeg is aware of; may be different
414                              from ctx.nb_streams if new streams appear during av_read_frame() */
415     int nb_streams_warn;  /* number of streams that the user was warned of */
416     int rate_emu;
417     int accurate_seek;
418
419 #if HAVE_THREADS
420     AVThreadMessageQueue *in_thread_queue;
421     pthread_t thread;           /* thread reading from this file */
422     int non_blocking;           /* reading packets from the thread should not block */
423     int joined;                 /* the thread has been joined */
424     int thread_queue_size;      /* maximum number of queued packets */
425 #endif
426 } InputFile;
427
428 enum forced_keyframes_const {
429     FKF_N,
430     FKF_N_FORCED,
431     FKF_PREV_FORCED_N,
432     FKF_PREV_FORCED_T,
433     FKF_T,
434     FKF_NB
435 };
436
437 #define ABORT_ON_FLAG_EMPTY_OUTPUT        (1 <<  0)
438 #define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM (1 <<  1)
439
440 extern const char *const forced_keyframes_const_names[];
441
442 typedef enum {
443     ENCODER_FINISHED = 1,
444     MUXER_FINISHED = 2,
445 } OSTFinished ;
446
447 typedef struct OutputStream {
448     int file_index;          /* file index */
449     int index;               /* stream index in the output file */
450     int source_index;        /* InputStream index */
451     AVStream *st;            /* stream in the output file */
452     int encoding_needed;     /* true if encoding needed for this stream */
453     int frame_number;
454     /* input pts and corresponding output pts
455        for A/V sync */
456     struct InputStream *sync_ist; /* input stream to sync against */
457     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
458     /* pts of the first frame encoded for this stream, used for limiting
459      * recording time */
460     int64_t first_pts;
461     /* dts of the last packet sent to the muxer */
462     int64_t last_mux_dts;
463     // the timebase of the packets sent to the muxer
464     AVRational mux_timebase;
465     AVRational enc_timebase;
466
467     AVBSFContext            *bsf_ctx;
468
469     AVCodecContext *enc_ctx;
470     AVCodecParameters *ref_par; /* associated input codec parameters with encoders options applied */
471     AVCodec *enc;
472     int64_t max_frames;
473     AVFrame *filtered_frame;
474     AVFrame *last_frame;
475     int last_dropped;
476     int last_nb0_frames[3];
477
478     void  *hwaccel_ctx;
479
480     /* video only */
481     AVRational frame_rate;
482     int is_cfr;
483     int force_fps;
484     int top_field_first;
485     int rotate_overridden;
486     int autoscale;
487     double rotate_override_value;
488
489     AVRational frame_aspect_ratio;
490
491     /* forced key frames */
492     int64_t forced_kf_ref_pts;
493     int64_t *forced_kf_pts;
494     int forced_kf_count;
495     int forced_kf_index;
496     char *forced_keyframes;
497     AVExpr *forced_keyframes_pexpr;
498     double forced_keyframes_expr_const_values[FKF_NB];
499
500     /* audio only */
501     int *audio_channels_map;             /* list of the channels id to pick from the source stream */
502     int audio_channels_mapped;           /* number of channels in audio_channels_map */
503
504     char *logfile_prefix;
505     FILE *logfile;
506
507     OutputFilter *filter;
508     char *avfilter;
509     char *filters;         ///< filtergraph associated to the -filter option
510     char *filters_script;  ///< filtergraph script associated to the -filter_script option
511
512     AVDictionary *encoder_opts;
513     AVDictionary *sws_dict;
514     AVDictionary *swr_opts;
515     AVDictionary *resample_opts;
516     char *apad;
517     OSTFinished finished;        /* no more packets should be written for this stream */
518     int unavailable;                     /* true if the steram is unavailable (possibly temporarily) */
519     int stream_copy;
520
521     // init_output_stream() has been called for this stream
522     // The encoder and the bitstream filters have been initialized and the stream
523     // parameters are set in the AVStream.
524     int initialized;
525
526     int inputs_done;
527
528     const char *attachment_filename;
529     int copy_initial_nonkeyframes;
530     int copy_prior_start;
531     char *disposition;
532
533     int keep_pix_fmt;
534
535     /* stats */
536     // combined size of all the packets written
537     uint64_t data_size;
538     // number of packets send to the muxer
539     uint64_t packets_written;
540     // number of frames/samples sent to the encoder
541     uint64_t frames_encoded;
542     uint64_t samples_encoded;
543
544     /* packet quality factor */
545     int quality;
546
547     int max_muxing_queue_size;
548
549     /* the packets are buffered here until the muxer is ready to be initialized */
550     AVFifoBuffer *muxing_queue;
551
552     /*
553      * The size of the AVPackets' buffers in queue.
554      * Updated when a packet is either pushed or pulled from the queue.
555      */
556     size_t muxing_queue_data_size;
557
558     /* Threshold after which max_muxing_queue_size will be in effect */
559     size_t muxing_queue_data_threshold;
560
561     /* packet picture type */
562     int pict_type;
563
564     /* frame encode sum of squared error values */
565     int64_t error[4];
566 } OutputStream;
567
568 typedef struct OutputFile {
569     AVFormatContext *ctx;
570     AVDictionary *opts;
571     int ost_index;       /* index of the first stream in output_streams */
572     int64_t recording_time;  ///< desired length of the resulting file in microseconds == AV_TIME_BASE units
573     int64_t start_time;      ///< start time in microseconds == AV_TIME_BASE units
574     uint64_t limit_filesize; /* filesize limit expressed in bytes */
575
576     int shortest;
577
578     int header_written;
579 } OutputFile;
580
581 extern InputStream **input_streams;
582 extern int        nb_input_streams;
583 extern InputFile   **input_files;
584 extern int        nb_input_files;
585
586 extern OutputStream **output_streams;
587 extern int         nb_output_streams;
588 extern OutputFile   **output_files;
589 extern int         nb_output_files;
590
591 extern FilterGraph **filtergraphs;
592 extern int        nb_filtergraphs;
593
594 extern char *vstats_filename;
595 extern char *sdp_filename;
596
597 extern float audio_drift_threshold;
598 extern float dts_delta_threshold;
599 extern float dts_error_threshold;
600
601 extern int audio_volume;
602 extern int audio_sync_method;
603 extern int video_sync_method;
604 extern float frame_drop_threshold;
605 extern int do_benchmark;
606 extern int do_benchmark_all;
607 extern int do_deinterlace;
608 extern int do_hex_dump;
609 extern int do_pkt_dump;
610 extern int copy_ts;
611 extern int start_at_zero;
612 extern int copy_tb;
613 extern int debug_ts;
614 extern int exit_on_error;
615 extern int abort_on_flags;
616 extern int print_stats;
617 extern int64_t stats_period;
618 extern int qp_hist;
619 extern int stdin_interaction;
620 extern int frame_bits_per_raw_sample;
621 extern AVIOContext *progress_avio;
622 extern float max_error_rate;
623 extern char *videotoolbox_pixfmt;
624
625 extern int filter_nbthreads;
626 extern int filter_complex_nbthreads;
627 extern int vstats_version;
628 extern int auto_conversion_filters;
629
630 extern const AVIOInterruptCB int_cb;
631
632 extern const OptionDef options[];
633 extern const HWAccel hwaccels[];
634 #if CONFIG_QSV
635 extern char *qsv_device;
636 #endif
637 extern HWDevice *filter_hw_device;
638
639
640 void term_init(void);
641 void term_exit(void);
642
643 void reset_options(OptionsContext *o, int is_input);
644 void show_usage(void);
645
646 void opt_output_file(void *optctx, const char *filename);
647
648 void remove_avoptions(AVDictionary **a, AVDictionary *b);
649 void assert_avoptions(AVDictionary *m);
650
651 int guess_input_channel_layout(InputStream *ist);
652
653 enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodecContext *avctx,
654                                     const AVCodec *codec, enum AVPixelFormat target);
655 void choose_sample_fmt(AVStream *st, const AVCodec *codec);
656
657 int configure_filtergraph(FilterGraph *fg);
658 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out);
659 void check_filter_outputs(void);
660 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist);
661 int filtergraph_is_simple(FilterGraph *fg);
662 int init_simple_filtergraph(InputStream *ist, OutputStream *ost);
663 int init_complex_filtergraph(FilterGraph *fg);
664
665 void sub2video_update(InputStream *ist, int64_t heartbeat_pts, AVSubtitle *sub);
666
667 int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame);
668
669 int ffmpeg_parse_options(int argc, char **argv);
670
671 int videotoolbox_init(AVCodecContext *s);
672 int qsv_init(AVCodecContext *s);
673
674 HWDevice *hw_device_get_by_name(const char *name);
675 int hw_device_init_from_string(const char *arg, HWDevice **dev);
676 void hw_device_free_all(void);
677
678 int hw_device_setup_for_decode(InputStream *ist);
679 int hw_device_setup_for_encode(OutputStream *ost);
680 int hw_device_setup_for_filter(FilterGraph *fg);
681
682 int hwaccel_decode_init(AVCodecContext *avctx);
683
684 #endif /* FFTOOLS_FFMPEG_H */