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