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