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.

930 lines
40KB

  1. /*
  2. * Generic DCT based hybrid video encoder
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. * Copyright (c) 2002-2004 Michael Niedermayer
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * Libav is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * mpegvideo header.
  25. */
  26. #ifndef AVCODEC_MPEGVIDEO_H
  27. #define AVCODEC_MPEGVIDEO_H
  28. #include "avcodec.h"
  29. #include "dsputil.h"
  30. #include "error_resilience.h"
  31. #include "get_bits.h"
  32. #include "put_bits.h"
  33. #include "ratecontrol.h"
  34. #include "parser.h"
  35. #include "mpeg12data.h"
  36. #include "rl.h"
  37. #include "thread.h"
  38. #include "videodsp.h"
  39. #include "libavutil/opt.h"
  40. #define FRAME_SKIPPED 100 ///< return value for header parsers if frame is not coded
  41. enum OutputFormat {
  42. FMT_MPEG1,
  43. FMT_H261,
  44. FMT_H263,
  45. FMT_MJPEG,
  46. };
  47. #define MPEG_BUF_SIZE (16 * 1024)
  48. #define QMAT_SHIFT_MMX 16
  49. #define QMAT_SHIFT 22
  50. #define MAX_FCODE 7
  51. #define MAX_MV 2048
  52. #define MAX_THREADS 16
  53. #define MAX_PICTURE_COUNT 32
  54. #define ME_MAP_SIZE 64
  55. #define ME_MAP_SHIFT 3
  56. #define ME_MAP_MV_BITS 11
  57. #define MAX_MB_BYTES (30*16*16*3/8 + 120)
  58. #define INPLACE_OFFSET 16
  59. /* Start codes. */
  60. #define SEQ_END_CODE 0x000001b7
  61. #define SEQ_START_CODE 0x000001b3
  62. #define GOP_START_CODE 0x000001b8
  63. #define PICTURE_START_CODE 0x00000100
  64. #define SLICE_MIN_START_CODE 0x00000101
  65. #define SLICE_MAX_START_CODE 0x000001af
  66. #define EXT_START_CODE 0x000001b5
  67. #define USER_START_CODE 0x000001b2
  68. /**
  69. * Value of Picture.reference when Picture is not a reference picture, but
  70. * is held for delayed output.
  71. */
  72. #define DELAYED_PIC_REF 4
  73. struct MpegEncContext;
  74. /**
  75. * Picture.
  76. */
  77. typedef struct Picture{
  78. struct AVFrame f;
  79. ThreadFrame tf;
  80. AVBufferRef *qscale_table_buf;
  81. int8_t *qscale_table;
  82. AVBufferRef *motion_val_buf[2];
  83. int16_t (*motion_val[2])[2];
  84. AVBufferRef *mb_type_buf;
  85. uint32_t *mb_type;
  86. AVBufferRef *mbskip_table_buf;
  87. uint8_t *mbskip_table;
  88. AVBufferRef *ref_index_buf[2];
  89. int8_t *ref_index[2];
  90. AVBufferRef *mb_var_buf;
  91. uint16_t *mb_var; ///< Table for MB variances
  92. AVBufferRef *mc_mb_var_buf;
  93. uint16_t *mc_mb_var; ///< Table for motion compensated MB variances
  94. AVBufferRef *mb_mean_buf;
  95. uint8_t *mb_mean; ///< Table for MB luminance
  96. AVBufferRef *hwaccel_priv_buf;
  97. /**
  98. * hardware accelerator private data
  99. */
  100. void *hwaccel_picture_private;
  101. #define MB_TYPE_INTRA MB_TYPE_INTRA4x4 //default mb_type if there is just one type
  102. #define IS_INTRA4x4(a) ((a)&MB_TYPE_INTRA4x4)
  103. #define IS_INTRA16x16(a) ((a)&MB_TYPE_INTRA16x16)
  104. #define IS_PCM(a) ((a)&MB_TYPE_INTRA_PCM)
  105. #define IS_INTRA(a) ((a)&7)
  106. #define IS_INTER(a) ((a)&(MB_TYPE_16x16|MB_TYPE_16x8|MB_TYPE_8x16|MB_TYPE_8x8))
  107. #define IS_SKIP(a) ((a)&MB_TYPE_SKIP)
  108. #define IS_INTRA_PCM(a) ((a)&MB_TYPE_INTRA_PCM)
  109. #define IS_INTERLACED(a) ((a)&MB_TYPE_INTERLACED)
  110. #define IS_DIRECT(a) ((a)&MB_TYPE_DIRECT2)
  111. #define IS_GMC(a) ((a)&MB_TYPE_GMC)
  112. #define IS_16X16(a) ((a)&MB_TYPE_16x16)
  113. #define IS_16X8(a) ((a)&MB_TYPE_16x8)
  114. #define IS_8X16(a) ((a)&MB_TYPE_8x16)
  115. #define IS_8X8(a) ((a)&MB_TYPE_8x8)
  116. #define IS_SUB_8X8(a) ((a)&MB_TYPE_16x16) //note reused
  117. #define IS_SUB_8X4(a) ((a)&MB_TYPE_16x8) //note reused
  118. #define IS_SUB_4X8(a) ((a)&MB_TYPE_8x16) //note reused
  119. #define IS_SUB_4X4(a) ((a)&MB_TYPE_8x8) //note reused
  120. #define IS_ACPRED(a) ((a)&MB_TYPE_ACPRED)
  121. #define IS_QUANT(a) ((a)&MB_TYPE_QUANT)
  122. #define IS_DIR(a, part, list) ((a) & (MB_TYPE_P0L0<<((part)+2*(list))))
  123. #define USES_LIST(a, list) ((a) & ((MB_TYPE_P0L0|MB_TYPE_P1L0)<<(2*(list)))) ///< does this mb use listX, note does not work if subMBs
  124. #define HAS_CBP(a) ((a)&MB_TYPE_CBP)
  125. int field_poc[2]; ///< h264 top/bottom POC
  126. int poc; ///< h264 frame POC
  127. int frame_num; ///< h264 frame_num (raw frame_num from slice header)
  128. int mmco_reset; ///< h264 MMCO_RESET set this 1. Reordering code must not mix pictures before and after MMCO_RESET.
  129. int pic_id; /**< h264 pic_num (short -> no wrap version of pic_num,
  130. pic_num & max_pic_num; long -> long_pic_num) */
  131. int long_ref; ///< 1->long term reference 0->short term reference
  132. int ref_poc[2][2][32]; ///< h264 POCs of the frames used as reference (FIXME need per slice)
  133. int ref_count[2][2]; ///< number of entries in ref_poc (FIXME need per slice)
  134. int mbaff; ///< h264 1 -> MBAFF frame 0-> not MBAFF
  135. int field_picture; ///< whether or not the picture was encoded in separate fields
  136. int mb_var_sum; ///< sum of MB variance for current frame
  137. int mc_mb_var_sum; ///< motion compensated MB variance for current frame
  138. int b_frame_score; /* */
  139. int needs_realloc; ///< Picture needs to be reallocated (eg due to a frame size change)
  140. int reference;
  141. int shared;
  142. } Picture;
  143. /**
  144. * Motion estimation context.
  145. */
  146. typedef struct MotionEstContext{
  147. AVCodecContext *avctx;
  148. int skip; ///< set if ME is skipped for the current MB
  149. int co_located_mv[4][2]; ///< mv from last P-frame for direct mode ME
  150. int direct_basis_mv[4][2];
  151. uint8_t *scratchpad; ///< data area for the ME algo, so that the ME does not need to malloc/free
  152. uint8_t *best_mb;
  153. uint8_t *temp_mb[2];
  154. uint8_t *temp;
  155. int best_bits;
  156. uint32_t *map; ///< map to avoid duplicate evaluations
  157. uint32_t *score_map; ///< map to store the scores
  158. unsigned map_generation;
  159. int pre_penalty_factor;
  160. int penalty_factor; /**< an estimate of the bits required to
  161. code a given mv value, e.g. (1,0) takes
  162. more bits than (0,0). We have to
  163. estimate whether any reduction in
  164. residual is worth the extra bits. */
  165. int sub_penalty_factor;
  166. int mb_penalty_factor;
  167. int flags;
  168. int sub_flags;
  169. int mb_flags;
  170. int pre_pass; ///< = 1 for the pre pass
  171. int dia_size;
  172. int xmin;
  173. int xmax;
  174. int ymin;
  175. int ymax;
  176. int pred_x;
  177. int pred_y;
  178. uint8_t *src[4][4];
  179. uint8_t *ref[4][4];
  180. int stride;
  181. int uvstride;
  182. /* temp variables for picture complexity calculation */
  183. int mc_mb_var_sum_temp;
  184. int mb_var_sum_temp;
  185. int scene_change_score;
  186. /* cmp, chroma_cmp;*/
  187. op_pixels_func (*hpel_put)[4];
  188. op_pixels_func (*hpel_avg)[4];
  189. qpel_mc_func (*qpel_put)[16];
  190. qpel_mc_func (*qpel_avg)[16];
  191. uint8_t (*mv_penalty)[MAX_MV*2+1]; ///< amount of bits needed to encode a MV
  192. uint8_t *current_mv_penalty;
  193. int (*sub_motion_search)(struct MpegEncContext * s,
  194. int *mx_ptr, int *my_ptr, int dmin,
  195. int src_index, int ref_index,
  196. int size, int h);
  197. }MotionEstContext;
  198. /**
  199. * MpegEncContext.
  200. */
  201. typedef struct MpegEncContext {
  202. AVClass *class;
  203. struct AVCodecContext *avctx;
  204. /* the following parameters must be initialized before encoding */
  205. int width, height;///< picture size. must be a multiple of 16
  206. int gop_size;
  207. int intra_only; ///< if true, only intra pictures are generated
  208. int bit_rate; ///< wanted bit rate
  209. enum OutputFormat out_format; ///< output format
  210. int h263_pred; ///< use mpeg4/h263 ac/dc predictions
  211. int pb_frame; ///< PB frame mode (0 = none, 1 = base, 2 = improved)
  212. /* the following codec id fields are deprecated in favor of codec_id */
  213. int h263_plus; ///< h263 plus headers
  214. int h263_flv; ///< use flv h263 header
  215. enum AVCodecID codec_id; /* see AV_CODEC_ID_xxx */
  216. int fixed_qscale; ///< fixed qscale if non zero
  217. int encoding; ///< true if we are encoding (vs decoding)
  218. int flags; ///< AVCodecContext.flags (HQ, MV4, ...)
  219. int flags2; ///< AVCodecContext.flags2
  220. int max_b_frames; ///< max number of b-frames for encoding
  221. int luma_elim_threshold;
  222. int chroma_elim_threshold;
  223. int strict_std_compliance; ///< strictly follow the std (MPEG4, ...)
  224. int workaround_bugs; ///< workaround bugs in encoders which cannot be detected automatically
  225. int codec_tag; ///< internal codec_tag upper case converted from avctx codec_tag
  226. int stream_codec_tag; ///< internal stream_codec_tag upper case converted from avctx stream_codec_tag
  227. /* the following fields are managed internally by the encoder */
  228. /* sequence parameters */
  229. int context_initialized;
  230. int input_picture_number; ///< used to set pic->display_picture_number, should not be used for/by anything else
  231. int coded_picture_number; ///< used to set pic->coded_picture_number, should not be used for/by anything else
  232. int picture_number; //FIXME remove, unclear definition
  233. int picture_in_gop_number; ///< 0-> first pic in gop, ...
  234. int mb_width, mb_height; ///< number of MBs horizontally & vertically
  235. int mb_stride; ///< mb_width+1 used for some arrays to allow simple addressing of left & top MBs without sig11
  236. int b8_stride; ///< 2*mb_width+1 used for some 8x8 block arrays to allow simple addressing
  237. int b4_stride; ///< 4*mb_width+1 used for some 4x4 block arrays to allow simple addressing
  238. int h_edge_pos, v_edge_pos;///< horizontal / vertical position of the right/bottom edge (pixel replication)
  239. int mb_num; ///< number of MBs of a picture
  240. int linesize; ///< line size, in bytes, may be different from width
  241. int uvlinesize; ///< line size, for chroma in bytes, may be different from width
  242. Picture *picture; ///< main picture buffer
  243. Picture **input_picture; ///< next pictures on display order for encoding
  244. Picture **reordered_input_picture; ///< pointer to the next pictures in codedorder for encoding
  245. int y_dc_scale, c_dc_scale;
  246. int ac_pred;
  247. int block_last_index[12]; ///< last non zero coefficient in block
  248. int h263_aic; ///< Advanded INTRA Coding (AIC)
  249. /* scantables */
  250. ScanTable inter_scantable; ///< if inter == intra then intra should be used to reduce tha cache usage
  251. ScanTable intra_scantable;
  252. ScanTable intra_h_scantable;
  253. ScanTable intra_v_scantable;
  254. /* WARNING: changes above this line require updates to hardcoded
  255. * offsets used in asm. */
  256. int64_t user_specified_pts;///< last non zero pts from AVFrame which was passed into avcodec_encode_video()
  257. /**
  258. * pts difference between the first and second input frame, used for
  259. * calculating dts of the first frame when there's a delay */
  260. int64_t dts_delta;
  261. /**
  262. * reordered pts to be used as dts for the next output frame when there's
  263. * a delay */
  264. int64_t reordered_pts;
  265. /** bit output */
  266. PutBitContext pb;
  267. int start_mb_y; ///< start mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
  268. int end_mb_y; ///< end mb_y of this thread (so current thread should process start_mb_y <= row < end_mb_y)
  269. struct MpegEncContext *thread_context[MAX_THREADS];
  270. int slice_context_count; ///< number of used thread_contexts
  271. /**
  272. * copy of the previous picture structure.
  273. * note, linesize & data, might not match the previous picture (for field pictures)
  274. */
  275. Picture last_picture;
  276. /**
  277. * copy of the next picture structure.
  278. * note, linesize & data, might not match the next picture (for field pictures)
  279. */
  280. Picture next_picture;
  281. /**
  282. * copy of the source picture structure for encoding.
  283. * note, linesize & data, might not match the source picture (for field pictures)
  284. */
  285. Picture new_picture;
  286. /**
  287. * copy of the current picture structure.
  288. * note, linesize & data, might not match the current picture (for field pictures)
  289. */
  290. Picture current_picture; ///< buffer to store the decompressed current picture
  291. Picture *last_picture_ptr; ///< pointer to the previous picture.
  292. Picture *next_picture_ptr; ///< pointer to the next picture (for bidir pred)
  293. Picture *current_picture_ptr; ///< pointer to the current picture
  294. int last_dc[3]; ///< last DC values for MPEG1
  295. int16_t *dc_val_base;
  296. int16_t *dc_val[3]; ///< used for mpeg4 DC prediction, all 3 arrays must be continuous
  297. const uint8_t *y_dc_scale_table; ///< qscale -> y_dc_scale table
  298. const uint8_t *c_dc_scale_table; ///< qscale -> c_dc_scale table
  299. const uint8_t *chroma_qscale_table; ///< qscale -> chroma_qscale (h263)
  300. uint8_t *coded_block_base;
  301. uint8_t *coded_block; ///< used for coded block pattern prediction (msmpeg4v3, wmv1)
  302. int16_t (*ac_val_base)[16];
  303. int16_t (*ac_val[3])[16]; ///< used for for mpeg4 AC prediction, all 3 arrays must be continuous
  304. int mb_skipped; ///< MUST BE SET only during DECODING
  305. uint8_t *mbskip_table; /**< used to avoid copy if macroblock skipped (for black regions for example)
  306. and used for b-frame encoding & decoding (contains skip table of next P Frame) */
  307. uint8_t *mbintra_table; ///< used to avoid setting {ac, dc, cbp}-pred stuff to zero on inter MB decoding
  308. uint8_t *cbp_table; ///< used to store cbp, ac_pred for partitioned decoding
  309. uint8_t *pred_dir_table; ///< used to store pred_dir for partitioned decoding
  310. uint8_t *edge_emu_buffer; ///< temporary buffer for if MVs point to out-of-frame data
  311. uint8_t *rd_scratchpad; ///< scratchpad for rate distortion mb decision
  312. uint8_t *obmc_scratchpad;
  313. uint8_t *b_scratchpad; ///< scratchpad used for writing into write only buffers
  314. int qscale; ///< QP
  315. int chroma_qscale; ///< chroma QP
  316. unsigned int lambda; ///< lagrange multipler used in rate distortion
  317. unsigned int lambda2; ///< (lambda*lambda) >> FF_LAMBDA_SHIFT
  318. int *lambda_table;
  319. int adaptive_quant; ///< use adaptive quantization
  320. int dquant; ///< qscale difference to prev qscale
  321. int pict_type; ///< AV_PICTURE_TYPE_I, AV_PICTURE_TYPE_P, AV_PICTURE_TYPE_B, ...
  322. int last_pict_type; //FIXME removes
  323. int last_non_b_pict_type; ///< used for mpeg4 gmc b-frames & ratecontrol
  324. int droppable;
  325. int frame_rate_index;
  326. int last_lambda_for[5]; ///< last lambda for a specific pict type
  327. int skipdct; ///< skip dct and code zero residual
  328. /* motion compensation */
  329. int unrestricted_mv; ///< mv can point outside of the coded picture
  330. int h263_long_vectors; ///< use horrible h263v1 long vector mode
  331. DSPContext dsp; ///< pointers for accelerated dsp functions
  332. VideoDSPContext vdsp;
  333. int f_code; ///< forward MV resolution
  334. int b_code; ///< backward MV resolution for B Frames (mpeg4)
  335. int16_t (*p_mv_table_base)[2];
  336. int16_t (*b_forw_mv_table_base)[2];
  337. int16_t (*b_back_mv_table_base)[2];
  338. int16_t (*b_bidir_forw_mv_table_base)[2];
  339. int16_t (*b_bidir_back_mv_table_base)[2];
  340. int16_t (*b_direct_mv_table_base)[2];
  341. int16_t (*p_field_mv_table_base[2][2])[2];
  342. int16_t (*b_field_mv_table_base[2][2][2])[2];
  343. int16_t (*p_mv_table)[2]; ///< MV table (1MV per MB) p-frame encoding
  344. int16_t (*b_forw_mv_table)[2]; ///< MV table (1MV per MB) forward mode b-frame encoding
  345. int16_t (*b_back_mv_table)[2]; ///< MV table (1MV per MB) backward mode b-frame encoding
  346. int16_t (*b_bidir_forw_mv_table)[2]; ///< MV table (1MV per MB) bidir mode b-frame encoding
  347. int16_t (*b_bidir_back_mv_table)[2]; ///< MV table (1MV per MB) bidir mode b-frame encoding
  348. int16_t (*b_direct_mv_table)[2]; ///< MV table (1MV per MB) direct mode b-frame encoding
  349. int16_t (*p_field_mv_table[2][2])[2]; ///< MV table (2MV per MB) interlaced p-frame encoding
  350. int16_t (*b_field_mv_table[2][2][2])[2];///< MV table (4MV per MB) interlaced b-frame encoding
  351. uint8_t (*p_field_select_table[2]);
  352. uint8_t (*b_field_select_table[2][2]);
  353. int me_method; ///< ME algorithm
  354. int mv_dir;
  355. #define MV_DIR_FORWARD 1
  356. #define MV_DIR_BACKWARD 2
  357. #define MV_DIRECT 4 ///< bidirectional mode where the difference equals the MV of the last P/S/I-Frame (mpeg4)
  358. int mv_type;
  359. #define MV_TYPE_16X16 0 ///< 1 vector for the whole mb
  360. #define MV_TYPE_8X8 1 ///< 4 vectors (h263, mpeg4 4MV)
  361. #define MV_TYPE_16X8 2 ///< 2 vectors, one per 16x8 block
  362. #define MV_TYPE_FIELD 3 ///< 2 vectors, one per field
  363. #define MV_TYPE_DMV 4 ///< 2 vectors, special mpeg2 Dual Prime Vectors
  364. /**motion vectors for a macroblock
  365. first coordinate : 0 = forward 1 = backward
  366. second " : depend on type
  367. third " : 0 = x, 1 = y
  368. */
  369. int mv[2][4][2];
  370. int field_select[2][2];
  371. int last_mv[2][2][2]; ///< last MV, used for MV prediction in MPEG1 & B-frame MPEG4
  372. uint8_t *fcode_tab; ///< smallest fcode needed for each MV
  373. int16_t direct_scale_mv[2][64]; ///< precomputed to avoid divisions in ff_mpeg4_set_direct_mv
  374. MotionEstContext me;
  375. int no_rounding; /**< apply no rounding to motion compensation (MPEG4, msmpeg4, ...)
  376. for b-frames rounding mode is always 0 */
  377. /* macroblock layer */
  378. int mb_x, mb_y;
  379. int mb_skip_run;
  380. int mb_intra;
  381. uint16_t *mb_type; ///< Table for candidate MB types for encoding
  382. #define CANDIDATE_MB_TYPE_INTRA 0x01
  383. #define CANDIDATE_MB_TYPE_INTER 0x02
  384. #define CANDIDATE_MB_TYPE_INTER4V 0x04
  385. #define CANDIDATE_MB_TYPE_SKIPPED 0x08
  386. //#define MB_TYPE_GMC 0x10
  387. #define CANDIDATE_MB_TYPE_DIRECT 0x10
  388. #define CANDIDATE_MB_TYPE_FORWARD 0x20
  389. #define CANDIDATE_MB_TYPE_BACKWARD 0x40
  390. #define CANDIDATE_MB_TYPE_BIDIR 0x80
  391. #define CANDIDATE_MB_TYPE_INTER_I 0x100
  392. #define CANDIDATE_MB_TYPE_FORWARD_I 0x200
  393. #define CANDIDATE_MB_TYPE_BACKWARD_I 0x400
  394. #define CANDIDATE_MB_TYPE_BIDIR_I 0x800
  395. #define CANDIDATE_MB_TYPE_DIRECT0 0x1000
  396. int block_index[6]; ///< index to current MB in block based arrays with edges
  397. int block_wrap[6];
  398. uint8_t *dest[3];
  399. int *mb_index2xy; ///< mb_index -> mb_x + mb_y*mb_stride
  400. /** matrix transmitted in the bitstream */
  401. uint16_t intra_matrix[64];
  402. uint16_t chroma_intra_matrix[64];
  403. uint16_t inter_matrix[64];
  404. uint16_t chroma_inter_matrix[64];
  405. #define QUANT_BIAS_SHIFT 8
  406. int intra_quant_bias; ///< bias for the quantizer
  407. int inter_quant_bias; ///< bias for the quantizer
  408. int min_qcoeff; ///< minimum encodable coefficient
  409. int max_qcoeff; ///< maximum encodable coefficient
  410. int ac_esc_length; ///< num of bits needed to encode the longest esc
  411. uint8_t *intra_ac_vlc_length;
  412. uint8_t *intra_ac_vlc_last_length;
  413. uint8_t *inter_ac_vlc_length;
  414. uint8_t *inter_ac_vlc_last_length;
  415. uint8_t *luma_dc_vlc_length;
  416. #define UNI_AC_ENC_INDEX(run,level) ((run)*128 + (level))
  417. int coded_score[8];
  418. /** precomputed matrix (combine qscale and DCT renorm) */
  419. int (*q_intra_matrix)[64];
  420. int (*q_inter_matrix)[64];
  421. /** identical to the above but for MMX & these are not permutated, second 64 entries are bias*/
  422. uint16_t (*q_intra_matrix16)[2][64];
  423. uint16_t (*q_inter_matrix16)[2][64];
  424. /* noise reduction */
  425. int (*dct_error_sum)[64];
  426. int dct_count[2];
  427. uint16_t (*dct_offset)[64];
  428. void *opaque; ///< private data for the user
  429. /* bit rate control */
  430. int64_t total_bits;
  431. int frame_bits; ///< bits used for the current frame
  432. int next_lambda; ///< next lambda used for retrying to encode a frame
  433. RateControlContext rc_context; ///< contains stuff only accessed in ratecontrol.c
  434. /* statistics, used for 2-pass encoding */
  435. int mv_bits;
  436. int header_bits;
  437. int i_tex_bits;
  438. int p_tex_bits;
  439. int i_count;
  440. int f_count;
  441. int b_count;
  442. int skip_count;
  443. int misc_bits; ///< cbp, mb_type
  444. int last_bits; ///< temp var used for calculating the above vars
  445. /* error concealment / resync */
  446. int resync_mb_x; ///< x position of last resync marker
  447. int resync_mb_y; ///< y position of last resync marker
  448. GetBitContext last_resync_gb; ///< used to search for the next resync marker
  449. int mb_num_left; ///< number of MBs left in this video packet (for partitioned Slices only)
  450. int next_p_frame_damaged; ///< set if the next p frame is damaged, to avoid showing trashed b frames
  451. int err_recognition;
  452. ParseContext parse_context;
  453. /* H.263 specific */
  454. int gob_index;
  455. int obmc; ///< overlapped block motion compensation
  456. int showed_packed_warning; ///< flag for having shown the warning about divxs invalid b frames
  457. int mb_info; ///< interval for outputting info about mb offsets as side data
  458. int prev_mb_info, last_mb_info;
  459. uint8_t *mb_info_ptr;
  460. int mb_info_size;
  461. /* H.263+ specific */
  462. int umvplus; ///< == H263+ && unrestricted_mv
  463. int h263_aic_dir; ///< AIC direction: 0 = left, 1 = top
  464. int h263_slice_structured;
  465. int alt_inter_vlc; ///< alternative inter vlc
  466. int modified_quant;
  467. int loop_filter;
  468. int custom_pcf;
  469. /* mpeg4 specific */
  470. int time_increment_bits; ///< number of bits to represent the fractional part of time
  471. int last_time_base;
  472. int time_base; ///< time in seconds of last I,P,S Frame
  473. int64_t time; ///< time of current frame
  474. int64_t last_non_b_time;
  475. uint16_t pp_time; ///< time distance between the last 2 p,s,i frames
  476. uint16_t pb_time; ///< time distance between the last b and p,s,i frame
  477. uint16_t pp_field_time;
  478. uint16_t pb_field_time; ///< like above, just for interlaced
  479. int shape;
  480. int vol_sprite_usage;
  481. int sprite_width;
  482. int sprite_height;
  483. int sprite_left;
  484. int sprite_top;
  485. int sprite_brightness_change;
  486. int num_sprite_warping_points;
  487. int real_sprite_warping_points;
  488. uint16_t sprite_traj[4][2]; ///< sprite trajectory points
  489. int sprite_offset[2][2]; ///< sprite offset[isChroma][isMVY]
  490. int sprite_delta[2][2]; ///< sprite_delta [isY][isMVY]
  491. int sprite_shift[2]; ///< sprite shift [isChroma]
  492. int mcsel;
  493. int quant_precision;
  494. int quarter_sample; ///< 1->qpel, 0->half pel ME/MC
  495. int scalability;
  496. int hierachy_type;
  497. int enhancement_type;
  498. int new_pred;
  499. int reduced_res_vop;
  500. int aspect_ratio_info; //FIXME remove
  501. int sprite_warping_accuracy;
  502. int low_latency_sprite;
  503. int data_partitioning; ///< data partitioning flag from header
  504. int partitioned_frame; ///< is current frame partitioned
  505. int rvlc; ///< reversible vlc
  506. int resync_marker; ///< could this stream contain resync markers
  507. int low_delay; ///< no reordering needed / has no b-frames
  508. int vo_type;
  509. int vol_control_parameters; ///< does the stream contain the low_delay flag, used to workaround buggy encoders
  510. int intra_dc_threshold; ///< QP above whch the ac VLC should be used for intra dc
  511. int use_intra_dc_vlc;
  512. PutBitContext tex_pb; ///< used for data partitioned VOPs
  513. PutBitContext pb2; ///< used for data partitioned VOPs
  514. int mpeg_quant;
  515. int t_frame; ///< time distance of first I -> B, used for interlaced b frames
  516. int padding_bug_score; ///< used to detect the VERY common padding bug in MPEG4
  517. int cplx_estimation_trash_i;
  518. int cplx_estimation_trash_p;
  519. int cplx_estimation_trash_b;
  520. /* divx specific, used to workaround (many) bugs in divx5 */
  521. int divx_version;
  522. int divx_build;
  523. int divx_packed;
  524. uint8_t *bitstream_buffer; //Divx 5.01 puts several frames in a single one, this is used to reorder them
  525. int bitstream_buffer_size;
  526. unsigned int allocated_bitstream_buffer_size;
  527. int xvid_build;
  528. /* lavc specific stuff, used to workaround bugs in libavcodec */
  529. int lavc_build;
  530. /* RV10 specific */
  531. int rv10_version; ///< RV10 version: 0 or 3
  532. int rv10_first_dc_coded[3];
  533. int orig_width, orig_height;
  534. /* MJPEG specific */
  535. struct MJpegContext *mjpeg_ctx;
  536. int mjpeg_vsample[3]; ///< vertical sampling factors, default = {2, 1, 1}
  537. int mjpeg_hsample[3]; ///< horizontal sampling factors, default = {2, 1, 1}
  538. /* MSMPEG4 specific */
  539. int mv_table_index;
  540. int rl_table_index;
  541. int rl_chroma_table_index;
  542. int dc_table_index;
  543. int use_skip_mb_code;
  544. int slice_height; ///< in macroblocks
  545. int first_slice_line; ///< used in mpeg4 too to handle resync markers
  546. int flipflop_rounding;
  547. int msmpeg4_version; ///< 0=not msmpeg4, 1=mp41, 2=mp42, 3=mp43/divx3 4=wmv1/7 5=wmv2/8
  548. int per_mb_rl_table;
  549. int esc3_level_length;
  550. int esc3_run_length;
  551. /** [mb_intra][isChroma][level][run][last] */
  552. int (*ac_stats)[2][MAX_LEVEL+1][MAX_RUN+1][2];
  553. int inter_intra_pred;
  554. int mspel;
  555. /* decompression specific */
  556. GetBitContext gb;
  557. /* Mpeg1 specific */
  558. int gop_picture_number; ///< index of the first picture of a GOP based on fake_pic_num & mpeg1 specific
  559. int last_mv_dir; ///< last mv_dir, used for b frame encoding
  560. int broken_link; ///< no_output_of_prior_pics_flag
  561. uint8_t *vbv_delay_ptr; ///< pointer to vbv_delay in the bitstream
  562. /* MPEG-2-specific - I wished not to have to support this mess. */
  563. int progressive_sequence;
  564. int mpeg_f_code[2][2];
  565. int picture_structure;
  566. /* picture type */
  567. #define PICT_TOP_FIELD 1
  568. #define PICT_BOTTOM_FIELD 2
  569. #define PICT_FRAME 3
  570. int intra_dc_precision;
  571. int frame_pred_frame_dct;
  572. int top_field_first;
  573. int concealment_motion_vectors;
  574. int q_scale_type;
  575. int intra_vlc_format;
  576. int alternate_scan;
  577. int repeat_first_field;
  578. int chroma_420_type;
  579. int chroma_format;
  580. #define CHROMA_420 1
  581. #define CHROMA_422 2
  582. #define CHROMA_444 3
  583. int chroma_x_shift;//depend on pix_format, that depend on chroma_format
  584. int chroma_y_shift;
  585. int progressive_frame;
  586. int full_pel[2];
  587. int interlaced_dct;
  588. int first_slice;
  589. int first_field; ///< is 1 for the first field of a field picture 0 otherwise
  590. int drop_frame_timecode; ///< timecode is in drop frame format.
  591. int scan_offset; ///< reserve space for SVCD scan offset user data.
  592. /* RTP specific */
  593. int rtp_mode;
  594. uint8_t *ptr_lastgob;
  595. int swap_uv; //vcr2 codec is an MPEG-2 variant with U and V swapped
  596. int16_t (*pblocks[12])[64];
  597. int16_t (*block)[64]; ///< points to one of the following blocks
  598. int16_t (*blocks)[8][64]; // for HQ mode we need to keep the best block
  599. int (*decode_mb)(struct MpegEncContext *s, int16_t block[6][64]); // used by some codecs to avoid a switch()
  600. #define SLICE_OK 0
  601. #define SLICE_ERROR -1
  602. #define SLICE_END -2 ///<end marker found
  603. #define SLICE_NOEND -3 ///<no end marker or error found but mb count exceeded
  604. void (*dct_unquantize_mpeg1_intra)(struct MpegEncContext *s,
  605. int16_t *block/*align 16*/, int n, int qscale);
  606. void (*dct_unquantize_mpeg1_inter)(struct MpegEncContext *s,
  607. int16_t *block/*align 16*/, int n, int qscale);
  608. void (*dct_unquantize_mpeg2_intra)(struct MpegEncContext *s,
  609. int16_t *block/*align 16*/, int n, int qscale);
  610. void (*dct_unquantize_mpeg2_inter)(struct MpegEncContext *s,
  611. int16_t *block/*align 16*/, int n, int qscale);
  612. void (*dct_unquantize_h263_intra)(struct MpegEncContext *s,
  613. int16_t *block/*align 16*/, int n, int qscale);
  614. void (*dct_unquantize_h263_inter)(struct MpegEncContext *s,
  615. int16_t *block/*align 16*/, int n, int qscale);
  616. void (*dct_unquantize_h261_intra)(struct MpegEncContext *s,
  617. int16_t *block/*align 16*/, int n, int qscale);
  618. void (*dct_unquantize_h261_inter)(struct MpegEncContext *s,
  619. int16_t *block/*align 16*/, int n, int qscale);
  620. void (*dct_unquantize_intra)(struct MpegEncContext *s, // unquantizer to use (mpeg4 can use both)
  621. int16_t *block/*align 16*/, int n, int qscale);
  622. void (*dct_unquantize_inter)(struct MpegEncContext *s, // unquantizer to use (mpeg4 can use both)
  623. int16_t *block/*align 16*/, int n, int qscale);
  624. int (*dct_quantize)(struct MpegEncContext *s, int16_t *block/*align 16*/, int n, int qscale, int *overflow);
  625. int (*fast_dct_quantize)(struct MpegEncContext *s, int16_t *block/*align 16*/, int n, int qscale, int *overflow);
  626. void (*denoise_dct)(struct MpegEncContext *s, int16_t *block);
  627. int mpv_flags; ///< flags set by private options
  628. int quantizer_noise_shaping;
  629. /* temp buffers for rate control */
  630. float *cplx_tab, *bits_tab;
  631. /* flag to indicate a reinitialization is required, e.g. after
  632. * a frame size change */
  633. int context_reinit;
  634. ERContext er;
  635. } MpegEncContext;
  636. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  637. ((pic && pic >= old_ctx->picture && \
  638. pic < old_ctx->picture + MAX_PICTURE_COUNT) ? \
  639. &new_ctx->picture[pic - old_ctx->picture] : NULL)
  640. /* mpegvideo_enc common options */
  641. #define FF_MPV_FLAG_SKIP_RD 0x0001
  642. #define FF_MPV_FLAG_STRICT_GOP 0x0002
  643. #define FF_MPV_FLAG_QP_RD 0x0004
  644. #define FF_MPV_FLAG_CBP_RD 0x0008
  645. #define FF_MPV_OFFSET(x) offsetof(MpegEncContext, x)
  646. #define FF_MPV_OPT_FLAGS (AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  647. #define FF_MPV_COMMON_OPTS \
  648. { "mpv_flags", "Flags common for all mpegvideo-based encoders.", FF_MPV_OFFSET(mpv_flags), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX, FF_MPV_OPT_FLAGS, "mpv_flags" },\
  649. { "skip_rd", "RD optimal MB level residual skipping", 0, AV_OPT_TYPE_CONST, { .i64 = FF_MPV_FLAG_SKIP_RD }, 0, 0, FF_MPV_OPT_FLAGS, "mpv_flags" },\
  650. { "strict_gop", "Strictly enforce gop size", 0, AV_OPT_TYPE_CONST, { .i64 = FF_MPV_FLAG_STRICT_GOP }, 0, 0, FF_MPV_OPT_FLAGS, "mpv_flags" },\
  651. { "qp_rd", "Use rate distortion optimization for qp selection", 0, AV_OPT_TYPE_CONST, { .i64 = FF_MPV_FLAG_QP_RD }, 0, 0, FF_MPV_OPT_FLAGS, "mpv_flags" },\
  652. { "cbp_rd", "use rate distortion optimization for CBP", 0, AV_OPT_TYPE_CONST, { .i64 = FF_MPV_FLAG_CBP_RD }, 0, 0, FF_MPV_OPT_FLAGS, "mpv_flags" },\
  653. { "luma_elim_threshold", "single coefficient elimination threshold for luminance (negative values also consider dc coefficient)",\
  654. FF_MPV_OFFSET(luma_elim_threshold), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FF_MPV_OPT_FLAGS },\
  655. { "chroma_elim_threshold", "single coefficient elimination threshold for chrominance (negative values also consider dc coefficient)",\
  656. FF_MPV_OFFSET(chroma_elim_threshold), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FF_MPV_OPT_FLAGS },\
  657. { "quantizer_noise_shaping", NULL, FF_MPV_OFFSET(quantizer_noise_shaping), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FF_MPV_OPT_FLAGS },
  658. extern const AVOption ff_mpv_generic_options[];
  659. #define FF_MPV_GENERIC_CLASS(name) \
  660. static const AVClass name ## _class = {\
  661. .class_name = #name " encoder",\
  662. .item_name = av_default_item_name,\
  663. .option = ff_mpv_generic_options,\
  664. .version = LIBAVUTIL_VERSION_INT,\
  665. };
  666. /**
  667. * Set the given MpegEncContext to common defaults (same for encoding
  668. * and decoding). The changed fields will not depend upon the prior
  669. * state of the MpegEncContext.
  670. */
  671. void ff_MPV_common_defaults(MpegEncContext *s);
  672. void ff_MPV_decode_defaults(MpegEncContext *s);
  673. int ff_MPV_common_init(MpegEncContext *s);
  674. int ff_mpv_frame_size_alloc(MpegEncContext *s, int linesize);
  675. int ff_MPV_common_frame_size_change(MpegEncContext *s);
  676. void ff_MPV_common_end(MpegEncContext *s);
  677. void ff_MPV_decode_mb(MpegEncContext *s, int16_t block[12][64]);
  678. int ff_MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx);
  679. void ff_MPV_frame_end(MpegEncContext *s);
  680. int ff_MPV_encode_init(AVCodecContext *avctx);
  681. int ff_MPV_encode_end(AVCodecContext *avctx);
  682. int ff_MPV_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
  683. const AVFrame *frame, int *got_packet);
  684. void ff_MPV_encode_init_x86(MpegEncContext *s);
  685. void ff_MPV_common_init_x86(MpegEncContext *s);
  686. void ff_MPV_common_init_axp(MpegEncContext *s);
  687. void ff_MPV_common_init_arm(MpegEncContext *s);
  688. void ff_MPV_common_init_altivec(MpegEncContext *s);
  689. void ff_MPV_common_init_bfin(MpegEncContext *s);
  690. void ff_clean_intra_table_entries(MpegEncContext *s);
  691. void ff_draw_horiz_band(AVCodecContext *avctx, DSPContext *dsp, Picture *cur,
  692. Picture *last, int y, int h, int picture_structure,
  693. int first_field, int draw_edges, int low_delay,
  694. int v_edge_pos, int h_edge_pos);
  695. void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h);
  696. void ff_mpeg_flush(AVCodecContext *avctx);
  697. void ff_print_debug_info(MpegEncContext *s, Picture *p);
  698. void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix);
  699. void ff_release_unused_pictures(MpegEncContext *s, int remove_current);
  700. int ff_find_unused_picture(MpegEncContext *s, int shared);
  701. void ff_denoise_dct(MpegEncContext *s, int16_t *block);
  702. int ff_update_duplicate_context(MpegEncContext *dst, MpegEncContext *src);
  703. int ff_MPV_lowest_referenced_row(MpegEncContext *s, int dir);
  704. void ff_MPV_report_decode_progress(MpegEncContext *s);
  705. int ff_mpeg_update_thread_context(AVCodecContext *dst, const AVCodecContext *src);
  706. void ff_set_qscale(MpegEncContext * s, int qscale);
  707. void ff_mpeg_er_frame_start(MpegEncContext *s);
  708. int ff_dct_common_init(MpegEncContext *s);
  709. void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
  710. const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra);
  711. int ff_dct_quantize_c(MpegEncContext *s, int16_t *block, int n, int qscale, int *overflow);
  712. void ff_init_block_index(MpegEncContext *s);
  713. void ff_MPV_motion(MpegEncContext *s,
  714. uint8_t *dest_y, uint8_t *dest_cb,
  715. uint8_t *dest_cr, int dir,
  716. uint8_t **ref_picture,
  717. op_pixels_func (*pix_op)[4],
  718. qpel_mc_func (*qpix_op)[16]);
  719. /**
  720. * Allocate a Picture.
  721. * The pixels are allocated/set by calling get_buffer() if shared = 0.
  722. */
  723. int ff_alloc_picture(MpegEncContext *s, Picture *pic, int shared);
  724. extern const enum AVPixelFormat ff_pixfmt_list_420[];
  725. /**
  726. * permute block according to permuatation.
  727. * @param last last non zero element in scantable order
  728. */
  729. void ff_block_permute(int16_t *block, uint8_t *permutation, const uint8_t *scantable, int last);
  730. static inline void ff_update_block_index(MpegEncContext *s){
  731. const int block_size = 8;
  732. s->block_index[0]+=2;
  733. s->block_index[1]+=2;
  734. s->block_index[2]+=2;
  735. s->block_index[3]+=2;
  736. s->block_index[4]++;
  737. s->block_index[5]++;
  738. s->dest[0]+= 2*block_size;
  739. s->dest[1]+= block_size;
  740. s->dest[2]+= block_size;
  741. }
  742. static inline int get_bits_diff(MpegEncContext *s){
  743. const int bits= put_bits_count(&s->pb);
  744. const int last= s->last_bits;
  745. s->last_bits = bits;
  746. return bits - last;
  747. }
  748. static inline int ff_h263_round_chroma(int x){
  749. static const uint8_t h263_chroma_roundtab[16] = {
  750. // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  751. 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1,
  752. };
  753. return h263_chroma_roundtab[x & 0xf] + (x >> 3);
  754. }
  755. /* motion_est.c */
  756. void ff_estimate_p_frame_motion(MpegEncContext * s,
  757. int mb_x, int mb_y);
  758. void ff_estimate_b_frame_motion(MpegEncContext * s,
  759. int mb_x, int mb_y);
  760. int ff_get_best_fcode(MpegEncContext * s, int16_t (*mv_table)[2], int type);
  761. void ff_fix_long_p_mvs(MpegEncContext * s);
  762. void ff_fix_long_mvs(MpegEncContext * s, uint8_t *field_select_table, int field_select,
  763. int16_t (*mv_table)[2], int f_code, int type, int truncate);
  764. int ff_init_me(MpegEncContext *s);
  765. int ff_pre_estimate_p_frame_motion(MpegEncContext * s, int mb_x, int mb_y);
  766. int ff_epzs_motion_search(MpegEncContext * s, int *mx_ptr, int *my_ptr,
  767. int P[10][2], int src_index, int ref_index, int16_t (*last_mv)[2],
  768. int ref_mv_scale, int size, int h);
  769. int ff_get_mb_score(MpegEncContext * s, int mx, int my, int src_index,
  770. int ref_index, int size, int h, int add_rate);
  771. /* mpeg12.c */
  772. extern const uint8_t ff_mpeg1_dc_scale_table[128];
  773. extern const uint8_t * const ff_mpeg2_dc_scale_table[4];
  774. void ff_mpeg1_encode_picture_header(MpegEncContext *s, int picture_number);
  775. void ff_mpeg1_encode_mb(MpegEncContext *s,
  776. int16_t block[6][64],
  777. int motion_x, int motion_y);
  778. void ff_mpeg1_encode_init(MpegEncContext *s);
  779. void ff_mpeg1_encode_slice_header(MpegEncContext *s);
  780. extern const uint8_t ff_aic_dc_scale_table[32];
  781. extern const uint8_t ff_h263_chroma_qscale_table[32];
  782. extern const uint8_t ff_h263_loop_filter_strength[32];
  783. /* rv10.c */
  784. void ff_rv10_encode_picture_header(MpegEncContext *s, int picture_number);
  785. int ff_rv_decode_dc(MpegEncContext *s, int n);
  786. void ff_rv20_encode_picture_header(MpegEncContext *s, int picture_number);
  787. /* msmpeg4.c */
  788. void ff_msmpeg4_encode_picture_header(MpegEncContext * s, int picture_number);
  789. void ff_msmpeg4_encode_ext_header(MpegEncContext * s);
  790. void ff_msmpeg4_encode_mb(MpegEncContext * s,
  791. int16_t block[6][64],
  792. int motion_x, int motion_y);
  793. int ff_msmpeg4_decode_picture_header(MpegEncContext * s);
  794. int ff_msmpeg4_decode_ext_header(MpegEncContext * s, int buf_size);
  795. int ff_msmpeg4_decode_init(AVCodecContext *avctx);
  796. void ff_msmpeg4_encode_init(MpegEncContext *s);
  797. int ff_wmv2_decode_picture_header(MpegEncContext * s);
  798. int ff_wmv2_decode_secondary_picture_header(MpegEncContext * s);
  799. void ff_wmv2_add_mb(MpegEncContext *s, int16_t block[6][64], uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr);
  800. void ff_mspel_motion(MpegEncContext *s,
  801. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  802. uint8_t **ref_picture, op_pixels_func (*pix_op)[4],
  803. int motion_x, int motion_y, int h);
  804. int ff_wmv2_encode_picture_header(MpegEncContext * s, int picture_number);
  805. void ff_wmv2_encode_mb(MpegEncContext * s,
  806. int16_t block[6][64],
  807. int motion_x, int motion_y);
  808. int ff_mpeg_ref_picture(MpegEncContext *s, Picture *dst, Picture *src);
  809. void ff_mpeg_unref_picture(MpegEncContext *s, Picture *picture);
  810. #endif /* AVCODEC_MPEGVIDEO_H */