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