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