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