Rename CONFIG_FFT_FLOAT ---> FFT_FLOAT
[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
291         put_header(s, GOP_START_CODE);
292         put_bits(&s->pb, 1, s->drop_frame_timecode);    // drop frame flag
293         /* time code: we must convert from the real frame rate to a
294          * fake MPEG frame rate in case of low frame rate */
295         fps       = (framerate.num + framerate.den / 2) / framerate.den;
296         time_code = s->current_picture_ptr->f.coded_picture_number +
297                     s->avctx->timecode_frame_start;
298
299         s->gop_picture_number = s->current_picture_ptr->f.coded_picture_number;
300         if (s->drop_frame_timecode) {
301             /* only works for NTSC 29.97 */
302             int d = time_code / 17982;
303             int m = time_code % 17982;
304             /* not needed since -2,-1 / 1798 in C returns 0 */
305             // if (m < 2)
306             //     m += 2;
307             time_code += 18 * d + 2 * ((m - 2) / 1798);
308         }
309         put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
310         put_bits(&s->pb, 6, (uint32_t)((time_code / (fps *   60)) % 60));
311         put_bits(&s->pb, 1, 1);
312         put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
313         put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
314         put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
315         put_bits(&s->pb, 1, 0);                     // broken link
316     }
317 }
318
319 static inline void encode_mb_skip_run(MpegEncContext *s, int run)
320 {
321     while (run >= 33) {
322         put_bits(&s->pb, 11, 0x008);
323         run -= 33;
324     }
325     put_bits(&s->pb, ff_mpeg12_mbAddrIncrTable[run][1],
326              ff_mpeg12_mbAddrIncrTable[run][0]);
327 }
328
329 static av_always_inline void put_qscale(MpegEncContext *s)
330 {
331     if (s->q_scale_type) {
332         assert(s->qscale >= 1 && s->qscale <= 12);
333         put_bits(&s->pb, 5, inv_non_linear_qscale[s->qscale]);
334     } else {
335         put_bits(&s->pb, 5, s->qscale);
336     }
337 }
338
339 void ff_mpeg1_encode_slice_header(MpegEncContext *s)
340 {
341     if (s->height > 2800) {
342         put_header(s, SLICE_MIN_START_CODE + (s->mb_y & 127));
343         /* slice_vertical_position_extension */
344         put_bits(&s->pb, 3, s->mb_y >> 7);
345     } else {
346         put_header(s, SLICE_MIN_START_CODE + s->mb_y);
347     }
348     put_qscale(s);
349     /* slice extra information */
350     put_bits(&s->pb, 1, 0);
351 }
352
353 void ff_mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
354 {
355     AVFrameSideData *side_data;
356     mpeg1_encode_sequence_header(s);
357
358     /* mpeg1 picture header */
359     put_header(s, PICTURE_START_CODE);
360     /* temporal reference */
361
362     // RAL: s->picture_number instead of s->fake_picture_number
363     put_bits(&s->pb, 10,
364              (s->picture_number - s->gop_picture_number) & 0x3ff);
365     put_bits(&s->pb, 3, s->pict_type);
366
367     s->vbv_delay_ptr = s->pb.buf + put_bits_count(&s->pb) / 8;
368     put_bits(&s->pb, 16, 0xFFFF);               /* vbv_delay */
369
370     // RAL: Forward f_code also needed for B-frames
371     if (s->pict_type == AV_PICTURE_TYPE_P ||
372         s->pict_type == AV_PICTURE_TYPE_B) {
373         put_bits(&s->pb, 1, 0);                 /* half pel coordinates */
374         if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
375             put_bits(&s->pb, 3, s->f_code);     /* forward_f_code */
376         else
377             put_bits(&s->pb, 3, 7);             /* forward_f_code */
378     }
379
380     // RAL: Backward f_code necessary for B-frames
381     if (s->pict_type == AV_PICTURE_TYPE_B) {
382         put_bits(&s->pb, 1, 0);                 /* half pel coordinates */
383         if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO)
384             put_bits(&s->pb, 3, s->b_code);     /* backward_f_code */
385         else
386             put_bits(&s->pb, 3, 7);             /* backward_f_code */
387     }
388
389     put_bits(&s->pb, 1, 0);                     /* extra bit picture */
390
391     s->frame_pred_frame_dct = 1;
392     if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
393         put_header(s, EXT_START_CODE);
394         put_bits(&s->pb, 4, 8);                 /* pic ext */
395         if (s->pict_type == AV_PICTURE_TYPE_P ||
396             s->pict_type == AV_PICTURE_TYPE_B) {
397             put_bits(&s->pb, 4, s->f_code);
398             put_bits(&s->pb, 4, s->f_code);
399         } else {
400             put_bits(&s->pb, 8, 255);
401         }
402         if (s->pict_type == AV_PICTURE_TYPE_B) {
403             put_bits(&s->pb, 4, s->b_code);
404             put_bits(&s->pb, 4, s->b_code);
405         } else {
406             put_bits(&s->pb, 8, 255);
407         }
408         put_bits(&s->pb, 2, s->intra_dc_precision);
409
410         assert(s->picture_structure == PICT_FRAME);
411         put_bits(&s->pb, 2, s->picture_structure);
412         if (s->progressive_sequence)
413             put_bits(&s->pb, 1, 0);             /* no repeat */
414         else
415             put_bits(&s->pb, 1, s->current_picture_ptr->f.top_field_first);
416         /* XXX: optimize the generation of this flag with entropy measures */
417         s->frame_pred_frame_dct = s->progressive_sequence;
418
419         put_bits(&s->pb, 1, s->frame_pred_frame_dct);
420         put_bits(&s->pb, 1, s->concealment_motion_vectors);
421         put_bits(&s->pb, 1, s->q_scale_type);
422         put_bits(&s->pb, 1, s->intra_vlc_format);
423         put_bits(&s->pb, 1, s->alternate_scan);
424         put_bits(&s->pb, 1, s->repeat_first_field);
425         s->progressive_frame = s->progressive_sequence;
426         /* chroma_420_type */
427         put_bits(&s->pb, 1, s->chroma_format ==
428                             CHROMA_420 ? s->progressive_frame : 0);
429         put_bits(&s->pb, 1, s->progressive_frame);
430         put_bits(&s->pb, 1, 0);                 /* composite_display_flag */
431     }
432     if (s->scan_offset) {
433         int i;
434
435         put_header(s, USER_START_CODE);
436         for (i = 0; i < sizeof(svcd_scan_offset_placeholder); i++)
437             put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
438     }
439     side_data = av_frame_get_side_data(&s->current_picture_ptr->f,
440                                        AV_FRAME_DATA_STEREO3D);
441     if (side_data) {
442         AVStereo3D *stereo = (AVStereo3D *)side_data->data;
443         uint8_t fpa_type;
444
445         switch (stereo->type) {
446         case AV_STEREO3D_SIDEBYSIDE:
447             fpa_type = 0x03;
448             break;
449         case AV_STEREO3D_TOPBOTTOM:
450             fpa_type = 0x04;
451             break;
452         case AV_STEREO3D_2D:
453             fpa_type = 0x08;
454             break;
455         case AV_STEREO3D_SIDEBYSIDE_QUINCUNX:
456             fpa_type = 0x23;
457             break;
458         default:
459             fpa_type = 0;
460             break;
461         }
462
463         if (fpa_type != 0) {
464             put_header(s, USER_START_CODE);
465             put_bits(&s->pb, 8, 'J');   // S3D_video_format_signaling_identifier
466             put_bits(&s->pb, 8, 'P');
467             put_bits(&s->pb, 8, '3');
468             put_bits(&s->pb, 8, 'D');
469             put_bits(&s->pb, 8, 0x03);  // S3D_video_format_length
470
471             put_bits(&s->pb, 1, 1);     // reserved_bit
472             put_bits(&s->pb, 7, fpa_type); // S3D_video_format_type
473             put_bits(&s->pb, 8, 0x04);  // reserved_data[0]
474             put_bits(&s->pb, 8, 0xFF);  // reserved_data[1]
475         }
476     }
477
478     s->mb_y = 0;
479     ff_mpeg1_encode_slice_header(s);
480 }
481
482 static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
483                                 int has_mv, int field_motion)
484 {
485     put_bits(&s->pb, n, bits);
486     if (!s->frame_pred_frame_dct) {
487         if (has_mv)
488             /* motion_type: frame/field */
489             put_bits(&s->pb, 2, 2 - field_motion);
490         put_bits(&s->pb, 1, s->interlaced_dct);
491     }
492 }
493
494 // RAL: Parameter added: f_or_b_code
495 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
496 {
497     if (val == 0) {
498         /* zero vector */
499         put_bits(&s->pb,
500                  ff_mpeg12_mbMotionVectorTable[0][1],
501                  ff_mpeg12_mbMotionVectorTable[0][0]);
502     } else {
503         int code, sign, bits;
504         int bit_size = f_or_b_code - 1;
505         int range    = 1 << bit_size;
506         /* modulo encoding */
507         val = sign_extend(val, 5 + bit_size);
508
509         if (val >= 0) {
510             val--;
511             code = (val >> bit_size) + 1;
512             bits = val & (range - 1);
513             sign = 0;
514         } else {
515             val = -val;
516             val--;
517             code = (val >> bit_size) + 1;
518             bits = val & (range - 1);
519             sign = 1;
520         }
521
522         assert(code > 0 && code <= 16);
523
524         put_bits(&s->pb,
525                  ff_mpeg12_mbMotionVectorTable[code][1],
526                  ff_mpeg12_mbMotionVectorTable[code][0]);
527
528         put_bits(&s->pb, 1, sign);
529         if (bit_size > 0)
530             put_bits(&s->pb, bit_size, bits);
531     }
532 }
533
534 static inline void encode_dc(MpegEncContext *s, int diff, int component)
535 {
536     if (((unsigned) (diff + 255)) >= 511) {
537         int index;
538
539         if (diff < 0) {
540             index = av_log2_16bit(-2 * diff);
541             diff--;
542         } else {
543             index = av_log2_16bit(2 * diff);
544         }
545         if (component == 0)
546             put_bits(&s->pb,
547                      ff_mpeg12_vlc_dc_lum_bits[index] + index,
548                      (ff_mpeg12_vlc_dc_lum_code[index] << index) +
549                      (diff & ((1 << index) - 1)));
550         else
551             put_bits(&s->pb,
552                      ff_mpeg12_vlc_dc_chroma_bits[index] + index,
553                      (ff_mpeg12_vlc_dc_chroma_code[index] << index) +
554                      (diff & ((1 << index) - 1)));
555     } else {
556         if (component == 0)
557             put_bits(&s->pb,
558                      mpeg1_lum_dc_uni[diff + 255] & 0xFF,
559                      mpeg1_lum_dc_uni[diff + 255] >> 8);
560         else
561             put_bits(&s->pb,
562                      mpeg1_chr_dc_uni[diff + 255] & 0xFF,
563                      mpeg1_chr_dc_uni[diff + 255] >> 8);
564     }
565 }
566
567 static void mpeg1_encode_block(MpegEncContext *s, int16_t *block, int n)
568 {
569     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
570     int code, component;
571     const uint16_t (*table_vlc)[2] = ff_rl_mpeg1.table_vlc;
572
573     last_index = s->block_last_index[n];
574
575     /* DC coef */
576     if (s->mb_intra) {
577         component = (n <= 3 ? 0 : (n & 1) + 1);
578         dc        = block[0];                   /* overflow is impossible */
579         diff      = dc - s->last_dc[component];
580         encode_dc(s, diff, component);
581         s->last_dc[component] = dc;
582         i = 1;
583         if (s->intra_vlc_format)
584             table_vlc = ff_rl_mpeg2.table_vlc;
585     } else {
586         /* encode the first coefficient: needs to be done here because
587          * it is handled slightly differently */
588         level = block[0];
589         if (abs(level) == 1) {
590             code = ((uint32_t)level >> 31);     /* the sign bit */
591             put_bits(&s->pb, 2, code | 0x02);
592             i = 1;
593         } else {
594             i             = 0;
595             last_non_zero = -1;
596             goto next_coef;
597         }
598     }
599
600     /* now quantify & encode AC coefs */
601     last_non_zero = i - 1;
602
603     for (; i <= last_index; i++) {
604         j     = s->intra_scantable.permutated[i];
605         level = block[j];
606
607 next_coef:
608         /* encode using VLC */
609         if (level != 0) {
610             run = i - last_non_zero - 1;
611
612             alevel = level;
613             MASK_ABS(sign, alevel);
614             sign &= 1;
615
616             if (alevel <= mpeg1_max_level[0][run]) {
617                 code = mpeg1_index_run[0][run] + alevel - 1;
618                 /* store the VLC & sign at once */
619                 put_bits(&s->pb, table_vlc[code][1] + 1,
620                          (table_vlc[code][0] << 1) + sign);
621             } else {
622                 /* escape seems to be pretty rare <5% so I do not optimize it */
623                 put_bits(&s->pb, table_vlc[111][1], table_vlc[111][0]);
624                 /* escape: only clip in this case */
625                 put_bits(&s->pb, 6, run);
626                 if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
627                     if (alevel < 128) {
628                         put_sbits(&s->pb, 8, level);
629                     } else {
630                         if (level < 0)
631                             put_bits(&s->pb, 16, 0x8001 + level + 255);
632                         else
633                             put_sbits(&s->pb, 16, level);
634                     }
635                 } else {
636                     put_sbits(&s->pb, 12, level);
637                 }
638             }
639             last_non_zero = i;
640         }
641     }
642     /* end of block */
643     put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
644 }
645
646 static av_always_inline void mpeg1_encode_mb_internal(MpegEncContext *s,
647                                                       int16_t block[6][64],
648                                                       int motion_x, int motion_y,
649                                                       int mb_block_count)
650 {
651     int i, cbp;
652     const int mb_x     = s->mb_x;
653     const int mb_y     = s->mb_y;
654     const int first_mb = mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
655
656     /* compute cbp */
657     cbp = 0;
658     for (i = 0; i < mb_block_count; i++)
659         if (s->block_last_index[i] >= 0)
660             cbp |= 1 << (mb_block_count - 1 - i);
661
662     if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
663         (mb_x != s->mb_width - 1 ||
664          (mb_y != s->mb_height - 1 && s->codec_id == AV_CODEC_ID_MPEG1VIDEO)) &&
665         ((s->pict_type == AV_PICTURE_TYPE_P && (motion_x | motion_y) == 0) ||
666          (s->pict_type == AV_PICTURE_TYPE_B && s->mv_dir == s->last_mv_dir &&
667           (((s->mv_dir & MV_DIR_FORWARD)
668             ? ((s->mv[0][0][0] - s->last_mv[0][0][0]) |
669                (s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
670            ((s->mv_dir & MV_DIR_BACKWARD)
671             ? ((s->mv[1][0][0] - s->last_mv[1][0][0]) |
672                (s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
673         s->mb_skip_run++;
674         s->qscale -= s->dquant;
675         s->skip_count++;
676         s->misc_bits++;
677         s->last_bits++;
678         if (s->pict_type == AV_PICTURE_TYPE_P) {
679             s->last_mv[0][0][0] =
680             s->last_mv[0][0][1] =
681             s->last_mv[0][1][0] =
682             s->last_mv[0][1][1] = 0;
683         }
684     } else {
685         if (first_mb) {
686             assert(s->mb_skip_run == 0);
687             encode_mb_skip_run(s, s->mb_x);
688         } else {
689             encode_mb_skip_run(s, s->mb_skip_run);
690         }
691
692         if (s->pict_type == AV_PICTURE_TYPE_I) {
693             if (s->dquant && cbp) {
694                 /* macroblock_type: macroblock_quant = 1 */
695                 put_mb_modes(s, 2, 1, 0, 0);
696                 put_qscale(s);
697             } else {
698                 /* macroblock_type: macroblock_quant = 0 */
699                 put_mb_modes(s, 1, 1, 0, 0);
700                 s->qscale -= s->dquant;
701             }
702             s->misc_bits += get_bits_diff(s);
703             s->i_count++;
704         } else if (s->mb_intra) {
705             if (s->dquant && cbp) {
706                 put_mb_modes(s, 6, 0x01, 0, 0);
707                 put_qscale(s);
708             } else {
709                 put_mb_modes(s, 5, 0x03, 0, 0);
710                 s->qscale -= s->dquant;
711             }
712             s->misc_bits += get_bits_diff(s);
713             s->i_count++;
714             memset(s->last_mv, 0, sizeof(s->last_mv));
715         } else if (s->pict_type == AV_PICTURE_TYPE_P) {
716             if (s->mv_type == MV_TYPE_16X16) {
717                 if (cbp != 0) {
718                     if ((motion_x | motion_y) == 0) {
719                         if (s->dquant) {
720                             /* macroblock_pattern & quant */
721                             put_mb_modes(s, 5, 1, 0, 0);
722                             put_qscale(s);
723                         } else {
724                             /* macroblock_pattern only */
725                             put_mb_modes(s, 2, 1, 0, 0);
726                         }
727                         s->misc_bits += get_bits_diff(s);
728                     } else {
729                         if (s->dquant) {
730                             put_mb_modes(s, 5, 2, 1, 0);    /* motion + cbp */
731                             put_qscale(s);
732                         } else {
733                             put_mb_modes(s, 1, 1, 1, 0);    /* motion + cbp */
734                         }
735                         s->misc_bits += get_bits_diff(s);
736                         // RAL: f_code parameter added
737                         mpeg1_encode_motion(s,
738                                             motion_x - s->last_mv[0][0][0],
739                                             s->f_code);
740                         // RAL: f_code parameter added
741                         mpeg1_encode_motion(s,
742                                             motion_y - s->last_mv[0][0][1],
743                                             s->f_code);
744                         s->mv_bits += get_bits_diff(s);
745                     }
746                 } else {
747                     put_bits(&s->pb, 3, 1);         /* motion only */
748                     if (!s->frame_pred_frame_dct)
749                         put_bits(&s->pb, 2, 2);     /* motion_type: frame */
750                     s->misc_bits += get_bits_diff(s);
751                     // RAL: f_code parameter added
752                     mpeg1_encode_motion(s,
753                                         motion_x - s->last_mv[0][0][0],
754                                         s->f_code);
755                     // RAL: f_code parameter added
756                     mpeg1_encode_motion(s,
757                                         motion_y - s->last_mv[0][0][1],
758                                         s->f_code);
759                     s->qscale  -= s->dquant;
760                     s->mv_bits += get_bits_diff(s);
761                 }
762                 s->last_mv[0][1][0] = s->last_mv[0][0][0] = motion_x;
763                 s->last_mv[0][1][1] = s->last_mv[0][0][1] = motion_y;
764             } else {
765                 assert(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
766
767                 if (cbp) {
768                     if (s->dquant) {
769                         put_mb_modes(s, 5, 2, 1, 1);    /* motion + cbp */
770                         put_qscale(s);
771                     } else {
772                         put_mb_modes(s, 1, 1, 1, 1);    /* motion + cbp */
773                     }
774                 } else {
775                     put_bits(&s->pb, 3, 1);             /* motion only */
776                     put_bits(&s->pb, 2, 1);             /* motion_type: field */
777                     s->qscale -= s->dquant;
778                 }
779                 s->misc_bits += get_bits_diff(s);
780                 for (i = 0; i < 2; i++) {
781                     put_bits(&s->pb, 1, s->field_select[0][i]);
782                     mpeg1_encode_motion(s,
783                                         s->mv[0][i][0] - s->last_mv[0][i][0],
784                                         s->f_code);
785                     mpeg1_encode_motion(s,
786                                         s->mv[0][i][1] - (s->last_mv[0][i][1] >> 1),
787                                         s->f_code);
788                     s->last_mv[0][i][0] = s->mv[0][i][0];
789                     s->last_mv[0][i][1] = 2 * s->mv[0][i][1];
790                 }
791                 s->mv_bits += get_bits_diff(s);
792             }
793             if (cbp) {
794                 if (s->chroma_y_shift) {
795                     put_bits(&s->pb,
796                              ff_mpeg12_mbPatTable[cbp][1],
797                              ff_mpeg12_mbPatTable[cbp][0]);
798                 } else {
799                     put_bits(&s->pb,
800                              ff_mpeg12_mbPatTable[cbp >> 2][1],
801                              ff_mpeg12_mbPatTable[cbp >> 2][0]);
802                     put_sbits(&s->pb, 2, cbp);
803                 }
804             }
805             s->f_count++;
806         } else {
807             if (s->mv_type == MV_TYPE_16X16) {
808                 if (cbp) {                      // With coded bloc pattern
809                     if (s->dquant) {
810                         if (s->mv_dir == MV_DIR_FORWARD)
811                             put_mb_modes(s, 6, 3, 1, 0);
812                         else
813                             put_mb_modes(s, 8 - s->mv_dir, 2, 1, 0);
814                         put_qscale(s);
815                     } else {
816                         put_mb_modes(s, 5 - s->mv_dir, 3, 1, 0);
817                     }
818                 } else {                        // No coded bloc pattern
819                     put_bits(&s->pb, 5 - s->mv_dir, 2);
820                     if (!s->frame_pred_frame_dct)
821                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
822                     s->qscale -= s->dquant;
823                 }
824                 s->misc_bits += get_bits_diff(s);
825                 if (s->mv_dir & MV_DIR_FORWARD) {
826                     mpeg1_encode_motion(s,
827                                         s->mv[0][0][0] - s->last_mv[0][0][0],
828                                         s->f_code);
829                     mpeg1_encode_motion(s,
830                                         s->mv[0][0][1] - s->last_mv[0][0][1],
831                                         s->f_code);
832                     s->last_mv[0][0][0] =
833                     s->last_mv[0][1][0] = s->mv[0][0][0];
834                     s->last_mv[0][0][1] =
835                     s->last_mv[0][1][1] = s->mv[0][0][1];
836                     s->f_count++;
837                 }
838                 if (s->mv_dir & MV_DIR_BACKWARD) {
839                     mpeg1_encode_motion(s,
840                                         s->mv[1][0][0] - s->last_mv[1][0][0],
841                                         s->b_code);
842                     mpeg1_encode_motion(s,
843                                         s->mv[1][0][1] - s->last_mv[1][0][1],
844                                         s->b_code);
845                     s->last_mv[1][0][0] =
846                     s->last_mv[1][1][0] = s->mv[1][0][0];
847                     s->last_mv[1][0][1] =
848                     s->last_mv[1][1][1] = s->mv[1][0][1];
849                     s->b_count++;
850                 }
851             } else {
852                 assert(s->mv_type == MV_TYPE_FIELD);
853                 assert(!s->frame_pred_frame_dct);
854                 if (cbp) {                      // With coded bloc pattern
855                     if (s->dquant) {
856                         if (s->mv_dir == MV_DIR_FORWARD)
857                             put_mb_modes(s, 6, 3, 1, 1);
858                         else
859                             put_mb_modes(s, 8 - s->mv_dir, 2, 1, 1);
860                         put_qscale(s);
861                     } else {
862                         put_mb_modes(s, 5 - s->mv_dir, 3, 1, 1);
863                     }
864                 } else {                        // No coded bloc pattern
865                     put_bits(&s->pb, 5 - s->mv_dir, 2);
866                     put_bits(&s->pb, 2, 1);     /* motion_type: field */
867                     s->qscale -= s->dquant;
868                 }
869                 s->misc_bits += get_bits_diff(s);
870                 if (s->mv_dir & MV_DIR_FORWARD) {
871                     for (i = 0; i < 2; i++) {
872                         put_bits(&s->pb, 1, s->field_select[0][i]);
873                         mpeg1_encode_motion(s,
874                                             s->mv[0][i][0] - s->last_mv[0][i][0],
875                                             s->f_code);
876                         mpeg1_encode_motion(s,
877                                             s->mv[0][i][1] - (s->last_mv[0][i][1] >> 1),
878                                             s->f_code);
879                         s->last_mv[0][i][0] = s->mv[0][i][0];
880                         s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
881                     }
882                     s->f_count++;
883                 }
884                 if (s->mv_dir & MV_DIR_BACKWARD) {
885                     for (i = 0; i < 2; i++) {
886                         put_bits(&s->pb, 1, s->field_select[1][i]);
887                         mpeg1_encode_motion(s,
888                                             s->mv[1][i][0] - s->last_mv[1][i][0],
889                                             s->b_code);
890                         mpeg1_encode_motion(s,
891                                             s->mv[1][i][1] - (s->last_mv[1][i][1] >> 1),
892                                             s->b_code);
893                         s->last_mv[1][i][0] = s->mv[1][i][0];
894                         s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
895                     }
896                     s->b_count++;
897                 }
898             }
899             s->mv_bits += get_bits_diff(s);
900             if (cbp) {
901                 if (s->chroma_y_shift) {
902                     put_bits(&s->pb,
903                              ff_mpeg12_mbPatTable[cbp][1],
904                              ff_mpeg12_mbPatTable[cbp][0]);
905                 } else {
906                     put_bits(&s->pb,
907                              ff_mpeg12_mbPatTable[cbp >> 2][1],
908                              ff_mpeg12_mbPatTable[cbp >> 2][0]);
909                     put_sbits(&s->pb, 2, cbp);
910                 }
911             }
912         }
913         for (i = 0; i < mb_block_count; i++)
914             if (cbp & (1 << (mb_block_count - 1 - i)))
915                 mpeg1_encode_block(s, block[i], i);
916         s->mb_skip_run = 0;
917         if (s->mb_intra)
918             s->i_tex_bits += get_bits_diff(s);
919         else
920             s->p_tex_bits += get_bits_diff(s);
921     }
922 }
923
924 void ff_mpeg1_encode_mb(MpegEncContext *s, int16_t block[6][64],
925                         int motion_x, int motion_y)
926 {
927     if (s->chroma_format == CHROMA_420)
928         mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 6);
929     else
930         mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 8);
931 }
932
933 av_cold void ff_mpeg1_encode_init(MpegEncContext *s)
934 {
935     static int done = 0;
936
937     ff_mpeg12_common_init(s);
938
939     if (!done) {
940         int f_code;
941         int mv;
942         int i;
943
944         done = 1;
945         ff_init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
946         ff_init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
947
948         for (i = 0; i < 64; i++) {
949             mpeg1_max_level[0][i] = ff_rl_mpeg1.max_level[0][i];
950             mpeg1_index_run[0][i] = ff_rl_mpeg1.index_run[0][i];
951         }
952
953         init_uni_ac_vlc(&ff_rl_mpeg1, uni_mpeg1_ac_vlc_len);
954         if (s->intra_vlc_format)
955             init_uni_ac_vlc(&ff_rl_mpeg2, uni_mpeg2_ac_vlc_len);
956
957         /* build unified dc encoding tables */
958         for (i = -255; i < 256; i++) {
959             int adiff, index;
960             int bits, code;
961             int diff = i;
962
963             adiff = FFABS(diff);
964             if (diff < 0)
965                 diff--;
966             index = av_log2(2 * adiff);
967
968             bits = ff_mpeg12_vlc_dc_lum_bits[index] + index;
969             code = (ff_mpeg12_vlc_dc_lum_code[index] << index) +
970                    (diff & ((1 << index) - 1));
971             mpeg1_lum_dc_uni[i + 255] = bits + (code << 8);
972
973             bits = ff_mpeg12_vlc_dc_chroma_bits[index] + index;
974             code = (ff_mpeg12_vlc_dc_chroma_code[index] << index) +
975                    (diff & ((1 << index) - 1));
976             mpeg1_chr_dc_uni[i + 255] = bits + (code << 8);
977         }
978
979         for (f_code = 1; f_code <= MAX_FCODE; f_code++)
980             for (mv = -MAX_MV; mv <= MAX_MV; mv++) {
981                 int len;
982
983                 if (mv == 0) {
984                     len = ff_mpeg12_mbMotionVectorTable[0][1];
985                 } else {
986                     int val, bit_size, code;
987
988                     bit_size = f_code - 1;
989
990                     val = mv;
991                     if (val < 0)
992                         val = -val;
993                     val--;
994                     code = (val >> bit_size) + 1;
995                     if (code < 17)
996                         len = ff_mpeg12_mbMotionVectorTable[code][1] +
997                               1 + bit_size;
998                     else
999                         len = ff_mpeg12_mbMotionVectorTable[16][1] +
1000                               2 + bit_size;
1001                 }
1002
1003                 mv_penalty[f_code][mv + MAX_MV] = len;
1004             }
1005
1006
1007         for (f_code = MAX_FCODE; f_code > 0; f_code--)
1008             for (mv = -(8 << f_code); mv < (8 << f_code); mv++)
1009                 fcode_tab[mv + MAX_MV] = f_code;
1010     }
1011     s->me.mv_penalty = mv_penalty;
1012     s->fcode_tab     = fcode_tab;
1013     if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
1014         s->min_qcoeff = -255;
1015         s->max_qcoeff = 255;
1016     } else {
1017         s->min_qcoeff = -2047;
1018         s->max_qcoeff = 2047;
1019     }
1020     if (s->intra_vlc_format) {
1021         s->intra_ac_vlc_length      =
1022         s->intra_ac_vlc_last_length = uni_mpeg2_ac_vlc_len;
1023     } else {
1024         s->intra_ac_vlc_length      =
1025         s->intra_ac_vlc_last_length = uni_mpeg1_ac_vlc_len;
1026     }
1027     s->inter_ac_vlc_length      =
1028     s->inter_ac_vlc_last_length = uni_mpeg1_ac_vlc_len;
1029 }
1030
1031 #define OFFSET(x) offsetof(MpegEncContext, x)
1032 #define VE AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
1033 #define COMMON_OPTS                                                           \
1034     { "intra_vlc",           "Use MPEG-2 intra VLC table.",                   \
1035       OFFSET(intra_vlc_format),    AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE }, \
1036     { "drop_frame_timecode", "Timecode is in drop frame format.",             \
1037       OFFSET(drop_frame_timecode), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE }, \
1038     { "scan_offset",         "Reserve space for SVCD scan offset user data.", \
1039       OFFSET(scan_offset),         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1040
1041 static const AVOption mpeg1_options[] = {
1042     COMMON_OPTS
1043     FF_MPV_COMMON_OPTS
1044     { NULL },
1045 };
1046
1047 static const AVOption mpeg2_options[] = {
1048     COMMON_OPTS
1049     { "non_linear_quant", "Use nonlinear quantizer.",    OFFSET(q_scale_type),   AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1050     { "alternate_scan",   "Enable alternate scantable.", OFFSET(alternate_scan), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1051     FF_MPV_COMMON_OPTS
1052     { NULL },
1053 };
1054
1055 #define mpeg12_class(x)                                 \
1056 static const AVClass mpeg ## x ## _class = {            \
1057     .class_name = "mpeg" # x "video encoder",           \
1058     .item_name  = av_default_item_name,                 \
1059     .option     = mpeg ## x ## _options,                \
1060     .version    = LIBAVUTIL_VERSION_INT,                \
1061 };
1062
1063 mpeg12_class(1)
1064 mpeg12_class(2)
1065
1066 AVCodec ff_mpeg1video_encoder = {
1067     .name                 = "mpeg1video",
1068     .long_name            = NULL_IF_CONFIG_SMALL("MPEG-1 video"),
1069     .type                 = AVMEDIA_TYPE_VIDEO,
1070     .id                   = AV_CODEC_ID_MPEG1VIDEO,
1071     .priv_data_size       = sizeof(MpegEncContext),
1072     .init                 = encode_init,
1073     .encode2              = ff_MPV_encode_picture,
1074     .close                = ff_MPV_encode_end,
1075     .supported_framerates = ff_mpeg12_frame_rate_tab + 1,
1076     .pix_fmts             = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
1077                                                            AV_PIX_FMT_NONE },
1078     .capabilities         = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
1079     .priv_class           = &mpeg1_class,
1080 };
1081
1082 AVCodec ff_mpeg2video_encoder = {
1083     .name                 = "mpeg2video",
1084     .long_name            = NULL_IF_CONFIG_SMALL("MPEG-2 video"),
1085     .type                 = AVMEDIA_TYPE_VIDEO,
1086     .id                   = AV_CODEC_ID_MPEG2VIDEO,
1087     .priv_data_size       = sizeof(MpegEncContext),
1088     .init                 = encode_init,
1089     .encode2              = ff_MPV_encode_picture,
1090     .close                = ff_MPV_encode_end,
1091     .supported_framerates = ff_mpeg12_frame_rate_tab + 1,
1092     .pix_fmts             = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
1093                                                            AV_PIX_FMT_YUV422P,
1094                                                            AV_PIX_FMT_NONE },
1095     .capabilities         = CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
1096     .priv_class           = &mpeg2_class,
1097 };