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