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