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