]> git.sesse.net Git - ffmpeg/blob - fftools/ffmpeg.h
Merge commit '508378556631dc18d32247b4a4e35703758e1ca9'
[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 #if HAVE_PTHREADS
29 #include <pthread.h>
30 #endif
31
32 #include "cmdutils.h"
33
34 #include "libavformat/avformat.h"
35 #include "libavformat/avio.h"
36
37 #include "libavcodec/avcodec.h"
38
39 #include "libavfilter/avfilter.h"
40
41 #include "libavutil/avutil.h"
42 #include "libavutil/dict.h"
43 #include "libavutil/eval.h"
44 #include "libavutil/fifo.h"
45 #include "libavutil/hwcontext.h"
46 #include "libavutil/pixfmt.h"
47 #include "libavutil/rational.h"
48 #include "libavutil/threadmessage.h"
49
50 #include "libswresample/swresample.h"
51
52 #define VSYNC_AUTO       -1
53 #define VSYNC_PASSTHROUGH 0
54 #define VSYNC_CFR         1
55 #define VSYNC_VFR         2
56 #define VSYNC_VSCFR       0xfe
57 #define VSYNC_DROP        0xff
58
59 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
60
61 enum HWAccelID {
62     HWACCEL_NONE = 0,
63     HWACCEL_AUTO,
64     HWACCEL_GENERIC,
65     HWACCEL_VIDEOTOOLBOX,
66     HWACCEL_QSV,
67     HWACCEL_CUVID,
68 };
69
70 typedef struct HWAccel {
71     const char *name;
72     int (*init)(AVCodecContext *s);
73     enum HWAccelID id;
74     enum AVPixelFormat pix_fmt;
75 } HWAccel;
76
77 typedef struct HWDevice {
78     char *name;
79     enum AVHWDeviceType type;
80     AVBufferRef *device_ref;
81 } HWDevice;
82
83 /* select an input stream for an output stream */
84 typedef struct StreamMap {
85     int disabled;           /* 1 is this mapping is disabled by a negative map */
86     int file_index;
87     int stream_index;
88     int sync_file_index;
89     int sync_stream_index;
90     char *linklabel;       /* name of an output link, for mapping lavfi outputs */
91 } StreamMap;
92
93 typedef struct {
94     int  file_idx,  stream_idx,  channel_idx; // input
95     int ofile_idx, ostream_idx;               // output
96 } AudioChannelMap;
97
98 typedef struct OptionsContext {
99     OptionGroup *g;
100
101     /* input/output options */
102     int64_t start_time;
103     int64_t start_time_eof;
104     int seek_timestamp;
105     const char *format;
106
107     SpecifierOpt *codec_names;
108     int        nb_codec_names;
109     SpecifierOpt *audio_channels;
110     int        nb_audio_channels;
111     SpecifierOpt *audio_sample_rate;
112     int        nb_audio_sample_rate;
113     SpecifierOpt *frame_rates;
114     int        nb_frame_rates;
115     SpecifierOpt *frame_sizes;
116     int        nb_frame_sizes;
117     SpecifierOpt *frame_pix_fmts;
118     int        nb_frame_pix_fmts;
119
120     /* input options */
121     int64_t input_ts_offset;
122     int loop;
123     int rate_emu;
124     int accurate_seek;
125     int thread_queue_size;
126
127     SpecifierOpt *ts_scale;
128     int        nb_ts_scale;
129     SpecifierOpt *dump_attachment;
130     int        nb_dump_attachment;
131     SpecifierOpt *hwaccels;
132     int        nb_hwaccels;
133     SpecifierOpt *hwaccel_devices;
134     int        nb_hwaccel_devices;
135     SpecifierOpt *hwaccel_output_formats;
136     int        nb_hwaccel_output_formats;
137     SpecifierOpt *autorotate;
138     int        nb_autorotate;
139
140     /* output options */
141     StreamMap *stream_maps;
142     int     nb_stream_maps;
143     AudioChannelMap *audio_channel_maps; /* one info entry per -map_channel */
144     int           nb_audio_channel_maps; /* number of (valid) -map_channel settings */
145     int metadata_global_manual;
146     int metadata_streams_manual;
147     int metadata_chapters_manual;
148     const char **attachments;
149     int       nb_attachments;
150
151     int chapters_input_file;
152
153     int64_t recording_time;
154     int64_t stop_time;
155     uint64_t limit_filesize;
156     float mux_preload;
157     float mux_max_delay;
158     int shortest;
159     int bitexact;
160
161     int video_disable;
162     int audio_disable;
163     int subtitle_disable;
164     int data_disable;
165
166     /* indexed by output file stream index */
167     int   *streamid_map;
168     int nb_streamid_map;
169
170     SpecifierOpt *metadata;
171     int        nb_metadata;
172     SpecifierOpt *max_frames;
173     int        nb_max_frames;
174     SpecifierOpt *bitstream_filters;
175     int        nb_bitstream_filters;
176     SpecifierOpt *codec_tags;
177     int        nb_codec_tags;
178     SpecifierOpt *sample_fmts;
179     int        nb_sample_fmts;
180     SpecifierOpt *qscale;
181     int        nb_qscale;
182     SpecifierOpt *forced_key_frames;
183     int        nb_forced_key_frames;
184     SpecifierOpt *force_fps;
185     int        nb_force_fps;
186     SpecifierOpt *frame_aspect_ratios;
187     int        nb_frame_aspect_ratios;
188     SpecifierOpt *rc_overrides;
189     int        nb_rc_overrides;
190     SpecifierOpt *intra_matrices;
191     int        nb_intra_matrices;
192     SpecifierOpt *inter_matrices;
193     int        nb_inter_matrices;
194     SpecifierOpt *chroma_intra_matrices;
195     int        nb_chroma_intra_matrices;
196     SpecifierOpt *top_field_first;
197     int        nb_top_field_first;
198     SpecifierOpt *metadata_map;
199     int        nb_metadata_map;
200     SpecifierOpt *presets;
201     int        nb_presets;
202     SpecifierOpt *copy_initial_nonkeyframes;
203     int        nb_copy_initial_nonkeyframes;
204     SpecifierOpt *copy_prior_start;
205     int        nb_copy_prior_start;
206     SpecifierOpt *filters;
207     int        nb_filters;
208     SpecifierOpt *filter_scripts;
209     int        nb_filter_scripts;
210     SpecifierOpt *reinit_filters;
211     int        nb_reinit_filters;
212     SpecifierOpt *fix_sub_duration;
213     int        nb_fix_sub_duration;
214     SpecifierOpt *canvas_sizes;
215     int        nb_canvas_sizes;
216     SpecifierOpt *pass;
217     int        nb_pass;
218     SpecifierOpt *passlogfiles;
219     int        nb_passlogfiles;
220     SpecifierOpt *max_muxing_queue_size;
221     int        nb_max_muxing_queue_size;
222     SpecifierOpt *guess_layout_max;
223     int        nb_guess_layout_max;
224     SpecifierOpt *apad;
225     int        nb_apad;
226     SpecifierOpt *discard;
227     int        nb_discard;
228     SpecifierOpt *disposition;
229     int        nb_disposition;
230     SpecifierOpt *program;
231     int        nb_program;
232     SpecifierOpt *time_bases;
233     int        nb_time_bases;
234     SpecifierOpt *enc_time_bases;
235     int        nb_enc_time_bases;
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     } sub2video;
356
357     int dr1;
358
359     /* decoded data from this stream goes into all those filters
360      * currently video and audio only */
361     InputFilter **filters;
362     int        nb_filters;
363
364     int reinit_filters;
365
366     /* hwaccel options */
367     enum HWAccelID hwaccel_id;
368     enum AVHWDeviceType hwaccel_device_type;
369     char  *hwaccel_device;
370     enum AVPixelFormat hwaccel_output_format;
371
372     /* hwaccel context */
373     void  *hwaccel_ctx;
374     void (*hwaccel_uninit)(AVCodecContext *s);
375     int  (*hwaccel_get_buffer)(AVCodecContext *s, AVFrame *frame, int flags);
376     int  (*hwaccel_retrieve_data)(AVCodecContext *s, AVFrame *frame);
377     enum AVPixelFormat hwaccel_pix_fmt;
378     enum AVPixelFormat hwaccel_retrieved_pix_fmt;
379     AVBufferRef *hw_frames_ctx;
380
381     /* stats */
382     // combined size of all the packets read
383     uint64_t data_size;
384     /* number of packets successfully read for this stream */
385     uint64_t nb_packets;
386     // number of frames/samples retrieved from the decoder
387     uint64_t frames_decoded;
388     uint64_t samples_decoded;
389
390     int64_t *dts_buffer;
391     int nb_dts_buffer;
392
393     int got_output;
394 } InputStream;
395
396 typedef struct InputFile {
397     AVFormatContext *ctx;
398     int eof_reached;      /* true if eof reached */
399     int eagain;           /* true if last read attempt returned EAGAIN */
400     int ist_index;        /* index of first stream in input_streams */
401     int loop;             /* set number of times input stream should be looped */
402     int64_t duration;     /* actual duration of the longest stream in a file
403                              at the moment when looping happens */
404     AVRational time_base; /* time base of the duration */
405     int64_t input_ts_offset;
406
407     int64_t ts_offset;
408     int64_t last_ts;
409     int64_t start_time;   /* user-specified start time in AV_TIME_BASE or AV_NOPTS_VALUE */
410     int seek_timestamp;
411     int64_t recording_time;
412     int nb_streams;       /* number of stream that ffmpeg is aware of; may be different
413                              from ctx.nb_streams if new streams appear during av_read_frame() */
414     int nb_streams_warn;  /* number of streams that the user was warned of */
415     int rate_emu;
416     int accurate_seek;
417
418 #if HAVE_PTHREADS
419     AVThreadMessageQueue *in_thread_queue;
420     pthread_t thread;           /* thread reading from this file */
421     int non_blocking;           /* reading packets from the thread should not block */
422     int joined;                 /* the thread has been joined */
423     int thread_queue_size;      /* maximum number of queued packets */
424 #endif
425 } InputFile;
426
427 enum forced_keyframes_const {
428     FKF_N,
429     FKF_N_FORCED,
430     FKF_PREV_FORCED_N,
431     FKF_PREV_FORCED_T,
432     FKF_T,
433     FKF_NB
434 };
435
436 #define ABORT_ON_FLAG_EMPTY_OUTPUT (1 <<  0)
437
438 extern const char *const forced_keyframes_const_names[];
439
440 typedef enum {
441     ENCODER_FINISHED = 1,
442     MUXER_FINISHED = 2,
443 } OSTFinished ;
444
445 typedef struct OutputStream {
446     int file_index;          /* file index */
447     int index;               /* stream index in the output file */
448     int source_index;        /* InputStream index */
449     AVStream *st;            /* stream in the output file */
450     int encoding_needed;     /* true if encoding needed for this stream */
451     int frame_number;
452     /* input pts and corresponding output pts
453        for A/V sync */
454     struct InputStream *sync_ist; /* input stream to sync against */
455     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
456     /* pts of the first frame encoded for this stream, used for limiting
457      * recording time */
458     int64_t first_pts;
459     /* dts of the last packet sent to the muxer */
460     int64_t last_mux_dts;
461     // the timebase of the packets sent to the muxer
462     AVRational mux_timebase;
463     AVRational enc_timebase;
464
465     int                    nb_bitstream_filters;
466     AVBSFContext            **bsf_ctx;
467
468     AVCodecContext *enc_ctx;
469     AVCodecParameters *ref_par; /* associated input codec parameters with encoders options applied */
470     AVCodec *enc;
471     int64_t max_frames;
472     AVFrame *filtered_frame;
473     AVFrame *last_frame;
474     int last_dropped;
475     int last_nb0_frames[3];
476
477     void  *hwaccel_ctx;
478
479     /* video only */
480     AVRational frame_rate;
481     int is_cfr;
482     int force_fps;
483     int top_field_first;
484     int rotate_overridden;
485     double rotate_override_value;
486
487     AVRational frame_aspect_ratio;
488
489     /* forced key frames */
490     int64_t *forced_kf_pts;
491     int forced_kf_count;
492     int forced_kf_index;
493     char *forced_keyframes;
494     AVExpr *forced_keyframes_pexpr;
495     double forced_keyframes_expr_const_values[FKF_NB];
496
497     /* audio only */
498     int *audio_channels_map;             /* list of the channels id to pick from the source stream */
499     int audio_channels_mapped;           /* number of channels in audio_channels_map */
500
501     char *logfile_prefix;
502     FILE *logfile;
503
504     OutputFilter *filter;
505     char *avfilter;
506     char *filters;         ///< filtergraph associated to the -filter option
507     char *filters_script;  ///< filtergraph script associated to the -filter_script option
508
509     AVDictionary *encoder_opts;
510     AVDictionary *sws_dict;
511     AVDictionary *swr_opts;
512     AVDictionary *resample_opts;
513     char *apad;
514     OSTFinished finished;        /* no more packets should be written for this stream */
515     int unavailable;                     /* true if the steram is unavailable (possibly temporarily) */
516     int stream_copy;
517
518     // init_output_stream() has been called for this stream
519     // The encoder and the bitstream filters have been initialized and the stream
520     // parameters are set in the AVStream.
521     int initialized;
522
523     int inputs_done;
524
525     const char *attachment_filename;
526     int copy_initial_nonkeyframes;
527     int copy_prior_start;
528     char *disposition;
529
530     int keep_pix_fmt;
531
532     AVCodecParserContext *parser;
533     AVCodecContext       *parser_avctx;
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     /* packet picture type */
553     int pict_type;
554
555     /* frame encode sum of squared error values */
556     int64_t error[4];
557 } OutputStream;
558
559 typedef struct OutputFile {
560     AVFormatContext *ctx;
561     AVDictionary *opts;
562     int ost_index;       /* index of the first stream in output_streams */
563     int64_t recording_time;  ///< desired length of the resulting file in microseconds == AV_TIME_BASE units
564     int64_t start_time;      ///< start time in microseconds == AV_TIME_BASE units
565     uint64_t limit_filesize; /* filesize limit expressed in bytes */
566
567     int shortest;
568
569     int header_written;
570 } OutputFile;
571
572 extern InputStream **input_streams;
573 extern int        nb_input_streams;
574 extern InputFile   **input_files;
575 extern int        nb_input_files;
576
577 extern OutputStream **output_streams;
578 extern int         nb_output_streams;
579 extern OutputFile   **output_files;
580 extern int         nb_output_files;
581
582 extern FilterGraph **filtergraphs;
583 extern int        nb_filtergraphs;
584
585 extern char *vstats_filename;
586 extern char *sdp_filename;
587
588 extern float audio_drift_threshold;
589 extern float dts_delta_threshold;
590 extern float dts_error_threshold;
591
592 extern int audio_volume;
593 extern int audio_sync_method;
594 extern int video_sync_method;
595 extern float frame_drop_threshold;
596 extern int do_benchmark;
597 extern int do_benchmark_all;
598 extern int do_deinterlace;
599 extern int do_hex_dump;
600 extern int do_pkt_dump;
601 extern int copy_ts;
602 extern int start_at_zero;
603 extern int copy_tb;
604 extern int debug_ts;
605 extern int exit_on_error;
606 extern int abort_on_flags;
607 extern int print_stats;
608 extern int qp_hist;
609 extern int stdin_interaction;
610 extern int frame_bits_per_raw_sample;
611 extern AVIOContext *progress_avio;
612 extern float max_error_rate;
613 extern char *videotoolbox_pixfmt;
614
615 extern int filter_nbthreads;
616 extern int filter_complex_nbthreads;
617 extern int vstats_version;
618
619 extern const AVIOInterruptCB int_cb;
620
621 extern const OptionDef options[];
622 extern const HWAccel hwaccels[];
623 extern AVBufferRef *hw_device_ctx;
624 #if CONFIG_QSV
625 extern char *qsv_device;
626 #endif
627 extern HWDevice *filter_hw_device;
628
629
630 void term_init(void);
631 void term_exit(void);
632
633 void reset_options(OptionsContext *o, int is_input);
634 void show_usage(void);
635
636 void opt_output_file(void *optctx, const char *filename);
637
638 void remove_avoptions(AVDictionary **a, AVDictionary *b);
639 void assert_avoptions(AVDictionary *m);
640
641 int guess_input_channel_layout(InputStream *ist);
642
643 enum AVPixelFormat choose_pixel_fmt(AVStream *st, AVCodecContext *avctx, AVCodec *codec, enum AVPixelFormat target);
644 void choose_sample_fmt(AVStream *st, AVCodec *codec);
645
646 int configure_filtergraph(FilterGraph *fg);
647 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out);
648 void check_filter_outputs(void);
649 int ist_in_filtergraph(FilterGraph *fg, InputStream *ist);
650 int filtergraph_is_simple(FilterGraph *fg);
651 int init_simple_filtergraph(InputStream *ist, OutputStream *ost);
652 int init_complex_filtergraph(FilterGraph *fg);
653
654 void sub2video_update(InputStream *ist, AVSubtitle *sub);
655
656 int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame);
657
658 int ffmpeg_parse_options(int argc, char **argv);
659
660 int videotoolbox_init(AVCodecContext *s);
661 int qsv_init(AVCodecContext *s);
662 int cuvid_init(AVCodecContext *s);
663
664 HWDevice *hw_device_get_by_name(const char *name);
665 int hw_device_init_from_string(const char *arg, HWDevice **dev);
666 void hw_device_free_all(void);
667
668 int hw_device_setup_for_decode(InputStream *ist);
669 int hw_device_setup_for_encode(OutputStream *ost);
670
671 int hwaccel_decode_init(AVCodecContext *avctx);
672
673 #endif /* FFTOOLS_FFMPEG_H */