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