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