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