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.

882 lines
37KB

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