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