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