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