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