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