1/*
2 * H261 encoder
3 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
4 * Copyright (c) 2004 Maarten Daniels
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
24 * @file
25 * H.261 encoder.
26 */
27
28#include "libavutil/attributes.h"
29#include "libavutil/avassert.h"
30#include "avcodec.h"
31#include "mpegutils.h"
32#include "mpegvideo.h"
33#include "h263.h"
34#include "h261.h"
35
36static uint8_t uni_h261_rl_len [64*64*2*2];
37#define UNI_ENC_INDEX(last,run,level) ((last)*128*64 + (run)*128 + (level))
38
39int ff_h261_get_picture_format(int width, int height)
40{
41    // QCIF
42    if (width == 176 && height == 144)
43        return 0;
44    // CIF
45    else if (width == 352 && height == 288)
46        return 1;
47    // ERROR
48    else
49        return -1;
50}
51
52void ff_h261_encode_picture_header(MpegEncContext *s, int picture_number)
53{
54    H261Context *h = (H261Context *)s;
55    int format, temp_ref;
56
57    avpriv_align_put_bits(&s->pb);
58
59    /* Update the pointer to last GOB */
60    s->ptr_lastgob = put_bits_ptr(&s->pb);
61
62    put_bits(&s->pb, 20, 0x10); /* PSC */
63
64    temp_ref = s->picture_number * (int64_t)30000 * s->avctx->time_base.num /
65               (1001 * (int64_t)s->avctx->time_base.den);   // FIXME maybe this should use a timestamp
66    put_sbits(&s->pb, 5, temp_ref); /* TemporalReference */
67
68    put_bits(&s->pb, 1, 0); /* split screen off */
69    put_bits(&s->pb, 1, 0); /* camera  off */
70    put_bits(&s->pb, 1, 0); /* freeze picture release off */
71
72    format = ff_h261_get_picture_format(s->width, s->height);
73
74    put_bits(&s->pb, 1, format); /* 0 == QCIF, 1 == CIF */
75
76    put_bits(&s->pb, 1, 0); /* still image mode */
77    put_bits(&s->pb, 1, 0); /* reserved */
78
79    put_bits(&s->pb, 1, 0); /* no PEI */
80    if (format == 0)
81        h->gob_number = -1;
82    else
83        h->gob_number = 0;
84    s->mb_skip_run = 0;
85}
86
87/**
88 * Encode a group of blocks header.
89 */
90static void h261_encode_gob_header(MpegEncContext *s, int mb_line)
91{
92    H261Context *h = (H261Context *)s;
93    if (ff_h261_get_picture_format(s->width, s->height) == 0) {
94        h->gob_number += 2; // QCIF
95    } else {
96        h->gob_number++;    // CIF
97    }
98    put_bits(&s->pb, 16, 1);            /* GBSC */
99    put_bits(&s->pb, 4, h->gob_number); /* GN */
100    put_bits(&s->pb, 5, s->qscale);     /* GQUANT */
101    put_bits(&s->pb, 1, 0);             /* no GEI */
102    s->mb_skip_run = 0;
103    s->last_mv[0][0][0] = 0;
104    s->last_mv[0][0][1] = 0;
105}
106
107void ff_h261_reorder_mb_index(MpegEncContext *s)
108{
109    int index = s->mb_x + s->mb_y * s->mb_width;
110
111    if (index % 11 == 0) {
112        if (index % 33 == 0)
113            h261_encode_gob_header(s, 0);
114        s->last_mv[0][0][0] = 0;
115        s->last_mv[0][0][1] = 0;
116    }
117
118    /* for CIF the GOB's are fragmented in the middle of a scanline
119     * that's why we need to adjust the x and y index of the macroblocks */
120    if (ff_h261_get_picture_format(s->width, s->height) == 1) { // CIF
121        s->mb_x  = index % 11;
122        index   /= 11;
123        s->mb_y  = index % 3;
124        index   /= 3;
125        s->mb_x += 11 * (index % 2);
126        index   /= 2;
127        s->mb_y += 3 * index;
128
129        ff_init_block_index(s);
130        ff_update_block_index(s);
131    }
132}
133
134static void h261_encode_motion(H261Context *h, int val)
135{
136    MpegEncContext *const s = &h->s;
137    int sign, code;
138    if (val == 0) {
139        code = 0;
140        put_bits(&s->pb, ff_h261_mv_tab[code][1], ff_h261_mv_tab[code][0]);
141    } else {
142        if (val > 15)
143            val -= 32;
144        if (val < -16)
145            val += 32;
146        sign = val < 0;
147        code = sign ? -val : val;
148        put_bits(&s->pb, ff_h261_mv_tab[code][1], ff_h261_mv_tab[code][0]);
149        put_bits(&s->pb, 1, sign);
150    }
151}
152
153static inline int get_cbp(MpegEncContext *s, int16_t block[6][64])
154{
155    int i, cbp;
156    cbp = 0;
157    for (i = 0; i < 6; i++)
158        if (s->block_last_index[i] >= 0)
159            cbp |= 1 << (5 - i);
160    return cbp;
161}
162
163/**
164 * Encode an 8x8 block.
165 * @param block the 8x8 block
166 * @param n block index (0-3 are luma, 4-5 are chroma)
167 */
168static void h261_encode_block(H261Context *h, int16_t *block, int n)
169{
170    MpegEncContext *const s = &h->s;
171    int level, run, i, j, last_index, last_non_zero, sign, slevel, code;
172    RLTable *rl;
173
174    rl = &ff_h261_rl_tcoeff;
175    if (s->mb_intra) {
176        /* DC coef */
177        level = block[0];
178        /* 255 cannot be represented, so we clamp */
179        if (level > 254) {
180            level    = 254;
181            block[0] = 254;
182        }
183        /* 0 cannot be represented also */
184        else if (level < 1) {
185            level    = 1;
186            block[0] = 1;
187        }
188        if (level == 128)
189            put_bits(&s->pb, 8, 0xff);
190        else
191            put_bits(&s->pb, 8, level);
192        i = 1;
193    } else if ((block[0] == 1 || block[0] == -1) &&
194               (s->block_last_index[n] > -1)) {
195        // special case
196        put_bits(&s->pb, 2, block[0] > 0 ? 2 : 3);
197        i = 1;
198    } else {
199        i = 0;
200    }
201
202    /* AC coefs */
203    last_index    = s->block_last_index[n];
204    last_non_zero = i - 1;
205    for (; i <= last_index; i++) {
206        j     = s->intra_scantable.permutated[i];
207        level = block[j];
208        if (level) {
209            run    = i - last_non_zero - 1;
210            sign   = 0;
211            slevel = level;
212            if (level < 0) {
213                sign  = 1;
214                level = -level;
215            }
216            code = get_rl_index(rl, 0 /*no last in H.261, EOB is used*/,
217                                run, level);
218            if (run == 0 && level < 16)
219                code += 1;
220            put_bits(&s->pb, rl->table_vlc[code][1], rl->table_vlc[code][0]);
221            if (code == rl->n) {
222                put_bits(&s->pb, 6, run);
223                av_assert1(slevel != 0);
224                av_assert1(level <= 127);
225                put_sbits(&s->pb, 8, slevel);
226            } else {
227                put_bits(&s->pb, 1, sign);
228            }
229            last_non_zero = i;
230        }
231    }
232    if (last_index > -1)
233        put_bits(&s->pb, rl->table_vlc[0][1], rl->table_vlc[0][0]); // EOB
234}
235
236void ff_h261_encode_mb(MpegEncContext *s, int16_t block[6][64],
237                       int motion_x, int motion_y)
238{
239    H261Context *h = (H261Context *)s;
240    int mvd, mv_diff_x, mv_diff_y, i, cbp;
241    cbp = 63; // avoid warning
242    mvd = 0;
243
244    h->mtype = 0;
245
246    if (!s->mb_intra) {
247        /* compute cbp */
248        cbp = get_cbp(s, block);
249
250        /* mvd indicates if this block is motion compensated */
251        mvd = motion_x | motion_y;
252
253        if ((cbp | mvd | s->dquant) == 0) {
254            /* skip macroblock */
255            s->skip_count++;
256            s->mb_skip_run++;
257            s->last_mv[0][0][0] = 0;
258            s->last_mv[0][0][1] = 0;
259            return;
260        }
261    }
262
263    /* MB is not skipped, encode MBA */
264    put_bits(&s->pb,
265             ff_h261_mba_bits[s->mb_skip_run],
266             ff_h261_mba_code[s->mb_skip_run]);
267    s->mb_skip_run = 0;
268
269    /* calculate MTYPE */
270    if (!s->mb_intra) {
271        h->mtype++;
272
273        if (mvd || s->loop_filter)
274            h->mtype += 3;
275        if (s->loop_filter)
276            h->mtype += 3;
277        if (cbp || s->dquant)
278            h->mtype++;
279        av_assert1(h->mtype > 1);
280    }
281
282    if (s->dquant)
283        h->mtype++;
284
285    put_bits(&s->pb,
286             ff_h261_mtype_bits[h->mtype],
287             ff_h261_mtype_code[h->mtype]);
288
289    h->mtype = ff_h261_mtype_map[h->mtype];
290
291    if (IS_QUANT(h->mtype)) {
292        ff_set_qscale(s, s->qscale + s->dquant);
293        put_bits(&s->pb, 5, s->qscale);
294    }
295
296    if (IS_16X16(h->mtype)) {
297        mv_diff_x       = (motion_x >> 1) - s->last_mv[0][0][0];
298        mv_diff_y       = (motion_y >> 1) - s->last_mv[0][0][1];
299        s->last_mv[0][0][0] = (motion_x >> 1);
300        s->last_mv[0][0][1] = (motion_y >> 1);
301        h261_encode_motion(h, mv_diff_x);
302        h261_encode_motion(h, mv_diff_y);
303    }
304
305    if (HAS_CBP(h->mtype)) {
306        av_assert1(cbp > 0);
307        put_bits(&s->pb,
308                 ff_h261_cbp_tab[cbp - 1][1],
309                 ff_h261_cbp_tab[cbp - 1][0]);
310    }
311    for (i = 0; i < 6; i++)
312        /* encode each block */
313        h261_encode_block(h, block[i], i);
314
315    if (!IS_16X16(h->mtype)) {
316        s->last_mv[0][0][0] = 0;
317        s->last_mv[0][0][1] = 0;
318    }
319}
320
321static av_cold void init_uni_h261_rl_tab(RLTable *rl, uint32_t *bits_tab,
322                                         uint8_t *len_tab)
323{
324    int slevel, run, last;
325
326    av_assert0(MAX_LEVEL >= 64);
327    av_assert0(MAX_RUN   >= 63);
328
329    for(slevel=-64; slevel<64; slevel++){
330        if(slevel==0) continue;
331        for(run=0; run<64; run++){
332            for(last=0; last<=1; last++){
333                const int index= UNI_ENC_INDEX(last, run, slevel+64);
334                int level= slevel < 0 ? -slevel : slevel;
335                int len, code;
336
337                len_tab[index]= 100;
338
339                /* ESC0 */
340                code= get_rl_index(rl, 0, run, level);
341                len=  rl->table_vlc[code][1] + 1;
342                if(last)
343                    len += 2;
344
345                if(code!=rl->n && len < len_tab[index]){
346                    len_tab [index]= len;
347                }
348                /* ESC */
349                len = rl->table_vlc[rl->n][1];
350                if(last)
351                    len += 2;
352
353                if(len < len_tab[index]){
354                    len_tab [index]= len;
355                }
356            }
357        }
358    }
359}
360
361av_cold void ff_h261_encode_init(MpegEncContext *s)
362{
363    ff_h261_common_init();
364
365    s->min_qcoeff       = -127;
366    s->max_qcoeff       = 127;
367    s->y_dc_scale_table =
368    s->c_dc_scale_table = ff_mpeg1_dc_scale_table;
369    s->ac_esc_length    = 6+6+8;
370
371    init_uni_h261_rl_tab(&ff_h261_rl_tcoeff, NULL, uni_h261_rl_len);
372
373    s->intra_ac_vlc_length      = s->inter_ac_vlc_length      = uni_h261_rl_len;
374    s->intra_ac_vlc_last_length = s->inter_ac_vlc_last_length = uni_h261_rl_len + 128*64;
375}
376
377FF_MPV_GENERIC_CLASS(h261)
378
379AVCodec ff_h261_encoder = {
380    .name           = "h261",
381    .long_name      = NULL_IF_CONFIG_SMALL("H.261"),
382    .type           = AVMEDIA_TYPE_VIDEO,
383    .id             = AV_CODEC_ID_H261,
384    .priv_data_size = sizeof(H261Context),
385    .init           = ff_MPV_encode_init,
386    .encode2        = ff_MPV_encode_picture,
387    .close          = ff_MPV_encode_end,
388    .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P,
389                                                     AV_PIX_FMT_NONE },
390    .priv_class     = &h261_class,
391};
392