You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

683 lines
20KB

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