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