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