1/*
2 * MPEG-4 encoder
3 * Copyright (c) 2000,2001 Fabrice Bellard
4 * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "libavutil/attributes.h"
24#include "libavutil/log.h"
25#include "libavutil/opt.h"
26#include "libavutil/thread.h"
27#include "codec_internal.h"
28#include "mpegutils.h"
29#include "mpegvideo.h"
30#include "h263.h"
31#include "h263enc.h"
32#include "mpeg4video.h"
33#include "mpeg4videodata.h"
34#include "mpeg4videoenc.h"
35#include "mpegvideoenc.h"
36#include "profiles.h"
37#include "version.h"
38
39/* The uni_DCtab_* tables below contain unified bits+length tables to encode DC
40 * differences in MPEG-4. Unified in the sense that the specification specifies
41 * this encoding in several steps. */
42static uint8_t  uni_DCtab_lum_len[512];
43static uint8_t  uni_DCtab_chrom_len[512];
44static uint16_t uni_DCtab_lum_bits[512];
45static uint16_t uni_DCtab_chrom_bits[512];
46
47/* Unified encoding tables for run length encoding of coefficients.
48 * Unified in the sense that the specification specifies the encoding in several steps. */
49static uint32_t uni_mpeg4_intra_rl_bits[64 * 64 * 2 * 2];
50static uint8_t  uni_mpeg4_intra_rl_len[64 * 64 * 2 * 2];
51static uint32_t uni_mpeg4_inter_rl_bits[64 * 64 * 2 * 2];
52static uint8_t  uni_mpeg4_inter_rl_len[64 * 64 * 2 * 2];
53
54//#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 + (run) * 256 + (level))
55//#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) + (level) * 64)
56#define UNI_MPEG4_ENC_INDEX(last, run, level) ((last) * 128 * 64 + (run) * 128 + (level))
57
58/* MPEG-4
59 * inter
60 * max level: 24/6
61 * max run: 53/63
62 *
63 * intra
64 * max level: 53/16
65 * max run: 29/41
66 */
67
68/**
69 * Return the number of bits that encoding the 8x8 block in block would need.
70 * @param[in]  block_last_index last index in scantable order that refers to a non zero element in block.
71 */
72static inline int get_block_rate(MpegEncContext *s, int16_t block[64],
73                                 int block_last_index, uint8_t scantable[64])
74{
75    int last = 0;
76    int j;
77    int rate = 0;
78
79    for (j = 1; j <= block_last_index; j++) {
80        const int index = scantable[j];
81        int level = block[index];
82        if (level) {
83            level += 64;
84            if ((level & (~127)) == 0) {
85                if (j < block_last_index)
86                    rate += s->intra_ac_vlc_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
87                else
88                    rate += s->intra_ac_vlc_last_length[UNI_AC_ENC_INDEX(j - last - 1, level)];
89            } else
90                rate += s->ac_esc_length;
91
92            last = j;
93        }
94    }
95
96    return rate;
97}
98
99/**
100 * Restore the ac coefficients in block that have been changed by decide_ac_pred().
101 * This function also restores s->block_last_index.
102 * @param[in,out] block MB coefficients, these will be restored
103 * @param[in] dir ac prediction direction for each 8x8 block
104 * @param[out] st scantable for each 8x8 block
105 * @param[in] zigzag_last_index index referring to the last non zero coefficient in zigzag order
106 */
107static inline void restore_ac_coeffs(MpegEncContext *s, int16_t block[6][64],
108                                     const int dir[6], uint8_t *st[6],
109                                     const int zigzag_last_index[6])
110{
111    int i, n;
112    memcpy(s->block_last_index, zigzag_last_index, sizeof(int) * 6);
113
114    for (n = 0; n < 6; n++) {
115        int16_t *ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
116
117        st[n] = s->intra_scantable.permutated;
118        if (dir[n]) {
119            /* top prediction */
120            for (i = 1; i < 8; i++)
121                block[n][s->idsp.idct_permutation[i]] = ac_val[i + 8];
122        } else {
123            /* left prediction */
124            for (i = 1; i < 8; i++)
125                block[n][s->idsp.idct_permutation[i << 3]] = ac_val[i];
126        }
127    }
128}
129
130/**
131 * Return the optimal value (0 or 1) for the ac_pred element for the given MB in MPEG-4.
132 * This function will also update s->block_last_index and s->ac_val.
133 * @param[in,out] block MB coefficients, these will be updated if 1 is returned
134 * @param[in] dir ac prediction direction for each 8x8 block
135 * @param[out] st scantable for each 8x8 block
136 * @param[out] zigzag_last_index index referring to the last non zero coefficient in zigzag order
137 */
138static inline int decide_ac_pred(MpegEncContext *s, int16_t block[6][64],
139                                 const int dir[6], uint8_t *st[6],
140                                 int zigzag_last_index[6])
141{
142    int score = 0;
143    int i, n;
144    int8_t *const qscale_table = s->current_picture.qscale_table;
145
146    memcpy(zigzag_last_index, s->block_last_index, sizeof(int) * 6);
147
148    for (n = 0; n < 6; n++) {
149        int16_t *ac_val, *ac_val1;
150
151        score -= get_block_rate(s, block[n], s->block_last_index[n],
152                                s->intra_scantable.permutated);
153
154        ac_val  = &s->ac_val[0][0][0] + s->block_index[n] * 16;
155        ac_val1 = ac_val;
156        if (dir[n]) {
157            const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
158            /* top prediction */
159            ac_val -= s->block_wrap[n] * 16;
160            if (s->mb_y == 0 || s->qscale == qscale_table[xy] || n == 2 || n == 3) {
161                /* same qscale */
162                for (i = 1; i < 8; i++) {
163                    const int level = block[n][s->idsp.idct_permutation[i]];
164                    block[n][s->idsp.idct_permutation[i]] = level - ac_val[i + 8];
165                    ac_val1[i]     = block[n][s->idsp.idct_permutation[i << 3]];
166                    ac_val1[i + 8] = level;
167                }
168            } else {
169                /* different qscale, we must rescale */
170                for (i = 1; i < 8; i++) {
171                    const int level = block[n][s->idsp.idct_permutation[i]];
172                    block[n][s->idsp.idct_permutation[i]] = level - ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
173                    ac_val1[i]     = block[n][s->idsp.idct_permutation[i << 3]];
174                    ac_val1[i + 8] = level;
175                }
176            }
177            st[n] = s->intra_h_scantable.permutated;
178        } else {
179            const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
180            /* left prediction */
181            ac_val -= 16;
182            if (s->mb_x == 0 || s->qscale == qscale_table[xy] || n == 1 || n == 3) {
183                /* same qscale */
184                for (i = 1; i < 8; i++) {
185                    const int level = block[n][s->idsp.idct_permutation[i << 3]];
186                    block[n][s->idsp.idct_permutation[i << 3]] = level - ac_val[i];
187                    ac_val1[i]     = level;
188                    ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
189                }
190            } else {
191                /* different qscale, we must rescale */
192                for (i = 1; i < 8; i++) {
193                    const int level = block[n][s->idsp.idct_permutation[i << 3]];
194                    block[n][s->idsp.idct_permutation[i << 3]] = level - ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
195                    ac_val1[i]     = level;
196                    ac_val1[i + 8] = block[n][s->idsp.idct_permutation[i]];
197                }
198            }
199            st[n] = s->intra_v_scantable.permutated;
200        }
201
202        for (i = 63; i > 0; i--)  // FIXME optimize
203            if (block[n][st[n][i]])
204                break;
205        s->block_last_index[n] = i;
206
207        score += get_block_rate(s, block[n], s->block_last_index[n], st[n]);
208    }
209
210    if (score < 0) {
211        return 1;
212    } else {
213        restore_ac_coeffs(s, block, dir, st, zigzag_last_index);
214        return 0;
215    }
216}
217
218/**
219 * modify mb_type & qscale so that encoding is actually possible in MPEG-4
220 */
221void ff_clean_mpeg4_qscales(MpegEncContext *s)
222{
223    int i;
224    int8_t *const qscale_table = s->current_picture.qscale_table;
225
226    ff_clean_h263_qscales(s);
227
228    if (s->pict_type == AV_PICTURE_TYPE_B) {
229        int odd = 0;
230        /* ok, come on, this isn't funny anymore, there's more code for
231         * handling this MPEG-4 mess than for the actual adaptive quantization */
232
233        for (i = 0; i < s->mb_num; i++) {
234            int mb_xy = s->mb_index2xy[i];
235            odd += qscale_table[mb_xy] & 1;
236        }
237
238        if (2 * odd > s->mb_num)
239            odd = 1;
240        else
241            odd = 0;
242
243        for (i = 0; i < s->mb_num; i++) {
244            int mb_xy = s->mb_index2xy[i];
245            if ((qscale_table[mb_xy] & 1) != odd)
246                qscale_table[mb_xy]++;
247            if (qscale_table[mb_xy] > 31)
248                qscale_table[mb_xy] = 31;
249        }
250
251        for (i = 1; i < s->mb_num; i++) {
252            int mb_xy = s->mb_index2xy[i];
253            if (qscale_table[mb_xy] != qscale_table[s->mb_index2xy[i - 1]] &&
254                (s->mb_type[mb_xy] & CANDIDATE_MB_TYPE_DIRECT)) {
255                s->mb_type[mb_xy] |= CANDIDATE_MB_TYPE_BIDIR;
256            }
257        }
258    }
259}
260
261/**
262 * Encode the dc value.
263 * @param n block index (0-3 are luma, 4-5 are chroma)
264 */
265static inline void mpeg4_encode_dc(PutBitContext *s, int level, int n)
266{
267    /* DC will overflow if level is outside the [-255,255] range. */
268    level += 256;
269    if (n < 4) {
270        /* luminance */
271        put_bits(s, uni_DCtab_lum_len[level], uni_DCtab_lum_bits[level]);
272    } else {
273        /* chrominance */
274        put_bits(s, uni_DCtab_chrom_len[level], uni_DCtab_chrom_bits[level]);
275    }
276}
277
278static inline int mpeg4_get_dc_length(int level, int n)
279{
280    if (n < 4)
281        return uni_DCtab_lum_len[level + 256];
282    else
283        return uni_DCtab_chrom_len[level + 256];
284}
285
286/**
287 * Encode an 8x8 block.
288 * @param n block index (0-3 are luma, 4-5 are chroma)
289 */
290static inline void mpeg4_encode_block(MpegEncContext *s,
291                                      int16_t *block, int n, int intra_dc,
292                                      uint8_t *scan_table, PutBitContext *dc_pb,
293                                      PutBitContext *ac_pb)
294{
295    int i, last_non_zero;
296    uint32_t *bits_tab;
297    uint8_t *len_tab;
298    const int last_index = s->block_last_index[n];
299
300    if (s->mb_intra) {  // Note gcc (3.2.1 at least) will optimize this away
301        /* MPEG-4 based DC predictor */
302        mpeg4_encode_dc(dc_pb, intra_dc, n);
303        if (last_index < 1)
304            return;
305        i = 1;
306        bits_tab = uni_mpeg4_intra_rl_bits;
307        len_tab  = uni_mpeg4_intra_rl_len;
308    } else {
309        if (last_index < 0)
310            return;
311        i = 0;
312        bits_tab = uni_mpeg4_inter_rl_bits;
313        len_tab  = uni_mpeg4_inter_rl_len;
314    }
315
316    /* AC coefs */
317    last_non_zero = i - 1;
318    for (; i < last_index; i++) {
319        int level = block[scan_table[i]];
320        if (level) {
321            int run = i - last_non_zero - 1;
322            level += 64;
323            if ((level & (~127)) == 0) {
324                const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
325                put_bits(ac_pb, len_tab[index], bits_tab[index]);
326            } else {  // ESC3
327                put_bits(ac_pb,
328                         7 + 2 + 1 + 6 + 1 + 12 + 1,
329                         (3 << 23) + (3 << 21) + (0 << 20) + (run << 14) +
330                         (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
331            }
332            last_non_zero = i;
333        }
334    }
335    /* if (i <= last_index) */ {
336        int level = block[scan_table[i]];
337        int run   = i - last_non_zero - 1;
338        level += 64;
339        if ((level & (~127)) == 0) {
340            const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
341            put_bits(ac_pb, len_tab[index], bits_tab[index]);
342        } else {  // ESC3
343            put_bits(ac_pb,
344                     7 + 2 + 1 + 6 + 1 + 12 + 1,
345                     (3 << 23) + (3 << 21) + (1 << 20) + (run << 14) +
346                     (1 << 13) + (((level - 64) & 0xfff) << 1) + 1);
347        }
348    }
349}
350
351static int mpeg4_get_block_length(MpegEncContext *s,
352                                  int16_t *block, int n,
353                                  int intra_dc, uint8_t *scan_table)
354{
355    int i, last_non_zero;
356    uint8_t *len_tab;
357    const int last_index = s->block_last_index[n];
358    int len = 0;
359
360    if (s->mb_intra) {  // Note gcc (3.2.1 at least) will optimize this away
361        /* MPEG-4 based DC predictor */
362        len += mpeg4_get_dc_length(intra_dc, n);
363        if (last_index < 1)
364            return len;
365        i = 1;
366        len_tab = uni_mpeg4_intra_rl_len;
367    } else {
368        if (last_index < 0)
369            return 0;
370        i = 0;
371        len_tab = uni_mpeg4_inter_rl_len;
372    }
373
374    /* AC coefs */
375    last_non_zero = i - 1;
376    for (; i < last_index; i++) {
377        int level = block[scan_table[i]];
378        if (level) {
379            int run = i - last_non_zero - 1;
380            level += 64;
381            if ((level & (~127)) == 0) {
382                const int index = UNI_MPEG4_ENC_INDEX(0, run, level);
383                len += len_tab[index];
384            } else {  // ESC3
385                len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
386            }
387            last_non_zero = i;
388        }
389    }
390    /* if (i <= last_index) */ {
391        int level = block[scan_table[i]];
392        int run   = i - last_non_zero - 1;
393        level += 64;
394        if ((level & (~127)) == 0) {
395            const int index = UNI_MPEG4_ENC_INDEX(1, run, level);
396            len += len_tab[index];
397        } else {  // ESC3
398            len += 7 + 2 + 1 + 6 + 1 + 12 + 1;
399        }
400    }
401
402    return len;
403}
404
405static inline void mpeg4_encode_blocks(MpegEncContext *s, int16_t block[6][64],
406                                       int intra_dc[6], uint8_t **scan_table,
407                                       PutBitContext *dc_pb,
408                                       PutBitContext *ac_pb)
409{
410    int i;
411
412    if (scan_table) {
413        if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
414            for (i = 0; i < 6; i++)
415                skip_put_bits(&s->pb,
416                              mpeg4_get_block_length(s, block[i], i,
417                                                     intra_dc[i], scan_table[i]));
418        } else {
419            /* encode each block */
420            for (i = 0; i < 6; i++)
421                mpeg4_encode_block(s, block[i], i,
422                                   intra_dc[i], scan_table[i], dc_pb, ac_pb);
423        }
424    } else {
425        if (s->avctx->flags2 & AV_CODEC_FLAG2_NO_OUTPUT) {
426            for (i = 0; i < 6; i++)
427                skip_put_bits(&s->pb,
428                              mpeg4_get_block_length(s, block[i], i, 0,
429                                                     s->intra_scantable.permutated));
430        } else {
431            /* encode each block */
432            for (i = 0; i < 6; i++)
433                mpeg4_encode_block(s, block[i], i, 0,
434                                   s->intra_scantable.permutated, dc_pb, ac_pb);
435        }
436    }
437}
438
439static inline int get_b_cbp(MpegEncContext *s, int16_t block[6][64],
440                            int motion_x, int motion_y, int mb_type)
441{
442    int cbp = 0, i;
443
444    if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
445        int score        = 0;
446        const int lambda = s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
447
448        for (i = 0; i < 6; i++) {
449            if (s->coded_score[i] < 0) {
450                score += s->coded_score[i];
451                cbp   |= 1 << (5 - i);
452            }
453        }
454
455        if (cbp) {
456            int zero_score = -6;
457            if ((motion_x | motion_y | s->dquant | mb_type) == 0)
458                zero_score -= 4;  // 2 * MV + mb_type + cbp bit
459
460            zero_score *= lambda;
461            if (zero_score <= score)
462                cbp = 0;
463        }
464
465        for (i = 0; i < 6; i++) {
466            if (s->block_last_index[i] >= 0 && ((cbp >> (5 - i)) & 1) == 0) {
467                s->block_last_index[i] = -1;
468                s->bdsp.clear_block(s->block[i]);
469            }
470        }
471    } else {
472        for (i = 0; i < 6; i++) {
473            if (s->block_last_index[i] >= 0)
474                cbp |= 1 << (5 - i);
475        }
476    }
477    return cbp;
478}
479
480// FIXME this is duplicated to h263.c
481static const int dquant_code[5] = { 1, 0, 9, 2, 3 };
482
483void ff_mpeg4_encode_mb(MpegEncContext *s, int16_t block[6][64],
484                        int motion_x, int motion_y)
485{
486    int cbpc, cbpy, pred_x, pred_y;
487    PutBitContext *const pb2    = s->data_partitioning ? &s->pb2 : &s->pb;
488    PutBitContext *const tex_pb = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B ? &s->tex_pb : &s->pb;
489    PutBitContext *const dc_pb  = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_I ? &s->pb2 : &s->pb;
490    const int interleaved_stats = (s->avctx->flags & AV_CODEC_FLAG_PASS1) && !s->data_partitioning ? 1 : 0;
491
492    if (!s->mb_intra) {
493        int i, cbp;
494
495        if (s->pict_type == AV_PICTURE_TYPE_B) {
496            /* convert from mv_dir to type */
497            static const int mb_type_table[8] = { -1, 3, 2, 1, -1, -1, -1, 0 };
498            int mb_type = mb_type_table[s->mv_dir];
499
500            if (s->mb_x == 0) {
501                for (i = 0; i < 2; i++)
502                    s->last_mv[i][0][0] =
503                    s->last_mv[i][0][1] =
504                    s->last_mv[i][1][0] =
505                    s->last_mv[i][1][1] = 0;
506            }
507
508            av_assert2(s->dquant >= -2 && s->dquant <= 2);
509            av_assert2((s->dquant & 1) == 0);
510            av_assert2(mb_type >= 0);
511
512            /* nothing to do if this MB was skipped in the next P-frame */
513            if (s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]) {  // FIXME avoid DCT & ...
514                s->skip_count++;
515                s->mv[0][0][0] =
516                s->mv[0][0][1] =
517                s->mv[1][0][0] =
518                s->mv[1][0][1] = 0;
519                s->mv_dir  = MV_DIR_FORWARD;  // doesn't matter
520                s->qscale -= s->dquant;
521//                s->mb_skipped = 1;
522
523                return;
524            }
525
526            cbp = get_b_cbp(s, block, motion_x, motion_y, mb_type);
527
528            if ((cbp | motion_x | motion_y | mb_type) == 0) {
529                /* direct MB with MV={0,0} */
530                av_assert2(s->dquant == 0);
531
532                put_bits(&s->pb, 1, 1); /* mb not coded modb1=1 */
533
534                if (interleaved_stats) {
535                    s->misc_bits++;
536                    s->last_bits++;
537                }
538                s->skip_count++;
539                return;
540            }
541
542            put_bits(&s->pb, 1, 0);            /* mb coded modb1=0 */
543            put_bits(&s->pb, 1, cbp ? 0 : 1);  /* modb2 */ // FIXME merge
544            put_bits(&s->pb, mb_type + 1, 1);  // this table is so simple that we don't need it :)
545            if (cbp)
546                put_bits(&s->pb, 6, cbp);
547
548            if (cbp && mb_type) {
549                if (s->dquant)
550                    put_bits(&s->pb, 2, (s->dquant >> 2) + 3);
551                else
552                    put_bits(&s->pb, 1, 0);
553            } else
554                s->qscale -= s->dquant;
555
556            if (!s->progressive_sequence) {
557                if (cbp)
558                    put_bits(&s->pb, 1, s->interlaced_dct);
559                if (mb_type)                  // not direct mode
560                    put_bits(&s->pb, 1, s->mv_type == MV_TYPE_FIELD);
561            }
562
563            if (interleaved_stats)
564                s->misc_bits += get_bits_diff(s);
565
566            if (!mb_type) {
567                av_assert2(s->mv_dir & MV_DIRECT);
568                ff_h263_encode_motion_vector(s, motion_x, motion_y, 1);
569            } else {
570                av_assert2(mb_type > 0 && mb_type < 4);
571                if (s->mv_type != MV_TYPE_FIELD) {
572                    if (s->mv_dir & MV_DIR_FORWARD) {
573                        ff_h263_encode_motion_vector(s,
574                                                     s->mv[0][0][0] - s->last_mv[0][0][0],
575                                                     s->mv[0][0][1] - s->last_mv[0][0][1],
576                                                     s->f_code);
577                        s->last_mv[0][0][0] =
578                        s->last_mv[0][1][0] = s->mv[0][0][0];
579                        s->last_mv[0][0][1] =
580                        s->last_mv[0][1][1] = s->mv[0][0][1];
581                    }
582                    if (s->mv_dir & MV_DIR_BACKWARD) {
583                        ff_h263_encode_motion_vector(s,
584                                                     s->mv[1][0][0] - s->last_mv[1][0][0],
585                                                     s->mv[1][0][1] - s->last_mv[1][0][1],
586                                                     s->b_code);
587                        s->last_mv[1][0][0] =
588                        s->last_mv[1][1][0] = s->mv[1][0][0];
589                        s->last_mv[1][0][1] =
590                        s->last_mv[1][1][1] = s->mv[1][0][1];
591                    }
592                } else {
593                    if (s->mv_dir & MV_DIR_FORWARD) {
594                        put_bits(&s->pb, 1, s->field_select[0][0]);
595                        put_bits(&s->pb, 1, s->field_select[0][1]);
596                    }
597                    if (s->mv_dir & MV_DIR_BACKWARD) {
598                        put_bits(&s->pb, 1, s->field_select[1][0]);
599                        put_bits(&s->pb, 1, s->field_select[1][1]);
600                    }
601                    if (s->mv_dir & MV_DIR_FORWARD) {
602                        for (i = 0; i < 2; i++) {
603                            ff_h263_encode_motion_vector(s,
604                                                         s->mv[0][i][0] - s->last_mv[0][i][0],
605                                                         s->mv[0][i][1] - s->last_mv[0][i][1] / 2,
606                                                         s->f_code);
607                            s->last_mv[0][i][0] = s->mv[0][i][0];
608                            s->last_mv[0][i][1] = s->mv[0][i][1] * 2;
609                        }
610                    }
611                    if (s->mv_dir & MV_DIR_BACKWARD) {
612                        for (i = 0; i < 2; i++) {
613                            ff_h263_encode_motion_vector(s,
614                                                         s->mv[1][i][0] - s->last_mv[1][i][0],
615                                                         s->mv[1][i][1] - s->last_mv[1][i][1] / 2,
616                                                         s->b_code);
617                            s->last_mv[1][i][0] = s->mv[1][i][0];
618                            s->last_mv[1][i][1] = s->mv[1][i][1] * 2;
619                        }
620                    }
621                }
622            }
623
624            if (interleaved_stats)
625                s->mv_bits += get_bits_diff(s);
626
627            mpeg4_encode_blocks(s, block, NULL, NULL, NULL, &s->pb);
628
629            if (interleaved_stats)
630                s->p_tex_bits += get_bits_diff(s);
631        } else { /* s->pict_type==AV_PICTURE_TYPE_B */
632            cbp = get_p_cbp(s, block, motion_x, motion_y);
633
634            if ((cbp | motion_x | motion_y | s->dquant) == 0 &&
635                s->mv_type == MV_TYPE_16X16) {
636                /* Check if the B-frames can skip it too, as we must skip it
637                 * if we skip here why didn't they just compress
638                 * the skip-mb bits instead of reusing them ?! */
639                if (s->max_b_frames > 0) {
640                    int i;
641                    int x, y, offset;
642                    uint8_t *p_pic;
643
644                    x = s->mb_x * 16;
645                    y = s->mb_y * 16;
646
647                    offset = x + y * s->linesize;
648                    p_pic  = s->new_picture->data[0] + offset;
649
650                    s->mb_skipped = 1;
651                    for (i = 0; i < s->max_b_frames; i++) {
652                        uint8_t *b_pic;
653                        int diff;
654                        Picture *pic = s->reordered_input_picture[i + 1];
655
656                        if (!pic || pic->f->pict_type != AV_PICTURE_TYPE_B)
657                            break;
658
659                        b_pic = pic->f->data[0] + offset;
660                        if (!pic->shared)
661                            b_pic += INPLACE_OFFSET;
662
663                        if (x + 16 > s->width || y + 16 > s->height) {
664                            int x1, y1;
665                            int xe = FFMIN(16, s->width - x);
666                            int ye = FFMIN(16, s->height - y);
667                            diff = 0;
668                            for (y1 = 0; y1 < ye; y1++) {
669                                for (x1 = 0; x1 < xe; x1++) {
670                                    diff += FFABS(p_pic[x1 + y1 * s->linesize] - b_pic[x1 + y1 * s->linesize]);
671                                }
672                            }
673                            diff = diff * 256 / (xe * ye);
674                        } else {
675                            diff = s->mecc.sad[0](NULL, p_pic, b_pic, s->linesize, 16);
676                        }
677                        if (diff > s->qscale * 70) {  // FIXME check that 70 is optimal
678                            s->mb_skipped = 0;
679                            break;
680                        }
681                    }
682                } else
683                    s->mb_skipped = 1;
684
685                if (s->mb_skipped == 1) {
686                    /* skip macroblock */
687                    put_bits(&s->pb, 1, 1);
688
689                    if (interleaved_stats) {
690                        s->misc_bits++;
691                        s->last_bits++;
692                    }
693                    s->skip_count++;
694
695                    return;
696                }
697            }
698
699            put_bits(&s->pb, 1, 0);     /* mb coded */
700            cbpc  = cbp & 3;
701            cbpy  = cbp >> 2;
702            cbpy ^= 0xf;
703            if (s->mv_type == MV_TYPE_16X16) {
704                if (s->dquant)
705                    cbpc += 8;
706                put_bits(&s->pb,
707                         ff_h263_inter_MCBPC_bits[cbpc],
708                         ff_h263_inter_MCBPC_code[cbpc]);
709
710                put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
711                if (s->dquant)
712                    put_bits(pb2, 2, dquant_code[s->dquant + 2]);
713
714                if (!s->progressive_sequence) {
715                    if (cbp)
716                        put_bits(pb2, 1, s->interlaced_dct);
717                    put_bits(pb2, 1, 0);
718                }
719
720                if (interleaved_stats)
721                    s->misc_bits += get_bits_diff(s);
722
723                /* motion vectors: 16x16 mode */
724                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
725
726                ff_h263_encode_motion_vector(s,
727                                             motion_x - pred_x,
728                                             motion_y - pred_y,
729                                             s->f_code);
730            } else if (s->mv_type == MV_TYPE_FIELD) {
731                if (s->dquant)
732                    cbpc += 8;
733                put_bits(&s->pb,
734                         ff_h263_inter_MCBPC_bits[cbpc],
735                         ff_h263_inter_MCBPC_code[cbpc]);
736
737                put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
738                if (s->dquant)
739                    put_bits(pb2, 2, dquant_code[s->dquant + 2]);
740
741                av_assert2(!s->progressive_sequence);
742                if (cbp)
743                    put_bits(pb2, 1, s->interlaced_dct);
744                put_bits(pb2, 1, 1);
745
746                if (interleaved_stats)
747                    s->misc_bits += get_bits_diff(s);
748
749                /* motion vectors: 16x8 interlaced mode */
750                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
751                pred_y /= 2;
752
753                put_bits(&s->pb, 1, s->field_select[0][0]);
754                put_bits(&s->pb, 1, s->field_select[0][1]);
755
756                ff_h263_encode_motion_vector(s,
757                                             s->mv[0][0][0] - pred_x,
758                                             s->mv[0][0][1] - pred_y,
759                                             s->f_code);
760                ff_h263_encode_motion_vector(s,
761                                             s->mv[0][1][0] - pred_x,
762                                             s->mv[0][1][1] - pred_y,
763                                             s->f_code);
764            } else {
765                av_assert2(s->mv_type == MV_TYPE_8X8);
766                put_bits(&s->pb,
767                         ff_h263_inter_MCBPC_bits[cbpc + 16],
768                         ff_h263_inter_MCBPC_code[cbpc + 16]);
769                put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
770
771                if (!s->progressive_sequence && cbp)
772                    put_bits(pb2, 1, s->interlaced_dct);
773
774                if (interleaved_stats)
775                    s->misc_bits += get_bits_diff(s);
776
777                for (i = 0; i < 4; i++) {
778                    /* motion vectors: 8x8 mode*/
779                    ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
780
781                    ff_h263_encode_motion_vector(s,
782                                                 s->current_picture.motion_val[0][s->block_index[i]][0] - pred_x,
783                                                 s->current_picture.motion_val[0][s->block_index[i]][1] - pred_y,
784                                                 s->f_code);
785                }
786            }
787
788            if (interleaved_stats)
789                s->mv_bits += get_bits_diff(s);
790
791            mpeg4_encode_blocks(s, block, NULL, NULL, NULL, tex_pb);
792
793            if (interleaved_stats)
794                s->p_tex_bits += get_bits_diff(s);
795        }
796    } else {
797        int cbp;
798        int dc_diff[6];  // dc values with the dc prediction subtracted
799        int dir[6];      // prediction direction
800        int zigzag_last_index[6];
801        uint8_t *scan_table[6];
802        int i;
803
804        for (i = 0; i < 6; i++)
805            dc_diff[i] = ff_mpeg4_pred_dc(s, i, block[i][0], &dir[i], 1);
806
807        if (s->avctx->flags & AV_CODEC_FLAG_AC_PRED) {
808            s->ac_pred = decide_ac_pred(s, block, dir, scan_table, zigzag_last_index);
809        } else {
810            for (i = 0; i < 6; i++)
811                scan_table[i] = s->intra_scantable.permutated;
812        }
813
814        /* compute cbp */
815        cbp = 0;
816        for (i = 0; i < 6; i++)
817            if (s->block_last_index[i] >= 1)
818                cbp |= 1 << (5 - i);
819
820        cbpc = cbp & 3;
821        if (s->pict_type == AV_PICTURE_TYPE_I) {
822            if (s->dquant)
823                cbpc += 4;
824            put_bits(&s->pb,
825                     ff_h263_intra_MCBPC_bits[cbpc],
826                     ff_h263_intra_MCBPC_code[cbpc]);
827        } else {
828            if (s->dquant)
829                cbpc += 8;
830            put_bits(&s->pb, 1, 0);     /* mb coded */
831            put_bits(&s->pb,
832                     ff_h263_inter_MCBPC_bits[cbpc + 4],
833                     ff_h263_inter_MCBPC_code[cbpc + 4]);
834        }
835        put_bits(pb2, 1, s->ac_pred);
836        cbpy = cbp >> 2;
837        put_bits(pb2, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);
838        if (s->dquant)
839            put_bits(dc_pb, 2, dquant_code[s->dquant + 2]);
840
841        if (!s->progressive_sequence)
842            put_bits(dc_pb, 1, s->interlaced_dct);
843
844        if (interleaved_stats)
845            s->misc_bits += get_bits_diff(s);
846
847        mpeg4_encode_blocks(s, block, dc_diff, scan_table, dc_pb, tex_pb);
848
849        if (interleaved_stats)
850            s->i_tex_bits += get_bits_diff(s);
851        s->i_count++;
852
853        /* restore ac coeffs & last_index stuff
854         * if we messed them up with the prediction */
855        if (s->ac_pred)
856            restore_ac_coeffs(s, block, dir, scan_table, zigzag_last_index);
857    }
858}
859
860/**
861 * add MPEG-4 stuffing bits (01...1)
862 */
863void ff_mpeg4_stuffing(PutBitContext *pbc)
864{
865    int length;
866    put_bits(pbc, 1, 0);
867    length = (-put_bits_count(pbc)) & 7;
868    if (length)
869        put_bits(pbc, length, (1 << length) - 1);
870}
871
872/* must be called before writing the header */
873void ff_set_mpeg4_time(MpegEncContext *s)
874{
875    if (s->pict_type == AV_PICTURE_TYPE_B) {
876        ff_mpeg4_init_direct_mv(s);
877    } else {
878        s->last_time_base = s->time_base;
879        s->time_base      = FFUDIV(s->time, s->avctx->time_base.den);
880    }
881}
882
883static void mpeg4_encode_gop_header(MpegEncContext *s)
884{
885    int64_t hours, minutes, seconds;
886    int64_t time;
887
888    put_bits(&s->pb, 16, 0);
889    put_bits(&s->pb, 16, GOP_STARTCODE);
890
891    time = s->current_picture_ptr->f->pts;
892    if (s->reordered_input_picture[1])
893        time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
894    time = time * s->avctx->time_base.num;
895    s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
896
897    seconds = FFUDIV(time, s->avctx->time_base.den);
898    minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
899    hours   = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
900    hours   = FFUMOD(hours  , 24);
901
902    put_bits(&s->pb, 5, hours);
903    put_bits(&s->pb, 6, minutes);
904    put_bits(&s->pb, 1, 1);
905    put_bits(&s->pb, 6, seconds);
906
907    put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
908    put_bits(&s->pb, 1, 0);  // broken link == NO
909
910    ff_mpeg4_stuffing(&s->pb);
911}
912
913static void mpeg4_encode_visual_object_header(MpegEncContext *s)
914{
915    int profile_and_level_indication;
916    int vo_ver_id;
917
918    if (s->avctx->profile != FF_PROFILE_UNKNOWN) {
919        profile_and_level_indication = s->avctx->profile << 4;
920    } else if (s->max_b_frames || s->quarter_sample) {
921        profile_and_level_indication = 0xF0;  // adv simple
922    } else {
923        profile_and_level_indication = 0x00;  // simple
924    }
925
926    if (s->avctx->level != FF_LEVEL_UNKNOWN)
927        profile_and_level_indication |= s->avctx->level;
928    else
929        profile_and_level_indication |= 1;   // level 1
930
931    if (profile_and_level_indication >> 4 == 0xF)
932        vo_ver_id = 5;
933    else
934        vo_ver_id = 1;
935
936    // FIXME levels
937
938    put_bits(&s->pb, 16, 0);
939    put_bits(&s->pb, 16, VOS_STARTCODE);
940
941    put_bits(&s->pb, 8, profile_and_level_indication);
942
943    put_bits(&s->pb, 16, 0);
944    put_bits(&s->pb, 16, VISUAL_OBJ_STARTCODE);
945
946    put_bits(&s->pb, 1, 1);
947    put_bits(&s->pb, 4, vo_ver_id);
948    put_bits(&s->pb, 3, 1);     // priority
949
950    put_bits(&s->pb, 4, 1);     // visual obj type== video obj
951
952    put_bits(&s->pb, 1, 0);     // video signal type == no clue // FIXME
953
954    ff_mpeg4_stuffing(&s->pb);
955}
956
957static void mpeg4_encode_vol_header(MpegEncContext *s,
958                                    int vo_number,
959                                    int vol_number)
960{
961    int vo_ver_id, vo_type, aspect_ratio_info;
962
963    if (s->max_b_frames || s->quarter_sample) {
964        vo_ver_id  = 5;
965        vo_type = ADV_SIMPLE_VO_TYPE;
966    } else {
967        vo_ver_id  = 1;
968        vo_type = SIMPLE_VO_TYPE;
969    }
970
971    put_bits(&s->pb, 16, 0);
972    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */
973    put_bits(&s->pb, 16, 0);
974    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */
975
976    put_bits(&s->pb, 1, 0);             /* random access vol */
977    put_bits(&s->pb, 8, vo_type);       /* video obj type indication */
978    if (s->workaround_bugs & FF_BUG_MS) {
979        put_bits(&s->pb, 1, 0);         /* is obj layer id= no */
980    } else {
981        put_bits(&s->pb, 1, 1);         /* is obj layer id= yes */
982        put_bits(&s->pb, 4, vo_ver_id); /* is obj layer ver id */
983        put_bits(&s->pb, 3, 1);         /* is obj layer priority */
984    }
985
986    aspect_ratio_info = ff_h263_aspect_to_info(s->avctx->sample_aspect_ratio);
987
988    put_bits(&s->pb, 4, aspect_ratio_info); /* aspect ratio info */
989    if (aspect_ratio_info == FF_ASPECT_EXTENDED) {
990        av_reduce(&s->avctx->sample_aspect_ratio.num, &s->avctx->sample_aspect_ratio.den,
991                   s->avctx->sample_aspect_ratio.num,  s->avctx->sample_aspect_ratio.den, 255);
992        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);
993        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);
994    }
995
996    if (s->workaround_bugs & FF_BUG_MS) {
997        put_bits(&s->pb, 1, 0);         /* vol control parameters= no @@@ */
998    } else {
999        put_bits(&s->pb, 1, 1);         /* vol control parameters= yes */
1000        put_bits(&s->pb, 2, 1);         /* chroma format YUV 420/YV12 */
1001        put_bits(&s->pb, 1, s->low_delay);
1002        put_bits(&s->pb, 1, 0);         /* vbv parameters= no */
1003    }
1004
1005    put_bits(&s->pb, 2, RECT_SHAPE);    /* vol shape= rectangle */
1006    put_bits(&s->pb, 1, 1);             /* marker bit */
1007
1008    put_bits(&s->pb, 16, s->avctx->time_base.den);
1009    if (s->time_increment_bits < 1)
1010        s->time_increment_bits = 1;
1011    put_bits(&s->pb, 1, 1);             /* marker bit */
1012    put_bits(&s->pb, 1, 0);             /* fixed vop rate=no */
1013    put_bits(&s->pb, 1, 1);             /* marker bit */
1014    put_bits(&s->pb, 13, s->width);     /* vol width */
1015    put_bits(&s->pb, 1, 1);             /* marker bit */
1016    put_bits(&s->pb, 13, s->height);    /* vol height */
1017    put_bits(&s->pb, 1, 1);             /* marker bit */
1018    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);
1019    put_bits(&s->pb, 1, 1);             /* obmc disable */
1020    if (vo_ver_id == 1)
1021        put_bits(&s->pb, 1, 0);       /* sprite enable */
1022    else
1023        put_bits(&s->pb, 2, 0);       /* sprite enable */
1024
1025    put_bits(&s->pb, 1, 0);             /* not 8 bit == false */
1026    put_bits(&s->pb, 1, s->mpeg_quant); /* quant type = (0 = H.263 style) */
1027
1028    if (s->mpeg_quant) {
1029        ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
1030        ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
1031    }
1032
1033    if (vo_ver_id != 1)
1034        put_bits(&s->pb, 1, s->quarter_sample);
1035    put_bits(&s->pb, 1, 1);             /* complexity estimation disable */
1036    put_bits(&s->pb, 1, s->rtp_mode ? 0 : 1); /* resync marker disable */
1037    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);
1038    if (s->data_partitioning)
1039        put_bits(&s->pb, 1, 0);         /* no rvlc */
1040
1041    if (vo_ver_id != 1) {
1042        put_bits(&s->pb, 1, 0);         /* newpred */
1043        put_bits(&s->pb, 1, 0);         /* reduced res vop */
1044    }
1045    put_bits(&s->pb, 1, 0);             /* scalability */
1046
1047    ff_mpeg4_stuffing(&s->pb);
1048
1049    /* user data */
1050    if (!(s->avctx->flags & AV_CODEC_FLAG_BITEXACT)) {
1051        put_bits(&s->pb, 16, 0);
1052        put_bits(&s->pb, 16, 0x1B2);    /* user_data */
1053        ff_put_string(&s->pb, LIBAVCODEC_IDENT, 0);
1054    }
1055}
1056
1057/* write MPEG-4 VOP header */
1058int ff_mpeg4_encode_picture_header(MpegEncContext *s, int picture_number)
1059{
1060    uint64_t time_incr;
1061    int64_t time_div, time_mod;
1062
1063    if (s->pict_type == AV_PICTURE_TYPE_I) {
1064        if (!(s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1065            if (s->avctx->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT)  // HACK, the reference sw is buggy
1066                mpeg4_encode_visual_object_header(s);
1067            if (s->avctx->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number == 0)  // HACK, the reference sw is buggy
1068                mpeg4_encode_vol_header(s, 0, 0);
1069        }
1070        if (!(s->workaround_bugs & FF_BUG_MS))
1071            mpeg4_encode_gop_header(s);
1072    }
1073
1074    s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
1075
1076    put_bits(&s->pb, 16, 0);                /* vop header */
1077    put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */
1078    put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */
1079
1080    time_div  = FFUDIV(s->time, s->avctx->time_base.den);
1081    time_mod  = FFUMOD(s->time, s->avctx->time_base.den);
1082    time_incr = time_div - s->last_time_base;
1083
1084    // This limits the frame duration to max 1 hour
1085    if (time_incr > 3600) {
1086        av_log(s->avctx, AV_LOG_ERROR, "time_incr %"PRIu64" too large\n", time_incr);
1087        return AVERROR(EINVAL);
1088    }
1089    while (time_incr--)
1090        put_bits(&s->pb, 1, 1);
1091
1092    put_bits(&s->pb, 1, 0);
1093
1094    put_bits(&s->pb, 1, 1);                             /* marker */
1095    put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */
1096    put_bits(&s->pb, 1, 1);                             /* marker */
1097    put_bits(&s->pb, 1, 1);                             /* vop coded */
1098    if (s->pict_type == AV_PICTURE_TYPE_P) {
1099        put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */
1100    }
1101    put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */
1102    if (!s->progressive_sequence) {
1103        put_bits(&s->pb, 1, s->current_picture_ptr->f->top_field_first);
1104        put_bits(&s->pb, 1, s->alternate_scan);
1105    }
1106    // FIXME sprite stuff
1107
1108    put_bits(&s->pb, 5, s->qscale);
1109
1110    if (s->pict_type != AV_PICTURE_TYPE_I)
1111        put_bits(&s->pb, 3, s->f_code);  /* fcode_for */
1112    if (s->pict_type == AV_PICTURE_TYPE_B)
1113        put_bits(&s->pb, 3, s->b_code);  /* fcode_back */
1114
1115    return 0;
1116}
1117
1118static av_cold void init_uni_dc_tab(void)
1119{
1120    int level, uni_code, uni_len;
1121
1122    for (level = -256; level < 256; level++) {
1123        int size, v, l;
1124        /* find number of bits */
1125        size = 0;
1126        v    = abs(level);
1127        while (v) {
1128            v >>= 1;
1129            size++;
1130        }
1131
1132        if (level < 0)
1133            l = (-level) ^ ((1 << size) - 1);
1134        else
1135            l = level;
1136
1137        /* luminance */
1138        uni_code = ff_mpeg4_DCtab_lum[size][0];
1139        uni_len  = ff_mpeg4_DCtab_lum[size][1];
1140
1141        if (size > 0) {
1142            uni_code <<= size;
1143            uni_code  |= l;
1144            uni_len   += size;
1145            if (size > 8) {
1146                uni_code <<= 1;
1147                uni_code  |= 1;
1148                uni_len++;
1149            }
1150        }
1151        uni_DCtab_lum_bits[level + 256] = uni_code;
1152        uni_DCtab_lum_len[level + 256]  = uni_len;
1153
1154        /* chrominance */
1155        uni_code = ff_mpeg4_DCtab_chrom[size][0];
1156        uni_len  = ff_mpeg4_DCtab_chrom[size][1];
1157
1158        if (size > 0) {
1159            uni_code <<= size;
1160            uni_code  |= l;
1161            uni_len   += size;
1162            if (size > 8) {
1163                uni_code <<= 1;
1164                uni_code  |= 1;
1165                uni_len++;
1166            }
1167        }
1168        uni_DCtab_chrom_bits[level + 256] = uni_code;
1169        uni_DCtab_chrom_len[level + 256]  = uni_len;
1170    }
1171}
1172
1173static av_cold void init_uni_mpeg4_rl_tab(RLTable *rl, uint32_t *bits_tab,
1174                                          uint8_t *len_tab)
1175{
1176    int slevel, run, last;
1177
1178    av_assert0(MAX_LEVEL >= 64);
1179    av_assert0(MAX_RUN >= 63);
1180
1181    for (slevel = -64; slevel < 64; slevel++) {
1182        if (slevel == 0)
1183            continue;
1184        for (run = 0; run < 64; run++) {
1185            for (last = 0; last <= 1; last++) {
1186                const int index = UNI_MPEG4_ENC_INDEX(last, run, slevel + 64);
1187                int level       = slevel < 0 ? -slevel : slevel;
1188                int sign        = slevel < 0 ? 1 : 0;
1189                int bits, len, code;
1190                int level1, run1;
1191
1192                len_tab[index] = 100;
1193
1194                /* ESC0 */
1195                code = get_rl_index(rl, last, run, level);
1196                bits = rl->table_vlc[code][0];
1197                len  = rl->table_vlc[code][1];
1198                bits = bits * 2 + sign;
1199                len++;
1200
1201                if (code != rl->n && len < len_tab[index]) {
1202                    bits_tab[index] = bits;
1203                    len_tab[index]  = len;
1204                }
1205                /* ESC1 */
1206                bits = rl->table_vlc[rl->n][0];
1207                len  = rl->table_vlc[rl->n][1];
1208                bits = bits * 2;
1209                len++;                 // esc1
1210                level1 = level - rl->max_level[last][run];
1211                if (level1 > 0) {
1212                    code   = get_rl_index(rl, last, run, level1);
1213                    bits <<= rl->table_vlc[code][1];
1214                    len   += rl->table_vlc[code][1];
1215                    bits  += rl->table_vlc[code][0];
1216                    bits   = bits * 2 + sign;
1217                    len++;
1218
1219                    if (code != rl->n && len < len_tab[index]) {
1220                        bits_tab[index] = bits;
1221                        len_tab[index]  = len;
1222                    }
1223                }
1224                /* ESC2 */
1225                bits = rl->table_vlc[rl->n][0];
1226                len  = rl->table_vlc[rl->n][1];
1227                bits = bits * 4 + 2;
1228                len += 2;                 // esc2
1229                run1 = run - rl->max_run[last][level] - 1;
1230                if (run1 >= 0) {
1231                    code   = get_rl_index(rl, last, run1, level);
1232                    bits <<= rl->table_vlc[code][1];
1233                    len   += rl->table_vlc[code][1];
1234                    bits  += rl->table_vlc[code][0];
1235                    bits   = bits * 2 + sign;
1236                    len++;
1237
1238                    if (code != rl->n && len < len_tab[index]) {
1239                        bits_tab[index] = bits;
1240                        len_tab[index]  = len;
1241                    }
1242                }
1243                /* ESC3 */
1244                bits = rl->table_vlc[rl->n][0];
1245                len  = rl->table_vlc[rl->n][1];
1246                bits = bits * 4 + 3;
1247                len += 2;                 // esc3
1248                bits = bits * 2 + last;
1249                len++;
1250                bits = bits * 64 + run;
1251                len += 6;
1252                bits = bits * 2 + 1;
1253                len++;                    // marker
1254                bits = bits * 4096 + (slevel & 0xfff);
1255                len += 12;
1256                bits = bits * 2 + 1;
1257                len++;                    // marker
1258
1259                if (len < len_tab[index]) {
1260                    bits_tab[index] = bits;
1261                    len_tab[index]  = len;
1262                }
1263            }
1264        }
1265    }
1266}
1267
1268static av_cold void mpeg4_encode_init_static(void)
1269{
1270    init_uni_dc_tab();
1271
1272    ff_mpeg4_init_rl_intra();
1273
1274    init_uni_mpeg4_rl_tab(&ff_mpeg4_rl_intra, uni_mpeg4_intra_rl_bits, uni_mpeg4_intra_rl_len);
1275    init_uni_mpeg4_rl_tab(&ff_h263_rl_inter,  uni_mpeg4_inter_rl_bits, uni_mpeg4_inter_rl_len);
1276}
1277
1278static av_cold int encode_init(AVCodecContext *avctx)
1279{
1280    static AVOnce init_static_once = AV_ONCE_INIT;
1281    MpegEncContext *s = avctx->priv_data;
1282    int ret;
1283
1284    if (avctx->width >= (1<<13) || avctx->height >= (1<<13)) {
1285        av_log(avctx, AV_LOG_ERROR, "dimensions too large for MPEG-4\n");
1286        return AVERROR(EINVAL);
1287    }
1288
1289    if ((ret = ff_mpv_encode_init(avctx)) < 0)
1290        return ret;
1291
1292    ff_thread_once(&init_static_once, mpeg4_encode_init_static);
1293
1294    s->min_qcoeff               = -2048;
1295    s->max_qcoeff               = 2047;
1296    s->intra_ac_vlc_length      = uni_mpeg4_intra_rl_len;
1297    s->intra_ac_vlc_last_length = uni_mpeg4_intra_rl_len + 128 * 64;
1298    s->inter_ac_vlc_length      = uni_mpeg4_inter_rl_len;
1299    s->inter_ac_vlc_last_length = uni_mpeg4_inter_rl_len + 128 * 64;
1300    s->luma_dc_vlc_length       = uni_DCtab_lum_len;
1301    s->ac_esc_length            = 7 + 2 + 1 + 6 + 1 + 12 + 1;
1302    s->y_dc_scale_table         = ff_mpeg4_y_dc_scale_table;
1303    s->c_dc_scale_table         = ff_mpeg4_c_dc_scale_table;
1304
1305    if (s->avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1306        s->avctx->extradata = av_malloc(1024);
1307        if (!s->avctx->extradata)
1308            return AVERROR(ENOMEM);
1309        init_put_bits(&s->pb, s->avctx->extradata, 1024);
1310
1311        if (!(s->workaround_bugs & FF_BUG_MS))
1312            mpeg4_encode_visual_object_header(s);
1313        mpeg4_encode_vol_header(s, 0, 0);
1314
1315//            ff_mpeg4_stuffing(&s->pb); ?
1316        flush_put_bits(&s->pb);
1317        s->avctx->extradata_size = put_bytes_output(&s->pb);
1318    }
1319    return 0;
1320}
1321
1322void ff_mpeg4_init_partitions(MpegEncContext *s)
1323{
1324    uint8_t *start = put_bits_ptr(&s->pb);
1325    uint8_t *end   = s->pb.buf_end;
1326    int size       = end - start;
1327    int pb_size    = (((intptr_t)start + size / 3) & (~3)) - (intptr_t)start;
1328    int tex_size   = (size - 2 * pb_size) & (~3);
1329
1330    set_put_bits_buffer_size(&s->pb, pb_size);
1331    init_put_bits(&s->tex_pb, start + pb_size, tex_size);
1332    init_put_bits(&s->pb2, start + pb_size + tex_size, pb_size);
1333}
1334
1335void ff_mpeg4_merge_partitions(MpegEncContext *s)
1336{
1337    const int pb2_len    = put_bits_count(&s->pb2);
1338    const int tex_pb_len = put_bits_count(&s->tex_pb);
1339    const int bits       = put_bits_count(&s->pb);
1340
1341    if (s->pict_type == AV_PICTURE_TYPE_I) {
1342        put_bits(&s->pb, 19, DC_MARKER);
1343        s->misc_bits  += 19 + pb2_len + bits - s->last_bits;
1344        s->i_tex_bits += tex_pb_len;
1345    } else {
1346        put_bits(&s->pb, 17, MOTION_MARKER);
1347        s->misc_bits  += 17 + pb2_len;
1348        s->mv_bits    += bits - s->last_bits;
1349        s->p_tex_bits += tex_pb_len;
1350    }
1351
1352    flush_put_bits(&s->pb2);
1353    flush_put_bits(&s->tex_pb);
1354
1355    set_put_bits_buffer_size(&s->pb, s->pb2.buf_end - s->pb.buf);
1356    ff_copy_bits(&s->pb, s->pb2.buf, pb2_len);
1357    ff_copy_bits(&s->pb, s->tex_pb.buf, tex_pb_len);
1358    s->last_bits = put_bits_count(&s->pb);
1359}
1360
1361void ff_mpeg4_encode_video_packet_header(MpegEncContext *s)
1362{
1363    int mb_num_bits = av_log2(s->mb_num - 1) + 1;
1364
1365    put_bits(&s->pb, ff_mpeg4_get_video_packet_prefix_length(s), 0);
1366    put_bits(&s->pb, 1, 1);
1367
1368    put_bits(&s->pb, mb_num_bits, s->mb_x + s->mb_y * s->mb_width);
1369    put_bits(&s->pb, s->quant_precision, s->qscale);
1370    put_bits(&s->pb, 1, 0); /* no HEC */
1371}
1372
1373#define OFFSET(x) offsetof(MpegEncContext, x)
1374#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1375static const AVOption options[] = {
1376    { "data_partitioning", "Use data partitioning.",      OFFSET(data_partitioning), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1377    { "alternate_scan",    "Enable alternate scantable.", OFFSET(alternate_scan),    AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1378    { "mpeg_quant",        "Use MPEG quantizers instead of H.263",
1379      OFFSET(mpeg_quant), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, VE },
1380    FF_MPV_COMMON_BFRAME_OPTS
1381    FF_MPV_COMMON_OPTS
1382    FF_MPV_COMMON_MOTION_EST_OPTS
1383    FF_MPEG4_PROFILE_OPTS
1384    { NULL },
1385};
1386
1387static const AVClass mpeg4enc_class = {
1388    .class_name = "MPEG4 encoder",
1389    .item_name  = av_default_item_name,
1390    .option     = options,
1391    .version    = LIBAVUTIL_VERSION_INT,
1392};
1393
1394const FFCodec ff_mpeg4_encoder = {
1395    .p.name         = "mpeg4",
1396    .p.long_name    = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
1397    .p.type         = AVMEDIA_TYPE_VIDEO,
1398    .p.id           = AV_CODEC_ID_MPEG4,
1399    .priv_data_size = sizeof(MpegEncContext),
1400    .init           = encode_init,
1401    FF_CODEC_ENCODE_CB(ff_mpv_encode_picture),
1402    .close          = ff_mpv_encode_end,
1403    .p.pix_fmts     = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
1404    .p.capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS,
1405    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
1406    .p.priv_class   = &mpeg4enc_class,
1407};
1408