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