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