mpeg12.c 114 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
Michael Niedermayer's avatar
Michael Niedermayer committed
2
 * MPEG1 codec / MPEG2 decoder
Fabrice Bellard's avatar
Fabrice Bellard committed
3
 * Copyright (c) 2000,2001 Fabrice Bellard.
4
 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
Fabrice Bellard's avatar
Fabrice Bellard committed
5
 *
6 7 8
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
9 10
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
12
 *
13
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
15 16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
17
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
21
 */
22

Michael Niedermayer's avatar
Michael Niedermayer committed
23 24
/**
 * @file mpeg12.c
Michael Niedermayer's avatar
Michael Niedermayer committed
25
 * MPEG1/2 codec
Michael Niedermayer's avatar
Michael Niedermayer committed
26
 */
27

Fabrice Bellard's avatar
Fabrice Bellard committed
28
//#define DEBUG
Fabrice Bellard's avatar
Fabrice Bellard committed
29 30 31 32 33
#include "avcodec.h"
#include "dsputil.h"
#include "mpegvideo.h"

#include "mpeg12data.h"
34
#include "bytestream.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
35

36 37 38
//#undef NDEBUG
//#include <assert.h>

39

40 41 42 43 44 45 46 47
#define DC_VLC_BITS 9
#define MV_VLC_BITS 9
#define MBINCR_VLC_BITS 9
#define MB_PAT_VLC_BITS 9
#define MB_PTYPE_VLC_BITS 6
#define MB_BTYPE_VLC_BITS 6
#define TEX_VLC_BITS 9

48
#ifdef CONFIG_ENCODERS
49 50
static void mpeg1_encode_block(MpegEncContext *s,
                         DCTELEM *block,
Fabrice Bellard's avatar
Fabrice Bellard committed
51
                         int component);
52
static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code);    // RAL: f_code parameter added
53
#endif //CONFIG_ENCODERS
54 55
static inline int mpeg1_decode_block_inter(MpegEncContext *s,
                              DCTELEM *block,
56
                              int n);
57 58
static inline int mpeg1_decode_block_intra(MpegEncContext *s,
                              DCTELEM *block,
Fabrice Bellard's avatar
Fabrice Bellard committed
59
                              int n);
60
static inline int mpeg1_fast_decode_block_inter(MpegEncContext *s, DCTELEM *block, int n);
61 62
static inline int mpeg2_decode_block_non_intra(MpegEncContext *s,
                                        DCTELEM *block,
Fabrice Bellard's avatar
Fabrice Bellard committed
63
                                        int n);
64 65
static inline int mpeg2_decode_block_intra(MpegEncContext *s,
                                    DCTELEM *block,
Fabrice Bellard's avatar
Fabrice Bellard committed
66
                                    int n);
67
static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s, DCTELEM *block, int n);
68
static inline int mpeg2_fast_decode_block_intra(MpegEncContext *s, DCTELEM *block, int n);
Fabrice Bellard's avatar
Fabrice Bellard committed
69
static int mpeg_decode_motion(MpegEncContext *s, int fcode, int pred);
Ivan Kalvachev's avatar
Ivan Kalvachev committed
70
static void exchange_uv(MpegEncContext *s);
Fabrice Bellard's avatar
Fabrice Bellard committed
71

Ivan Kalvachev's avatar
Ivan Kalvachev committed
72 73 74
#ifdef HAVE_XVMC
extern int XVMC_field_start(MpegEncContext *s, AVCodecContext *avctx);
extern int XVMC_field_end(MpegEncContext *s);
75
extern void XVMC_pack_pblocks(MpegEncContext *s,int cbp);
Ivan Kalvachev's avatar
Ivan Kalvachev committed
76
extern void XVMC_init_block(MpegEncContext *s);//set s->block
Ivan Kalvachev's avatar
Ivan Kalvachev committed
77 78
#endif

Måns Rullgård's avatar
Måns Rullgård committed
79 80 81 82
static const enum PixelFormat pixfmt_yuv_420[]= {PIX_FMT_YUV420P,-1};
static const enum PixelFormat pixfmt_yuv_422[]= {PIX_FMT_YUV422P,-1};
static const enum PixelFormat pixfmt_yuv_444[]= {PIX_FMT_YUV444P,-1};
static const enum PixelFormat pixfmt_xvmc_mpg2_420[] = {
Ivan Kalvachev's avatar
Ivan Kalvachev committed
83 84
                                           PIX_FMT_XVMC_MPEG2_IDCT,
                                           PIX_FMT_XVMC_MPEG2_MC,
85
                                           -1};
86
#ifdef CONFIG_ENCODERS
87
static uint8_t mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
88
static uint8_t fcode_tab[MAX_MV*2+1];
89

90
static uint8_t  uni_mpeg1_ac_vlc_len [64*64*2];
91
static uint8_t  uni_mpeg2_ac_vlc_len [64*64*2];
Michael Niedermayer's avatar
Michael Niedermayer committed
92 93 94 95 96 97 98

/* simple include everything table for dc, first byte is bits number next 3 are code*/
static uint32_t mpeg1_lum_dc_uni[512];
static uint32_t mpeg1_chr_dc_uni[512];

static uint8_t mpeg1_index_run[2][64];
static int8_t mpeg1_max_level[2][64];
99
#endif //CONFIG_ENCODERS
100

101 102
static uint8_t static_rl_table_store[2][2][2*MAX_RUN + MAX_LEVEL + 3];

103
static void init_2d_vlc_rl(RLTable *rl, int use_static)
104
{
105
    int i;
106 107

    init_vlc(&rl->vlc, TEX_VLC_BITS, rl->n + 2,
108
             &rl->table_vlc[0][1], 4, 2,
109 110
             &rl->table_vlc[0][0], 4, 2, use_static);

111
    if(use_static)
112 113 114
        rl->rl_vlc[0]= av_mallocz_static(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
    else
        rl->rl_vlc[0]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));
115 116 117 118 119

    for(i=0; i<rl->vlc.table_size; i++){
        int code= rl->vlc.table[i][0];
        int len = rl->vlc.table[i][1];
        int level, run;
120

121 122 123 124 125 126 127 128 129 130 131
        if(len==0){ // illegal code
            run= 65;
            level= MAX_LEVEL;
        }else if(len<0){ //more bits needed
            run= 0;
            level= code;
        }else{
            if(code==rl->n){ //esc
                run= 65;
                level= 0;
            }else if(code==rl->n+1){ //eob
132 133
                run= 0;
                level= 127;
134 135 136 137 138 139 140 141 142 143 144
            }else{
                run=   rl->table_run  [code] + 1;
                level= rl->table_level[code];
            }
        }
        rl->rl_vlc[0][i].len= len;
        rl->rl_vlc[0][i].level= level;
        rl->rl_vlc[0][i].run= run;
    }
}

Michael Niedermayer's avatar
Michael Niedermayer committed
145
#ifdef CONFIG_ENCODERS
Baptiste Coudurier's avatar
Baptiste Coudurier committed
146
static void init_uni_ac_vlc(RLTable *rl, uint8_t *uni_ac_vlc_len){
147 148 149 150 151 152 153
    int i;

    for(i=0; i<128; i++){
        int level= i-64;
        int run;
        for(run=0; run<64; run++){
            int len, bits, code;
154

Diego Biurrun's avatar
Diego Biurrun committed
155
            int alevel= FFABS(level);
156 157 158 159 160 161 162 163
            int sign= (level>>31)&1;

            if (alevel > rl->max_level[0][run])
                code= 111; /*rl->n*/
            else
                code= rl->index_run[0][run] + alevel - 1;

            if (code < 111 /* rl->n */) {
164
                /* store the vlc & sign at once */
165 166
                len=   rl->table_vlc[code][1]+1;
                bits= (rl->table_vlc[code][0]<<1) + sign;
167
            } else {
168 169
                len=  rl->table_vlc[111/*rl->n*/][1]+6;
                bits= rl->table_vlc[111/*rl->n*/][0]<<6;
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

                bits|= run;
                if (alevel < 128) {
                    bits<<=8; len+=8;
                    bits|= level & 0xff;
                } else {
                    bits<<=16; len+=16;
                    bits|= level & 0xff;
                    if (level < 0) {
                        bits|= 0x8001 + level + 255;
                    } else {
                        bits|= level & 0xffff;
                    }
                }
            }

            uni_ac_vlc_len [UNI_AC_ENC_INDEX(run, i)]= len;
        }
    }
}
190

191 192 193 194 195 196 197

static int find_frame_rate_index(MpegEncContext *s){
    int i;
    int64_t dmin= INT64_MAX;
    int64_t d;

    for(i=1;i<14;i++) {
198
        int64_t n0= 1001LL/ff_frame_rate_tab[i].den*ff_frame_rate_tab[i].num*s->avctx->time_base.num;
199
        int64_t n1= 1001LL*s->avctx->time_base.den;
200
        if(s->avctx->strict_std_compliance > FF_COMPLIANCE_INOFFICIAL && i>=9) break;
201

Diego Biurrun's avatar
Diego Biurrun committed
202
        d = FFABS(n0 - n1);
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        if(d < dmin){
            dmin=d;
            s->frame_rate_index= i;
        }
    }
    if(dmin)
        return -1;
    else
        return 0;
}

static int encode_init(AVCodecContext *avctx)
{
    MpegEncContext *s = avctx->priv_data;

    if(MPV_encode_init(avctx) < 0)
        return -1;

    if(find_frame_rate_index(s) < 0){
222
        if(s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){
223
            av_log(avctx, AV_LOG_ERROR, "MPEG1/2 does not support %d/%d fps\n", avctx->time_base.den, avctx->time_base.num);
224 225
            return -1;
        }else{
226
            av_log(avctx, AV_LOG_INFO, "MPEG1/2 does not support %d/%d fps, there may be AV sync issues\n", avctx->time_base.den, avctx->time_base.num);
227 228
        }
    }
229

230 231 232 233 234 235 236
    if(avctx->profile == FF_PROFILE_UNKNOWN){
        if(avctx->level != FF_LEVEL_UNKNOWN){
            av_log(avctx, AV_LOG_ERROR, "Set profile and level\n");
            return -1;
        }
        avctx->profile = s->chroma_format == CHROMA_420 ? 4 : 0; /* Main or 4:2:2 */
    }
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251
    if(avctx->level == FF_LEVEL_UNKNOWN){
        if(avctx->profile == 0){ /* 4:2:2 */
            if(avctx->width <= 720 && avctx->height <= 608) avctx->level = 5; /* Main */
            else                                            avctx->level = 2; /* High */
        }else{
            if(avctx->profile != 1 && s->chroma_format != CHROMA_420){
                av_log(avctx, AV_LOG_ERROR, "Only High(1) and 4:2:2(0) profiles support 4:2:2 color sampling\n");
                return -1;
            }
            if(avctx->width <= 720 && avctx->height <= 576) avctx->level = 8; /* Main */
            else if(avctx->width <= 1440)                   avctx->level = 6; /* High 1440 */
            else                                            avctx->level = 4; /* High */
        }
    }
252

253 254 255 256 257
    if((avctx->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE) && s->frame_rate_index != 4){
        av_log(avctx, AV_LOG_ERROR, "Drop frame time code only allowed with 1001/30000 fps\n");
        return -1;
    }

258 259 260
    return 0;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
261 262 263
static void put_header(MpegEncContext *s, int header)
{
    align_put_bits(&s->pb);
264 265
    put_bits(&s->pb, 16, header>>16);
    put_bits(&s->pb, 16, header&0xFFFF);
Fabrice Bellard's avatar
Fabrice Bellard committed
266 267 268 269 270 271
}

/* put sequence header if needed */
static void mpeg1_encode_sequence_header(MpegEncContext *s)
{
        unsigned int vbv_buffer_size;
Fabrice Bellard's avatar
Fabrice Bellard committed
272
        unsigned int fps, v;
Falk Hüffner's avatar
Falk Hüffner committed
273
        int i;
274
        uint64_t time_code;
275
        float best_aspect_error= 1E10;
Michael Niedermayer's avatar
Michael Niedermayer committed
276
        float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio);
277
        int constraint_parameter_flag;
278

Michael Niedermayer's avatar
Michael Niedermayer committed
279
        if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)
280

Michael Niedermayer's avatar
cleanup  
Michael Niedermayer committed
281
        if (s->current_picture.key_frame) {
282
            AVRational framerate= ff_frame_rate_tab[s->frame_rate_index];
283

Fabrice Bellard's avatar
Fabrice Bellard committed
284 285
            /* mpeg1 header repeated every gop */
            put_header(s, SEQ_START_CODE);
286

Fabrice Bellard's avatar
Fabrice Bellard committed
287 288
            put_bits(&s->pb, 12, s->width);
            put_bits(&s->pb, 12, s->height);
289

290
            for(i=1; i<15; i++){
291 292
                float error= aspect_ratio;
                if(s->codec_id == CODEC_ID_MPEG1VIDEO || i <=1)
293
                    error-= 1.0/mpeg1_aspect[i];
294 295
                else
                    error-= av_q2d(mpeg2_aspect[i])*s->height/s->width;
296

Diego Biurrun's avatar
Diego Biurrun committed
297
                error= FFABS(error);
298

299 300 301 302 303
                if(error < best_aspect_error){
                    best_aspect_error= error;
                    s->aspect_ratio_info= i;
                }
            }
304

305
            put_bits(&s->pb, 4, s->aspect_ratio_info);
Fabrice Bellard's avatar
Fabrice Bellard committed
306
            put_bits(&s->pb, 4, s->frame_rate_index);
307

308 309 310 311 312 313 314
            if(s->avctx->rc_max_rate){
                v = (s->avctx->rc_max_rate + 399) / 400;
                if (v > 0x3ffff && s->codec_id == CODEC_ID_MPEG1VIDEO)
                    v = 0x3ffff;
            }else{
                v= 0x3FFFF;
            }
315 316 317 318 319

            if(s->avctx->rc_buffer_size)
                vbv_buffer_size = s->avctx->rc_buffer_size;
            else
                /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */
320 321 322 323 324
                vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;
            vbv_buffer_size= (vbv_buffer_size + 16383) / 16384;

            put_bits(&s->pb, 18, v & 0x3FFFF);
            put_bits(&s->pb, 1, 1); /* marker */
325 326
            put_bits(&s->pb, 10, vbv_buffer_size & 0x3FF);

327 328
            constraint_parameter_flag=
                s->width <= 768 && s->height <= 576 &&
329
                s->mb_width * s->mb_height <= 396 &&
330 331
                s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 &&
                framerate.num <= framerate.den*30 &&
332
                s->avctx->me_range && s->avctx->me_range < 128 &&
333 334 335
                vbv_buffer_size <= 20 &&
                v <= 1856000/400 &&
                s->codec_id == CODEC_ID_MPEG1VIDEO;
336

337
            put_bits(&s->pb, 1, constraint_parameter_flag);
338

339 340
            ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);
            ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);
Fabrice Bellard's avatar
Fabrice Bellard committed
341

Michael Niedermayer's avatar
Michael Niedermayer committed
342 343 344
            if(s->codec_id == CODEC_ID_MPEG2VIDEO){
                put_header(s, EXT_START_CODE);
                put_bits(&s->pb, 4, 1); //seq ext
345

346
                put_bits(&s->pb, 1, s->avctx->profile == 0); //escx 1 for 4:2:2 profile */
347

348 349
                put_bits(&s->pb, 3, s->avctx->profile); //profile
                put_bits(&s->pb, 4, s->avctx->level); //level
350

351
                put_bits(&s->pb, 1, s->progressive_sequence);
352
                put_bits(&s->pb, 2, s->chroma_format);
Michael Niedermayer's avatar
Michael Niedermayer committed
353 354 355 356 357 358 359 360 361
                put_bits(&s->pb, 2, 0); //horizontal size ext
                put_bits(&s->pb, 2, 0); //vertical size ext
                put_bits(&s->pb, 12, v>>18); //bitrate ext
                put_bits(&s->pb, 1, 1); //marker
                put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext
                put_bits(&s->pb, 1, s->low_delay);
                put_bits(&s->pb, 2, 0); // frame_rate_ext_n
                put_bits(&s->pb, 5, 0); // frame_rate_ext_d
            }
362

Fabrice Bellard's avatar
Fabrice Bellard committed
363
            put_header(s, GOP_START_CODE);
364
            put_bits(&s->pb, 1, !!(s->avctx->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE)); /* drop frame flag */
Fabrice Bellard's avatar
Fabrice Bellard committed
365 366
            /* time code : we must convert from the real frame rate to a
               fake mpeg frame rate in case of low frame rate */
367
            fps = (framerate.num + framerate.den/2)/ framerate.den;
368 369 370 371 372 373 374
            time_code = s->current_picture_ptr->coded_picture_number + s->avctx->timecode_frame_start;

            s->gop_picture_number = s->current_picture_ptr->coded_picture_number;
            if (s->avctx->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE) {
                /* only works for NTSC 29.97 */
                int d = time_code / 17982;
                int m = time_code % 17982;
Baptiste Coudurier's avatar
typo  
Baptiste Coudurier committed
375
                //if (m < 2) m += 2; /* not needed since -2,-1 / 1798 in C returns 0 */
376 377
                time_code += 18 * d + 2 * ((m - 2) / 1798);
            }
378 379
            put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));
            put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));
Fabrice Bellard's avatar
Fabrice Bellard committed
380
            put_bits(&s->pb, 1, 1);
381
            put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));
Michael Niedermayer's avatar
Michael Niedermayer committed
382
            put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));
383
            put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));
Fabrice Bellard's avatar
Fabrice Bellard committed
384 385 386 387
            put_bits(&s->pb, 1, 0); /* broken link */
        }
}

388 389 390 391 392
static inline void encode_mb_skip_run(MpegEncContext *s, int run){
    while (run >= 33) {
        put_bits(&s->pb, 11, 0x008);
        run -= 33;
    }
393
    put_bits(&s->pb, mbAddrIncrTable[run][1],
394 395
             mbAddrIncrTable[run][0]);
}
396
#endif //CONFIG_ENCODERS
Fabrice Bellard's avatar
Fabrice Bellard committed
397

398
static void common_init(MpegEncContext *s)
Fabrice Bellard's avatar
Fabrice Bellard committed
399
{
400

401
    s->y_dc_scale_table=
402
    s->c_dc_scale_table= mpeg2_dc_scale_table[s->intra_dc_precision];
Michael Niedermayer's avatar
Michael Niedermayer committed
403

404
}
405

Michael Niedermayer's avatar
Michael Niedermayer committed
406 407 408 409 410 411 412
void ff_mpeg1_clean_buffers(MpegEncContext *s){
    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);
    s->last_dc[1] = s->last_dc[0];
    s->last_dc[2] = s->last_dc[0];
    memset(s->last_mv, 0, sizeof(s->last_mv));
}

413
#ifdef CONFIG_ENCODERS
414

415 416 417 418 419 420 421 422 423 424
static av_always_inline void put_qscale(MpegEncContext *s)
{
    if(s->q_scale_type){
        assert(s->qscale>=1 && s->qscale <=12);
        put_bits(&s->pb, 5, inv_non_linear_qscale[s->qscale]);
    }else{
        put_bits(&s->pb, 5, s->qscale);
    }
}

425 426
void ff_mpeg1_encode_slice_header(MpegEncContext *s){
    put_header(s, SLICE_MIN_START_CODE + s->mb_y);
427
    put_qscale(s);
428 429 430
    put_bits(&s->pb, 1, 0); /* slice extra information */
}

431 432
void mpeg1_encode_picture_header(MpegEncContext *s, int picture_number)
{
Fabrice Bellard's avatar
Fabrice Bellard committed
433 434 435 436 437
    mpeg1_encode_sequence_header(s);

    /* mpeg1 picture header */
    put_header(s, PICTURE_START_CODE);
    /* temporal reference */
438 439

    // RAL: s->picture_number instead of s->fake_picture_number
440 441
    put_bits(&s->pb, 10, (s->picture_number -
                          s->gop_picture_number) & 0x3ff);
Fabrice Bellard's avatar
Fabrice Bellard committed
442
    put_bits(&s->pb, 3, s->pict_type);
Michael Niedermayer's avatar
Michael Niedermayer committed
443

444
    s->vbv_delay_ptr= s->pb.buf + put_bits_count(&s->pb)/8;
Michael Niedermayer's avatar
Michael Niedermayer committed
445
    put_bits(&s->pb, 16, 0xFFFF); /* vbv_delay */
446

447 448
    // RAL: Forward f_code also needed for B frames
    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
Fabrice Bellard's avatar
Fabrice Bellard committed
449
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
450 451 452 453
        if(s->codec_id == CODEC_ID_MPEG1VIDEO)
            put_bits(&s->pb, 3, s->f_code); /* forward_f_code */
        else
            put_bits(&s->pb, 3, 7); /* forward_f_code */
Fabrice Bellard's avatar
Fabrice Bellard committed
454
    }
455

456 457 458
    // RAL: Backward f_code necessary for B frames
    if (s->pict_type == B_TYPE) {
        put_bits(&s->pb, 1, 0); /* half pel coordinates */
459 460 461 462
        if(s->codec_id == CODEC_ID_MPEG1VIDEO)
            put_bits(&s->pb, 3, s->b_code); /* backward_f_code */
        else
            put_bits(&s->pb, 3, 7); /* backward_f_code */
Michael Niedermayer's avatar
Michael Niedermayer committed
463
    }
464

Fabrice Bellard's avatar
Fabrice Bellard committed
465
    put_bits(&s->pb, 1, 0); /* extra bit picture */
466 467

    s->frame_pred_frame_dct = 1;
Michael Niedermayer's avatar
Michael Niedermayer committed
468 469 470
    if(s->codec_id == CODEC_ID_MPEG2VIDEO){
        put_header(s, EXT_START_CODE);
        put_bits(&s->pb, 4, 8); //pic ext
471 472 473 474 475 476 477 478 479 480 481 482
        if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {
            put_bits(&s->pb, 4, s->f_code);
            put_bits(&s->pb, 4, s->f_code);
        }else{
            put_bits(&s->pb, 8, 255);
        }
        if (s->pict_type == B_TYPE) {
            put_bits(&s->pb, 4, s->b_code);
            put_bits(&s->pb, 4, s->b_code);
        }else{
            put_bits(&s->pb, 8, 255);
        }
Michael Niedermayer's avatar
Michael Niedermayer committed
483
        put_bits(&s->pb, 2, s->intra_dc_precision);
484

485 486
        assert(s->picture_structure == PICT_FRAME);
        put_bits(&s->pb, 2, s->picture_structure);
487 488 489 490 491
        if (s->progressive_sequence) {
            put_bits(&s->pb, 1, 0); /* no repeat */
        } else {
            put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);
        }
492 493 494
        /* XXX: optimize the generation of this flag with entropy
           measures */
        s->frame_pred_frame_dct = s->progressive_sequence;
495

496
        put_bits(&s->pb, 1, s->frame_pred_frame_dct);
Michael Niedermayer's avatar
Michael Niedermayer committed
497 498 499 500 501
        put_bits(&s->pb, 1, s->concealment_motion_vectors);
        put_bits(&s->pb, 1, s->q_scale_type);
        put_bits(&s->pb, 1, s->intra_vlc_format);
        put_bits(&s->pb, 1, s->alternate_scan);
        put_bits(&s->pb, 1, s->repeat_first_field);
502
        s->progressive_frame = s->progressive_sequence;
503
        put_bits(&s->pb, 1, s->chroma_format == CHROMA_420 ? s->progressive_frame : 0); /* chroma_420_type */
504
        put_bits(&s->pb, 1, s->progressive_frame);
Michael Niedermayer's avatar
Michael Niedermayer committed
505 506
        put_bits(&s->pb, 1, 0); //composite_display_flag
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
507 508 509 510 511 512 513 514
    if(s->flags & CODEC_FLAG_SVCD_SCAN_OFFSET){
        int i;

        put_header(s, USER_START_CODE);
        for(i=0; i<sizeof(svcd_scan_offset_placeholder); i++){
            put_bits(&s->pb, 8, svcd_scan_offset_placeholder[i]);
        }
    }
515

516 517
    s->mb_y=0;
    ff_mpeg1_encode_slice_header(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
518 519
}

520
static inline void put_mb_modes(MpegEncContext *s, int n, int bits,
521
                                int has_mv, int field_motion)
522 523 524
{
    put_bits(&s->pb, n, bits);
    if (!s->frame_pred_frame_dct) {
525
        if (has_mv)
526
            put_bits(&s->pb, 2, 2 - field_motion); /* motion_type: frame/field */
527 528 529 530
        put_bits(&s->pb, 1, s->interlaced_dct);
    }
}

531
static av_always_inline void mpeg1_encode_mb_internal(MpegEncContext *s,
532 533 534
                                                   DCTELEM block[6][64],
                                                   int motion_x, int motion_y,
                                                   int mb_block_count)
Fabrice Bellard's avatar
Fabrice Bellard committed
535
{
536 537 538 539
    int i, cbp;
    const int mb_x = s->mb_x;
    const int mb_y = s->mb_y;
    const int first_mb= mb_x == s->resync_mb_x && mb_y == s->resync_mb_y;
Fabrice Bellard's avatar
Fabrice Bellard committed
540 541 542

    /* compute cbp */
    cbp = 0;
543
    for(i=0;i<mb_block_count;i++) {
Fabrice Bellard's avatar
Fabrice Bellard committed
544
        if (s->block_last_index[i] >= 0)
545
            cbp |= 1 << (mb_block_count - 1 - i);
Fabrice Bellard's avatar
Fabrice Bellard committed
546
    }
547

548
    if (cbp == 0 && !first_mb && s->mv_type == MV_TYPE_16X16 &&
549
        (mb_x != s->mb_width - 1 || (mb_y != s->mb_height - 1 && s->codec_id == CODEC_ID_MPEG1VIDEO)) &&
550
        ((s->pict_type == P_TYPE && (motion_x | motion_y) == 0) ||
551 552
        (s->pict_type == B_TYPE && s->mv_dir == s->last_mv_dir && (((s->mv_dir & MV_DIR_FORWARD) ? ((s->mv[0][0][0] - s->last_mv[0][0][0])|(s->mv[0][0][1] - s->last_mv[0][0][1])) : 0) |
        ((s->mv_dir & MV_DIR_BACKWARD) ? ((s->mv[1][0][0] - s->last_mv[1][0][0])|(s->mv[1][0][1] - s->last_mv[1][0][1])) : 0)) == 0))) {
553
        s->mb_skip_run++;
554
        s->qscale -= s->dquant;
Michael Niedermayer's avatar
Michael Niedermayer committed
555 556 557
        s->skip_count++;
        s->misc_bits++;
        s->last_bits++;
558
        if(s->pict_type == P_TYPE){
559
            s->last_mv[0][1][0]= s->last_mv[0][0][0]=
560 561
            s->last_mv[0][1][1]= s->last_mv[0][0][1]= 0;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
562
    } else {
563 564 565 566 567
        if(first_mb){
            assert(s->mb_skip_run == 0);
            encode_mb_skip_run(s, s->mb_x);
        }else{
            encode_mb_skip_run(s, s->mb_skip_run);
Fabrice Bellard's avatar
Fabrice Bellard committed
568
        }
569

Fabrice Bellard's avatar
Fabrice Bellard committed
570
        if (s->pict_type == I_TYPE) {
571
            if(s->dquant && cbp){
572
                put_mb_modes(s, 2, 1, 0, 0); /* macroblock_type : macroblock_quant = 1 */
573
                put_qscale(s);
574
            }else{
575
                put_mb_modes(s, 1, 1, 0, 0); /* macroblock_type : macroblock_quant = 0 */
576 577
                s->qscale -= s->dquant;
            }
Michael Niedermayer's avatar
Michael Niedermayer committed
578 579
            s->misc_bits+= get_bits_diff(s);
            s->i_count++;
580 581
        } else if (s->mb_intra) {
            if(s->dquant && cbp){
582
                put_mb_modes(s, 6, 0x01, 0, 0);
583
                put_qscale(s);
584
            }else{
585
                put_mb_modes(s, 5, 0x03, 0, 0);
586 587 588 589
                s->qscale -= s->dquant;
            }
            s->misc_bits+= get_bits_diff(s);
            s->i_count++;
590
            memset(s->last_mv, 0, sizeof(s->last_mv));
591
        } else if (s->pict_type == P_TYPE) {
592
            if(s->mv_type == MV_TYPE_16X16){
Fabrice Bellard's avatar
Fabrice Bellard committed
593
                if (cbp != 0) {
594
                    if ((motion_x|motion_y) == 0) {
595
                        if(s->dquant){
596
                            put_mb_modes(s, 5, 1, 0, 0); /* macroblock_pattern & quant */
597
                            put_qscale(s);
598
                        }else{
599
                            put_mb_modes(s, 2, 1, 0, 0); /* macroblock_pattern only */
600
                        }
Michael Niedermayer's avatar
Michael Niedermayer committed
601
                        s->misc_bits+= get_bits_diff(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
602
                    } else {
603
                        if(s->dquant){
604
                            put_mb_modes(s, 5, 2, 1, 0); /* motion + cbp */
605
                            put_qscale(s);
606
                        }else{
607
                            put_mb_modes(s, 1, 1, 1, 0); /* motion + cbp */
608
                        }
Michael Niedermayer's avatar
Michael Niedermayer committed
609
                        s->misc_bits+= get_bits_diff(s);
610 611
                        mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
                        mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
Michael Niedermayer's avatar
Michael Niedermayer committed
612
                        s->mv_bits+= get_bits_diff(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
613 614 615
                    }
                } else {
                    put_bits(&s->pb, 3, 1); /* motion only */
616 617
                    if (!s->frame_pred_frame_dct)
                        put_bits(&s->pb, 2, 2); /* motion_type: frame */
618
                    s->misc_bits+= get_bits_diff(s);
619 620
                    mpeg1_encode_motion(s, motion_x - s->last_mv[0][0][0], s->f_code);    // RAL: f_code parameter added
                    mpeg1_encode_motion(s, motion_y - s->last_mv[0][0][1], s->f_code);    // RAL: f_code parameter added
621
                    s->qscale -= s->dquant;
Michael Niedermayer's avatar
Michael Niedermayer committed
622
                    s->mv_bits+= get_bits_diff(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
623
                }
624 625 626 627 628 629 630 631
                s->last_mv[0][1][0]= s->last_mv[0][0][0]= motion_x;
                s->last_mv[0][1][1]= s->last_mv[0][0][1]= motion_y;
            }else{
                assert(!s->frame_pred_frame_dct && s->mv_type == MV_TYPE_FIELD);

                if (cbp) {
                    if(s->dquant){
                        put_mb_modes(s, 5, 2, 1, 1); /* motion + cbp */
632
                        put_qscale(s);
633 634
                    }else{
                        put_mb_modes(s, 1, 1, 1, 1); /* motion + cbp */
635
                    }
636 637 638
                } else {
                    put_bits(&s->pb, 3, 1); /* motion only */
                    put_bits(&s->pb, 2, 1); /* motion_type: field */
639
                    s->qscale -= s->dquant;
640 641 642 643 644 645 646 647 648 649 650
                }
                s->misc_bits+= get_bits_diff(s);
                for(i=0; i<2; i++){
                    put_bits(&s->pb, 1, s->field_select[0][i]);
                    mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
                    mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
                    s->last_mv[0][i][0]=   s->mv[0][i][0];
                    s->last_mv[0][i][1]= 2*s->mv[0][i][1];
                }
                s->mv_bits+= get_bits_diff(s);
            }
651 652 653 654 655 656 657 658
            if(cbp) {
                if (s->chroma_y_shift) {
                    put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
                } else {
                    put_bits(&s->pb, mbPatTable[cbp>>2][1], mbPatTable[cbp>>2][0]);
                    put_bits(&s->pb, 2, cbp & 3);
                }
            }
659
            s->f_count++;
660
        } else{
661 662 663 664 665 666 667 668 669
            static const int mb_type_len[4]={0,3,4,2}; //bak,for,bi

            if(s->mv_type == MV_TYPE_16X16){
                if (cbp){    // With coded bloc pattern
                    if (s->dquant) {
                        if(s->mv_dir == MV_DIR_FORWARD)
                            put_mb_modes(s, 6, 3, 1, 0);
                        else
                            put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 0);
670
                        put_qscale(s);
671 672 673 674 675 676 677 678 679 680 681
                    } else {
                        put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 0);
                    }
                }else{    // No coded bloc pattern
                    put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
                    if (!s->frame_pred_frame_dct)
                        put_bits(&s->pb, 2, 2); /* motion_type: frame */
                    s->qscale -= s->dquant;
                }
                s->misc_bits += get_bits_diff(s);
                if (s->mv_dir&MV_DIR_FORWARD){
682 683
                    mpeg1_encode_motion(s, s->mv[0][0][0] - s->last_mv[0][0][0], s->f_code);
                    mpeg1_encode_motion(s, s->mv[0][0][1] - s->last_mv[0][0][1], s->f_code);
684 685 686 687 688
                    s->last_mv[0][0][0]=s->last_mv[0][1][0]= s->mv[0][0][0];
                    s->last_mv[0][0][1]=s->last_mv[0][1][1]= s->mv[0][0][1];
                    s->f_count++;
                }
                if (s->mv_dir&MV_DIR_BACKWARD){
689 690
                    mpeg1_encode_motion(s, s->mv[1][0][0] - s->last_mv[1][0][0], s->b_code);
                    mpeg1_encode_motion(s, s->mv[1][0][1] - s->last_mv[1][0][1], s->b_code);
691 692 693 694 695 696 697 698 699 700 701 702 703
                    s->last_mv[1][0][0]=s->last_mv[1][1][0]= s->mv[1][0][0];
                    s->last_mv[1][0][1]=s->last_mv[1][1][1]= s->mv[1][0][1];
                    s->b_count++;
                }
            }else{
                assert(s->mv_type == MV_TYPE_FIELD);
                assert(!s->frame_pred_frame_dct);
                if (cbp){    // With coded bloc pattern
                    if (s->dquant) {
                        if(s->mv_dir == MV_DIR_FORWARD)
                            put_mb_modes(s, 6, 3, 1, 1);
                        else
                            put_mb_modes(s, mb_type_len[s->mv_dir]+3, 2, 1, 1);
704
                        put_qscale(s);
705 706
                    } else {
                        put_mb_modes(s, mb_type_len[s->mv_dir], 3, 1, 1);
707
                    }
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
                }else{    // No coded bloc pattern
                    put_bits(&s->pb, mb_type_len[s->mv_dir], 2);
                    put_bits(&s->pb, 2, 1); /* motion_type: field */
                    s->qscale -= s->dquant;
                }
                s->misc_bits += get_bits_diff(s);
                if (s->mv_dir&MV_DIR_FORWARD){
                    for(i=0; i<2; i++){
                        put_bits(&s->pb, 1, s->field_select[0][i]);
                        mpeg1_encode_motion(s, s->mv[0][i][0] -  s->last_mv[0][i][0]    , s->f_code);
                        mpeg1_encode_motion(s, s->mv[0][i][1] - (s->last_mv[0][i][1]>>1), s->f_code);
                        s->last_mv[0][i][0]=   s->mv[0][i][0];
                        s->last_mv[0][i][1]= 2*s->mv[0][i][1];
                    }
                    s->f_count++;
                }
                if (s->mv_dir&MV_DIR_BACKWARD){
                    for(i=0; i<2; i++){
                        put_bits(&s->pb, 1, s->field_select[1][i]);
                        mpeg1_encode_motion(s, s->mv[1][i][0] -  s->last_mv[1][i][0]    , s->b_code);
                        mpeg1_encode_motion(s, s->mv[1][i][1] - (s->last_mv[1][i][1]>>1), s->b_code);
                        s->last_mv[1][i][0]=   s->mv[1][i][0];
                        s->last_mv[1][i][1]= 2*s->mv[1][i][1];
                    }
                    s->b_count++;
                }
Fabrice Bellard's avatar
Fabrice Bellard committed
734
            }
735
            s->mv_bits += get_bits_diff(s);
736 737 738 739 740 741 742 743
            if(cbp) {
                if (s->chroma_y_shift) {
                    put_bits(&s->pb, mbPatTable[cbp][1], mbPatTable[cbp][0]);
                } else {
                    put_bits(&s->pb, mbPatTable[cbp>>2][1], mbPatTable[cbp>>2][0]);
                    put_bits(&s->pb, 2, cbp & 3);
                }
            }
744
        }
745 746
        for(i=0;i<mb_block_count;i++) {
            if (cbp & (1 << (mb_block_count - 1 - i))) {
Fabrice Bellard's avatar
Fabrice Bellard committed
747 748 749
                mpeg1_encode_block(s, block[i], i);
            }
        }
750
        s->mb_skip_run = 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
751 752 753 754
        if(s->mb_intra)
            s->i_tex_bits+= get_bits_diff(s);
        else
            s->p_tex_bits+= get_bits_diff(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
755 756 757
    }
}

758 759 760 761 762 763
void mpeg1_encode_mb(MpegEncContext *s, DCTELEM block[6][64], int motion_x, int motion_y)
{
    if (s->chroma_format == CHROMA_420) mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 6);
    else                                mpeg1_encode_mb_internal(s, block, motion_x, motion_y, 8);
}

764 765
// RAL: Parameter added: f_or_b_code
static void mpeg1_encode_motion(MpegEncContext *s, int val, int f_or_b_code)
Fabrice Bellard's avatar
Fabrice Bellard committed
766
{
Michael Niedermayer's avatar
Michael Niedermayer committed
767
    int code, bit_size, l, bits, range, sign;
Fabrice Bellard's avatar
Fabrice Bellard committed
768 769 770 771 772

    if (val == 0) {
        /* zero vector */
        code = 0;
        put_bits(&s->pb,
773 774
                 mbMotionVectorTable[0][1],
                 mbMotionVectorTable[0][0]);
Fabrice Bellard's avatar
Fabrice Bellard committed
775
    } else {
776
        bit_size = f_or_b_code - 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
777 778
        range = 1 << bit_size;
        /* modulo encoding */
Michael Niedermayer's avatar
Michael Niedermayer committed
779 780
        l= INT_BIT - 5 - bit_size;
        val= (val<<l)>>l;
Fabrice Bellard's avatar
Fabrice Bellard committed
781 782 783 784 785 786 787 788 789 790 791 792 793

        if (val >= 0) {
            val--;
            code = (val >> bit_size) + 1;
            bits = val & (range - 1);
            sign = 0;
        } else {
            val = -val;
            val--;
            code = (val >> bit_size) + 1;
            bits = val & (range - 1);
            sign = 1;
        }
794 795 796

        assert(code > 0 && code <= 16);

Fabrice Bellard's avatar
Fabrice Bellard committed
797
        put_bits(&s->pb,
798 799
                 mbMotionVectorTable[code][1],
                 mbMotionVectorTable[code][0]);
800

Fabrice Bellard's avatar
Fabrice Bellard committed
801 802 803 804 805 806 807
        put_bits(&s->pb, 1, sign);
        if (bit_size > 0) {
            put_bits(&s->pb, bit_size, bits);
        }
    }
}

808
void ff_mpeg1_encode_init(MpegEncContext *s)
809 810
{
    static int done=0;
811 812 813

    common_init(s);

814 815 816
    if(!done){
        int f_code;
        int mv;
Diego Biurrun's avatar