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.

1024 lines
38KB

  1. /*
  2. * MPEG1/2 encoder
  3. * Copyright (c) 2000,2001 Fabrice Bellard
  4. * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  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. * MPEG1/2 encoder
  25. */
  26. #include "avcodec.h"
  27. #include "mathops.h"
  28. #include "mpegvideo.h"
  29. #include "mpeg12.h"
  30. #include "mpeg12data.h"
  31. #include "bytestream.h"
  32. #include "libavutil/log.h"
  33. #include "libavutil/opt.h"
  34. #include "libavutil/avassert.h"
  35. #include "libavutil/timecode.h"
  36. static const uint8_t inv_non_linear_qscale[13] = {
  37. 0, 2, 4, 6, 8,
  38. 9,10,11,12,13,14,15,16,
  39. };
  40. static const uint8_t svcd_scan_offset_placeholder[14] = {
  41. 0x10, 0x0E,
  42. 0x00, 0x80, 0x81,
  43. 0x00, 0x80, 0x81,
  44. 0xff, 0xff, 0xff,
  45. 0xff, 0xff, 0xff,
  46. };
  47. static void mpeg1_encode_block(MpegEncContext *s,
  48. int16_t *block,
  49. int component);
  50. static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code); // RAL: f_code parameter added
  51. static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
  52. static uint8_t fcode_tab[MAX_MV*2+1];
  53. static uint8_t uni_mpeg1_ac_vlc_len [64*64*2];
  54. static uint8_t uni_mpeg2_ac_vlc_len [64*64*2];
  55. /* simple include everything table for dc, first byte is bits number next 3 are code*/
  56. static uint32_t mpeg1_lum_dc_uni[512];
  57. static uint32_t mpeg1_chr_dc_uni[512];
  58. static uint8_t mpeg1_index_run[2][64];
  59. static int8_t mpeg1_max_level[2][64];
  60. static void init_uni_ac_vlc(RLTable *rl, uint8_t *uni_ac_vlc_len){
  61. int i;
  62. for(i=0; i<128; i++){
  63. int level= i-64;
  64. int run;
  65. if (!level)
  66. continue;
  67. for(run=0; run<64; run++){
  68. int len, code;
  69. int alevel= FFABS(level);
  70. if (alevel > rl->max_level[0][run])
  71. code= 111; /*rl->n*/
  72. else
  73. code= rl->index_run[0][run] + alevel - 1;
  74. if (code < 111 /* rl->n */) {
  75. /* length of vlc and sign */
  76. len= rl->table_vlc[code][1]+1;
  77. } else {
  78. len= rl->table_vlc[111/*rl->n*/][1]+6;
  79. if (alevel < 128) {
  80. len += 8;
  81. } else {
  82. len += 16;
  83. }
  84. }
  85. uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;
  86. }
  87. }
  88. }
  89. static int find_frame_rate_index(MpegEncContext *s){
  90. int i;
  91. AVRational bestq= (AVRational){0, 0};
  92. AVRational ext;
  93. AVRational target = av_inv_q(s->avctx->time_base);
  94. for(i=1;i<14;i++) {
  95. if(s->avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL && i>=9) break;
  96. for (ext.num=1; ext.num <= 4; ext.num++) {
  97. for (ext.den=1; ext.den <= 32; ext.den++) {
  98. AVRational q = av_mul_q(ext, ff_mpeg12_frame_rate_tab[i]);
  99. if(s->codec_id != AV_CODEC_ID_MPEG2VIDEO && (ext.den!=1 || ext.num!=1))
  100. continue;
  101. if(av_gcd(ext.den, ext.num) != 1)
  102. continue;
  103. if( bestq.num==0
  104. || av_nearer_q(target, bestq, q) < 0
  105. || ext.num==1 && ext.den==1 && av_nearer_q(target, bestq, q) == 0){
  106. bestq = q;
  107. s->frame_rate_index= i;
  108. s->mpeg2_frame_rate_ext.num = ext.num;
  109. s->mpeg2_frame_rate_ext.den = ext.den;
  110. }
  111. }
  112. }
  113. }
  114. if(av_cmp_q(target, bestq))
  115. return -1;
  116. else
  117. return 0;
  118. }
  119. static av_cold int encode_init(AVCodecContext *avctx)
  120. {
  121. MpegEncContext *s = avctx->priv_data;
  122. if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && avctx->height > 2800)
  123. avctx->thread_count = 1;
  124. if(ff_MPV_encode_init(avctx) < 0)
  125. return -1;
  126. if(find_frame_rate_index(s) < 0){
  127. if(s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
  128. av_log(avctx, AV_LOG_ERROR, "MPEG1/2 does not support %d/%d fps\n", avctx->time_base.den, avctx->time_base.num);
  129. return -1;
  130. }else{
  131. av_log(avctx, AV_LOG_INFO, "MPEG1/2 does not support %d/%d fps, there may be AV sync issues\n", avctx->time_base.den, avctx->time_base.num);
  132. }
  133. }
  134. if(avctx->profile == FF_PROFILE_UNKNOWN){
  135. if(avctx->level != FF_LEVEL_UNKNOWN){
  136. av_log(avctx, AV_LOG_ERROR, "Set profile and level\n");
  137. return -1;
  138. }
  139. avctx->profile = s->chroma_format == CHROMA_420 ? 4 : 0; /* Main or 4:2:2 */
  140. }
  141. if(avctx->level == FF_LEVEL_UNKNOWN){
  142. if(avctx->profile == 0){ /* 4:2:2 */
  143. if(avctx->width <= 720 && avctx->height <= 608) avctx->level = 5; /* Main */
  144. else avctx->level = 2; /* High */
  145. }else{
  146. if(avctx->profile != 1 && s->chroma_format != CHROMA_420){
  147. av_log(avctx, AV_LOG_ERROR, "Only High(1) and 4:2:2(0) profiles support 4:2:2 color sampling\n");
  148. return -1;
  149. }
  150. if(avctx->width <= 720 && avctx->height <= 576) avctx->level = 8; /* Main */
  151. else if(avctx->width <= 1440) avctx->level = 6; /* High 1440 */
  152. else avctx->level = 4; /* High */
  153. }
  154. }
  155. if ((avctx->width & 0xFFF) == 0 && (avctx->height & 0xFFF) == 1) {
  156. av_log(avctx, AV_LOG_ERROR, "Width / Height is invalid for MPEG2\n");
  157. return AVERROR(EINVAL);
  158. }
  159. if (s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL) {
  160. if ((avctx->width & 0xFFF) == 0 || (avctx->height & 0xFFF) == 0) {
  161. av_log(avctx, AV_LOG_ERROR, "Width or Height are not allowed to be multiplies of 4096\n"
  162. "add '-strict %d' if you want to use them anyway.\n", FF_COMPLIANCE_UNOFFICIAL);
  163. return AVERROR(EINVAL);
  164. }
  165. }
  166. s->drop_frame_timecode = s->drop_frame_timecode || !!(avctx->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE);
  167. if (s->drop_frame_timecode)
  168. s->tc.flags |= AV_TIMECODE_FLAG_DROPFRAME;
  169. if (s->drop_frame_timecode && s->frame_rate_index != 4) {
  170. av_log(avctx, AV_LOG_ERROR, "Drop frame time code only allowed with 1001/30000 fps\n");
  171. return -1;
  172. }
  173. if (s->tc_opt_str) {
  174. AVRational rate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
  175. int ret = av_timecode_init_from_string(&s->tc, rate, s->tc_opt_str, s);
  176. if (ret < 0)
  177. return ret;
  178. s->drop_frame_timecode = !!(s->tc.flags & AV_TIMECODE_FLAG_DROPFRAME);
  179. s->avctx->timecode_frame_start = s->tc.start;
  180. } else {
  181. s->avctx->timecode_frame_start = 0; // default is -1
  182. }
  183. return 0;
  184. }
  185. static void put_header(MpegEncContext *s, int header)
  186. {
  187. avpriv_align_put_bits(&s->pb);
  188. put_bits(&s->pb, 16, header>>16);
  189. put_sbits(&s->pb, 16, header);
  190. }
  191. /* put sequence header if needed */
  192. static void mpeg1_encode_sequence_header(MpegEncContext *s)
  193. {
  194. unsigned int vbv_buffer_size;
  195. unsigned int fps, v;
  196. int i;
  197. uint64_t time_code;
  198. float best_aspect_error= 1E10;
  199. float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio);
  200. int constraint_parameter_flag;
  201. if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)
  202. if (s->current_picture.f.key_frame) {
  203. AVRational framerate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];
  204. /* mpeg1 header repeated every gop */
  205. put_header(s, SEQ_START_CODE);
  206. put_sbits(&s->pb, 12, s->width & 0xFFF);
  207. put_sbits(&s->pb, 12, s->height & 0xFFF);
  208. for(i=1; i<15; i++){
  209. float error= aspect_ratio;
  210. if(s->codec_id == AV_CODEC_ID_MPEG1VIDEO || i <=1)
  211. error-= 1.0/ff_mpeg1_aspect[i];
  212. else
  213. error-= av_q2d(ff_mpeg2_aspect[i])*s->height/s->width;
  214. error= FFABS(error);
  215. if(error < best_aspect_error){
  216. best_aspect_error= error;
  217. s->aspect_ratio_info= i;
  218. }
  219. }
  220. put_bits(&s->pb, 4, s->aspect_ratio_info);
  221. put_bits(&s->pb, 4, s->frame_rate_index);
  222. if(s->avctx->rc_max_rate){
  223. v = (s->avctx->rc_max_rate + 399) / 400;
  224. if (v > 0x3ffff && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
  225. v = 0x3ffff;
  226. }else{
  227. v= 0x3FFFF;
  228. }
  229. if(s->avctx->rc_buffer_size)
  230. vbv_buffer_size = s->avctx->rc_buffer_size;
  231. else
  232. /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
  233. vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
  234. vbv_buffer_size= (vbv_buffer_size + 16383) / 16384;
  235. put_sbits(&s->pb, 18, v);
  236. put_bits(&s->pb, 1, 1); /* marker */
  237. put_sbits(&s->pb, 10, vbv_buffer_size);
  238. constraint_parameter_flag=
  239. s->width <= 768 && s->height <= 576 &&
  240. s->mb_width * s->mb_height <= 396 &&
  241. s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 &&
  242. framerate.num <= framerate.den*30 &&
  243. s->avctx->me_range && s->avctx->me_range < 128 &&
  244. vbv_buffer_size <= 20 &&
  245. v <= 1856000/400 &&
  246. s->codec_id == AV_CODEC_ID_MPEG1VIDEO;
  247. put_bits(&s->pb, 1, constraint_parameter_flag);
  248. ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
  249. ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
  250. if(s->codec_id == AV_CODEC_ID_MPEG2VIDEO){
  251. put_header(s, EXT_START_CODE);
  252. put_bits(&s->pb, 4, 1); //seq ext
  253. put_bits(&s->pb, 1, s->avctx->profile == 0); //escx 1 for 4:2:2 profile */
  254. put_bits(&s->pb, 3, s->avctx->profile); //profile
  255. put_bits(&s->pb, 4, s->avctx->level); //level
  256. put_bits(&s->pb, 1, s->progressive_sequence);
  257. put_bits(&s->pb, 2, s->chroma_format);
  258. put_bits(&s->pb, 2, s->width >>12);
  259. put_bits(&s->pb, 2, s->height>>12);
  260. put_bits(&s->pb, 12, v>>18); //bitrate ext
  261. put_bits(&s->pb, 1, 1); //marker
  262. put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext
  263. put_bits(&s->pb, 1, s->low_delay);
  264. put_bits(&s->pb, 2, s->mpeg2_frame_rate_ext.num-1); // frame_rate_ext_n
  265. put_bits(&s->pb, 5, s->mpeg2_frame_rate_ext.den-1); // frame_rate_ext_d
  266. }
  267. put_header(s, GOP_START_CODE);
  268. put_bits(&s->pb, 1, s->drop_frame_timecode); /* drop frame flag */
  269. /* time code : we must convert from the real frame rate to a
  270. fake mpeg frame rate in case of low frame rate */
  271. fps = (framerate.num + framerate.den/2)/ framerate.den;
  272. time_code = s->current_picture_ptr->f.coded_picture_number + s->avctx->timecode_frame_start;
  273. s->gop_picture_number = s->current_picture_ptr->f.coded_picture_number;
  274. av_assert0(s->drop_frame_timecode == !!(s->tc.flags & AV_TIMECODE_FLAG_DROPFRAME));
  275. if (s->drop_frame_timecode)
  276. time_code = av_timecode_adjust_ntsc_framenum2(time_code, fps);
  277. put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
  278. put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
  279. put_bits(&s->pb, 1, 1);
  280. put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
  281. put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
  282. put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
  283. put_bits(&s->pb, 1, 0); /* broken link */
  284. }
  285. }
  286. static inline void encode_mb_skip_run(MpegEncContext *s, int run){
  287. while (run >= 33) {
  288. put_bits(&s->pb, 11, 0x008);
  289. run -= 33;
  290. }
  291. put_bits(&s->pb, ff_mpeg12_mbAddrIncrTable[run][1],
  292. ff_mpeg12_mbAddrIncrTable[run][0]);
  293. }
  294. static av_always_inline void put_qscale(MpegEncContext *s)
  295. {
  296. if(s->q_scale_type){
  297. av_assert2(s->qscale>=1 && s->qscale <=12);
  298. put_bits(&s->pb, 5, inv_non_linear_qscale[s->qscale]);
  299. }else{
  300. put_bits(&s->pb, 5, s->qscale);
  301. }
  302. }
  303. void ff_mpeg1_encode_slice_header(MpegEncContext *s){
  304. if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->height > 2800) {
  305. put_header(s, SLICE_MIN_START_CODE + (s->mb_y & 127));
  306. put_bits(&s->pb, 3, s->mb_y >> 7); /* slice_vertical_position_extension */
  307. } else {
  308. put_header(s, SLICE_MIN_START_CODE + s->mb_y);
  309. }
  310. put_qscale(s);
  311. put_bits(&s->pb, 1, 0); /* slice extra information */
  312. }
  313. void ff_mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
  314. {
  315. mpeg1_encode_sequence_header(s);
  316. /* mpeg1 picture header */
  317. put_header(s, PICTURE_START_CODE);
  318. /* temporal reference */
  319. // RAL: s->picture_number instead of s->fake_picture_number
  320. put_bits(&s->pb, 10, (s->picture_number -
  321. s->gop_picture_number) & 0x3ff);
  322. put_bits(&s->pb, 3, s->pict_type);
  323. s->vbv_delay_ptr= s->pb.buf + put_bits_count(&s->pb)/8;
  324. put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
  325. // RAL: Forward f_code also needed for B frames
  326. if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_B) {
  327. put_bits(&s->pb, 1, 0); /* half pel coordinates */
  328. if(s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
  329. put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
  330. else
  331. put_bits(&s->pb, 3, 7); /* forward_f_code */
  332. }
  333. // RAL: Backward f_code necessary for B frames
  334. if (s->pict_type == AV_PICTURE_TYPE_B) {
  335. put_bits(&s->pb, 1, 0); /* half pel coordinates */
  336. if(s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
  337. put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
  338. else
  339. put_bits(&s->pb, 3, 7); /* backward_f_code */
  340. }
  341. put_bits(&s->pb, 1, 0); /* extra bit picture */
  342. s->frame_pred_frame_dct = 1;
  343. if(s->codec_id == AV_CODEC_ID_MPEG2VIDEO){
  344. put_header(s, EXT_START_CODE);
  345. put_bits(&s->pb, 4, 8); //pic ext
  346. if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_B) {
  347. put_bits(&s->pb, 4, s->f_code);
  348. put_bits(&s->pb, 4, s->f_code);
  349. }else{
  350. put_bits(&s->pb, 8, 255);
  351. }
  352. if (s->pict_type == AV_PICTURE_TYPE_B) {
  353. put_bits(&s->pb, 4, s->b_code);
  354. put_bits(&s->pb, 4, s->b_code);
  355. }else{
  356. put_bits(&s->pb, 8, 255);
  357. }
  358. put_bits(&s->pb, 2, s->intra_dc_precision);
  359. av_assert0(s->picture_structure == PICT_FRAME);
  360. put_bits(&s->pb, 2, s->picture_structure);
  361. if (s->progressive_sequence) {
  362. put_bits(&s->pb, 1, 0); /* no repeat */
  363. } else {
  364. put_bits(&s->pb, 1, s->current_picture_ptr->f.top_field_first);
  365. }
  366. /* XXX: optimize the generation of this flag with entropy
  367. measures */
  368. s->frame_pred_frame_dct = s->progressive_sequence;
  369. put_bits(&s->pb, 1, s->frame_pred_frame_dct);
  370. put_bits(&s->pb, 1, s->concealment_motion_vectors);
  371. put_bits(&s->pb, 1, s->q_scale_type);
  372. put_bits(&s->pb, 1, s->intra_vlc_format);
  373. put_bits(&s->pb, 1, s->alternate_scan);
  374. put_bits(&s->pb, 1, s->repeat_first_field);
  375. s->progressive_frame = s->progressive_sequence;
  376. put_bits(&s->pb, 1, s->chroma_format == CHROMA_420 ? s->progressive_frame : 0); /* chroma_420_type */
  377. put_bits(&s->pb, 1, s->progressive_frame);
  378. put_bits(&s->pb, 1, 0); //composite_display_flag
  379. }
  380. if (s->scan_offset) {
  381. int i;
  382. put_header(s, USER_START_CODE);
  383. for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){
  384. put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
  385. }
  386. }
  387. s->mb_y=0;
  388. ff_mpeg1_encode_slice_header(s);
  389. }
  390. static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
  391. int has_mv, int field_motion)
  392. {
  393. put_bits(&s->pb, n, bits);
  394. if (!s->frame_pred_frame_dct) {
  395. if (has_mv)
  396. put_bits(&s->pb, 2, 2 - field_motion); /* motion_type: frame/field */
  397. put_bits(&s->pb, 1, s->interlaced_dct);
  398. }
  399. }
  400. static av_always_inline void mpeg1_encode_mb_internal(MpegEncContext *s,
  401. int16_t block[6][64],
  402. int motion_x, int motion_y,
  403. int mb_block_count)
  404. {
  405. int i, cbp;
  406. const int mb_x = s->mb_x;
  407. const int mb_y = s->mb_y;
  408. const int first_mb= mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
  409. /* compute cbp */
  410. cbp = 0;
  411. for(i=0;i<mb_block_count;i++) {
  412. if (s->block_last_index[i] >= 0)
  413. cbp |= 1 << (mb_block_count - 1 - i);
  414. }
  415. if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
  416. (mb_x != s->mb_width - 1 || (mb_y != s->end_mb_y - 1 && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)) &&
  417. ((s->pict_type == AV_PICTURE_TYPE_P && (motion_x | motion_y) == 0) ||
  418. (s->pict_type == AV_PICTURE_TYPE_B && s->mv_dir == s->last_mv_dir && (((s->mv_dir & MV_DIR_FORWARD) ? ((s->mv[0][0][0] - s->last_mv[0][0][0])|(s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
  419. ((s->mv_dir & MV_DIR_BACKWARD) ? ((s->mv[1][0][0] - s->last_mv[1][0][0])|(s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
  420. s->mb_skip_run++;
  421. s->qscale -= s->dquant;
  422. s->skip_count++;
  423. s->misc_bits++;
  424. s->last_bits++;
  425. if(s->pict_type == AV_PICTURE_TYPE_P){
  426. s->last_mv[0][1][0]= s->last_mv[0][0][0]=
  427. s->last_mv[0][1][1]= s->last_mv[0][0][1]= 0;
  428. }
  429. } else {
  430. if(first_mb){
  431. av_assert0(s->mb_skip_run == 0);
  432. encode_mb_skip_run(s, s->mb_x);
  433. }else{
  434. encode_mb_skip_run(s, s->mb_skip_run);
  435. }
  436. if (s->pict_type == AV_PICTURE_TYPE_I) {
  437. if(s->dquant && cbp){
  438. put_mb_modes(s, 2, 1, 0, 0); /* macroblock_type : macroblock_quant = 1 */
  439. put_qscale(s);
  440. }else{
  441. put_mb_modes(s, 1, 1, 0, 0); /* macroblock_type : macroblock_quant = 0 */
  442. s->qscale -= s->dquant;
  443. }
  444. s->misc_bits+= get_bits_diff(s);
  445. s->i_count++;
  446. } else if (s->mb_intra) {
  447. if(s->dquant && cbp){
  448. put_mb_modes(s, 6, 0x01, 0, 0);
  449. put_qscale(s);
  450. }else{
  451. put_mb_modes(s, 5, 0x03, 0, 0);
  452. s->qscale -= s->dquant;
  453. }
  454. s->misc_bits+= get_bits_diff(s);
  455. s->i_count++;
  456. memset(s->last_mv, 0, sizeof(s->last_mv));
  457. } else if (s->pict_type == AV_PICTURE_TYPE_P) {
  458. if(s->mv_type == MV_TYPE_16X16){
  459. if (cbp != 0) {
  460. if ((motion_x|motion_y) == 0) {
  461. if(s->dquant){
  462. put_mb_modes(s, 5, 1, 0, 0); /* macroblock_pattern & quant */
  463. put_qscale(s);
  464. }else{
  465. put_mb_modes(s, 2, 1, 0, 0); /* macroblock_pattern only */
  466. }
  467. s->misc_bits+= get_bits_diff(s);
  468. } else {
  469. if(s->dquant){
  470. put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
  471. put_qscale(s);
  472. }else{
  473. put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
  474. }
  475. s->misc_bits+= get_bits_diff(s);
  476. mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code); // RAL: f_code parameter added
  477. mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code); // RAL: f_code parameter added
  478. s->mv_bits+= get_bits_diff(s);
  479. }
  480. } else {
  481. put_bits(&s->pb, 3, 1); /* motion only */
  482. if (!s->frame_pred_frame_dct)
  483. put_bits(&s->pb, 2, 2); /* motion_type: frame */
  484. s->misc_bits+= get_bits_diff(s);
  485. mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code); // RAL: f_code parameter added
  486. mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code); // RAL: f_code parameter added
  487. s->qscale -= s->dquant;
  488. s->mv_bits+= get_bits_diff(s);
  489. }
  490. s->last_mv[0][1][0]= s->last_mv[0][0][0]= motion_x;
  491. s->last_mv[0][1][1]= s->last_mv[0][0][1]= motion_y;
  492. }else{
  493. av_assert2(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
  494. if (cbp) {
  495. if(s->dquant){
  496. put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
  497. put_qscale(s);
  498. }else{
  499. put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
  500. }
  501. } else {
  502. put_bits(&s->pb, 3, 1); /* motion only */
  503. put_bits(&s->pb, 2, 1); /* motion_type: field */
  504. s->qscale -= s->dquant;
  505. }
  506. s->misc_bits+= get_bits_diff(s);
  507. for(i=0; i<2; i++){
  508. put_bits(&s->pb, 1, s->field_select[0][i]);
  509. mpeg1_encode_motion(s, s->mv[0][i][0] - s->last_mv[0][i][0] , s->f_code);
  510. mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
  511. s->last_mv[0][i][0]= s->mv[0][i][0];
  512. s->last_mv[0][i][1]= 2*s->mv[0][i][1];
  513. }
  514. s->mv_bits+= get_bits_diff(s);
  515. }
  516. if(cbp) {
  517. if (s->chroma_y_shift) {
  518. put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp][1], ff_mpeg12_mbPatTable[cbp][0]);
  519. } else {
  520. put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp>>2][1], ff_mpeg12_mbPatTable[cbp>>2][0]);
  521. put_sbits(&s->pb, 2, cbp);
  522. }
  523. }
  524. s->f_count++;
  525. } else{
  526. if(s->mv_type == MV_TYPE_16X16){
  527. if (cbp){ // With coded bloc pattern
  528. if (s->dquant) {
  529. if(s->mv_dir == MV_DIR_FORWARD)
  530. put_mb_modes(s, 6, 3, 1, 0);
  531. else
  532. put_mb_modes(s, 8-s->mv_dir, 2, 1, 0);
  533. put_qscale(s);
  534. } else {
  535. put_mb_modes(s, 5-s->mv_dir, 3, 1, 0);
  536. }
  537. }else{ // No coded bloc pattern
  538. put_bits(&s->pb, 5-s->mv_dir, 2);
  539. if (!s->frame_pred_frame_dct)
  540. put_bits(&s->pb, 2, 2); /* motion_type: frame */
  541. s->qscale -= s->dquant;
  542. }
  543. s->misc_bits += get_bits_diff(s);
  544. if (s->mv_dir&MV_DIR_FORWARD){
  545. mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
  546. mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
  547. s->last_mv[0][0][0]=s->last_mv[0][1][0]= s->mv[0][0][0];
  548. s->last_mv[0][0][1]=s->last_mv[0][1][1]= s->mv[0][0][1];
  549. s->f_count++;
  550. }
  551. if (s->mv_dir&MV_DIR_BACKWARD){
  552. mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
  553. mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
  554. s->last_mv[1][0][0]=s->last_mv[1][1][0]= s->mv[1][0][0];
  555. s->last_mv[1][0][1]=s->last_mv[1][1][1]= s->mv[1][0][1];
  556. s->b_count++;
  557. }
  558. }else{
  559. av_assert2(s->mv_type == MV_TYPE_FIELD);
  560. av_assert2(!s->frame_pred_frame_dct);
  561. if (cbp){ // With coded bloc pattern
  562. if (s->dquant) {
  563. if(s->mv_dir == MV_DIR_FORWARD)
  564. put_mb_modes(s, 6, 3, 1, 1);
  565. else
  566. put_mb_modes(s, 8-s->mv_dir, 2, 1, 1);
  567. put_qscale(s);
  568. } else {
  569. put_mb_modes(s, 5-s->mv_dir, 3, 1, 1);
  570. }
  571. }else{ // No coded bloc pattern
  572. put_bits(&s->pb, 5-s->mv_dir, 2);
  573. put_bits(&s->pb, 2, 1); /* motion_type: field */
  574. s->qscale -= s->dquant;
  575. }
  576. s->misc_bits += get_bits_diff(s);
  577. if (s->mv_dir&MV_DIR_FORWARD){
  578. for(i=0; i<2; i++){
  579. put_bits(&s->pb, 1, s->field_select[0][i]);
  580. mpeg1_encode_motion(s, s->mv[0][i][0] - s->last_mv[0][i][0] , s->f_code);
  581. mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
  582. s->last_mv[0][i][0]= s->mv[0][i][0];
  583. s->last_mv[0][i][1]= 2*s->mv[0][i][1];
  584. }
  585. s->f_count++;
  586. }
  587. if (s->mv_dir&MV_DIR_BACKWARD){
  588. for(i=0; i<2; i++){
  589. put_bits(&s->pb, 1, s->field_select[1][i]);
  590. mpeg1_encode_motion(s, s->mv[1][i][0] - s->last_mv[1][i][0] , s->b_code);
  591. mpeg1_encode_motion(s, s->mv[1][i][1] - (s->last_mv[1][i][1]>>1), s->b_code);
  592. s->last_mv[1][i][0]= s->mv[1][i][0];
  593. s->last_mv[1][i][1]= 2*s->mv[1][i][1];
  594. }
  595. s->b_count++;
  596. }
  597. }
  598. s->mv_bits += get_bits_diff(s);
  599. if(cbp) {
  600. if (s->chroma_y_shift) {
  601. put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp][1], ff_mpeg12_mbPatTable[cbp][0]);
  602. } else {
  603. put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp>>2][1], ff_mpeg12_mbPatTable[cbp>>2][0]);
  604. put_sbits(&s->pb, 2, cbp);
  605. }
  606. }
  607. }
  608. for(i=0;i<mb_block_count;i++) {
  609. if (cbp & (1 << (mb_block_count - 1 - i))) {
  610. mpeg1_encode_block(s, block[i], i);
  611. }
  612. }
  613. s->mb_skip_run = 0;
  614. if(s->mb_intra)
  615. s->i_tex_bits+= get_bits_diff(s);
  616. else
  617. s->p_tex_bits+= get_bits_diff(s);
  618. }
  619. }
  620. void ff_mpeg1_encode_mb(MpegEncContext *s, int16_t block[6][64], int motion_x, int motion_y)
  621. {
  622. if (s->chroma_format == CHROMA_420) mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 6);
  623. else mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 8);
  624. }
  625. // RAL: Parameter added: f_or_b_code
  626. static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
  627. {
  628. if (val == 0) {
  629. /* zero vector */
  630. put_bits(&s->pb,
  631. ff_mpeg12_mbMotionVectorTable[0][1],
  632. ff_mpeg12_mbMotionVectorTable[0][0]);
  633. } else {
  634. int code, sign, bits;
  635. int bit_size = f_or_b_code - 1;
  636. int range = 1 << bit_size;
  637. /* modulo encoding */
  638. val = sign_extend(val, 5 + bit_size);
  639. if (val >= 0) {
  640. val--;
  641. code = (val >> bit_size) + 1;
  642. bits = val & (range - 1);
  643. sign = 0;
  644. } else {
  645. val = -val;
  646. val--;
  647. code = (val >> bit_size) + 1;
  648. bits = val & (range - 1);
  649. sign = 1;
  650. }
  651. av_assert2(code > 0 && code <= 16);
  652. put_bits(&s->pb,
  653. ff_mpeg12_mbMotionVectorTable[code][1],
  654. ff_mpeg12_mbMotionVectorTable[code][0]);
  655. put_bits(&s->pb, 1, sign);
  656. if (bit_size > 0) {
  657. put_bits(&s->pb, bit_size, bits);
  658. }
  659. }
  660. }
  661. void ff_mpeg1_encode_init(MpegEncContext *s)
  662. {
  663. static int done=0;
  664. ff_mpeg12_common_init(s);
  665. if(!done){
  666. int f_code;
  667. int mv;
  668. int i;
  669. done=1;
  670. ff_init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
  671. ff_init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
  672. for(i=0; i<64; i++)
  673. {
  674. mpeg1_max_level[0][i]= ff_rl_mpeg1.max_level[0][i];
  675. mpeg1_index_run[0][i]= ff_rl_mpeg1.index_run[0][i];
  676. }
  677. init_uni_ac_vlc(&ff_rl_mpeg1, uni_mpeg1_ac_vlc_len);
  678. if(s->intra_vlc_format)
  679. init_uni_ac_vlc(&ff_rl_mpeg2, uni_mpeg2_ac_vlc_len);
  680. /* build unified dc encoding tables */
  681. for(i=-255; i<256; i++)
  682. {
  683. int adiff, index;
  684. int bits, code;
  685. int diff=i;
  686. adiff = FFABS(diff);
  687. if(diff<0) diff--;
  688. index = av_log2(2*adiff);
  689. bits= ff_mpeg12_vlc_dc_lum_bits[index] + index;
  690. code= (ff_mpeg12_vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
  691. mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
  692. bits= ff_mpeg12_vlc_dc_chroma_bits[index] + index;
  693. code= (ff_mpeg12_vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
  694. mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
  695. }
  696. for(f_code=1; f_code<=MAX_FCODE; f_code++){
  697. for(mv=-MAX_MV; mv<=MAX_MV; mv++){
  698. int len;
  699. if(mv==0) len= ff_mpeg12_mbMotionVectorTable[0][1];
  700. else{
  701. int val, bit_size, code;
  702. bit_size = f_code - 1;
  703. val=mv;
  704. if (val < 0)
  705. val = -val;
  706. val--;
  707. code = (val >> bit_size) + 1;
  708. if(code<17){
  709. len= ff_mpeg12_mbMotionVectorTable[code][1] + 1 + bit_size;
  710. }else{
  711. len= ff_mpeg12_mbMotionVectorTable[16][1] + 2 + bit_size;
  712. }
  713. }
  714. mv_penalty[f_code][mv+MAX_MV]= len;
  715. }
  716. }
  717. for(f_code=MAX_FCODE; f_code>0; f_code--){
  718. for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
  719. fcode_tab[mv+MAX_MV]= f_code;
  720. }
  721. }
  722. }
  723. s->me.mv_penalty= mv_penalty;
  724. s->fcode_tab= fcode_tab;
  725. if(s->codec_id == AV_CODEC_ID_MPEG1VIDEO){
  726. s->min_qcoeff=-255;
  727. s->max_qcoeff= 255;
  728. }else{
  729. s->min_qcoeff=-2047;
  730. s->max_qcoeff= 2047;
  731. }
  732. if (s->intra_vlc_format) {
  733. s->intra_ac_vlc_length=
  734. s->intra_ac_vlc_last_length= uni_mpeg2_ac_vlc_len;
  735. } else {
  736. s->intra_ac_vlc_length=
  737. s->intra_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
  738. }
  739. s->inter_ac_vlc_length=
  740. s->inter_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
  741. }
  742. static inline void encode_dc(MpegEncContext *s, int diff, int component)
  743. {
  744. if(((unsigned) (diff+255)) >= 511){
  745. int index;
  746. if(diff<0){
  747. index= av_log2_16bit(-2*diff);
  748. diff--;
  749. }else{
  750. index= av_log2_16bit(2*diff);
  751. }
  752. if (component == 0) {
  753. put_bits(
  754. &s->pb,
  755. ff_mpeg12_vlc_dc_lum_bits[index] + index,
  756. (ff_mpeg12_vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1)));
  757. }else{
  758. put_bits(
  759. &s->pb,
  760. ff_mpeg12_vlc_dc_chroma_bits[index] + index,
  761. (ff_mpeg12_vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1)));
  762. }
  763. }else{
  764. if (component == 0) {
  765. put_bits(
  766. &s->pb,
  767. mpeg1_lum_dc_uni[diff+255]&0xFF,
  768. mpeg1_lum_dc_uni[diff+255]>>8);
  769. } else {
  770. put_bits(
  771. &s->pb,
  772. mpeg1_chr_dc_uni[diff+255]&0xFF,
  773. mpeg1_chr_dc_uni[diff+255]>>8);
  774. }
  775. }
  776. }
  777. static void mpeg1_encode_block(MpegEncContext *s,
  778. int16_t *block,
  779. int n)
  780. {
  781. int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
  782. int code, component;
  783. const uint16_t (*table_vlc)[2] = ff_rl_mpeg1.table_vlc;
  784. last_index = s->block_last_index[n];
  785. /* DC coef */
  786. if (s->mb_intra) {
  787. component = (n <= 3 ? 0 : (n&1) + 1);
  788. dc = block[0]; /* overflow is impossible */
  789. diff = dc - s->last_dc[component];
  790. encode_dc(s, diff, component);
  791. s->last_dc[component] = dc;
  792. i = 1;
  793. if (s->intra_vlc_format)
  794. table_vlc = ff_rl_mpeg2.table_vlc;
  795. } else {
  796. /* encode the first coefficient : needs to be done here because
  797. it is handled slightly differently */
  798. level = block[0];
  799. if (abs(level) == 1) {
  800. code = ((uint32_t)level >> 31); /* the sign bit */
  801. put_bits(&s->pb, 2, code | 0x02);
  802. i = 1;
  803. } else {
  804. i = 0;
  805. last_non_zero = -1;
  806. goto next_coef;
  807. }
  808. }
  809. /* now quantify & encode AC coefs */
  810. last_non_zero = i - 1;
  811. for(;i<=last_index;i++) {
  812. j = s->intra_scantable.permutated[i];
  813. level = block[j];
  814. next_coef:
  815. /* encode using VLC */
  816. if (level != 0) {
  817. run = i - last_non_zero - 1;
  818. alevel= level;
  819. MASK_ABS(sign, alevel);
  820. sign&=1;
  821. if (alevel <= mpeg1_max_level[0][run]){
  822. code= mpeg1_index_run[0][run] + alevel - 1;
  823. /* store the vlc & sign at once */
  824. put_bits(&s->pb, table_vlc[code][1]+1, (table_vlc[code][0]<<1) + sign);
  825. } else {
  826. /* escape seems to be pretty rare <5% so I do not optimize it */
  827. put_bits(&s->pb, table_vlc[111][1], table_vlc[111][0]);
  828. /* escape: only clip in this case */
  829. put_bits(&s->pb, 6, run);
  830. if(s->codec_id == AV_CODEC_ID_MPEG1VIDEO){
  831. if (alevel < 128) {
  832. put_sbits(&s->pb, 8, level);
  833. } else {
  834. if (level < 0) {
  835. put_bits(&s->pb, 16, 0x8001 + level + 255);
  836. } else {
  837. put_sbits(&s->pb, 16, level);
  838. }
  839. }
  840. }else{
  841. put_sbits(&s->pb, 12, level);
  842. }
  843. }
  844. last_non_zero = i;
  845. }
  846. }
  847. /* end of block */
  848. put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
  849. }
  850. #define OFFSET(x) offsetof(MpegEncContext, x)
  851. #define VE AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
  852. #define COMMON_OPTS\
  853. { "gop_timecode", "MPEG GOP Timecode in hh:mm:ss[:;.]ff format", OFFSET(tc_opt_str), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, VE },\
  854. { "intra_vlc", "Use MPEG-2 intra VLC table.", OFFSET(intra_vlc_format), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },\
  855. { "drop_frame_timecode", "Timecode is in drop frame format.", OFFSET(drop_frame_timecode), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE}, \
  856. { "scan_offset", "Reserve space for SVCD scan offset user data.", OFFSET(scan_offset), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  857. static const AVOption mpeg1_options[] = {
  858. COMMON_OPTS
  859. FF_MPV_COMMON_OPTS
  860. { NULL },
  861. };
  862. static const AVOption mpeg2_options[] = {
  863. COMMON_OPTS
  864. { "non_linear_quant", "Use nonlinear quantizer.", OFFSET(q_scale_type), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  865. { "alternate_scan", "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  866. FF_MPV_COMMON_OPTS
  867. { NULL },
  868. };
  869. #define mpeg12_class(x)\
  870. static const AVClass mpeg## x ##_class = {\
  871. .class_name = "mpeg" #x "video encoder",\
  872. .item_name = av_default_item_name,\
  873. .option = mpeg## x ##_options,\
  874. .version = LIBAVUTIL_VERSION_INT,\
  875. };
  876. mpeg12_class(1)
  877. mpeg12_class(2)
  878. AVCodec ff_mpeg1video_encoder = {
  879. .name = "mpeg1video",
  880. .type = AVMEDIA_TYPE_VIDEO,
  881. .id = AV_CODEC_ID_MPEG1VIDEO,
  882. .priv_data_size = sizeof(MpegEncContext),
  883. .init = encode_init,
  884. .encode2 = ff_MPV_encode_picture,
  885. .close = ff_MPV_encode_end,
  886. .supported_framerates = ff_mpeg12_frame_rate_tab + 1,
  887. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P,
  888. AV_PIX_FMT_NONE },
  889. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
  890. .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
  891. .priv_class = &mpeg1_class,
  892. };
  893. AVCodec ff_mpeg2video_encoder = {
  894. .name = "mpeg2video",
  895. .type = AVMEDIA_TYPE_VIDEO,
  896. .id = AV_CODEC_ID_MPEG2VIDEO,
  897. .priv_data_size = sizeof(MpegEncContext),
  898. .init = encode_init,
  899. .encode2 = ff_MPV_encode_picture,
  900. .close = ff_MPV_encode_end,
  901. .supported_framerates = ff_mpeg2_frame_rate_tab,
  902. .pix_fmts = (const enum AVPixelFormat[]){
  903. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_NONE
  904. },
  905. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
  906. .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
  907. .priv_class = &mpeg2_class,
  908. };