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