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