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