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