OSDN Git Service

Fixed invalid access in wavpack decoder on corrupted bitstream.
[coroid/libav_saccubus.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 FF_API_MPEGVIDEO_GLOBAL_OPTS
146     if (avctx->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE)
147         s->drop_frame_timecode = 1;
148     if (avctx->flags & CODEC_FLAG_SVCD_SCAN_OFFSET)
149         s->scan_offset = 1;
150 #endif
151
152     if(find_frame_rate_index(s) < 0){
153         if(s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
154             av_log(avctx, AV_LOG_ERROR, "MPEG1/2 does not support %d/%d fps\n", avctx->time_base.den, avctx->time_base.num);
155             return -1;
156         }else{
157             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);
158         }
159     }
160
161     if(avctx->profile == FF_PROFILE_UNKNOWN){
162         if(avctx->level != FF_LEVEL_UNKNOWN){
163             av_log(avctx, AV_LOG_ERROR, "Set profile and level\n");
164             return -1;
165         }
166         avctx->profile = s->chroma_format == CHROMA_420 ? 4 : 0; /* Main or 4:2:2 */
167     }
168
169     if(avctx->level == FF_LEVEL_UNKNOWN){
170         if(avctx->profile == 0){ /* 4:2:2 */
171             if(avctx->width <= 720 && avctx->height <= 608) avctx->level = 5; /* Main */
172             else                                            avctx->level = 2; /* High */
173         }else{
174             if(avctx->profile != 1 && s->chroma_format != CHROMA_420){
175                 av_log(avctx, AV_LOG_ERROR, "Only High(1) and 4:2:2(0) profiles support 4:2:2 color sampling\n");
176                 return -1;
177             }
178             if(avctx->width <= 720 && avctx->height <= 576) avctx->level = 8; /* Main */
179             else if(avctx->width <= 1440)                   avctx->level = 6; /* High 1440 */
180             else                                            avctx->level = 4; /* High */
181         }
182     }
183
184     if (s->drop_frame_timecode && s->frame_rate_index != 4) {
185         av_log(avctx, AV_LOG_ERROR, "Drop frame time code only allowed with 1001/30000 fps\n");
186         return -1;
187     }
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->drop_frame_timecode); /* drop frame flag */
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->drop_frame_timecode) {
303                 /* only works for NTSC 29.97 */
304                 int d = time_code / 17982;
305                 int m = time_code % 17982;
306                 //if (m < 2) m += 2; /* not needed since -2,-1 / 1798 in C returns 0 */
307                 time_code += 18 * d + 2 * ((m - 2) / 1798);
308             }
309             put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
310             put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
311             put_bits(&s->pb, 1, 1);
312             put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
313             put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
314             put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
315             put_bits(&s->pb, 1, 0); /* broken link */
316         }
317 }
318
319 static inline void encode_mb_skip_run(MpegEncContext *s, int run){
320     while (run >= 33) {
321         put_bits(&s->pb, 11, 0x008);
322         run -= 33;
323     }
324     put_bits(&s->pb, ff_mpeg12_mbAddrIncrTable[run][1],
325              ff_mpeg12_mbAddrIncrTable[run][0]);
326 }
327
328 static av_always_inline void put_qscale(MpegEncContext *s)
329 {
330     if(s->q_scale_type){
331         assert(s->qscale>=1 && s->qscale <=12);
332         put_bits(&s->pb, 5, inv_non_linear_qscale[s->qscale]);
333     }else{
334         put_bits(&s->pb, 5, s->qscale);
335     }
336 }
337
338 void ff_mpeg1_encode_slice_header(MpegEncContext *s){
339     if (s->height > 2800) {
340         put_header(s, SLICE_MIN_START_CODE + (s->mb_y & 127));
341         put_bits(&s->pb, 3, s->mb_y >> 7);  /* slice_vertical_position_extension */
342     } else {
343         put_header(s, SLICE_MIN_START_CODE + s->mb_y);
344     }
345     put_qscale(s);
346     put_bits(&s->pb, 1, 0); /* slice extra information */
347 }
348
349 void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
350 {
351     mpeg1_encode_sequence_header(s);
352
353     /* mpeg1 picture header */
354     put_header(s, PICTURE_START_CODE);
355     /* temporal reference */
356
357     // RAL: s->picture_number instead of s->fake_picture_number
358     put_bits(&s->pb, 10, (s->picture_number -
359                           s->gop_picture_number) & 0x3ff);
360     put_bits(&s->pb, 3, s->pict_type);
361
362     s->vbv_delay_ptr= s->pb.buf + put_bits_count(&s->pb)/8;
363     put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
364
365     // RAL: Forward f_code also needed for B frames
366     if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_B) {
367         put_bits(&s->pb, 1, 0); /* half pel coordinates */
368         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
369             put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
370         else
371             put_bits(&s->pb, 3, 7); /* forward_f_code */
372     }
373
374     // RAL: Backward f_code necessary for B frames
375     if (s->pict_type == AV_PICTURE_TYPE_B) {
376         put_bits(&s->pb, 1, 0); /* half pel coordinates */
377         if(s->codec_id == CODEC_ID_MPEG1VIDEO)
378             put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
379         else
380             put_bits(&s->pb, 3, 7); /* backward_f_code */
381     }
382
383     put_bits(&s->pb, 1, 0); /* extra bit picture */
384
385     s->frame_pred_frame_dct = 1;
386     if(s->codec_id == CODEC_ID_MPEG2VIDEO){
387         put_header(s, EXT_START_CODE);
388         put_bits(&s->pb, 4, 8); //pic ext
389         if (s->pict_type == AV_PICTURE_TYPE_P || s->pict_type == AV_PICTURE_TYPE_B) {
390             put_bits(&s->pb, 4, s->f_code);
391             put_bits(&s->pb, 4, s->f_code);
392         }else{
393             put_bits(&s->pb, 8, 255);
394         }
395         if (s->pict_type == AV_PICTURE_TYPE_B) {
396             put_bits(&s->pb, 4, s->b_code);
397             put_bits(&s->pb, 4, s->b_code);
398         }else{
399             put_bits(&s->pb, 8, 255);
400         }
401         put_bits(&s->pb, 2, s->intra_dc_precision);
402
403         assert(s->picture_structure == PICT_FRAME);
404         put_bits(&s->pb, 2, s->picture_structure);
405         if (s->progressive_sequence) {
406             put_bits(&s->pb, 1, 0); /* no repeat */
407         } else {
408             put_bits(&s->pb, 1, s->current_picture_ptr->f.top_field_first);
409         }
410         /* XXX: optimize the generation of this flag with entropy
411            measures */
412         s->frame_pred_frame_dct = s->progressive_sequence;
413
414         put_bits(&s->pb, 1, s->frame_pred_frame_dct);
415         put_bits(&s->pb, 1, s->concealment_motion_vectors);
416         put_bits(&s->pb, 1, s->q_scale_type);
417         put_bits(&s->pb, 1, s->intra_vlc_format);
418         put_bits(&s->pb, 1, s->alternate_scan);
419         put_bits(&s->pb, 1, s->repeat_first_field);
420         s->progressive_frame = s->progressive_sequence;
421         put_bits(&s->pb, 1, s->chroma_format == CHROMA_420 ? s->progressive_frame : 0); /* chroma_420_type */
422         put_bits(&s->pb, 1, s->progressive_frame);
423         put_bits(&s->pb, 1, 0); //composite_display_flag
424     }
425     if (s->scan_offset) {
426         int i;
427
428         put_header(s, USER_START_CODE);
429         for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){
430             put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
431         }
432     }
433
434     s->mb_y=0;
435     ff_mpeg1_encode_slice_header(s);
436 }
437
438 static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
439                                 int has_mv, int field_motion)
440 {
441     put_bits(&s->pb, n, bits);
442     if (!s->frame_pred_frame_dct) {
443         if (has_mv)
444             put_bits(&s->pb, 2, 2 - field_motion); /* motion_type: frame/field */
445         put_bits(&s->pb, 1, s->interlaced_dct);
446     }
447 }
448
449 static av_always_inline void mpeg1_encode_mb_internal(MpegEncContext *s,
450                                                    DCTELEM block[6][64],
451                                                    int motion_x, int motion_y,
452                                                    int mb_block_count)
453 {
454     int i, cbp;
455     const int mb_x = s->mb_x;
456     const int mb_y = s->mb_y;
457     const int first_mb= mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
458
459     /* compute cbp */
460     cbp = 0;
461     for(i=0;i<mb_block_count;i++) {
462         if (s->block_last_index[i] >= 0)
463             cbp |= 1 << (mb_block_count - 1 - i);
464     }
465
466     if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
467         (mb_x != s->mb_width - 1 || (mb_y != s->mb_height - 1 && s->codec_id == CODEC_ID_MPEG1VIDEO)) &&
468         ((s->pict_type == AV_PICTURE_TYPE_P && (motion_x | motion_y) == 0) ||
469         (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) |
470         ((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))) {
471         s->mb_skip_run++;
472         s->qscale -= s->dquant;
473         s->skip_count++;
474         s->misc_bits++;
475         s->last_bits++;
476         if(s->pict_type == AV_PICTURE_TYPE_P){
477             s->last_mv[0][1][0]= s->last_mv[0][0][0]=
478             s->last_mv[0][1][1]= s->last_mv[0][0][1]= 0;
479         }
480     } else {
481         if(first_mb){
482             assert(s->mb_skip_run == 0);
483             encode_mb_skip_run(s, s->mb_x);
484         }else{
485             encode_mb_skip_run(s, s->mb_skip_run);
486         }
487
488         if (s->pict_type == AV_PICTURE_TYPE_I) {
489             if(s->dquant && cbp){
490                 put_mb_modes(s, 2, 1, 0, 0); /* macroblock_type : macroblock_quant = 1 */
491                 put_qscale(s);
492             }else{
493                 put_mb_modes(s, 1, 1, 0, 0); /* macroblock_type : macroblock_quant = 0 */
494                 s->qscale -= s->dquant;
495             }
496             s->misc_bits+= get_bits_diff(s);
497             s->i_count++;
498         } else if (s->mb_intra) {
499             if(s->dquant && cbp){
500                 put_mb_modes(s, 6, 0x01, 0, 0);
501                 put_qscale(s);
502             }else{
503                 put_mb_modes(s, 5, 0x03, 0, 0);
504                 s->qscale -= s->dquant;
505             }
506             s->misc_bits+= get_bits_diff(s);
507             s->i_count++;
508             memset(s->last_mv, 0, sizeof(s->last_mv));
509         } else if (s->pict_type == AV_PICTURE_TYPE_P) {
510             if(s->mv_type == MV_TYPE_16X16){
511                 if (cbp != 0) {
512                     if ((motion_x|motion_y) == 0) {
513                         if(s->dquant){
514                             put_mb_modes(s, 5, 1, 0, 0); /* macroblock_pattern & quant */
515                             put_qscale(s);
516                         }else{
517                             put_mb_modes(s, 2, 1, 0, 0); /* macroblock_pattern only */
518                         }
519                         s->misc_bits+= get_bits_diff(s);
520                     } else {
521                         if(s->dquant){
522                             put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
523                             put_qscale(s);
524                         }else{
525                             put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
526                         }
527                         s->misc_bits+= get_bits_diff(s);
528                         mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
529                         mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
530                         s->mv_bits+= get_bits_diff(s);
531                     }
532                 } else {
533                     put_bits(&s->pb, 3, 1); /* motion only */
534                     if (!s->frame_pred_frame_dct)
535                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
536                     s->misc_bits+= get_bits_diff(s);
537                     mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
538                     mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
539                     s->qscale -= s->dquant;
540                     s->mv_bits+= get_bits_diff(s);
541                 }
542                 s->last_mv[0][1][0]= s->last_mv[0][0][0]= motion_x;
543                 s->last_mv[0][1][1]= s->last_mv[0][0][1]= motion_y;
544             }else{
545                 assert(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);
546
547                 if (cbp) {
548                     if(s->dquant){
549                         put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
550                         put_qscale(s);
551                     }else{
552                         put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
553                     }
554                 } else {
555                     put_bits(&s->pb, 3, 1); /* motion only */
556                     put_bits(&s->pb, 2, 1); /* motion_type: field */
557                     s->qscale -= s->dquant;
558                 }
559                 s->misc_bits+= get_bits_diff(s);
560                 for(i=0; i<2; i++){
561                     put_bits(&s->pb, 1, s->field_select[0][i]);
562                     mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
563                     mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
564                     s->last_mv[0][i][0]=   s->mv[0][i][0];
565                     s->last_mv[0][i][1]= 2*s->mv[0][i][1];
566                 }
567                 s->mv_bits+= get_bits_diff(s);
568             }
569             if(cbp) {
570                 if (s->chroma_y_shift) {
571                     put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp][1], ff_mpeg12_mbPatTable[cbp][0]);
572                 } else {
573                     put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp>>2][1], ff_mpeg12_mbPatTable[cbp>>2][0]);
574                     put_sbits(&s->pb, 2, cbp);
575                 }
576             }
577             s->f_count++;
578         } else{
579             if(s->mv_type == MV_TYPE_16X16){
580                 if (cbp){    // With coded bloc pattern
581                     if (s->dquant) {
582                         if(s->mv_dir == MV_DIR_FORWARD)
583                             put_mb_modes(s, 6, 3, 1, 0);
584                         else
585                             put_mb_modes(s, 8-s->mv_dir, 2, 1, 0);
586                         put_qscale(s);
587                     } else {
588                         put_mb_modes(s, 5-s->mv_dir, 3, 1, 0);
589                     }
590                 }else{    // No coded bloc pattern
591                     put_bits(&s->pb, 5-s->mv_dir, 2);
592                     if (!s->frame_pred_frame_dct)
593                         put_bits(&s->pb, 2, 2); /* motion_type: frame */
594                     s->qscale -= s->dquant;
595                 }
596                 s->misc_bits += get_bits_diff(s);
597                 if (s->mv_dir&MV_DIR_FORWARD){
598                     mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
599                     mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
600                     s->last_mv[0][0][0]=s->last_mv[0][1][0]= s->mv[0][0][0];
601                     s->last_mv[0][0][1]=s->last_mv[0][1][1]= s->mv[0][0][1];
602                     s->f_count++;
603                 }
604                 if (s->mv_dir&MV_DIR_BACKWARD){
605                     mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
606                     mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
607                     s->last_mv[1][0][0]=s->last_mv[1][1][0]= s->mv[1][0][0];
608                     s->last_mv[1][0][1]=s->last_mv[1][1][1]= s->mv[1][0][1];
609                     s->b_count++;
610                 }
611             }else{
612                 assert(s->mv_type == MV_TYPE_FIELD);
613                 assert(!s->frame_pred_frame_dct);
614                 if (cbp){    // With coded bloc pattern
615                     if (s->dquant) {
616                         if(s->mv_dir == MV_DIR_FORWARD)
617                             put_mb_modes(s, 6, 3, 1, 1);
618                         else
619                             put_mb_modes(s, 8-s->mv_dir, 2, 1, 1);
620                         put_qscale(s);
621                     } else {
622                         put_mb_modes(s, 5-s->mv_dir, 3, 1, 1);
623                     }
624                 }else{    // No coded bloc pattern
625                     put_bits(&s->pb, 5-s->mv_dir, 2);
626                     put_bits(&s->pb, 2, 1); /* motion_type: field */
627                     s->qscale -= s->dquant;
628                 }
629                 s->misc_bits += get_bits_diff(s);
630                 if (s->mv_dir&MV_DIR_FORWARD){
631                     for(i=0; i<2; i++){
632                         put_bits(&s->pb, 1, s->field_select[0][i]);
633                         mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
634                         mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
635                         s->last_mv[0][i][0]=   s->mv[0][i][0];
636                         s->last_mv[0][i][1]= 2*s->mv[0][i][1];
637                     }
638                     s->f_count++;
639                 }
640                 if (s->mv_dir&MV_DIR_BACKWARD){
641                     for(i=0; i<2; i++){
642                         put_bits(&s->pb, 1, s->field_select[1][i]);
643                         mpeg1_encode_motion(s, s->mv[1][i][0] -  s->last_mv[1][i][0]    , s->b_code);
644                         mpeg1_encode_motion(s, s->mv[1][i][1] - (s->last_mv[1][i][1]>>1), s->b_code);
645                         s->last_mv[1][i][0]=   s->mv[1][i][0];
646                         s->last_mv[1][i][1]= 2*s->mv[1][i][1];
647                     }
648                     s->b_count++;
649                 }
650             }
651             s->mv_bits += get_bits_diff(s);
652             if(cbp) {
653                 if (s->chroma_y_shift) {
654                     put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp][1], ff_mpeg12_mbPatTable[cbp][0]);
655                 } else {
656                     put_bits(&s->pb, ff_mpeg12_mbPatTable[cbp>>2][1], ff_mpeg12_mbPatTable[cbp>>2][0]);
657                     put_sbits(&s->pb, 2, cbp);
658                 }
659             }
660         }
661         for(i=0;i<mb_block_count;i++) {
662             if (cbp & (1 << (mb_block_count - 1 - i))) {
663                 mpeg1_encode_block(s, block[i], i);
664             }
665         }
666         s->mb_skip_run = 0;
667         if(s->mb_intra)
668             s->i_tex_bits+= get_bits_diff(s);
669         else
670             s->p_tex_bits+= get_bits_diff(s);
671     }
672 }
673
674 void mpeg1_encode_mb(MpegEncContext *s, DCTELEM block[6][64], int motion_x, int motion_y)
675 {
676     if (s->chroma_format == CHROMA_420) mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 6);
677     else                                mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 8);
678 }
679
680 // RAL: Parameter added: f_or_b_code
681 static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
682 {
683     if (val == 0) {
684         /* zero vector */
685         put_bits(&s->pb,
686                  ff_mpeg12_mbMotionVectorTable[0][1],
687                  ff_mpeg12_mbMotionVectorTable[0][0]);
688     } else {
689         int code, sign, bits;
690         int bit_size = f_or_b_code - 1;
691         int range = 1 << bit_size;
692         /* modulo encoding */
693         int l= INT_BIT - 5 - bit_size;
694         val= (val<<l)>>l;
695
696         if (val >= 0) {
697             val--;
698             code = (val >> bit_size) + 1;
699             bits = val & (range - 1);
700             sign = 0;
701         } else {
702             val = -val;
703             val--;
704             code = (val >> bit_size) + 1;
705             bits = val & (range - 1);
706             sign = 1;
707         }
708
709         assert(code > 0 && code <= 16);
710
711         put_bits(&s->pb,
712                  ff_mpeg12_mbMotionVectorTable[code][1],
713                  ff_mpeg12_mbMotionVectorTable[code][0]);
714
715         put_bits(&s->pb, 1, sign);
716         if (bit_size > 0) {
717             put_bits(&s->pb, bit_size, bits);
718         }
719     }
720 }
721
722 void ff_mpeg1_encode_init(MpegEncContext *s)
723 {
724     static int done=0;
725
726     ff_mpeg12_common_init(s);
727
728     if(!done){
729         int f_code;
730         int mv;
731         int i;
732
733         done=1;
734         init_rl(&ff_rl_mpeg1, ff_mpeg12_static_rl_table_store[0]);
735         init_rl(&ff_rl_mpeg2, ff_mpeg12_static_rl_table_store[1]);
736
737         for(i=0; i<64; i++)
738         {
739                 mpeg1_max_level[0][i]= ff_rl_mpeg1.max_level[0][i];
740                 mpeg1_index_run[0][i]= ff_rl_mpeg1.index_run[0][i];
741         }
742
743         init_uni_ac_vlc(&ff_rl_mpeg1, uni_mpeg1_ac_vlc_len);
744         if(s->intra_vlc_format)
745             init_uni_ac_vlc(&ff_rl_mpeg2, uni_mpeg2_ac_vlc_len);
746
747         /* build unified dc encoding tables */
748         for(i=-255; i<256; i++)
749         {
750                 int adiff, index;
751                 int bits, code;
752                 int diff=i;
753
754                 adiff = FFABS(diff);
755                 if(diff<0) diff--;
756                 index = av_log2(2*adiff);
757
758                 bits= ff_mpeg12_vlc_dc_lum_bits[index] + index;
759                 code= (ff_mpeg12_vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1));
760                 mpeg1_lum_dc_uni[i+255]= bits + (code<<8);
761
762                 bits= ff_mpeg12_vlc_dc_chroma_bits[index] + index;
763                 code= (ff_mpeg12_vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1));
764                 mpeg1_chr_dc_uni[i+255]= bits + (code<<8);
765         }
766
767         for(f_code=1; f_code<=MAX_FCODE; f_code++){
768             for(mv=-MAX_MV; mv<=MAX_MV; mv++){
769                 int len;
770
771                 if(mv==0) len= ff_mpeg12_mbMotionVectorTable[0][1];
772                 else{
773                     int val, bit_size, code;
774
775                     bit_size = f_code - 1;
776
777                     val=mv;
778                     if (val < 0)
779                         val = -val;
780                     val--;
781                     code = (val >> bit_size) + 1;
782                     if(code<17){
783                         len= ff_mpeg12_mbMotionVectorTable[code][1] + 1 + bit_size;
784                     }else{
785                         len= ff_mpeg12_mbMotionVectorTable[16][1] + 2 + bit_size;
786                     }
787                 }
788
789                 mv_penalty[f_code][mv+MAX_MV]= len;
790             }
791         }
792
793
794         for(f_code=MAX_FCODE; f_code>0; f_code--){
795             for(mv=-(8<<f_code); mv<(8<<f_code); mv++){
796                 fcode_tab[mv+MAX_MV]= f_code;
797             }
798         }
799     }
800     s->me.mv_penalty= mv_penalty;
801     s->fcode_tab= fcode_tab;
802     if(s->codec_id == CODEC_ID_MPEG1VIDEO){
803         s->min_qcoeff=-255;
804         s->max_qcoeff= 255;
805     }else{
806         s->min_qcoeff=-2047;
807         s->max_qcoeff= 2047;
808     }
809     if (s->intra_vlc_format) {
810         s->intra_ac_vlc_length=
811         s->intra_ac_vlc_last_length= uni_mpeg2_ac_vlc_len;
812     } else {
813         s->intra_ac_vlc_length=
814         s->intra_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
815     }
816     s->inter_ac_vlc_length=
817     s->inter_ac_vlc_last_length= uni_mpeg1_ac_vlc_len;
818 }
819
820 static inline void encode_dc(MpegEncContext *s, int diff, int component)
821 {
822   if(((unsigned) (diff+255)) >= 511){
823         int index;
824
825         if(diff<0){
826             index= av_log2_16bit(-2*diff);
827             diff--;
828         }else{
829             index= av_log2_16bit(2*diff);
830         }
831         if (component == 0) {
832             put_bits(
833                 &s->pb,
834                 ff_mpeg12_vlc_dc_lum_bits[index] + index,
835                 (ff_mpeg12_vlc_dc_lum_code[index]<<index) + (diff & ((1 << index) - 1)));
836         }else{
837             put_bits(
838                 &s->pb,
839                 ff_mpeg12_vlc_dc_chroma_bits[index] + index,
840                 (ff_mpeg12_vlc_dc_chroma_code[index]<<index) + (diff & ((1 << index) - 1)));
841         }
842   }else{
843     if (component == 0) {
844         put_bits(
845             &s->pb,
846             mpeg1_lum_dc_uni[diff+255]&0xFF,
847             mpeg1_lum_dc_uni[diff+255]>>8);
848     } else {
849         put_bits(
850             &s->pb,
851             mpeg1_chr_dc_uni[diff+255]&0xFF,
852             mpeg1_chr_dc_uni[diff+255]>>8);
853     }
854   }
855 }
856
857 static void mpeg1_encode_block(MpegEncContext *s,
858                                DCTELEM *block,
859                                int n)
860 {
861     int alevel, level, last_non_zero, dc, diff, i, j, run, last_index, sign;
862     int code, component;
863     const uint16_t (*table_vlc)[2] = ff_rl_mpeg1.table_vlc;
864
865     last_index = s->block_last_index[n];
866
867     /* DC coef */
868     if (s->mb_intra) {
869         component = (n <= 3 ? 0 : (n&1) + 1);
870         dc = block[0]; /* overflow is impossible */
871         diff = dc - s->last_dc[component];
872         encode_dc(s, diff, component);
873         s->last_dc[component] = dc;
874         i = 1;
875         if (s->intra_vlc_format)
876             table_vlc = ff_rl_mpeg2.table_vlc;
877     } else {
878         /* encode the first coefficient : needs to be done here because
879            it is handled slightly differently */
880         level = block[0];
881         if (abs(level) == 1) {
882                 code = ((uint32_t)level >> 31); /* the sign bit */
883                 put_bits(&s->pb, 2, code | 0x02);
884                 i = 1;
885         } else {
886             i = 0;
887             last_non_zero = -1;
888             goto next_coef;
889         }
890     }
891
892     /* now quantify & encode AC coefs */
893     last_non_zero = i - 1;
894
895     for(;i<=last_index;i++) {
896         j = s->intra_scantable.permutated[i];
897         level = block[j];
898     next_coef:
899         /* encode using VLC */
900         if (level != 0) {
901             run = i - last_non_zero - 1;
902
903             alevel= level;
904             MASK_ABS(sign, alevel)
905             sign&=1;
906
907             if (alevel <= mpeg1_max_level[0][run]){
908                 code= mpeg1_index_run[0][run] + alevel - 1;
909                 /* store the vlc & sign at once */
910                 put_bits(&s->pb, table_vlc[code][1]+1, (table_vlc[code][0]<<1) + sign);
911             } else {
912                 /* escape seems to be pretty rare <5% so I do not optimize it */
913                 put_bits(&s->pb, table_vlc[111][1], table_vlc[111][0]);
914                 /* escape: only clip in this case */
915                 put_bits(&s->pb, 6, run);
916                 if(s->codec_id == CODEC_ID_MPEG1VIDEO){
917                     if (alevel < 128) {
918                         put_sbits(&s->pb, 8, level);
919                     } else {
920                         if (level < 0) {
921                             put_bits(&s->pb, 16, 0x8001 + level + 255);
922                         } else {
923                             put_sbits(&s->pb, 16, level);
924                         }
925                     }
926                 }else{
927                     put_sbits(&s->pb, 12, level);
928                 }
929             }
930             last_non_zero = i;
931         }
932     }
933     /* end of block */
934     put_bits(&s->pb, table_vlc[112][1], table_vlc[112][0]);
935 }
936
937 #define OFFSET(x) offsetof(MpegEncContext, x)
938 #define VE AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
939 #define COMMON_OPTS\
940     { "intra_vlc",           "Use MPEG-2 intra VLC table.",       OFFSET(intra_vlc_format),    FF_OPT_TYPE_INT, { 0 }, 0, 1, VE },\
941     { "drop_frame_timecode", "Timecode is in drop frame format.", OFFSET(drop_frame_timecode), FF_OPT_TYPE_INT, { 0 }, 0, 1, VE}, \
942     { "scan_offset",         "Reserve space for SVCD scan offset user data.", OFFSET(scan_offset), FF_OPT_TYPE_INT, { 0 }, 0, 1, VE },
943
944 static const AVOption mpeg1_options[] = {
945     COMMON_OPTS
946     { NULL },
947 };
948
949 static const AVOption mpeg2_options[] = {
950     COMMON_OPTS
951     { "non_linear_quant",    "Use nonlinear quantizer.",          OFFSET(q_scale_type),         FF_OPT_TYPE_INT, { 0 }, 0, 1, VE },
952     { "alternate_scan",      "Enable alternate scantable.",       OFFSET(alternate_scan),       FF_OPT_TYPE_INT, { 0 }, 0, 1, VE },
953     { NULL },
954 };
955
956 #define mpeg12_class(x)\
957 static const AVClass mpeg## x ##_class = {\
958     .class_name   = "mpeg" #x "video encoder",\
959     .item_name    = av_default_item_name,\
960     .option       = mpeg## x ##_options,\
961     .version      = LIBAVUTIL_VERSION_INT,\
962 };
963
964 mpeg12_class(1)
965 mpeg12_class(2)
966
967 AVCodec ff_mpeg1video_encoder = {
968     .name           = "mpeg1video",
969     .type           = AVMEDIA_TYPE_VIDEO,
970     .id             = CODEC_ID_MPEG1VIDEO,
971     .priv_data_size = sizeof(MpegEncContext),
972     .init           = encode_init,
973     .encode         = MPV_encode_picture,
974     .close          = MPV_encode_end,
975     .supported_framerates= ff_frame_rate_tab+1,
976     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
977     .capabilities= CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
978     .long_name= NULL_IF_CONFIG_SMALL("MPEG-1 video"),
979     .priv_class     = &mpeg1_class,
980 };
981
982 AVCodec ff_mpeg2video_encoder = {
983     .name           = "mpeg2video",
984     .type           = AVMEDIA_TYPE_VIDEO,
985     .id             = CODEC_ID_MPEG2VIDEO,
986     .priv_data_size = sizeof(MpegEncContext),
987     .init           = encode_init,
988     .encode         = MPV_encode_picture,
989     .close          = MPV_encode_end,
990     .supported_framerates= ff_frame_rate_tab+1,
991     .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE},
992     .capabilities= CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS,
993     .long_name= NULL_IF_CONFIG_SMALL("MPEG-2 video"),
994     .priv_class     = &mpeg2_class,
995 };