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