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