vc1dec.c 226 KB
Newer Older
1 2
/*
 * VC-1 and WMV3 decoder
3
 * Copyright (c) 2011 Mashiat Sarker Shakkhar
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Copyright (c) 2006-2007 Konstantin Shishkov
 * Partly based on vc9.c (c) 2005 Anonymous, Alex Beregszaszi, Michael Niedermayer
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
25
 * @file
26 27
 * VC-1 and WMV3 decoder
 */
28

29 30 31 32
#include "internal.h"
#include "dsputil.h"
#include "avcodec.h"
#include "mpegvideo.h"
33
#include "h263.h"
34 35 36 37 38 39 40
#include "vc1.h"
#include "vc1data.h"
#include "vc1acdata.h"
#include "msmpeg4data.h"
#include "unary.h"
#include "mathops.h"
#include "vdpau_internal.h"
41
#include "libavutil/avassert.h"
42 43 44 45 46 47 48 49

#undef NDEBUG
#include <assert.h>

#define MB_INTRA_VLC_BITS 9
#define DC_VLC_BITS 9


50
// offset tables for interlaced picture MVDATA decoding
51 52
static const int offset_table1[9] = {  0,  1,  2,  4,  8, 16, 32,  64, 128 };
static const int offset_table2[9] = {  0,  1,  3,  7, 15, 31, 63, 127, 255 };
53

54 55
/***********************************************************************/
/**
56
 * @name VC-1 Bitplane decoding
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
 * @see 8.7, p56
 * @{
 */

/**
 * Imode types
 * @{
 */
enum Imode {
    IMODE_RAW,
    IMODE_NORM2,
    IMODE_DIFF2,
    IMODE_NORM6,
    IMODE_DIFF6,
    IMODE_ROWSKIP,
    IMODE_COLSKIP
};
/** @} */ //imode defines


/** @} */ //Bitplane group

79 80 81
static void vc1_put_signed_blocks_clamped(VC1Context *v)
{
    MpegEncContext *s = &v->s;
82 83 84
    int topleft_mb_pos, top_mb_pos;
    int stride_y, fieldtx;
    int v_dist;
85 86 87 88 89 90 91 92 93 94

    /* The put pixels loop is always one MB row behind the decoding loop,
     * because we can only put pixels when overlap filtering is done, and
     * for filtering of the bottom edge of a MB, we need the next MB row
     * present as well.
     * Within the row, the put pixels loop is also one MB col behind the
     * decoding loop. The reason for this is again, because for filtering
     * of the right MB edge, we need the next MB present. */
    if (!s->first_slice_line) {
        if (s->mb_x) {
95
            topleft_mb_pos = (s->mb_y - 1) * s->mb_stride + s->mb_x - 1;
96
            fieldtx        = v->fieldtx_plane[topleft_mb_pos];
97
            stride_y       = s->linesize << fieldtx;
98
            v_dist         = (16 - fieldtx) >> (fieldtx == 0);
99 100
            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][0],
                                             s->dest[0] - 16 * s->linesize - 16,
101
                                             stride_y);
102 103
            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][1],
                                             s->dest[0] - 16 * s->linesize - 8,
104
                                             stride_y);
105
            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][2],
106 107
                                             s->dest[0] - v_dist * s->linesize - 16,
                                             stride_y);
108
            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][3],
109 110
                                             s->dest[0] - v_dist * s->linesize - 8,
                                             stride_y);
111 112 113 114 115 116 117 118
            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][4],
                                             s->dest[1] - 8 * s->uvlinesize - 8,
                                             s->uvlinesize);
            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][5],
                                             s->dest[2] - 8 * s->uvlinesize - 8,
                                             s->uvlinesize);
        }
        if (s->mb_x == s->mb_width - 1) {
119
            top_mb_pos = (s->mb_y - 1) * s->mb_stride + s->mb_x;
120 121 122
            fieldtx    = v->fieldtx_plane[top_mb_pos];
            stride_y   = s->linesize << fieldtx;
            v_dist     = fieldtx ? 15 : 8;
123 124
            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][0],
                                             s->dest[0] - 16 * s->linesize,
125
                                             stride_y);
126 127
            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][1],
                                             s->dest[0] - 16 * s->linesize + 8,
128
                                             stride_y);
129
            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][2],
130 131
                                             s->dest[0] - v_dist * s->linesize,
                                             stride_y);
132
            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][3],
133 134
                                             s->dest[0] - v_dist * s->linesize + 8,
                                             stride_y);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][4],
                                             s->dest[1] - 8 * s->uvlinesize,
                                             s->uvlinesize);
            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][5],
                                             s->dest[2] - 8 * s->uvlinesize,
                                             s->uvlinesize);
        }
    }

#define inc_blk_idx(idx) do { \
        idx++; \
        if (idx >= v->n_allocated_blks) \
            idx = 0; \
    } while (0)

    inc_blk_idx(v->topleft_blk_idx);
    inc_blk_idx(v->top_blk_idx);
    inc_blk_idx(v->left_blk_idx);
    inc_blk_idx(v->cur_blk_idx);
}

156
static void vc1_loop_filter_iblk(VC1Context *v, int pq)
157
{
158
    MpegEncContext *s = &v->s;
159 160
    int j;
    if (!s->first_slice_line) {
161
        v->vc1dsp.vc1_v_loop_filter16(s->dest[0], s->linesize, pq);
162
        if (s->mb_x)
163 164 165 166
            v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16 * s->linesize, s->linesize, pq);
        v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16 * s->linesize + 8, s->linesize, pq);
        for (j = 0; j < 2; j++) {
            v->vc1dsp.vc1_v_loop_filter8(s->dest[j + 1], s->uvlinesize, pq);
167
            if (s->mb_x)
168
                v->vc1dsp.vc1_h_loop_filter8(s->dest[j + 1] - 8 * s->uvlinesize, s->uvlinesize, pq);
169 170
        }
    }
171
    v->vc1dsp.vc1_v_loop_filter16(s->dest[0] + 8 * s->linesize, s->linesize, pq);
172

173
    if (s->mb_y == s->end_mb_y - 1) {
174
        if (s->mb_x) {
175 176 177
            v->vc1dsp.vc1_h_loop_filter16(s->dest[0], s->linesize, pq);
            v->vc1dsp.vc1_h_loop_filter8(s->dest[1], s->uvlinesize, pq);
            v->vc1dsp.vc1_h_loop_filter8(s->dest[2], s->uvlinesize, pq);
178
        }
179
        v->vc1dsp.vc1_h_loop_filter16(s->dest[0] + 8, s->linesize, pq);
180 181 182
    }
}

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
static void vc1_loop_filter_iblk_delayed(VC1Context *v, int pq)
{
    MpegEncContext *s = &v->s;
    int j;

    /* The loopfilter runs 1 row and 1 column behind the overlap filter, which
     * means it runs two rows/cols behind the decoding loop. */
    if (!s->first_slice_line) {
        if (s->mb_x) {
            if (s->mb_y >= s->start_mb_y + 2) {
                v->vc1dsp.vc1_v_loop_filter16(s->dest[0] - 16 * s->linesize - 16, s->linesize, pq);

                if (s->mb_x >= 2)
                    v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 32 * s->linesize - 16, s->linesize, pq);
                v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 32 * s->linesize - 8, s->linesize, pq);
198 199
                for (j = 0; j < 2; j++) {
                    v->vc1dsp.vc1_v_loop_filter8(s->dest[j + 1] - 8 * s->uvlinesize - 8, s->uvlinesize, pq);
200
                    if (s->mb_x >= 2) {
201
                        v->vc1dsp.vc1_h_loop_filter8(s->dest[j + 1] - 16 * s->uvlinesize - 8, s->uvlinesize, pq);
202 203 204 205 206 207 208 209 210 211 212 213 214
                    }
                }
            }
            v->vc1dsp.vc1_v_loop_filter16(s->dest[0] - 8 * s->linesize - 16, s->linesize, pq);
        }

        if (s->mb_x == s->mb_width - 1) {
            if (s->mb_y >= s->start_mb_y + 2) {
                v->vc1dsp.vc1_v_loop_filter16(s->dest[0] - 16 * s->linesize, s->linesize, pq);

                if (s->mb_x)
                    v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 32 * s->linesize, s->linesize, pq);
                v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 32 * s->linesize + 8, s->linesize, pq);
215 216
                for (j = 0; j < 2; j++) {
                    v->vc1dsp.vc1_v_loop_filter8(s->dest[j + 1] - 8 * s->uvlinesize, s->uvlinesize, pq);
217
                    if (s->mb_x >= 2) {
218
                        v->vc1dsp.vc1_h_loop_filter8(s->dest[j + 1] - 16 * s->uvlinesize, s->uvlinesize, pq);
219 220 221 222 223 224
                    }
                }
            }
            v->vc1dsp.vc1_v_loop_filter16(s->dest[0] - 8 * s->linesize, s->linesize, pq);
        }

225
        if (s->mb_y == s->end_mb_y) {
226 227 228 229 230
            if (s->mb_x) {
                if (s->mb_x >= 2)
                    v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16 * s->linesize - 16, s->linesize, pq);
                v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16 * s->linesize - 8, s->linesize, pq);
                if (s->mb_x >= 2) {
231 232
                    for (j = 0; j < 2; j++) {
                        v->vc1dsp.vc1_h_loop_filter8(s->dest[j + 1] - 8 * s->uvlinesize - 8, s->uvlinesize, pq);
233 234 235 236 237 238 239 240 241
                    }
                }
            }

            if (s->mb_x == s->mb_width - 1) {
                if (s->mb_x)
                    v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16 * s->linesize, s->linesize, pq);
                v->vc1dsp.vc1_h_loop_filter16(s->dest[0] - 16 * s->linesize + 8, s->linesize, pq);
                if (s->mb_x) {
242 243
                    for (j = 0; j < 2; j++) {
                        v->vc1dsp.vc1_h_loop_filter8(s->dest[j + 1] - 8 * s->uvlinesize, s->uvlinesize, pq);
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                    }
                }
            }
        }
    }
}

static void vc1_smooth_overlap_filter_iblk(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    int mb_pos;

    if (v->condover == CONDOVER_NONE)
        return;

    mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    /* Within a MB, the horizontal overlap always runs before the vertical.
     * To accomplish that, we run the H on left and internal borders of the
     * currently decoded MB. Then, we wait for the next overlap iteration
     * to do H overlap on the right edge of this MB, before moving over and
     * running the V overlap. Therefore, the V overlap makes us trail by one
     * MB col and the H overlap filter makes us trail by one MB row. This
     * is reflected in the time at which we run the put_pixels loop. */
268 269 270
    if (v->condover == CONDOVER_ALL || v->pq >= 9 || v->over_flags_plane[mb_pos]) {
        if (s->mb_x && (v->condover == CONDOVER_ALL || v->pq >= 9 ||
                        v->over_flags_plane[mb_pos - 1])) {
271 272 273 274
            v->vc1dsp.vc1_h_s_overlap(v->block[v->left_blk_idx][1],
                                      v->block[v->cur_blk_idx][0]);
            v->vc1dsp.vc1_h_s_overlap(v->block[v->left_blk_idx][3],
                                      v->block[v->cur_blk_idx][2]);
275
            if (!(s->flags & CODEC_FLAG_GRAY)) {
276 277 278 279 280 281 282 283 284 285 286 287
                v->vc1dsp.vc1_h_s_overlap(v->block[v->left_blk_idx][4],
                                          v->block[v->cur_blk_idx][4]);
                v->vc1dsp.vc1_h_s_overlap(v->block[v->left_blk_idx][5],
                                          v->block[v->cur_blk_idx][5]);
            }
        }
        v->vc1dsp.vc1_h_s_overlap(v->block[v->cur_blk_idx][0],
                                  v->block[v->cur_blk_idx][1]);
        v->vc1dsp.vc1_h_s_overlap(v->block[v->cur_blk_idx][2],
                                  v->block[v->cur_blk_idx][3]);

        if (s->mb_x == s->mb_width - 1) {
288 289
            if (!s->first_slice_line && (v->condover == CONDOVER_ALL || v->pq >= 9 ||
                                         v->over_flags_plane[mb_pos - s->mb_stride])) {
290 291 292 293
                v->vc1dsp.vc1_v_s_overlap(v->block[v->top_blk_idx][2],
                                          v->block[v->cur_blk_idx][0]);
                v->vc1dsp.vc1_v_s_overlap(v->block[v->top_blk_idx][3],
                                          v->block[v->cur_blk_idx][1]);
294
                if (!(s->flags & CODEC_FLAG_GRAY)) {
295 296 297 298 299 300 301 302 303 304 305 306 307
                    v->vc1dsp.vc1_v_s_overlap(v->block[v->top_blk_idx][4],
                                              v->block[v->cur_blk_idx][4]);
                    v->vc1dsp.vc1_v_s_overlap(v->block[v->top_blk_idx][5],
                                              v->block[v->cur_blk_idx][5]);
                }
            }
            v->vc1dsp.vc1_v_s_overlap(v->block[v->cur_blk_idx][0],
                                      v->block[v->cur_blk_idx][2]);
            v->vc1dsp.vc1_v_s_overlap(v->block[v->cur_blk_idx][1],
                                      v->block[v->cur_blk_idx][3]);
        }
    }
    if (s->mb_x && (v->condover == CONDOVER_ALL || v->over_flags_plane[mb_pos - 1])) {
308 309
        if (!s->first_slice_line && (v->condover == CONDOVER_ALL || v->pq >= 9 ||
                                     v->over_flags_plane[mb_pos - s->mb_stride - 1])) {
310 311 312 313
            v->vc1dsp.vc1_v_s_overlap(v->block[v->topleft_blk_idx][2],
                                      v->block[v->left_blk_idx][0]);
            v->vc1dsp.vc1_v_s_overlap(v->block[v->topleft_blk_idx][3],
                                      v->block[v->left_blk_idx][1]);
314
            if (!(s->flags & CODEC_FLAG_GRAY)) {
315 316 317 318 319 320 321 322 323 324 325 326 327
                v->vc1dsp.vc1_v_s_overlap(v->block[v->topleft_blk_idx][4],
                                          v->block[v->left_blk_idx][4]);
                v->vc1dsp.vc1_v_s_overlap(v->block[v->topleft_blk_idx][5],
                                          v->block[v->left_blk_idx][5]);
            }
        }
        v->vc1dsp.vc1_v_s_overlap(v->block[v->left_blk_idx][0],
                                  v->block[v->left_blk_idx][2]);
        v->vc1dsp.vc1_v_s_overlap(v->block[v->left_blk_idx][1],
                                  v->block[v->left_blk_idx][3]);
    }
}

328 329 330 331 332 333
/** Do motion compensation over 1 macroblock
 * Mostly adapted hpel_motion and qpel_motion from mpegvideo.c
 */
static void vc1_mc_1mv(VC1Context *v, int dir)
{
    MpegEncContext *s = &v->s;
334
    DSPContext *dsp   = &v->s.dsp;
335 336
    uint8_t *srcY, *srcU, *srcV;
    int dxy, mx, my, uvmx, uvmy, src_x, src_y, uvsrc_x, uvsrc_y;
337 338
    int off, off_uv;
    int v_edge_pos = s->v_edge_pos >> v->field_mode;
339 340 341 342

    if ((!v->field_mode ||
         (v->ref_field_type[dir] == 1 && v->cur_field_type == 1)) &&
        !v->s.last_picture.f.data[0])
343
        return;
344 345 346 347 348

    mx = s->mv[dir][0][0];
    my = s->mv[dir][0][1];

    // store motion vectors for further use in B frames
349
    if (s->pict_type == AV_PICTURE_TYPE_P) {
350 351
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = mx;
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = my;
352
    }
353

354 355
    uvmx = (mx + ((mx & 3) == 3)) >> 1;
    uvmy = (my + ((my & 3) == 3)) >> 1;
356 357
    v->luma_mv[s->mb_x][0] = uvmx;
    v->luma_mv[s->mb_x][1] = uvmy;
358 359 360

    if (v->field_mode &&
        v->cur_field_type != v->ref_field_type[dir]) {
361
        my   = my   - 2 + 4 * v->cur_field_type;
362 363 364
        uvmy = uvmy - 2 + 4 * v->cur_field_type;
    }

365 366
    // fastuvmc shall be ignored for interlaced frame picture
    if (v->fastuvmc && (v->fcm != ILACE_FRAME)) {
367 368
        uvmx = uvmx + ((uvmx < 0) ? (uvmx & 1) : -(uvmx & 1));
        uvmy = uvmy + ((uvmy < 0) ? (uvmy & 1) : -(uvmy & 1));
369
    }
370 371
    if (v->field_mode) { // interlaced field picture
        if (!dir) {
372
            if ((v->cur_field_type != v->ref_field_type[dir]) && v->second_field) {
373 374 375 376 377 378 379 380 381 382 383 384 385
                srcY = s->current_picture.f.data[0];
                srcU = s->current_picture.f.data[1];
                srcV = s->current_picture.f.data[2];
            } else {
                srcY = s->last_picture.f.data[0];
                srcU = s->last_picture.f.data[1];
                srcV = s->last_picture.f.data[2];
            }
        } else {
            srcY = s->next_picture.f.data[0];
            srcU = s->next_picture.f.data[1];
            srcV = s->next_picture.f.data[2];
        }
386
    } else {
387
        if (!dir) {
388 389 390 391 392 393 394 395
            srcY = s->last_picture.f.data[0];
            srcU = s->last_picture.f.data[1];
            srcV = s->last_picture.f.data[2];
        } else {
            srcY = s->next_picture.f.data[0];
            srcU = s->next_picture.f.data[1];
            srcV = s->next_picture.f.data[2];
        }
396 397
    }

398 399 400
    if(!srcY)
        return;

401 402 403 404
    src_x   = s->mb_x * 16 + (mx   >> 2);
    src_y   = s->mb_y * 16 + (my   >> 2);
    uvsrc_x = s->mb_x *  8 + (uvmx >> 2);
    uvsrc_y = s->mb_y *  8 + (uvmy >> 2);
405

406
    if (v->profile != PROFILE_ADVANCED) {
407 408 409 410
        src_x   = av_clip(  src_x, -16, s->mb_width  * 16);
        src_y   = av_clip(  src_y, -16, s->mb_height * 16);
        uvsrc_x = av_clip(uvsrc_x,  -8, s->mb_width  *  8);
        uvsrc_y = av_clip(uvsrc_y,  -8, s->mb_height *  8);
411
    } else {
412 413 414 415 416 417
        src_x   = av_clip(  src_x, -17, s->avctx->coded_width);
        src_y   = av_clip(  src_y, -18, s->avctx->coded_height + 1);
        uvsrc_x = av_clip(uvsrc_x,  -8, s->avctx->coded_width  >> 1);
        uvsrc_y = av_clip(uvsrc_y,  -8, s->avctx->coded_height >> 1);
    }

418
    srcY += src_y   * s->linesize   + src_x;
419 420 421
    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

422 423 424 425 426 427
    if (v->field_mode && v->ref_field_type[dir]) {
        srcY += s->current_picture_ptr->f.linesize[0];
        srcU += s->current_picture_ptr->f.linesize[1];
        srcV += s->current_picture_ptr->f.linesize[2];
    }

428
    /* for grayscale we should not try to read from unknown area */
429
    if (s->flags & CODEC_FLAG_GRAY) {
430 431 432 433
        srcU = s->edge_emu_buffer + 18 * s->linesize;
        srcV = s->edge_emu_buffer + 18 * s->linesize;
    }

434
    if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
435
        || s->h_edge_pos < 22 || v_edge_pos < 22
436
        || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx&3) - 16 - s->mspel * 3
437
        || (unsigned)(src_y - 1)        > v_edge_pos    - (my&3) - 16 - 3) {
438
        uint8_t *uvbuf = s->edge_emu_buffer + 19 * s->linesize;
439 440

        srcY -= s->mspel * (1 + s->linesize);
441 442 443 444
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize,
                                17 + s->mspel * 2, 17 + s->mspel * 2,
                                src_x - s->mspel, src_y - s->mspel,
                                s->h_edge_pos, v_edge_pos);
445
        srcY = s->edge_emu_buffer;
446 447 448 449
        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, 8 + 1, 8 + 1,
                                uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, v_edge_pos >> 1);
        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, 8 + 1, 8 + 1,
                                uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, v_edge_pos >> 1);
450 451 452
        srcU = uvbuf;
        srcV = uvbuf + 16;
        /* if we deal with range reduction we need to scale source blocks */
453
        if (v->rangeredfrm) {
454 455 456 457
            int i, j;
            uint8_t *src, *src2;

            src = srcY;
458 459 460
            for (j = 0; j < 17 + s->mspel * 2; j++) {
                for (i = 0; i < 17 + s->mspel * 2; i++)
                    src[i] = ((src[i] - 128) >> 1) + 128;
461 462
                src += s->linesize;
            }
463 464 465 466 467
            src  = srcU;
            src2 = srcV;
            for (j = 0; j < 9; j++) {
                for (i = 0; i < 9; i++) {
                    src[i]  = ((src[i]  - 128) >> 1) + 128;
468 469
                    src2[i] = ((src2[i] - 128) >> 1) + 128;
                }
470
                src  += s->uvlinesize;
471 472 473 474
                src2 += s->uvlinesize;
            }
        }
        /* if we deal with intensity compensation we need to scale source blocks */
475
        if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
476 477 478 479
            int i, j;
            uint8_t *src, *src2;

            src = srcY;
480 481 482
            for (j = 0; j < 17 + s->mspel * 2; j++) {
                for (i = 0; i < 17 + s->mspel * 2; i++)
                    src[i] = v->luty[src[i]];
483 484
                src += s->linesize;
            }
485 486 487 488 489
            src  = srcU;
            src2 = srcV;
            for (j = 0; j < 9; j++) {
                for (i = 0; i < 9; i++) {
                    src[i]  = v->lutuv[src[i]];
490 491
                    src2[i] = v->lutuv[src2[i]];
                }
492
                src  += s->uvlinesize;
493 494 495 496 497 498
                src2 += s->uvlinesize;
            }
        }
        srcY += s->mspel * (1 + s->linesize);
    }

499
    if (v->field_mode && v->second_field) {
500 501 502 503 504 505
        off    = s->current_picture_ptr->f.linesize[0];
        off_uv = s->current_picture_ptr->f.linesize[1];
    } else {
        off    = 0;
        off_uv = 0;
    }
506
    if (s->mspel) {
507
        dxy = ((my & 3) << 2) | (mx & 3);
508 509
        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off    , srcY    , s->linesize, v->rnd);
        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8, srcY + 8, s->linesize, v->rnd);
510
        srcY += s->linesize * 8;
511 512
        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8 * s->linesize    , srcY    , s->linesize, v->rnd);
        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);
513 514
    } else { // hpel mc - always used for luma
        dxy = (my & 2) | ((mx & 2) >> 1);
515
        if (!v->rnd)
516
            dsp->put_pixels_tab[0][dxy](s->dest[0] + off, srcY, s->linesize, 16);
517
        else
518
            dsp->put_no_rnd_pixels_tab[0][dxy](s->dest[0] + off, srcY, s->linesize, 16);
519 520
    }

521
    if (s->flags & CODEC_FLAG_GRAY) return;
522
    /* Chroma MC always uses qpel bilinear */
523 524 525
    uvmx = (uvmx & 3) << 1;
    uvmy = (uvmy & 3) << 1;
    if (!v->rnd) {
526 527
        dsp->put_h264_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);
        dsp->put_h264_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);
528
    } else {
529 530 531 532 533 534 535
        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);
        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);
    }
}

static inline int median4(int a, int b, int c, int d)
{
536 537 538
    if (a < b) {
        if (c < d) return (FFMIN(b, d) + FFMAX(a, c)) / 2;
        else       return (FFMIN(b, c) + FFMAX(a, d)) / 2;
539
    } else {
540 541
        if (c < d) return (FFMIN(a, d) + FFMAX(b, c)) / 2;
        else       return (FFMIN(a, c) + FFMAX(b, d)) / 2;
542 543 544 545 546
    }
}

/** Do motion compensation for 4-MV macroblock - luminance block
 */
547
static void vc1_mc_4mv_luma(VC1Context *v, int n, int dir)
548 549 550 551 552 553
{
    MpegEncContext *s = &v->s;
    DSPContext *dsp = &v->s.dsp;
    uint8_t *srcY;
    int dxy, mx, my, src_x, src_y;
    int off;
554
    int fieldmv = (v->fcm == ILACE_FRAME) ? v->blk_mv_type[s->block_index[n]] : 0;
555
    int v_edge_pos = s->v_edge_pos >> v->field_mode;
556

557 558 559
    if ((!v->field_mode ||
         (v->ref_field_type[dir] == 1 && v->cur_field_type == 1)) &&
        !v->s.last_picture.f.data[0])
560 561
        return;

562 563 564 565 566
    mx = s->mv[dir][n][0];
    my = s->mv[dir][n][1];

    if (!dir) {
        if (v->field_mode) {
567
            if ((v->cur_field_type != v->ref_field_type[dir]) && v->second_field)
568 569 570 571 572 573 574
                srcY = s->current_picture.f.data[0];
            else
                srcY = s->last_picture.f.data[0];
        } else
            srcY = s->last_picture.f.data[0];
    } else
        srcY = s->next_picture.f.data[0];
575

576 577 578
    if(!srcY)
        return;

579 580 581 582 583 584 585 586 587 588 589 590 591
    if (v->field_mode) {
        if (v->cur_field_type != v->ref_field_type[dir])
            my = my - 2 + 4 * v->cur_field_type;
    }

    if (s->pict_type == AV_PICTURE_TYPE_P && n == 3 && v->field_mode) {
        int same_count = 0, opp_count = 0, k;
        int chosen_mv[2][4][2], f;
        int tx, ty;
        for (k = 0; k < 4; k++) {
            f = v->mv_f[0][s->block_index[k] + v->blocks_off];
            chosen_mv[f][f ? opp_count : same_count][0] = s->mv[0][k][0];
            chosen_mv[f][f ? opp_count : same_count][1] = s->mv[0][k][1];
592
            opp_count  += f;
593 594 595 596 597
            same_count += 1 - f;
        }
        f = opp_count > same_count;
        switch (f ? opp_count : same_count) {
        case 4:
598 599 600 601
            tx = median4(chosen_mv[f][0][0], chosen_mv[f][1][0],
                         chosen_mv[f][2][0], chosen_mv[f][3][0]);
            ty = median4(chosen_mv[f][0][1], chosen_mv[f][1][1],
                         chosen_mv[f][2][1], chosen_mv[f][3][1]);
602 603 604 605 606 607 608 609 610
            break;
        case 3:
            tx = mid_pred(chosen_mv[f][0][0], chosen_mv[f][1][0], chosen_mv[f][2][0]);
            ty = mid_pred(chosen_mv[f][0][1], chosen_mv[f][1][1], chosen_mv[f][2][1]);
            break;
        case 2:
            tx = (chosen_mv[f][0][0] + chosen_mv[f][1][0]) / 2;
            ty = (chosen_mv[f][0][1] + chosen_mv[f][1][1]) / 2;
            break;
611 612
        default:
            av_assert2(0);
613 614 615
        }
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;
616 617
        for (k = 0; k < 4; k++)
            v->mv_f[1][s->block_index[k] + v->blocks_off] = f;
618 619
    }

620
    if (v->fcm == ILACE_FRAME) {  // not sure if needed for other types of picture
621
        int qx, qy;
622
        int width  = s->avctx->coded_width;
623 624 625 626 627 628 629 630 631 632 633 634 635 636
        int height = s->avctx->coded_height >> 1;
        qx = (s->mb_x * 16) + (mx >> 2);
        qy = (s->mb_y *  8) + (my >> 3);

        if (qx < -17)
            mx -= 4 * (qx + 17);
        else if (qx > width)
            mx -= 4 * (qx - width);
        if (qy < -18)
            my -= 8 * (qy + 18);
        else if (qy > height + 1)
            my -= 8 * (qy - height - 1);
    }

637
    if ((v->fcm == ILACE_FRAME) && fieldmv)
638
        off = ((n > 1) ? s->linesize : 0) + (n & 1) * 8;
639
    else
640
        off = s->linesize * 4 * (n & 2) + (n & 1) * 8;
641
    if (v->field_mode && v->second_field)
642
        off += s->current_picture_ptr->f.linesize[0];
643

644
    src_x = s->mb_x * 16 + (n & 1) * 8 + (mx >> 2);
645
    if (!fieldmv)
646
        src_y = s->mb_y * 16 + (n & 2) * 4 + (my >> 2);
647 648
    else
        src_y = s->mb_y * 16 + ((n > 1) ? 1 : 0) + (my >> 2);
649

650 651 652 653 654
    if (v->profile != PROFILE_ADVANCED) {
        src_x = av_clip(src_x, -16, s->mb_width  * 16);
        src_y = av_clip(src_y, -16, s->mb_height * 16);
    } else {
        src_x = av_clip(src_x, -17, s->avctx->coded_width);
655
        if (v->fcm == ILACE_FRAME) {
656
            if (src_y & 1)
657
                src_y = av_clip(src_y, -17, s->avctx->coded_height + 1);
658
            else
659
                src_y = av_clip(src_y, -18, s->avctx->coded_height);
660
        } else {
661
            src_y = av_clip(src_y, -18, s->avctx->coded_height + 1);
662
        }
663 664 665
    }

    srcY += src_y * s->linesize + src_x;
666 667
    if (v->field_mode && v->ref_field_type[dir])
        srcY += s->current_picture_ptr->f.linesize[0];
668

669 670 671 672
    if (fieldmv && !(src_y & 1))
        v_edge_pos--;
    if (fieldmv && (src_y & 1) && src_y < 4)
        src_y--;
673
    if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
674
        || s->h_edge_pos < 13 || v_edge_pos < 23
675 676
        || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx & 3) - 8 - s->mspel * 2
        || (unsigned)(src_y - (s->mspel << fieldmv)) > v_edge_pos - (my & 3) - ((8 + s->mspel * 2) << fieldmv)) {
677 678
        srcY -= s->mspel * (1 + (s->linesize << fieldmv));
        /* check emulate edge stride and offset */
679 680 681 682
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize,
                                9 + s->mspel * 2, (9 + s->mspel * 2) << fieldmv,
                                src_x - s->mspel, src_y - (s->mspel << fieldmv),
                                s->h_edge_pos, v_edge_pos);
683 684
        srcY = s->edge_emu_buffer;
        /* if we deal with range reduction we need to scale source blocks */
685
        if (v->rangeredfrm) {
686 687 688 689
            int i, j;
            uint8_t *src;

            src = srcY;
690 691 692
            for (j = 0; j < 9 + s->mspel * 2; j++) {
                for (i = 0; i < 9 + s->mspel * 2; i++)
                    src[i] = ((src[i] - 128) >> 1) + 128;
693
                src += s->linesize << fieldmv;
694 695 696
            }
        }
        /* if we deal with intensity compensation we need to scale source blocks */
697
        if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
698 699 700 701
            int i, j;
            uint8_t *src;

            src = srcY;
702 703 704
            for (j = 0; j < 9 + s->mspel * 2; j++) {
                for (i = 0; i < 9 + s->mspel * 2; i++)
                    src[i] = v->luty[src[i]];
705
                src += s->linesize << fieldmv;
706 707
            }
        }
708
        srcY += s->mspel * (1 + (s->linesize << fieldmv));
709 710
    }

711
    if (s->mspel) {
712
        dxy = ((my & 3) << 2) | (mx & 3);
713
        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize << fieldmv, v->rnd);
714 715
    } else { // hpel mc - always used for luma
        dxy = (my & 2) | ((mx & 2) >> 1);
716
        if (!v->rnd)
717 718 719 720 721 722
            dsp->put_pixels_tab[1][dxy](s->dest[0] + off, srcY, s->linesize, 8);
        else
            dsp->put_no_rnd_pixels_tab[1][dxy](s->dest[0] + off, srcY, s->linesize, 8);
    }
}

723
static av_always_inline int get_chroma_mv(int *mvx, int *mvy, int *a, int flag, int *tx, int *ty)
724
{
725 726
    int idx, i;
    static const int count[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
727 728 729 730 731 732

    idx =  ((a[3] != flag) << 3)
         | ((a[2] != flag) << 2)
         | ((a[1] != flag) << 1)
         |  (a[0] != flag);
    if (!idx) {
733 734 735
        *tx = median4(mvx[0], mvx[1], mvx[2], mvx[3]);
        *ty = median4(mvy[0], mvy[1], mvy[2], mvy[3]);
        return 4;
736 737
    } else if (count[idx] == 1) {
        switch (idx) {
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        case 0x1:
            *tx = mid_pred(mvx[1], mvx[2], mvx[3]);
            *ty = mid_pred(mvy[1], mvy[2], mvy[3]);
            return 3;
        case 0x2:
            *tx = mid_pred(mvx[0], mvx[2], mvx[3]);
            *ty = mid_pred(mvy[0], mvy[2], mvy[3]);
            return 3;
        case 0x4:
            *tx = mid_pred(mvx[0], mvx[1], mvx[3]);
            *ty = mid_pred(mvy[0], mvy[1], mvy[3]);
            return 3;
        case 0x8:
            *tx = mid_pred(mvx[0], mvx[1], mvx[2]);
            *ty = mid_pred(mvy[0], mvy[1], mvy[2]);
            return 3;
        }
755
    } else if (count[idx] == 2) {
756 757 758 759 760 761 762 763 764 765 766 767 768 769
        int t1 = 0, t2 = 0;
        for (i = 0; i < 3; i++)
            if (!a[i]) {
                t1 = i;
                break;
            }
        for (i = t1 + 1; i < 4; i++)
            if (!a[i]) {
                t2 = i;
                break;
            }
        *tx = (mvx[t1] + mvx[t2]) / 2;
        *ty = (mvy[t1] + mvy[t2]) / 2;
        return 2;
770
    } else {
771
        return 0;
772
    }
773
    return -1;
774 775 776 777
}

/** Do motion compensation for 4-MV macroblock - both chroma blocks
 */
778
static void vc1_mc_4mv_chroma(VC1Context *v, int dir)
779 780
{
    MpegEncContext *s = &v->s;
781
    DSPContext *dsp   = &v->s.dsp;
782 783
    uint8_t *srcU, *srcV;
    int uvmx, uvmy, uvsrc_x, uvsrc_y;
784 785 786 787 788
    int k, tx = 0, ty = 0;
    int mvx[4], mvy[4], intra[4], mv_f[4];
    int valid_count;
    int chroma_ref_type = v->cur_field_type, off = 0;
    int v_edge_pos = s->v_edge_pos >> v->field_mode;
789

790 791 792 793
    if (!v->field_mode && !v->s.last_picture.f.data[0])
        return;
    if (s->flags & CODEC_FLAG_GRAY)
        return;
794

795
    for (k = 0; k < 4; k++) {
796 797 798 799 800
        mvx[k] = s->mv[dir][k][0];
        mvy[k] = s->mv[dir][k][1];
        intra[k] = v->mb_type[0][s->block_index[k]];
        if (v->field_mode)
            mv_f[k] = v->mv_f[dir][s->block_index[k] + v->blocks_off];
801 802 803
    }

    /* calculate chroma MV vector from four luma MVs */
804 805
    if (!v->field_mode || (v->field_mode && !v->numref)) {
        valid_count = get_chroma_mv(mvx, mvy, intra, 0, &tx, &ty);
806
        chroma_ref_type = v->reffield;
807
        if (!valid_count) {
808 809
            s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;
            s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;
810 811
            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
            return; //no need to do MC for intra blocks
812 813
        }
    } else {
814 815 816 817 818 819
        int dominant = 0;
        if (mv_f[0] + mv_f[1] + mv_f[2] + mv_f[3] > 2)
            dominant = 1;
        valid_count = get_chroma_mv(mvx, mvy, mv_f, dominant, &tx, &ty);
        if (dominant)
            chroma_ref_type = !v->cur_field_type;
820
    }
821 822
    if (v->field_mode && chroma_ref_type == 1 && v->cur_field_type == 1 && !v->s.last_picture.f.data[0])
        return;
823 824
    s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;
    s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;
825 826
    uvmx = (tx + ((tx & 3) == 3)) >> 1;
    uvmy = (ty + ((ty & 3) == 3)) >> 1;
827

828 829
    v->luma_mv[s->mb_x][0] = uvmx;
    v->luma_mv[s->mb_x][1] = uvmy;
830

831 832 833
    if (v->fastuvmc) {
        uvmx = uvmx + ((uvmx < 0) ? (uvmx & 1) : -(uvmx & 1));
        uvmy = uvmy + ((uvmy < 0) ? (uvmy & 1) : -(uvmy & 1));
834
    }
835 836 837
    // Field conversion bias
    if (v->cur_field_type != chroma_ref_type)
        uvmy += 2 - 4 * chroma_ref_type;
838 839 840 841

    uvsrc_x = s->mb_x * 8 + (uvmx >> 2);
    uvsrc_y = s->mb_y * 8 + (uvmy >> 2);

842 843 844 845 846 847
    if (v->profile != PROFILE_ADVANCED) {
        uvsrc_x = av_clip(uvsrc_x, -8, s->mb_width  * 8);
        uvsrc_y = av_clip(uvsrc_y, -8, s->mb_height * 8);
    } else {
        uvsrc_x = av_clip(uvsrc_x, -8, s->avctx->coded_width  >> 1);
        uvsrc_y = av_clip(uvsrc_y, -8, s->avctx->coded_height >> 1);
848 849
    }

850 851 852
    if (!dir) {
        if (v->field_mode) {
            if ((v->cur_field_type != chroma_ref_type) && v->cur_field_type) {
853 854
                srcU = s->current_picture.f.data[1];
                srcV = s->current_picture.f.data[2];
855
            } else {
856 857
                srcU = s->last_picture.f.data[1];
                srcV = s->last_picture.f.data[2];
858 859
            }
        } else {
860 861
            srcU = s->last_picture.f.data[1];
            srcV = s->last_picture.f.data[2];
862 863
        }
    } else {
864 865
        srcU = s->next_picture.f.data[1];
        srcV = s->next_picture.f.data[2];
866 867
    }

868 869 870
    if(!srcU)
        return;

871 872 873
    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

874 875 876 877 878
    if (v->field_mode) {
        if (chroma_ref_type) {
            srcU += s->current_picture_ptr->f.linesize[1];
            srcV += s->current_picture_ptr->f.linesize[2];
        }
879
        off = v->second_field ? s->current_picture_ptr->f.linesize[1] : 0;
880 881
    }

882
    if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
883
        || s->h_edge_pos < 18 || v_edge_pos < 18
884 885 886 887 888 889 890 891
        || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 9
        || (unsigned)uvsrc_y > (v_edge_pos    >> 1) - 9) {
        s->dsp.emulated_edge_mc(s->edge_emu_buffer     , srcU, s->uvlinesize,
                                8 + 1, 8 + 1, uvsrc_x, uvsrc_y,
                                s->h_edge_pos >> 1, v_edge_pos >> 1);
        s->dsp.emulated_edge_mc(s->edge_emu_buffer + 16, srcV, s->uvlinesize,
                                8 + 1, 8 + 1, uvsrc_x, uvsrc_y,
                                s->h_edge_pos >> 1, v_edge_pos >> 1);
892 893 894 895
        srcU = s->edge_emu_buffer;
        srcV = s->edge_emu_buffer + 16;

        /* if we deal with range reduction we need to scale source blocks */
896
        if (v->rangeredfrm) {
897 898 899
            int i, j;
            uint8_t *src, *src2;

900 901 902 903 904
            src  = srcU;
            src2 = srcV;
            for (j = 0; j < 9; j++) {
                for (i = 0; i < 9; i++) {
                    src[i]  = ((src[i]  - 128) >> 1) + 128;
905 906
                    src2[i] = ((src2[i] - 128) >> 1) + 128;
                }
907
                src  += s->uvlinesize;
908 909 910 911
                src2 += s->uvlinesize;
            }
        }
        /* if we deal with intensity compensation we need to scale source blocks */
912
        if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
913 914 915
            int i, j;
            uint8_t *src, *src2;

916 917 918 919 920
            src  = srcU;
            src2 = srcV;
            for (j = 0; j < 9; j++) {
                for (i = 0; i < 9; i++) {
                    src[i]  = v->lutuv[src[i]];
921 922
                    src2[i] = v->lutuv[src2[i]];
                }
923
                src  += s->uvlinesize;
924 925 926 927 928 929
                src2 += s->uvlinesize;
            }
        }
    }

    /* Chroma MC always uses qpel bilinear */
930 931 932
    uvmx = (uvmx & 3) << 1;
    uvmy = (uvmy & 3) << 1;
    if (!v->rnd) {
933 934
        dsp->put_h264_chroma_pixels_tab[0](s->dest[1] + off, srcU, s->uvlinesize, 8, uvmx, uvmy);
        dsp->put_h264_chroma_pixels_tab[0](s->dest[2] + off, srcV, s->uvlinesize, 8, uvmx, uvmy);
935
    } else {
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1] + off, srcU, s->uvlinesize, 8, uvmx, uvmy);
        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2] + off, srcV, s->uvlinesize, 8, uvmx, uvmy);
    }
}

/** Do motion compensation for 4-MV field chroma macroblock (both U and V)
 */
static void vc1_mc_4mv_chroma4(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    DSPContext *dsp = &v->s.dsp;
    uint8_t *srcU, *srcV;
    int uvsrc_x, uvsrc_y;
    int uvmx_field[4], uvmy_field[4];
    int i, off, tx, ty;
    int fieldmv = v->blk_mv_type[s->block_index[0]];
952
    static const int s_rndtblfield[16] = { 0, 0, 1, 2, 4, 4, 5, 6, 2, 2, 3, 8, 6, 6, 7, 12 };
953 954 955
    int v_dist = fieldmv ? 1 : 4; // vertical offset for lower sub-blocks
    int v_edge_pos = s->v_edge_pos >> 1;

956 957 958 959
    if (!v->s.last_picture.f.data[0])
        return;
    if (s->flags & CODEC_FLAG_GRAY)
        return;
960 961 962 963 964 965 966 967 968 969 970 971 972

    for (i = 0; i < 4; i++) {
        tx = s->mv[0][i][0];
        uvmx_field[i] = (tx + ((tx & 3) == 3)) >> 1;
        ty = s->mv[0][i][1];
        if (fieldmv)
            uvmy_field[i] = (ty >> 4) * 8 + s_rndtblfield[ty & 0xF];
        else
            uvmy_field[i] = (ty + ((ty & 3) == 3)) >> 1;
    }

    for (i = 0; i < 4; i++) {
        off = (i & 1) * 4 + ((i & 2) ? v_dist * s->uvlinesize : 0);
973
        uvsrc_x = s->mb_x * 8 +  (i & 1) * 4           + (uvmx_field[i] >> 2);
974 975
        uvsrc_y = s->mb_y * 8 + ((i & 2) ? v_dist : 0) + (uvmy_field[i] >> 2);
        // FIXME: implement proper pull-back (see vc1cropmv.c, vc1CROPMV_ChromaPullBack())
976 977
        uvsrc_x = av_clip(uvsrc_x, -8, s->avctx->coded_width  >> 1);
        uvsrc_y = av_clip(uvsrc_y, -8, s->avctx->coded_height >> 1);
978 979 980 981 982 983
        srcU = s->last_picture.f.data[1] + uvsrc_y * s->uvlinesize + uvsrc_x;
        srcV = s->last_picture.f.data[2] + uvsrc_y * s->uvlinesize + uvsrc_x;
        uvmx_field[i] = (uvmx_field[i] & 3) << 1;
        uvmy_field[i] = (uvmy_field[i] & 3) << 1;

        if (fieldmv && !(uvsrc_y & 1))
984 985
            v_edge_pos = (s->v_edge_pos >> 1) - 1;

986 987
        if (fieldmv && (uvsrc_y & 1) && uvsrc_y < 2)
            uvsrc_y--;
988
        if ((v->mv_mode == MV_PMODE_INTENSITY_COMP)
989
            || s->h_edge_pos < 10 || v_edge_pos < (5 << fieldmv)
990
            || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 5
991 992 993 994 995 996 997
            || (unsigned)uvsrc_y > v_edge_pos - (5 << fieldmv)) {
            s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcU, s->uvlinesize,
                                    5, (5 << fieldmv), uvsrc_x, uvsrc_y,
                                    s->h_edge_pos >> 1, v_edge_pos);
            s->dsp.emulated_edge_mc(s->edge_emu_buffer + 16, srcV, s->uvlinesize,
                                    5, (5 << fieldmv), uvsrc_x, uvsrc_y,
                                    s->h_edge_pos >> 1, v_edge_pos);
998 999 1000 1001
            srcU = s->edge_emu_buffer;
            srcV = s->edge_emu_buffer + 16;

            /* if we deal with intensity compensation we need to scale source blocks */
1002
            if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
1003 1004 1005
                int i, j;
                uint8_t *src, *src2;

1006 1007 1008 1009 1010
                src  = srcU;
                src2 = srcV;
                for (j = 0; j < 5; j++) {
                    for (i = 0; i < 5; i++) {
                        src[i]  = v->lutuv[src[i]];
1011 1012
                        src2[i] = v->lutuv[src2[i]];
                    }
1013
                    src  += s->uvlinesize << 1;
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
                    src2 += s->uvlinesize << 1;
                }
            }
        }
        if (!v->rnd) {
            dsp->put_h264_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);
            dsp->put_h264_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);
        } else {
            v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[1](s->dest[1] + off, srcU, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);
            v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[1](s->dest[2] + off, srcV, s->uvlinesize << fieldmv, 4, uvmx_field[i], uvmy_field[i]);
        }
1025 1026 1027 1028 1029
    }
}

/***********************************************************************/
/**
1030
 * @name VC-1 Block-level functions
1031 1032 1033 1034 1035 1036 1037 1038 1039
 * @see 7.1.4, p91 and 8.1.1.7, p(1)04
 * @{
 */

/**
 * @def GET_MQUANT
 * @brief Get macroblock-level quantizer scale
 */
#define GET_MQUANT()                                           \
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    if (v->dquantfrm) {                                        \
        int edges = 0;                                         \
        if (v->dqprofile == DQPROFILE_ALL_MBS) {               \
            if (v->dqbilevel) {                                \
                mquant = (get_bits1(gb)) ? v->altpq : v->pq;   \
            } else {                                           \
                mqdiff = get_bits(gb, 3);                      \
                if (mqdiff != 7)                               \
                    mquant = v->pq + mqdiff;                   \
                else                                           \
                    mquant = get_bits(gb, 5);                  \
            }                                                  \
        }                                                      \
        if (v->dqprofile == DQPROFILE_SINGLE_EDGE)             \
            edges = 1 << v->dqsbedge;                          \
        else if (v->dqprofile == DQPROFILE_DOUBLE_EDGES)       \
            edges = (3 << v->dqsbedge) % 15;                   \
        else if (v->dqprofile == DQPROFILE_FOUR_EDGES)         \
            edges = 15;                                        \
        if ((edges&1) && !s->mb_x)                             \
            mquant = v->altpq;                                 \
        if ((edges&2) && s->first_slice_line)                  \
            mquant = v->altpq;                                 \
        if ((edges&4) && s->mb_x == (s->mb_width - 1))         \
            mquant = v->altpq;                                 \
        if ((edges&8) && s->mb_y == (s->mb_height - 1))        \
            mquant = v->altpq;                                 \
1067
        if (!mquant || mquant > 31) {                          \
1068 1069 1070 1071
            av_log(v->s.avctx, AV_LOG_ERROR,                   \
                   "Overriding invalid mquant %d\n", mquant);  \
            mquant = 1;                                        \
        }                                                      \
1072
    }
1073 1074 1075 1076 1077 1078 1079 1080

/**
 * @def GET_MVDATA(_dmv_x, _dmv_y)
 * @brief Get MV differentials
 * @see MVDATA decoding from 8.3.5.2, p(1)20
 * @param _dmv_x Horizontal differential for decoded MV
 * @param _dmv_y Vertical differential for decoded MV
 */
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
#define GET_MVDATA(_dmv_x, _dmv_y)                                      \
    index = 1 + get_vlc2(gb, ff_vc1_mv_diff_vlc[s->mv_table_index].table, \
                         VC1_MV_DIFF_VLC_BITS, 2);                      \
    if (index > 36) {                                                   \
        mb_has_coeffs = 1;                                              \
        index -= 37;                                                    \
    } else                                                              \
        mb_has_coeffs = 0;                                              \
    s->mb_intra = 0;                                                    \
    if (!index) {                                                       \
        _dmv_x = _dmv_y = 0;                                            \
    } else if (index == 35) {                                           \
        _dmv_x = get_bits(gb, v->k_x - 1 + s->quarter_sample);          \
        _dmv_y = get_bits(gb, v->k_y - 1 + s->quarter_sample);          \
    } else if (index == 36) {                                           \
        _dmv_x = 0;                                                     \
        _dmv_y = 0;                                                     \
        s->mb_intra = 1;                                                \
    } else {                                                            \
        index1 = index % 6;                                             \
        if (!s->quarter_sample && index1 == 5) val = 1;                 \
        else                                   val = 0;                 \
        if (size_table[index1] - val > 0)                               \
            val = get_bits(gb, size_table[index1] - val);               \
        else                                   val = 0;                 \
        sign = 0 - (val&1);                                             \
        _dmv_x = (sign ^ ((val>>1) + offset_table[index1])) - sign;     \
                                                                        \
        index1 = index / 6;                                             \
        if (!s->quarter_sample && index1 == 5) val = 1;                 \
        else                                   val = 0;                 \
        if (size_table[index1] - val > 0)                               \
            val = get_bits(gb, size_table[index1] - val);               \
        else                                   val = 0;                 \
        sign = 0 - (val & 1);                                           \
        _dmv_y = (sign ^ ((val >> 1) + offset_table[index1])) - sign;   \
    }

static av_always_inline void get_mvdata_interlaced(VC1Context *v, int *dmv_x,
                                                   int *dmv_y, int *pred_flag)
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
{
    int index, index1;
    int extend_x = 0, extend_y = 0;
    GetBitContext *gb = &v->s.gb;
    int bits, esc;
    int val, sign;
    const int* offs_tab;

    if (v->numref) {
        bits = VC1_2REF_MVDATA_VLC_BITS;
1131
        esc  = 125;
1132 1133
    } else {
        bits = VC1_1REF_MVDATA_VLC_BITS;
1134
        esc  = 71;
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    }
    switch (v->dmvrange) {
    case 1:
        extend_x = 1;
        break;
    case 2:
        extend_y = 1;
        break;
    case 3:
        extend_x = extend_y = 1;
        break;
    }
    index = get_vlc2(gb, v->imv_vlc->table, bits, 3);
    if (index == esc) {
        *dmv_x = get_bits(gb, v->k_x);
        *dmv_y = get_bits(gb, v->k_y);
        if (v->numref) {
            *pred_flag = *dmv_y & 1;
1153
            *dmv_y     = (*dmv_y + *pred_flag) >> 1;
1154 1155 1156
        }
    }
    else {
1157
        av_assert0(index < esc);
1158 1159 1160 1161 1162 1163
        if (extend_x)
            offs_tab = offset_table2;
        else
            offs_tab = offset_table1;
        index1 = (index + 1) % 9;
        if (index1 != 0) {
1164 1165
            val    = get_bits(gb, index1 + extend_x);
            sign   = 0 -(val & 1);
1166 1167 1168 1169 1170 1171 1172 1173 1174
            *dmv_x = (sign ^ ((val >> 1) + offs_tab[index1])) - sign;
        } else
            *dmv_x = 0;
        if (extend_y)
            offs_tab = offset_table2;
        else
            offs_tab = offset_table1;
        index1 = (index + 1) / 9;
        if (index1 > v->numref) {
1175 1176
            val    = get_bits(gb, (index1 + (extend_y << v->numref)) >> v->numref);
            sign   = 0 - (val & 1);
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
            *dmv_y = (sign ^ ((val >> 1) + offs_tab[index1 >> v->numref])) - sign;
        } else
            *dmv_y = 0;
        if (v->numref)
            *pred_flag = index1 & 1;
    }
}

static av_always_inline int scaleforsame_x(VC1Context *v, int n /* MV */, int dir)
{
    int scaledvalue, refdist;
    int scalesame1, scalesame2;
    int scalezone1_x, zone1offset_x;
1190
    int table_index = dir ^ v->second_field;
1191 1192 1193 1194 1195 1196 1197

    if (v->s.pict_type != AV_PICTURE_TYPE_B)
        refdist = v->refdist;
    else
        refdist = dir ? v->brfd : v->frfd;
    if (refdist > 3)
        refdist = 3;
1198 1199 1200 1201
    scalesame1    = ff_vc1_field_mvpred_scales[table_index][1][refdist];
    scalesame2    = ff_vc1_field_mvpred_scales[table_index][2][refdist];
    scalezone1_x  = ff_vc1_field_mvpred_scales[table_index][3][refdist];
    zone1offset_x = ff_vc1_field_mvpred_scales[table_index][5][refdist];
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

    if (FFABS(n) > 255)
        scaledvalue = n;
    else {
        if (FFABS(n) < scalezone1_x)
            scaledvalue = (n * scalesame1) >> 8;
        else {
            if (n < 0)
                scaledvalue = ((n * scalesame2) >> 8) - zone1offset_x;
            else
                scaledvalue = ((n * scalesame2) >> 8) + zone1offset_x;
        }
    }
    return av_clip(scaledvalue, -v->range_x, v->range_x - 1);
}

static av_always_inline int scaleforsame_y(VC1Context *v, int i, int n /* MV */, int dir)
{
    int scaledvalue, refdist;
    int scalesame1, scalesame2;
    int scalezone1_y, zone1offset_y;
1223
    int table_index = dir ^ v->second_field;
1224 1225 1226 1227 1228 1229 1230

    if (v->s.pict_type != AV_PICTURE_TYPE_B)
        refdist = v->refdist;
    else
        refdist = dir ? v->brfd : v->frfd;
    if (refdist > 3)
        refdist = 3;
1231 1232 1233 1234
    scalesame1    = ff_vc1_field_mvpred_scales[table_index][1][refdist];
    scalesame2    = ff_vc1_field_mvpred_scales[table_index][2][refdist];
    scalezone1_y  = ff_vc1_field_mvpred_scales[table_index][4][refdist];
    zone1offset_y = ff_vc1_field_mvpred_scales[table_index][6][refdist];
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

    if (FFABS(n) > 63)
        scaledvalue = n;
    else {
        if (FFABS(n) < scalezone1_y)
            scaledvalue = (n * scalesame1) >> 8;
        else {
            if (n < 0)
                scaledvalue = ((n * scalesame2) >> 8) - zone1offset_y;
            else
                scaledvalue = ((n * scalesame2) >> 8) + zone1offset_y;
        }
    }

    if (v->cur_field_type && !v->ref_field_type[dir])
        return av_clip(scaledvalue, -v->range_y / 2 + 1, v->range_y / 2);
    else
        return av_clip(scaledvalue, -v->range_y / 2, v->range_y / 2 - 1);
}

static av_always_inline int scaleforopp_x(VC1Context *v, int n /* MV */)
{
    int scalezone1_x, zone1offset_x;
    int scaleopp1, scaleopp2, brfd;
    int scaledvalue;

    brfd = FFMIN(v->brfd, 3);
1262 1263 1264 1265
    scalezone1_x  = ff_vc1_b_field_mvpred_scales[3][brfd];
    zone1offset_x = ff_vc1_b_field_mvpred_scales[5][brfd];
    scaleopp1     = ff_vc1_b_field_mvpred_scales[1][brfd];
    scaleopp2     = ff_vc1_b_field_mvpred_scales[2][brfd];
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

    if (FFABS(n) > 255)
        scaledvalue = n;
    else {
        if (FFABS(n) < scalezone1_x)
            scaledvalue = (n * scaleopp1) >> 8;
        else {
            if (n < 0)
                scaledvalue = ((n * scaleopp2) >> 8) - zone1offset_x;
            else
                scaledvalue = ((n * scaleopp2) >> 8) + zone1offset_x;
        }
    }
    return av_clip(scaledvalue, -v->range_x, v->range_x - 1);
}

static av_always_inline int scaleforopp_y(VC1Context *v, int n /* MV */, int dir)
{
    int scalezone1_y, zone1offset_y;
    int scaleopp1, scaleopp2, brfd;
    int scaledvalue;

    brfd = FFMIN(v->brfd, 3);
1289 1290 1291 1292
    scalezone1_y  = ff_vc1_b_field_mvpred_scales[4][brfd];
    zone1offset_y = ff_vc1_b_field_mvpred_scales[6][brfd];
    scaleopp1     = ff_vc1_b_field_mvpred_scales[1][brfd];
    scaleopp2     = ff_vc1_b_field_mvpred_scales[2][brfd];
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

    if (FFABS(n) > 63)
        scaledvalue = n;
    else {
        if (FFABS(n) < scalezone1_y)
            scaledvalue = (n * scaleopp1) >> 8;
        else {
            if (n < 0)
                scaledvalue = ((n * scaleopp2) >> 8) - zone1offset_y;
            else
                scaledvalue = ((n * scaleopp2) >> 8) + zone1offset_y;
        }
    }
    if (v->cur_field_type && !v->ref_field_type[dir]) {
        return av_clip(scaledvalue, -v->range_y / 2 + 1, v->range_y / 2);
    } else {
        return av_clip(scaledvalue, -v->range_y / 2, v->range_y / 2 - 1);
    }
}

1313 1314
static av_always_inline int scaleforsame(VC1Context *v, int i, int n /* MV */,
                                         int dim, int dir)
1315 1316
{
    int brfd, scalesame;
1317
    int hpel = 1 - v->s.quarter_sample;
1318

1319
    n >>= hpel;
1320 1321
    if (v->s.pict_type != AV_PICTURE_TYPE_B || v->second_field || !dir) {
        if (dim)
1322
            n = scaleforsame_y(v, i, n, dir) << hpel;
1323
        else
1324 1325
            n = scaleforsame_x(v, n, dir) << hpel;
        return n;
1326
    }
1327
    brfd      = FFMIN(v->brfd, 3);
1328
    scalesame = ff_vc1_b_field_mvpred_scales[0][brfd];
1329

1330 1331
    n = (n * scalesame >> 8) << hpel;
    return n;
1332 1333
}

1334 1335
static av_always_inline int scaleforopp(VC1Context *v, int n /* MV */,
                                        int dim, int dir)
1336 1337
{
    int refdist, scaleopp;
1338
    int hpel = 1 - v->s.quarter_sample;
1339

1340
    n >>= hpel;
1341 1342
    if (v->s.pict_type == AV_PICTURE_TYPE_B && !v->second_field && dir == 1) {
        if (dim)
1343
            n = scaleforopp_y(v, n, dir) << hpel;
1344
        else
1345 1346
            n = scaleforopp_x(v, n) << hpel;
        return n;
1347 1348 1349 1350 1351
    }
    if (v->s.pict_type != AV_PICTURE_TYPE_B)
        refdist = FFMIN(v->refdist, 3);
    else
        refdist = dir ? v->brfd : v->frfd;
1352
    scaleopp = ff_vc1_field_mvpred_scales[dir ^ v->second_field][0][refdist];
1353

1354 1355
    n = (n * scaleopp >> 8) << hpel;
    return n;
1356 1357
}

1358 1359
/** Predict and set motion vector
 */
1360 1361 1362
static inline void vc1_pred_mv(VC1Context *v, int n, int dmv_x, int dmv_y,
                               int mv1, int r_x, int r_y, uint8_t* is_intra,
                               int pred_flag, int dir)
1363
{
1364
    MpegEncContext *s = &v->s;
1365 1366 1367 1368
    int xy, wrap, off = 0;
    int16_t *A, *B, *C;
    int px, py;
    int sum;
1369
    int mixedmv_pic, num_samefield = 0, num_oppfield = 0;
1370
    int opposite, a_f, b_f, c_f;
1371 1372 1373
    int16_t field_predA[2];
    int16_t field_predB[2];
    int16_t field_predC[2];
1374 1375 1376 1377
    int a_valid, b_valid, c_valid;
    int hybridmv_thresh, y_bias = 0;

    if (v->mv_mode == MV_PMODE_MIXED_MV ||
1378 1379 1380 1381
        ((v->mv_mode == MV_PMODE_INTENSITY_COMP) && (v->mv_mode2 == MV_PMODE_MIXED_MV)))
        mixedmv_pic = 1;
    else
        mixedmv_pic = 0;
1382 1383 1384 1385 1386
    /* scale MV difference to be quad-pel */
    dmv_x <<= 1 - s->quarter_sample;
    dmv_y <<= 1 - s->quarter_sample;

    wrap = s->b8_stride;
1387
    xy   = s->block_index[n];
1388

1389
    if (s->mb_intra) {
1390 1391 1392 1393
        s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy + v->blocks_off][0] = 0;
        s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy + v->blocks_off][1] = 0;
        s->current_picture.f.motion_val[1][xy + v->blocks_off][0] = 0;
        s->current_picture.f.motion_val[1][xy + v->blocks_off][1] = 0;
1394 1395 1396 1397 1398
        if (mv1) { /* duplicate motion data for 1-MV block */
            s->current_picture.f.motion_val[0][xy + 1 + v->blocks_off][0]        = 0;
            s->current_picture.f.motion_val[0][xy + 1 + v->blocks_off][1]        = 0;
            s->current_picture.f.motion_val[0][xy + wrap + v->blocks_off][0]     = 0;
            s->current_picture.f.motion_val[0][xy + wrap + v->blocks_off][1]     = 0;
1399 1400
            s->current_picture.f.motion_val[0][xy + wrap + 1 + v->blocks_off][0] = 0;
            s->current_picture.f.motion_val[0][xy + wrap + 1 + v->blocks_off][1] = 0;
1401
            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
1402 1403 1404 1405
            s->current_picture.f.motion_val[1][xy + 1 + v->blocks_off][0]        = 0;
            s->current_picture.f.motion_val[1][xy + 1 + v->blocks_off][1]        = 0;
            s->current_picture.f.motion_val[1][xy + wrap][0]                     = 0;
            s->current_picture.f.motion_val[1][xy + wrap + v->blocks_off][1]     = 0;
1406 1407
            s->current_picture.f.motion_val[1][xy + wrap + 1 + v->blocks_off][0] = 0;
            s->current_picture.f.motion_val[1][xy + wrap + 1 + v->blocks_off][1] = 0;
1408 1409 1410 1411
        }
        return;
    }

1412
    C = s->current_picture.f.motion_val[dir][xy -    1 + v->blocks_off];
1413
    A = s->current_picture.f.motion_val[dir][xy - wrap + v->blocks_off];
1414
    if (mv1) {
1415 1416 1417 1418 1419
        if (v->field_mode && mixedmv_pic)
            off = (s->mb_x == (s->mb_width - 1)) ? -2 : 2;
        else
            off = (s->mb_x == (s->mb_width - 1)) ? -1 : 2;
    } else {
1420
        //in 4-MV mode different blocks have different B predictor position
1421
        switch (n) {
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
        case 0:
            off = (s->mb_x > 0) ? -1 : 1;
            break;
        case 1:
            off = (s->mb_x == (s->mb_width - 1)) ? -1 : 1;
            break;
        case 2:
            off = 1;
            break;
        case 3:
            off = -1;
        }
    }
1435 1436
    B = s->current_picture.f.motion_val[dir][xy - wrap + off + v->blocks_off];

1437
    a_valid = !s->first_slice_line || (n == 2 || n == 3);
1438
    b_valid = a_valid && (s->mb_width > 1);
1439
    c_valid = s->mb_x || (n == 1 || n == 3);
1440 1441 1442 1443 1444 1445 1446
    if (v->field_mode) {
        a_valid = a_valid && !is_intra[xy - wrap];
        b_valid = b_valid && !is_intra[xy - wrap + off];
        c_valid = c_valid && !is_intra[xy - 1];
    }

    if (a_valid) {
1447 1448 1449 1450 1451
        a_f = v->mv_f[dir][xy - wrap + v->blocks_off];
        num_oppfield  += a_f;
        num_samefield += 1 - a_f;
        field_predA[0] = A[0];
        field_predA[1] = A[1];
1452
    } else {
1453 1454
        field_predA[0] = field_predA[1] = 0;
        a_f = 0;
1455 1456
    }
    if (b_valid) {
1457 1458 1459 1460 1461
        b_f = v->mv_f[dir][xy - wrap + off + v->blocks_off];
        num_oppfield  += b_f;
        num_samefield += 1 - b_f;
        field_predB[0] = B[0];
        field_predB[1] = B[1];
1462
    } else {
1463 1464
        field_predB[0] = field_predB[1] = 0;
        b_f = 0;
1465
    }
1466 1467 1468 1469 1470 1471
    if (c_valid) {
        c_f = v->mv_f[dir][xy - 1 + v->blocks_off];
        num_oppfield  += c_f;
        num_samefield += 1 - c_f;
        field_predC[0] = C[0];
        field_predC[1] = C[1];
1472
    } else {
1473 1474
        field_predC[0] = field_predC[1] = 0;
        c_f = 0;
1475 1476 1477
    }

    if (v->field_mode) {
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
        if (!v->numref)
            // REFFIELD determines if the last field or the second-last field is
            // to be used as reference
            opposite = 1 - v->reffield;
        else {
            if (num_samefield <= num_oppfield)
                opposite = 1 - pred_flag;
            else
                opposite = pred_flag;
        }
1488
    } else
1489 1490
        opposite = 0;
    if (opposite) {
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
        if (a_valid && !a_f) {
            field_predA[0] = scaleforopp(v, field_predA[0], 0, dir);
            field_predA[1] = scaleforopp(v, field_predA[1], 1, dir);
        }
        if (b_valid && !b_f) {
            field_predB[0] = scaleforopp(v, field_predB[0], 0, dir);
            field_predB[1] = scaleforopp(v, field_predB[1], 1, dir);
        }
        if (c_valid && !c_f) {
            field_predC[0] = scaleforopp(v, field_predC[0], 0, dir);
            field_predC[1] = scaleforopp(v, field_predC[1], 1, dir);
        }
        v->mv_f[dir][xy + v->blocks_off] = 1;
1504 1505
        v->ref_field_type[dir] = !v->cur_field_type;
    } else {
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
        if (a_valid && a_f) {
            field_predA[0] = scaleforsame(v, n, field_predA[0], 0, dir);
            field_predA[1] = scaleforsame(v, n, field_predA[1], 1, dir);
        }
        if (b_valid && b_f) {
            field_predB[0] = scaleforsame(v, n, field_predB[0], 0, dir);
            field_predB[1] = scaleforsame(v, n, field_predB[1], 1, dir);
        }
        if (c_valid && c_f) {
            field_predC[0] = scaleforsame(v, n, field_predC[0], 0, dir);
            field_predC[1] = scaleforsame(v, n, field_predC[1], 1, dir);
        }
        v->mv_f[dir][xy + v->blocks_off] = 0;
1519
        v->ref_field_type[dir] = v->cur_field_type;
1520
    }
1521

1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
    if (a_valid) {
        px = field_predA[0];
        py = field_predA[1];
    } else if (c_valid) {
        px = field_predC[0];
        py = field_predC[1];
    } else if (b_valid) {
        px = field_predB[0];
        py = field_predB[1];
    } else {
        px = 0;
        py = 0;
    }

    if (num_samefield + num_oppfield > 1) {
        px = mid_pred(field_predA[0], field_predB[0], field_predC[0]);
        py = mid_pred(field_predA[1], field_predB[1], field_predC[1]);
    }

1541
    /* Pullback MV as specified in 8.3.5.3.4 */
1542
    if (!v->field_mode) {
1543
        int qx, qy, X, Y;
1544 1545 1546 1547 1548 1549 1550
        qx = (s->mb_x << 6) + ((n == 1 || n == 3) ? 32 : 0);
        qy = (s->mb_y << 6) + ((n == 2 || n == 3) ? 32 : 0);
        X  = (s->mb_width  << 6) - 4;
        Y  = (s->mb_height << 6) - 4;
        if (mv1) {
            if (qx + px < -60) px = -60 - qx;
            if (qy + py < -60) py = -60 - qy;
1551
        } else {
1552 1553
            if (qx + px < -28) px = -28 - qx;
            if (qy + py < -28) py = -28 - qy;
1554
        }
1555 1556
        if (qx + px > X) px = X - qx;
        if (qy + py > Y) py = Y - qy;
1557
    }
1558 1559 1560

    if (!v->field_mode || s->pict_type != AV_PICTURE_TYPE_B) {
        /* Calculate hybrid prediction as specified in 8.3.5.3.5 (also 10.3.5.4.3.5) */
1561
        hybridmv_thresh = 32;
1562 1563 1564 1565
        if (a_valid && c_valid) {
            if (is_intra[xy - wrap])
                sum = FFABS(px) + FFABS(py);
            else
1566
                sum = FFABS(px - field_predA[0]) + FFABS(py - field_predA[1]);
1567 1568
            if (sum > hybridmv_thresh) {
                if (get_bits1(&s->gb)) {     // read HYBRIDPRED bit
1569 1570
                    px = field_predA[0];
                    py = field_predA[1];
1571
                } else {
1572 1573
                    px = field_predC[0];
                    py = field_predC[1];
1574
                }
1575
            } else {
1576 1577 1578
                if (is_intra[xy - 1])
                    sum = FFABS(px) + FFABS(py);
                else
1579
                    sum = FFABS(px - field_predC[0]) + FFABS(py - field_predC[1]);
1580
                if (sum > hybridmv_thresh) {
1581
                    if (get_bits1(&s->gb)) {
1582 1583
                        px = field_predA[0];
                        py = field_predA[1];
1584
                    } else {
1585 1586
                        px = field_predC[0];
                        py = field_predC[1];
1587 1588
                    }
                }
1589
            }
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
        }
    }

    if (v->field_mode && v->numref)
        r_y >>= 1;
    if (v->field_mode && v->cur_field_type && v->ref_field_type[dir] == 0)
        y_bias = 1;
    /* store MV using signed modulus of MV range defined in 4.11 */
    s->mv[dir][n][0] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][0] = ((px + dmv_x + r_x) & ((r_x << 1) - 1)) - r_x;
    s->mv[dir][n][1] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][1] = ((py + dmv_y + r_y - y_bias) & ((r_y << 1) - 1)) - r_y + y_bias;
1600 1601 1602 1603 1604
    if (mv1) { /* duplicate motion data for 1-MV block */
        s->current_picture.f.motion_val[dir][xy +    1 +     v->blocks_off][0] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][0];
        s->current_picture.f.motion_val[dir][xy +    1 +     v->blocks_off][1] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][1];
        s->current_picture.f.motion_val[dir][xy + wrap +     v->blocks_off][0] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][0];
        s->current_picture.f.motion_val[dir][xy + wrap +     v->blocks_off][1] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][1];
1605 1606
        s->current_picture.f.motion_val[dir][xy + wrap + 1 + v->blocks_off][0] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][0];
        s->current_picture.f.motion_val[dir][xy + wrap + 1 + v->blocks_off][1] = s->current_picture.f.motion_val[dir][xy + v->blocks_off][1];
1607
        v->mv_f[dir][xy +    1 + v->blocks_off] = v->mv_f[dir][xy +            v->blocks_off];
1608 1609 1610 1611 1612 1613
        v->mv_f[dir][xy + wrap + v->blocks_off] = v->mv_f[dir][xy + wrap + 1 + v->blocks_off] = v->mv_f[dir][xy + v->blocks_off];
    }
}

/** Predict and set motion vector for interlaced frame picture MBs
 */
1614 1615
static inline void vc1_pred_mv_intfr(VC1Context *v, int n, int dmv_x, int dmv_y,
                                     int mvn, int r_x, int r_y, uint8_t* is_intra)
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
{
    MpegEncContext *s = &v->s;
    int xy, wrap, off = 0;
    int A[2], B[2], C[2];
    int px, py;
    int a_valid = 0, b_valid = 0, c_valid = 0;
    int field_a, field_b, field_c; // 0: same, 1: opposit
    int total_valid, num_samefield, num_oppfield;
    int pos_c, pos_b, n_adj;

    wrap = s->b8_stride;
    xy = s->block_index[n];

1629
    if (s->mb_intra) {
1630 1631 1632 1633
        s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy][0] = 0;
        s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy][1] = 0;
        s->current_picture.f.motion_val[1][xy][0] = 0;
        s->current_picture.f.motion_val[1][xy][1] = 0;
1634 1635 1636 1637 1638
        if (mvn == 1) { /* duplicate motion data for 1-MV block */
            s->current_picture.f.motion_val[0][xy + 1][0]        = 0;
            s->current_picture.f.motion_val[0][xy + 1][1]        = 0;
            s->current_picture.f.motion_val[0][xy + wrap][0]     = 0;
            s->current_picture.f.motion_val[0][xy + wrap][1]     = 0;
1639 1640 1641
            s->current_picture.f.motion_val[0][xy + wrap + 1][0] = 0;
            s->current_picture.f.motion_val[0][xy + wrap + 1][1] = 0;
            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;
1642 1643 1644 1645
            s->current_picture.f.motion_val[1][xy + 1][0]        = 0;
            s->current_picture.f.motion_val[1][xy + 1][1]        = 0;
            s->current_picture.f.motion_val[1][xy + wrap][0]     = 0;
            s->current_picture.f.motion_val[1][xy + wrap][1]     = 0;
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
            s->current_picture.f.motion_val[1][xy + wrap + 1][0] = 0;
            s->current_picture.f.motion_val[1][xy + wrap + 1][1] = 0;
        }
        return;
    }

    off = ((n == 0) || (n == 1)) ? 1 : -1;
    /* predict A */
    if (s->mb_x || (n == 1) || (n == 3)) {
        if ((v->blk_mv_type[xy]) // current block (MB) has a field MV
1656
            || (!v->blk_mv_type[xy] && !v->blk_mv_type[xy - 1])) { // or both have frame MV
1657 1658 1659 1660 1661
            A[0] = s->current_picture.f.motion_val[0][xy - 1][0];
            A[1] = s->current_picture.f.motion_val[0][xy - 1][1];
            a_valid = 1;
        } else { // current block has frame mv and cand. has field MV (so average)
            A[0] = (s->current_picture.f.motion_val[0][xy - 1][0]
1662
                    + s->current_picture.f.motion_val[0][xy - 1 + off * wrap][0] + 1) >> 1;
1663
            A[1] = (s->current_picture.f.motion_val[0][xy - 1][1]
1664
                    + s->current_picture.f.motion_val[0][xy - 1 + off * wrap][1] + 1) >> 1;
1665 1666 1667 1668 1669 1670
            a_valid = 1;
        }
        if (!(n & 1) && v->is_intra[s->mb_x - 1]) {
            a_valid = 0;
            A[0] = A[1] = 0;
        }
1671 1672
    } else
        A[0] = A[1] = 0;
1673 1674 1675 1676 1677 1678
    /* Predict B and C */
    B[0] = B[1] = C[0] = C[1] = 0;
    if (n == 0 || n == 1 || v->blk_mv_type[xy]) {
        if (!s->first_slice_line) {
            if (!v->is_intra[s->mb_x - s->mb_stride]) {
                b_valid = 1;
1679 1680
                n_adj   = n | 2;
                pos_b   = s->block_index[n_adj] - 2 * wrap;
1681 1682 1683 1684 1685 1686
                if (v->blk_mv_type[pos_b] && v->blk_mv_type[xy]) {
                    n_adj = (n & 2) | (n & 1);
                }
                B[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap][0];
                B[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap][1];
                if (v->blk_mv_type[pos_b] && !v->blk_mv_type[xy]) {
1687 1688
                    B[0] = (B[0] + s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap][0] + 1) >> 1;
                    B[1] = (B[1] + s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap][1] + 1) >> 1;
1689 1690 1691 1692 1693
                }
            }
            if (s->mb_width > 1) {
                if (!v->is_intra[s->mb_x - s->mb_stride + 1]) {
                    c_valid = 1;
1694 1695
                    n_adj   = 2;
                    pos_c   = s->block_index[2] - 2 * wrap + 2;
1696 1697 1698
                    if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {
                        n_adj = n & 2;
                    }
1699 1700
                    C[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap + 2][0];
                    C[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap + 2][1];
1701 1702 1703 1704 1705 1706 1707
                    if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {
                        C[0] = (1 + C[0] + (s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap + 2][0])) >> 1;
                        C[1] = (1 + C[1] + (s->current_picture.f.motion_val[0][s->block_index[n_adj ^ 2] - 2 * wrap + 2][1])) >> 1;
                    }
                    if (s->mb_x == s->mb_width - 1) {
                        if (!v->is_intra[s->mb_x - s->mb_stride - 1]) {
                            c_valid = 1;
1708 1709
                            n_adj   = 3;
                            pos_c   = s->block_index[3] - 2 * wrap - 2;
1710 1711 1712
                            if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {
                                n_adj = n | 1;
                            }
1713 1714
                            C[0] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap - 2][0];
                            C[1] = s->current_picture.f.motion_val[0][s->block_index[n_adj] - 2 * wrap - 2][1];
1715
                            if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {
1716 1717
                                C[0] = (1 + C[0] + s->current_picture.f.motion_val[0][s->block_index[1] - 2 * wrap - 2][0]) >> 1;
                                C[1] = (1 + C[1] + s->current_picture.f.motion_val[0][s->block_index[1] - 2 * wrap - 2][1]) >> 1;
1718
                            }
1719 1720
                        } else
                            c_valid = 0;
1721 1722 1723 1724 1725
                    }
                }
            }
        }
    } else {
1726
        pos_b   = s->block_index[1];
1727
        b_valid = 1;
1728 1729 1730
        B[0]    = s->current_picture.f.motion_val[0][pos_b][0];
        B[1]    = s->current_picture.f.motion_val[0][pos_b][1];
        pos_c   = s->block_index[0];
1731
        c_valid = 1;
1732 1733
        C[0]    = s->current_picture.f.motion_val[0][pos_c][0];
        C[1]    = s->current_picture.f.motion_val[0][pos_c][1];
1734 1735 1736 1737
    }

    total_valid = a_valid + b_valid + c_valid;
    // check if predictor A is out of bounds
1738
    if (!s->mb_x && !(n == 1 || n == 3)) {
1739 1740 1741 1742 1743 1744 1745
        A[0] = A[1] = 0;
    }
    // check if predictor B is out of bounds
    if ((s->first_slice_line && v->blk_mv_type[xy]) || (s->first_slice_line && !(n & 2))) {
        B[0] = B[1] = C[0] = C[1] = 0;
    }
    if (!v->blk_mv_type[xy]) {
1746
        if (s->mb_width == 1) {
1747 1748
            px = B[0];
            py = B[1];
1749
        } else {
1750 1751 1752 1753 1754 1755 1756
            if (total_valid >= 2) {
                px = mid_pred(A[0], B[0], C[0]);
                py = mid_pred(A[1], B[1], C[1]);
            } else if (total_valid) {
                if (a_valid) { px = A[0]; py = A[1]; }
                if (b_valid) { px = B[0]; py = B[1]; }
                if (c_valid) { px = C[0]; py = C[1]; }
1757 1758
            } else
                px = py = 0;
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
        }
    } else {
        if (a_valid)
            field_a = (A[1] & 4) ? 1 : 0;
        else
            field_a = 0;
        if (b_valid)
            field_b = (B[1] & 4) ? 1 : 0;
        else
            field_b = 0;
        if (c_valid)
            field_c = (C[1] & 4) ? 1 : 0;
        else
            field_c = 0;

1774
        num_oppfield  = field_a + field_b + field_c;
1775 1776 1777 1778 1779 1780 1781 1782
        num_samefield = total_valid - num_oppfield;
        if (total_valid == 3) {
            if ((num_samefield == 3) || (num_oppfield == 3)) {
                px = mid_pred(A[0], B[0], C[0]);
                py = mid_pred(A[1], B[1], C[1]);
            } else if (num_samefield >= num_oppfield) {
                /* take one MV from same field set depending on priority
                the check for B may not be necessary */
1783 1784
                px = !field_a ? A[0] : B[0];
                py = !field_a ? A[1] : B[1];
1785
            } else {
1786 1787
                px =  field_a ? A[0] : B[0];
                py =  field_a ? A[1] : B[1];
1788 1789 1790 1791
            }
        } else if (total_valid == 2) {
            if (num_samefield >= num_oppfield) {
                if (!field_a && a_valid) {
1792 1793
                    px = A[0];
                    py = A[1];
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
                } else if (!field_b && b_valid) {
                    px = B[0];
                    py = B[1];
                } else if (c_valid) {
                    px = C[0];
                    py = C[1];
                } else px = py = 0;
            } else {
                if (field_a && a_valid) {
                    px = A[0];
                    py = A[1];
                } else if (field_b && b_valid) {
                    px = B[0];
                    py = B[1];
                } else if (c_valid) {
1809 1810
                    px = C[0];
                    py = C[1];
1811
                } else px = py = 0;
1812
            }
1813 1814 1815
        } else if (total_valid == 1) {
            px = (a_valid) ? A[0] : ((b_valid) ? B[0] : C[0]);
            py = (a_valid) ? A[1] : ((b_valid) ? B[1] : C[1]);
1816 1817
        } else
            px = py = 0;
1818
    }
1819

1820
    /* store MV using signed modulus of MV range defined in 4.11 */
1821 1822
    s->mv[0][n][0] = s->current_picture.f.motion_val[0][xy][0] = ((px + dmv_x + r_x) & ((r_x << 1) - 1)) - r_x;
    s->mv[0][n][1] = s->current_picture.f.motion_val[0][xy][1] = ((py + dmv_y + r_y) & ((r_y << 1) - 1)) - r_y;
1823 1824 1825 1826 1827
    if (mvn == 1) { /* duplicate motion data for 1-MV block */
        s->current_picture.f.motion_val[0][xy +    1    ][0] = s->current_picture.f.motion_val[0][xy][0];
        s->current_picture.f.motion_val[0][xy +    1    ][1] = s->current_picture.f.motion_val[0][xy][1];
        s->current_picture.f.motion_val[0][xy + wrap    ][0] = s->current_picture.f.motion_val[0][xy][0];
        s->current_picture.f.motion_val[0][xy + wrap    ][1] = s->current_picture.f.motion_val[0][xy][1];
1828 1829
        s->current_picture.f.motion_val[0][xy + wrap + 1][0] = s->current_picture.f.motion_val[0][xy][0];
        s->current_picture.f.motion_val[0][xy + wrap + 1][1] = s->current_picture.f.motion_val[0][xy][1];
1830 1831 1832 1833 1834
    } else if (mvn == 2) { /* duplicate motion data for 2-Field MV block */
        s->current_picture.f.motion_val[0][xy + 1][0] = s->current_picture.f.motion_val[0][xy][0];
        s->current_picture.f.motion_val[0][xy + 1][1] = s->current_picture.f.motion_val[0][xy][1];
        s->mv[0][n + 1][0] = s->mv[0][n][0];
        s->mv[0][n + 1][1] = s->mv[0][n][1];
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
    }
}

/** Motion compensation for direct or interpolated blocks in B-frames
 */
static void vc1_interp_mc(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    DSPContext *dsp = &v->s.dsp;
    uint8_t *srcY, *srcU, *srcV;
    int dxy, mx, my, uvmx, uvmy, src_x, src_y, uvsrc_x, uvsrc_y;
1846 1847
    int off, off_uv;
    int v_edge_pos = s->v_edge_pos >> v->field_mode;
1848

1849 1850
    if (!v->field_mode && !v->s.next_picture.f.data[0])
        return;
1851

1852 1853
    mx   = s->mv[1][0][0];
    my   = s->mv[1][0][1];
1854 1855
    uvmx = (mx + ((mx & 3) == 3)) >> 1;
    uvmy = (my + ((my & 3) == 3)) >> 1;
1856 1857
    if (v->field_mode) {
        if (v->cur_field_type != v->ref_field_type[1])
1858
            my   = my   - 2 + 4 * v->cur_field_type;
1859 1860
            uvmy = uvmy - 2 + 4 * v->cur_field_type;
    }
1861 1862 1863
    if (v->fastuvmc) {
        uvmx = uvmx + ((uvmx < 0) ? -(uvmx & 1) : (uvmx & 1));
        uvmy = uvmy + ((uvmy < 0) ? -(uvmy & 1) : (uvmy & 1));
1864
    }
1865 1866 1867
    srcY = s->next_picture.f.data[0];
    srcU = s->next_picture.f.data[1];
    srcV = s->next_picture.f.data[2];
1868

1869 1870 1871 1872
    src_x   = s->mb_x * 16 + (mx   >> 2);
    src_y   = s->mb_y * 16 + (my   >> 2);
    uvsrc_x = s->mb_x *  8 + (uvmx >> 2);
    uvsrc_y = s->mb_y *  8 + (uvmy >> 2);
1873

1874
    if (v->profile != PROFILE_ADVANCED) {
1875 1876 1877 1878
        src_x   = av_clip(  src_x, -16, s->mb_width  * 16);
        src_y   = av_clip(  src_y, -16, s->mb_height * 16);
        uvsrc_x = av_clip(uvsrc_x,  -8, s->mb_width  *  8);
        uvsrc_y = av_clip(uvsrc_y,  -8, s->mb_height *  8);
1879
    } else {
1880 1881 1882 1883 1884 1885
        src_x   = av_clip(  src_x, -17, s->avctx->coded_width);
        src_y   = av_clip(  src_y, -18, s->avctx->coded_height + 1);
        uvsrc_x = av_clip(uvsrc_x,  -8, s->avctx->coded_width  >> 1);
        uvsrc_y = av_clip(uvsrc_y,  -8, s->avctx->coded_height >> 1);
    }

1886
    srcY += src_y   * s->linesize   + src_x;
1887 1888 1889
    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;
    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

1890 1891 1892 1893 1894 1895
    if (v->field_mode && v->ref_field_type[1]) {
        srcY += s->current_picture_ptr->f.linesize[0];
        srcU += s->current_picture_ptr->f.linesize[1];
        srcV += s->current_picture_ptr->f.linesize[2];
    }

1896
    /* for grayscale we should not try to read from unknown area */
1897
    if (s->flags & CODEC_FLAG_GRAY) {
1898 1899 1900 1901
        srcU = s->edge_emu_buffer + 18 * s->linesize;
        srcV = s->edge_emu_buffer + 18 * s->linesize;
    }

1902
    if (v->rangeredfrm || s->h_edge_pos < 22 || v_edge_pos < 22
1903 1904
        || (unsigned)(src_x - 1) > s->h_edge_pos - (mx & 3) - 16 - 3
        || (unsigned)(src_y - 1) > v_edge_pos    - (my & 3) - 16 - 3) {
1905
        uint8_t *uvbuf = s->edge_emu_buffer + 19 * s->linesize;
1906 1907

        srcY -= s->mspel * (1 + s->linesize);
1908 1909 1910 1911
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize,
                                17 + s->mspel * 2, 17 + s->mspel * 2,
                                src_x - s->mspel, src_y - s->mspel,
                                s->h_edge_pos, v_edge_pos);
1912
        srcY = s->edge_emu_buffer;
1913 1914 1915 1916
        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, 8 + 1, 8 + 1,
                                uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, v_edge_pos >> 1);
        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, 8 + 1, 8 + 1,
                                uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, v_edge_pos >> 1);
1917 1918 1919
        srcU = uvbuf;
        srcV = uvbuf + 16;
        /* if we deal with range reduction we need to scale source blocks */
1920
        if (v->rangeredfrm) {
1921 1922 1923 1924
            int i, j;
            uint8_t *src, *src2;

            src = srcY;
1925 1926 1927
            for (j = 0; j < 17 + s->mspel * 2; j++) {
                for (i = 0; i < 17 + s->mspel * 2; i++)
                    src[i] = ((src[i] - 128) >> 1) + 128;
1928 1929
                src += s->linesize;
            }
1930 1931 1932 1933 1934
            src = srcU;
            src2 = srcV;
            for (j = 0; j < 9; j++) {
                for (i = 0; i < 9; i++) {
                    src[i]  = ((src[i]  - 128) >> 1) + 128;
1935 1936
                    src2[i] = ((src2[i] - 128) >> 1) + 128;
                }
1937
                src  += s->uvlinesize;
1938 1939 1940 1941 1942 1943
                src2 += s->uvlinesize;
            }
        }
        srcY += s->mspel * (1 + s->linesize);
    }

1944
    if (v->field_mode && v->second_field) {
1945
        off    = s->current_picture_ptr->f.linesize[0];
1946 1947
        off_uv = s->current_picture_ptr->f.linesize[1];
    } else {
1948
        off    = 0;
1949 1950 1951
        off_uv = 0;
    }

1952
    if (s->mspel) {
1953
        dxy = ((my & 3) << 2) | (mx & 3);
1954 1955
        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off    , srcY    , s->linesize, v->rnd);
        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8, srcY + 8, s->linesize, v->rnd);
1956
        srcY += s->linesize * 8;
1957 1958
        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8 * s->linesize    , srcY    , s->linesize, v->rnd);
        v->vc1dsp.avg_vc1_mspel_pixels_tab[dxy](s->dest[0] + off + 8 * s->linesize + 8, srcY + 8, s->linesize, v->rnd);
1959 1960 1961
    } else { // hpel mc
        dxy = (my & 2) | ((mx & 2) >> 1);

1962
        if (!v->rnd)
1963
            dsp->avg_pixels_tab[0][dxy](s->dest[0] + off, srcY, s->linesize, 16);
1964
        else
1965
            dsp->avg_no_rnd_pixels_tab[0][dxy](s->dest[0] + off, srcY, s->linesize, 16);
1966 1967
    }

1968
    if (s->flags & CODEC_FLAG_GRAY) return;
1969
    /* Chroma MC always uses qpel blilinear */
1970 1971 1972
    uvmx = (uvmx & 3) << 1;
    uvmy = (uvmy & 3) << 1;
    if (!v->rnd) {
1973 1974
        dsp->avg_h264_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);
        dsp->avg_h264_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);
1975
    } else {
1976 1977
        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1] + off_uv, srcU, s->uvlinesize, 8, uvmx, uvmy);
        v->vc1dsp.avg_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2] + off_uv, srcV, s->uvlinesize, 8, uvmx, uvmy);
1978 1979 1980 1981 1982 1983 1984 1985
    }
}

static av_always_inline int scale_mv(int value, int bfrac, int inv, int qs)
{
    int n = bfrac;

#if B_FRACTION_DEN==256
1986
    if (inv)
1987
        n -= 256;
1988
    if (!qs)
1989 1990 1991
        return 2 * ((value * n + 255) >> 9);
    return (value * n + 128) >> 8;
#else
1992
    if (inv)
1993
        n -= B_FRACTION_DEN;
1994
    if (!qs)
1995 1996 1997 1998 1999 2000 2001
        return 2 * ((value * n + B_FRACTION_DEN - 1) / (2 * B_FRACTION_DEN));
    return (value * n + B_FRACTION_DEN/2) / B_FRACTION_DEN;
#endif
}

/** Reconstruct motion vector for B-frame and do motion compensation
 */
2002 2003
static inline void vc1_b_mc(VC1Context *v, int dmv_x[2], int dmv_y[2],
                            int direct, int mode)
2004
{
2005
    if (v->use_ic) {
2006
        v->mv_mode2 = v->mv_mode;
2007
        v->mv_mode  = MV_PMODE_INTENSITY_COMP;
2008
    }
2009
    if (direct) {
2010 2011
        vc1_mc_1mv(v, 0);
        vc1_interp_mc(v);
2012 2013
        if (v->use_ic)
            v->mv_mode = v->mv_mode2;
2014 2015
        return;
    }
2016
    if (mode == BMV_TYPE_INTERPOLATED) {
2017 2018
        vc1_mc_1mv(v, 0);
        vc1_interp_mc(v);
2019 2020
        if (v->use_ic)
            v->mv_mode = v->mv_mode2;
2021 2022 2023
        return;
    }

2024 2025
    if (v->use_ic && (mode == BMV_TYPE_BACKWARD))
        v->mv_mode = v->mv_mode2;
2026
    vc1_mc_1mv(v, (mode == BMV_TYPE_BACKWARD));
2027 2028
    if (v->use_ic)
        v->mv_mode = v->mv_mode2;
2029 2030
}

2031 2032
static inline void vc1_pred_b_mv(VC1Context *v, int dmv_x[2], int dmv_y[2],
                                 int direct, int mvtype)
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
{
    MpegEncContext *s = &v->s;
    int xy, wrap, off = 0;
    int16_t *A, *B, *C;
    int px, py;
    int sum;
    int r_x, r_y;
    const uint8_t *is_intra = v->mb_type[0];

    r_x = v->range_x;
    r_y = v->range_y;
    /* scale MV difference to be quad-pel */
    dmv_x[0] <<= 1 - s->quarter_sample;
    dmv_y[0] <<= 1 - s->quarter_sample;
    dmv_x[1] <<= 1 - s->quarter_sample;
    dmv_y[1] <<= 1 - s->quarter_sample;

    wrap = s->b8_stride;
    xy = s->block_index[0];

2053
    if (s->mb_intra) {
2054 2055 2056 2057
        s->current_picture.f.motion_val[0][xy + v->blocks_off][0] =
        s->current_picture.f.motion_val[0][xy + v->blocks_off][1] =
        s->current_picture.f.motion_val[1][xy + v->blocks_off][0] =
        s->current_picture.f.motion_val[1][xy + v->blocks_off][1] = 0;
2058 2059
        return;
    }
2060 2061 2062 2063 2064
    if (!v->field_mode) {
        s->mv[0][0][0] = scale_mv(s->next_picture.f.motion_val[1][xy][0], v->bfraction, 0, s->quarter_sample);
        s->mv[0][0][1] = scale_mv(s->next_picture.f.motion_val[1][xy][1], v->bfraction, 0, s->quarter_sample);
        s->mv[1][0][0] = scale_mv(s->next_picture.f.motion_val[1][xy][0], v->bfraction, 1, s->quarter_sample);
        s->mv[1][0][1] = scale_mv(s->next_picture.f.motion_val[1][xy][1], v->bfraction, 1, s->quarter_sample);
2065

2066 2067 2068 2069 2070 2071
        /* Pullback predicted motion vectors as specified in 8.4.5.4 */
        s->mv[0][0][0] = av_clip(s->mv[0][0][0], -60 - (s->mb_x << 6), (s->mb_width  << 6) - 4 - (s->mb_x << 6));
        s->mv[0][0][1] = av_clip(s->mv[0][0][1], -60 - (s->mb_y << 6), (s->mb_height << 6) - 4 - (s->mb_y << 6));
        s->mv[1][0][0] = av_clip(s->mv[1][0][0], -60 - (s->mb_x << 6), (s->mb_width  << 6) - 4 - (s->mb_x << 6));
        s->mv[1][0][1] = av_clip(s->mv[1][0][1], -60 - (s->mb_y << 6), (s->mb_height << 6) - 4 - (s->mb_y << 6));
    }
2072
    if (direct) {
2073 2074 2075 2076
        s->current_picture.f.motion_val[0][xy + v->blocks_off][0] = s->mv[0][0][0];
        s->current_picture.f.motion_val[0][xy + v->blocks_off][1] = s->mv[0][0][1];
        s->current_picture.f.motion_val[1][xy + v->blocks_off][0] = s->mv[1][0][0];
        s->current_picture.f.motion_val[1][xy + v->blocks_off][1] = s->mv[1][0][1];
2077 2078 2079
        return;
    }

2080 2081 2082
    if ((mvtype == BMV_TYPE_FORWARD) || (mvtype == BMV_TYPE_INTERPOLATED)) {
        C   = s->current_picture.f.motion_val[0][xy - 2];
        A   = s->current_picture.f.motion_val[0][xy - wrap * 2];
2083
        off = (s->mb_x == (s->mb_width - 1)) ? -2 : 2;
2084
        B   = s->current_picture.f.motion_val[0][xy - wrap * 2 + off];
2085

2086 2087 2088
        if (!s->mb_x) C[0] = C[1] = 0;
        if (!s->first_slice_line) { // predictor A is not out of bounds
            if (s->mb_width == 1) {
2089 2090 2091 2092 2093 2094
                px = A[0];
                py = A[1];
            } else {
                px = mid_pred(A[0], B[0], C[0]);
                py = mid_pred(A[1], B[1], C[1]);
            }
2095
        } else if (s->mb_x) { // predictor C is not out of bounds
2096 2097 2098 2099 2100 2101 2102 2103
            px = C[0];
            py = C[1];
        } else {
            px = py = 0;
        }
        /* Pullback MV as specified in 8.3.5.3.4 */
        {
            int qx, qy, X, Y;
2104
            if (v->profile < PROFILE_ADVANCED) {
2105 2106
                qx = (s->mb_x << 5);
                qy = (s->mb_y << 5);
2107 2108 2109 2110 2111 2112
                X  = (s->mb_width  << 5) - 4;
                Y  = (s->mb_height << 5) - 4;
                if (qx + px < -28) px = -28 - qx;
                if (qy + py < -28) py = -28 - qy;
                if (qx + px > X) px = X - qx;
                if (qy + py > Y) py = Y - qy;
2113 2114 2115
            } else {
                qx = (s->mb_x << 6);
                qy = (s->mb_y << 6);
2116 2117 2118 2119 2120 2121
                X  = (s->mb_width  << 6) - 4;
                Y  = (s->mb_height << 6) - 4;
                if (qx + px < -60) px = -60 - qx;
                if (qy + py < -60) py = -60 - qy;
                if (qx + px > X) px = X - qx;
                if (qy + py > Y) py = Y - qy;
2122 2123 2124
            }
        }
        /* Calculate hybrid prediction as specified in 8.3.5.3.5 */
2125 2126
        if (0 && !s->first_slice_line && s->mb_x) {
            if (is_intra[xy - wrap])
2127 2128 2129
                sum = FFABS(px) + FFABS(py);
            else
                sum = FFABS(px - A[0]) + FFABS(py - A[1]);
2130 2131
            if (sum > 32) {
                if (get_bits1(&s->gb)) {
2132 2133 2134 2135 2136 2137 2138
                    px = A[0];
                    py = A[1];
                } else {
                    px = C[0];
                    py = C[1];
                }
            } else {
2139
                if (is_intra[xy - 2])
2140 2141 2142
                    sum = FFABS(px) + FFABS(py);
                else
                    sum = FFABS(px - C[0]) + FFABS(py - C[1]);
2143 2144
                if (sum > 32) {
                    if (get_bits1(&s->gb)) {
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
                        px = A[0];
                        py = A[1];
                    } else {
                        px = C[0];
                        py = C[1];
                    }
                }
            }
        }
        /* store MV using signed modulus of MV range defined in 4.11 */
        s->mv[0][0][0] = ((px + dmv_x[0] + r_x) & ((r_x << 1) - 1)) - r_x;
        s->mv[0][0][1] = ((py + dmv_y[0] + r_y) & ((r_y << 1) - 1)) - r_y;
    }
2158 2159 2160
    if ((mvtype == BMV_TYPE_BACKWARD) || (mvtype == BMV_TYPE_INTERPOLATED)) {
        C   = s->current_picture.f.motion_val[1][xy - 2];
        A   = s->current_picture.f.motion_val[1][xy - wrap * 2];
2161
        off = (s->mb_x == (s->mb_width - 1)) ? -2 : 2;
2162
        B   = s->current_picture.f.motion_val[1][xy - wrap * 2 + off];
2163

2164 2165 2166 2167
        if (!s->mb_x)
            C[0] = C[1] = 0;
        if (!s->first_slice_line) { // predictor A is not out of bounds
            if (s->mb_width == 1) {
2168 2169 2170 2171 2172 2173
                px = A[0];
                py = A[1];
            } else {
                px = mid_pred(A[0], B[0], C[0]);
                py = mid_pred(A[1], B[1], C[1]);
            }
2174
        } else if (s->mb_x) { // predictor C is not out of bounds
2175 2176 2177 2178 2179 2180 2181 2182
            px = C[0];
            py = C[1];
        } else {
            px = py = 0;
        }
        /* Pullback MV as specified in 8.3.5.3.4 */
        {
            int qx, qy, X, Y;
2183
            if (v->profile < PROFILE_ADVANCED) {
2184 2185
                qx = (s->mb_x << 5);
                qy = (s->mb_y << 5);
2186 2187 2188 2189 2190 2191
                X  = (s->mb_width  << 5) - 4;
                Y  = (s->mb_height << 5) - 4;
                if (qx + px < -28) px = -28 - qx;
                if (qy + py < -28) py = -28 - qy;
                if (qx + px > X) px = X - qx;
                if (qy + py > Y) py = Y - qy;
2192 2193 2194
            } else {
                qx = (s->mb_x << 6);
                qy = (s->mb_y << 6);
2195 2196 2197 2198 2199 2200
                X  = (s->mb_width  << 6) - 4;
                Y  = (s->mb_height << 6) - 4;
                if (qx + px < -60) px = -60 - qx;
                if (qy + py < -60) py = -60 - qy;
                if (qx + px > X) px = X - qx;
                if (qy + py > Y) py = Y - qy;
2201 2202 2203
            }
        }
        /* Calculate hybrid prediction as specified in 8.3.5.3.5 */
2204 2205
        if (0 && !s->first_slice_line && s->mb_x) {
            if (is_intra[xy - wrap])
2206 2207 2208
                sum = FFABS(px) + FFABS(py);
            else
                sum = FFABS(px - A[0]) + FFABS(py - A[1]);
2209 2210
            if (sum > 32) {
                if (get_bits1(&s->gb)) {
2211 2212 2213 2214 2215 2216 2217
                    px = A[0];
                    py = A[1];
                } else {
                    px = C[0];
                    py = C[1];
                }
            } else {
2218
                if (is_intra[xy - 2])
2219 2220 2221
                    sum = FFABS(px) + FFABS(py);
                else
                    sum = FFABS(px - C[0]) + FFABS(py - C[1]);
2222 2223
                if (sum > 32) {
                    if (get_bits1(&s->gb)) {
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
                        px = A[0];
                        py = A[1];
                    } else {
                        px = C[0];
                        py = C[1];
                    }
                }
            }
        }
        /* store MV using signed modulus of MV range defined in 4.11 */

        s->mv[1][0][0] = ((px + dmv_x[1] + r_x) & ((r_x << 1) - 1)) - r_x;
        s->mv[1][0][1] = ((py + dmv_y[1] + r_y) & ((r_y << 1) - 1)) - r_y;
    }
2238 2239 2240 2241
    s->current_picture.f.motion_val[0][xy][0] = s->mv[0][0][0];
    s->current_picture.f.motion_val[0][xy][1] = s->mv[0][0][1];
    s->current_picture.f.motion_val[1][xy][0] = s->mv[1][0][0];
    s->current_picture.f.motion_val[1][xy][1] = s->mv[1][0][1];
2242 2243
}

2244 2245 2246 2247 2248 2249 2250 2251 2252
static inline void vc1_pred_b_mv_intfi(VC1Context *v, int n, int *dmv_x, int *dmv_y, int mv1, int *pred_flag)
{
    int dir = (v->bmvtype == BMV_TYPE_BACKWARD) ? 1 : 0;
    MpegEncContext *s = &v->s;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    if (v->bmvtype == BMV_TYPE_DIRECT) {
        int total_opp, k, f;
        if (s->next_picture.f.mb_type[mb_pos + v->mb_off] != MB_TYPE_INTRA) {
2253 2254 2255 2256 2257 2258 2259 2260
            s->mv[0][0][0] = scale_mv(s->next_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0],
                                      v->bfraction, 0, s->quarter_sample);
            s->mv[0][0][1] = scale_mv(s->next_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1],
                                      v->bfraction, 0, s->quarter_sample);
            s->mv[1][0][0] = scale_mv(s->next_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0],
                                      v->bfraction, 1, s->quarter_sample);
            s->mv[1][0][1] = scale_mv(s->next_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1],
                                      v->bfraction, 1, s->quarter_sample);
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290

            total_opp = v->mv_f_next[0][s->block_index[0] + v->blocks_off]
                      + v->mv_f_next[0][s->block_index[1] + v->blocks_off]
                      + v->mv_f_next[0][s->block_index[2] + v->blocks_off]
                      + v->mv_f_next[0][s->block_index[3] + v->blocks_off];
            f = (total_opp > 2) ? 1 : 0;
        } else {
            s->mv[0][0][0] = s->mv[0][0][1] = 0;
            s->mv[1][0][0] = s->mv[1][0][1] = 0;
            f = 0;
        }
        v->ref_field_type[0] = v->ref_field_type[1] = v->cur_field_type ^ f;
        for (k = 0; k < 4; k++) {
            s->current_picture.f.motion_val[0][s->block_index[k] + v->blocks_off][0] = s->mv[0][0][0];
            s->current_picture.f.motion_val[0][s->block_index[k] + v->blocks_off][1] = s->mv[0][0][1];
            s->current_picture.f.motion_val[1][s->block_index[k] + v->blocks_off][0] = s->mv[1][0][0];
            s->current_picture.f.motion_val[1][s->block_index[k] + v->blocks_off][1] = s->mv[1][0][1];
            v->mv_f[0][s->block_index[k] + v->blocks_off] = f;
            v->mv_f[1][s->block_index[k] + v->blocks_off] = f;
        }
        return;
    }
    if (v->bmvtype == BMV_TYPE_INTERPOLATED) {
        vc1_pred_mv(v, 0, dmv_x[0], dmv_y[0],   1, v->range_x, v->range_y, v->mb_type[0], pred_flag[0], 0);
        vc1_pred_mv(v, 0, dmv_x[1], dmv_y[1],   1, v->range_x, v->range_y, v->mb_type[0], pred_flag[1], 1);
        return;
    }
    if (dir) { // backward
        vc1_pred_mv(v, n, dmv_x[1], dmv_y[1], mv1, v->range_x, v->range_y, v->mb_type[0], pred_flag[1], 1);
        if (n == 3 || mv1) {
2291
            vc1_pred_mv(v, 0, dmv_x[0], dmv_y[0],   1, v->range_x, v->range_y, v->mb_type[0], 0, 0);
2292 2293 2294 2295
        }
    } else { // forward
        vc1_pred_mv(v, n, dmv_x[0], dmv_y[0], mv1, v->range_x, v->range_y, v->mb_type[0], pred_flag[0], 0);
        if (n == 3 || mv1) {
2296
            vc1_pred_mv(v, 0, dmv_x[1], dmv_y[1],   1, v->range_x, v->range_y, v->mb_type[0], 0, 1);
2297 2298 2299 2300
        }
    }
}

2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
/** Get predicted DC value for I-frames only
 * prediction dir: left=0, top=1
 * @param s MpegEncContext
 * @param overlap flag indicating that overlap filtering is used
 * @param pq integer part of picture quantizer
 * @param[in] n block index in the current MB
 * @param dc_val_ptr Pointer to DC predictor
 * @param dir_ptr Prediction direction for use in AC prediction
 */
static inline int vc1_i_pred_dc(MpegEncContext *s, int overlap, int pq, int n,
2311
                                int16_t **dc_val_ptr, int *dir_ptr)
2312 2313 2314 2315
{
    int a, b, c, wrap, pred, scale;
    int16_t *dc_val;
    static const uint16_t dcpred[32] = {
2316 2317 2318 2319
        -1, 1024,  512,  341,  256,  205,  171,  146,  128,
             114,  102,   93,   85,   79,   73,   68,   64,
              60,   57,   54,   51,   49,   47,   45,   43,
              41,   39,   38,   37,   35,   34,   33
2320 2321 2322
    };

    /* find prediction - wmv3_dc_scale always used here in fact */
2323 2324
    if (n < 4) scale = s->y_dc_scale;
    else       scale = s->c_dc_scale;
2325

2326 2327
    wrap   = s->block_wrap[n];
    dc_val = s->dc_val[0] + s->block_index[n];
2328 2329 2330 2331 2332 2333 2334 2335

    /* B A
     * C X
     */
    c = dc_val[ - 1];
    b = dc_val[ - 1 - wrap];
    a = dc_val[ - wrap];

2336
    if (pq < 9 || !overlap) {
2337
        /* Set outer values */
2338 2339 2340 2341 2342
        if (s->first_slice_line && (n != 2 && n != 3))
            b = a = dcpred[scale];
        if (s->mb_x == 0 && (n != 1 && n != 3))
            b = c = dcpred[scale];
    } else {
2343
        /* Set outer values */
2344 2345 2346 2347
        if (s->first_slice_line && (n != 2 && n != 3))
            b = a = 0;
        if (s->mb_x == 0 && (n != 1 && n != 3))
            b = c = 0;
2348 2349 2350
    }

    if (abs(a - b) <= abs(b - c)) {
2351 2352
        pred     = c;
        *dir_ptr = 1; // left
2353
    } else {
2354 2355
        pred     = a;
        *dir_ptr = 0; // top
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    }

    /* update predictor */
    *dc_val_ptr = &dc_val[0];
    return pred;
}


/** Get predicted DC value
 * prediction dir: left=0, top=1
 * @param s MpegEncContext
 * @param overlap flag indicating that overlap filtering is used
 * @param pq integer part of picture quantizer
 * @param[in] n block index in the current MB
 * @param a_avail flag indicating top block availability
 * @param c_avail flag indicating left block availability
 * @param dc_val_ptr Pointer to DC predictor
 * @param dir_ptr Prediction direction for use in AC prediction
 */
static inline int vc1_pred_dc(MpegEncContext *s, int overlap, int pq, int n,
                              int a_avail, int c_avail,
                              int16_t **dc_val_ptr, int *dir_ptr)
{
    int a, b, c, wrap, pred;
    int16_t *dc_val;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int q1, q2 = 0;
2383
    int dqscale_index;
2384 2385

    wrap = s->block_wrap[n];
2386
    dc_val = s->dc_val[0] + s->block_index[n];
2387 2388 2389 2390 2391 2392 2393 2394

    /* B A
     * C X
     */
    c = dc_val[ - 1];
    b = dc_val[ - 1 - wrap];
    a = dc_val[ - wrap];
    /* scale predictors if needed */
2395
    q1 = s->current_picture.f.qscale_table[mb_pos];
2396 2397 2398
    dqscale_index = s->y_dc_scale_table[q1] - 1;
    if (dqscale_index < 0)
        return 0;
2399
    if (c_avail && (n != 1 && n != 3)) {
2400
        q2 = s->current_picture.f.qscale_table[mb_pos - 1];
2401
        if (q2 && q2 != q1)
2402
            c = (c * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
2403
    }
2404
    if (a_avail && (n != 2 && n != 3)) {
2405
        q2 = s->current_picture.f.qscale_table[mb_pos - s->mb_stride];
2406
        if (q2 && q2 != q1)
2407
            a = (a * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
2408
    }
2409
    if (a_avail && c_avail && (n != 3)) {
2410
        int off = mb_pos;
2411 2412 2413 2414
        if (n != 1)
            off--;
        if (n != 2)
            off -= s->mb_stride;
2415
        q2 = s->current_picture.f.qscale_table[off];
2416
        if (q2 && q2 != q1)
2417
            b = (b * s->y_dc_scale_table[q2] * ff_vc1_dqscale[dqscale_index] + 0x20000) >> 18;
2418 2419
    }

2420 2421 2422 2423
    if (a_avail && c_avail) {
        if (abs(a - b) <= abs(b - c)) {
            pred     = c;
            *dir_ptr = 1; // left
2424
        } else {
2425 2426 2427 2428 2429 2430 2431 2432 2433
            pred     = a;
            *dir_ptr = 0; // top
        }
    } else if (a_avail) {
        pred     = a;
        *dir_ptr = 0; // top
    } else if (c_avail) {
        pred     = c;
        *dir_ptr = 1; // left
2434
    } else {
2435 2436
        pred     = 0;
        *dir_ptr = 1; // left
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
    }

    /* update predictor */
    *dc_val_ptr = &dc_val[0];
    return pred;
}

/** @} */ // Block group

/**
2447
 * @name VC1 Macroblock-level functions in Simple/Main Profiles
2448 2449 2450 2451
 * @see 7.1.4, p91 and 8.1.1.7, p(1)04
 * @{
 */

2452 2453
static inline int vc1_coded_block_pred(MpegEncContext * s, int n,
                                       uint8_t **coded_block_ptr)
2454 2455 2456
{
    int xy, wrap, pred, a, b, c;

2457
    xy   = s->block_index[n];
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
    wrap = s->b8_stride;

    /* B C
     * A X
     */
    a = s->coded_block[xy - 1       ];
    b = s->coded_block[xy - 1 - wrap];
    c = s->coded_block[xy     - wrap];

    if (b == c) {
        pred = a;
    } else {
        pred = c;
    }

    /* store value */
    *coded_block_ptr = &s->coded_block[xy];

    return pred;
}

/**
 * Decode one AC coefficient
 * @param v The VC1 context
 * @param last Last coefficient
 * @param skip How much zero coefficients to skip
 * @param value Decoded AC coefficient value
 * @param codingset set of VLC to decode data
 * @see 8.1.3.4
 */
2488 2489
static void vc1_decode_ac_coeff(VC1Context *v, int *last, int *skip,
                                int *value, int codingset)
2490 2491 2492 2493 2494
{
    GetBitContext *gb = &v->s.gb;
    int index, escape, run = 0, level = 0, lst = 0;

    index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3);
2495
    if (index != ff_vc1_ac_sizes[codingset] - 1) {
2496
        run   = vc1_index_decode_table[codingset][index][0];
2497
        level = vc1_index_decode_table[codingset][index][1];
2498 2499
        lst   = index >= vc1_last_decode_table[codingset] || get_bits_left(gb) < 0;
        if (get_bits1(gb))
2500 2501 2502 2503 2504
            level = -level;
    } else {
        escape = decode210(gb);
        if (escape != 2) {
            index = get_vlc2(gb, ff_vc1_ac_coeff_table[codingset].table, AC_VLC_BITS, 3);
2505
            run   = vc1_index_decode_table[codingset][index][0];
2506
            level = vc1_index_decode_table[codingset][index][1];
2507 2508 2509
            lst   = index >= vc1_last_decode_table[codingset];
            if (escape == 0) {
                if (lst)
2510 2511 2512 2513
                    level += vc1_last_delta_level_table[codingset][run];
                else
                    level += vc1_delta_level_table[codingset][run];
            } else {
2514
                if (lst)
2515 2516 2517 2518
                    run += vc1_last_delta_run_table[codingset][level] + 1;
                else
                    run += vc1_delta_run_table[codingset][level] + 1;
            }
2519
            if (get_bits1(gb))
2520 2521 2522 2523
                level = -level;
        } else {
            int sign;
            lst = get_bits1(gb);
2524 2525
            if (v->s.esc3_level_length == 0) {
                if (v->pq < 8 || v->dquantfrm) { // table 59
2526
                    v->s.esc3_level_length = get_bits(gb, 3);
2527
                    if (!v->s.esc3_level_length)
2528
                        v->s.esc3_level_length = get_bits(gb, 2) + 8;
2529
                } else { // table 60
2530 2531 2532 2533
                    v->s.esc3_level_length = get_unary(gb, 1, 6) + 2;
                }
                v->s.esc3_run_length = 3 + get_bits(gb, 2);
            }
2534 2535
            run   = get_bits(gb, v->s.esc3_run_length);
            sign  = get_bits1(gb);
2536
            level = get_bits(gb, v->s.esc3_level_length);
2537
            if (sign)
2538 2539 2540 2541
                level = -level;
        }
    }

2542 2543
    *last  = lst;
    *skip  = run;
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
    *value = level;
}

/** Decode intra block in intra frames - should be faster than decode_intra_block
 * @param v VC1Context
 * @param block block to decode
 * @param[in] n subblock index
 * @param coded are AC coeffs present or not
 * @param codingset set of VLC to decode data
 */
2554 2555
static int vc1_decode_i_block(VC1Context *v, DCTELEM block[64], int n,
                              int coded, int codingset)
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
{
    GetBitContext *gb = &v->s.gb;
    MpegEncContext *s = &v->s;
    int dc_pred_dir = 0; /* Direction of the DC prediction used */
    int i;
    int16_t *dc_val;
    int16_t *ac_val, *ac_val2;
    int dcdiff;

    /* Get DC differential */
    if (n < 4) {
        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
    } else {
        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
    }
2571
    if (dcdiff < 0) {
2572 2573 2574
        av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");
        return -1;
    }
2575 2576
    if (dcdiff) {
        if (dcdiff == 119 /* ESC index value */) {
2577
            /* TODO: Optimize */
2578
            if (v->pq == 1)      dcdiff = get_bits(gb, 10);
2579
            else if (v->pq == 2) dcdiff = get_bits(gb, 9);
2580 2581
            else                 dcdiff = get_bits(gb, 8);
        } else {
2582
            if (v->pq == 1)
2583
                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;
2584
            else if (v->pq == 2)
2585
                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
        }
        if (get_bits1(gb))
            dcdiff = -dcdiff;
    }

    /* Prediction */
    dcdiff += vc1_i_pred_dc(&v->s, v->overlap, v->pq, n, &dc_val, &dc_pred_dir);
    *dc_val = dcdiff;

    /* Store the quantized DC coeff, used for prediction */
    if (n < 4) {
        block[0] = dcdiff * s->y_dc_scale;
    } else {
        block[0] = dcdiff * s->c_dc_scale;
    }
    /* Skip ? */
    if (!coded) {
        goto not_coded;
    }

2606
    // AC Decoding
2607 2608 2609 2610
    i = 1;

    {
        int last = 0, skip, value;
2611
        const uint8_t *zz_table;
2612 2613 2614 2615 2616
        int scale;
        int k;

        scale = v->pq * 2 + v->halfpq;

2617 2618
        if (v->s.ac_pred) {
            if (!dc_pred_dir)
2619
                zz_table = v->zz_8x8[2];
2620
            else
2621
                zz_table = v->zz_8x8[3];
2622
        } else
2623
            zz_table = v->zz_8x8[1];
2624

2625
        ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
2626
        ac_val2 = ac_val;
2627
        if (dc_pred_dir) // left
2628
            ac_val -= 16;
2629
        else // top
2630 2631 2632 2633 2634
            ac_val -= 16 * s->block_wrap[n];

        while (!last) {
            vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
            i += skip;
2635
            if (i > 63)
2636 2637 2638 2639 2640
                break;
            block[zz_table[i++]] = value;
        }

        /* apply AC prediction if needed */
2641 2642 2643
        if (s->ac_pred) {
            if (dc_pred_dir) { // left
                for (k = 1; k < 8; k++)
2644
                    block[k << v->left_blk_sh] += ac_val[k];
2645 2646
            } else { // top
                for (k = 1; k < 8; k++)
2647
                    block[k << v->top_blk_sh] += ac_val[k + 8];
2648 2649 2650
            }
        }
        /* save AC coeffs for further prediction */
2651
        for (k = 1; k < 8; k++) {
2652 2653
            ac_val2[k]     = block[k << v->left_blk_sh];
            ac_val2[k + 8] = block[k << v->top_blk_sh];
2654 2655 2656
        }

        /* scale AC coeffs */
2657 2658
        for (k = 1; k < 64; k++)
            if (block[k]) {
2659
                block[k] *= scale;
2660
                if (!v->pquantizer)
2661 2662 2663
                    block[k] += (block[k] < 0) ? -v->pq : v->pq;
            }

2664
        if (s->ac_pred) i = 63;
2665 2666 2667
    }

not_coded:
2668
    if (!coded) {
2669
        int k, scale;
2670
        ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
2671 2672 2673 2674 2675
        ac_val2 = ac_val;

        i = 0;
        scale = v->pq * 2 + v->halfpq;
        memset(ac_val2, 0, 16 * 2);
2676
        if (dc_pred_dir) { // left
2677
            ac_val -= 16;
2678
            if (s->ac_pred)
2679
                memcpy(ac_val2, ac_val, 8 * 2);
2680
        } else { // top
2681
            ac_val -= 16 * s->block_wrap[n];
2682
            if (s->ac_pred)
2683 2684 2685 2686
                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);
        }

        /* apply AC prediction if needed */
2687 2688 2689
        if (s->ac_pred) {
            if (dc_pred_dir) { //left
                for (k = 1; k < 8; k++) {
2690
                    block[k << v->left_blk_sh] = ac_val[k] * scale;
2691
                    if (!v->pquantizer && block[k << v->left_blk_sh])
2692
                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -v->pq : v->pq;
2693
                }
2694 2695
            } else { // top
                for (k = 1; k < 8; k++) {
2696
                    block[k << v->top_blk_sh] = ac_val[k + 8] * scale;
2697
                    if (!v->pquantizer && block[k << v->top_blk_sh])
2698
                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -v->pq : v->pq;
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
                }
            }
            i = 63;
        }
    }
    s->block_last_index[n] = i;

    return 0;
}

/** Decode intra block in intra frames - should be faster than decode_intra_block
 * @param v VC1Context
 * @param block block to decode
 * @param[in] n subblock number
 * @param coded are AC coeffs present or not
 * @param codingset set of VLC to decode data
 * @param mquant quantizer value for this macroblock
 */
2717 2718
static int vc1_decode_i_block_adv(VC1Context *v, DCTELEM block[64], int n,
                                  int coded, int codingset, int mquant)
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738
{
    GetBitContext *gb = &v->s.gb;
    MpegEncContext *s = &v->s;
    int dc_pred_dir = 0; /* Direction of the DC prediction used */
    int i;
    int16_t *dc_val;
    int16_t *ac_val, *ac_val2;
    int dcdiff;
    int a_avail = v->a_avail, c_avail = v->c_avail;
    int use_pred = s->ac_pred;
    int scale;
    int q1, q2 = 0;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    /* Get DC differential */
    if (n < 4) {
        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
    } else {
        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
    }
2739
    if (dcdiff < 0) {
2740 2741 2742
        av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");
        return -1;
    }
2743 2744
    if (dcdiff) {
        if (dcdiff == 119 /* ESC index value */) {
2745
            /* TODO: Optimize */
2746
            if (mquant == 1)      dcdiff = get_bits(gb, 10);
2747
            else if (mquant == 2) dcdiff = get_bits(gb, 9);
2748 2749
            else                  dcdiff = get_bits(gb, 8);
        } else {
2750
            if (mquant == 1)
2751
                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;
2752
            else if (mquant == 2)
2753
                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
        }
        if (get_bits1(gb))
            dcdiff = -dcdiff;
    }

    /* Prediction */
    dcdiff += vc1_pred_dc(&v->s, v->overlap, mquant, n, v->a_avail, v->c_avail, &dc_val, &dc_pred_dir);
    *dc_val = dcdiff;

    /* Store the quantized DC coeff, used for prediction */
    if (n < 4) {
        block[0] = dcdiff * s->y_dc_scale;
    } else {
        block[0] = dcdiff * s->c_dc_scale;
    }

    //AC Decoding
    i = 1;

    /* check if AC is needed at all */
2774 2775 2776
    if (!a_avail && !c_avail)
        use_pred = 0;
    ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
2777 2778 2779 2780
    ac_val2 = ac_val;

    scale = mquant * 2 + ((mquant == v->pq) ? v->halfpq : 0);

2781
    if (dc_pred_dir) // left
2782
        ac_val -= 16;
2783
    else // top
2784 2785
        ac_val -= 16 * s->block_wrap[n];

2786
    q1 = s->current_picture.f.qscale_table[mb_pos];
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
    if ( dc_pred_dir && c_avail && mb_pos)
        q2 = s->current_picture.f.qscale_table[mb_pos - 1];
    if (!dc_pred_dir && a_avail && mb_pos >= s->mb_stride)
        q2 = s->current_picture.f.qscale_table[mb_pos - s->mb_stride];
    if ( dc_pred_dir && n == 1)
        q2 = q1;
    if (!dc_pred_dir && n == 2)
        q2 = q1;
    if (n == 3)
        q2 = q1;

    if (coded) {
2799
        int last = 0, skip, value;
2800
        const uint8_t *zz_table;
2801 2802
        int k;

2803
        if (v->s.ac_pred) {
2804
            if (!use_pred && v->fcm == ILACE_FRAME) {
2805 2806
                zz_table = v->zzi_8x8;
            } else {
2807
                if (!dc_pred_dir) // top
2808
                    zz_table = v->zz_8x8[2];
2809
                else // left
2810 2811 2812
                    zz_table = v->zz_8x8[3];
            }
        } else {
2813
            if (v->fcm != ILACE_FRAME)
2814
                zz_table = v->zz_8x8[1];
2815
            else
2816 2817
                zz_table = v->zzi_8x8;
        }
2818 2819 2820 2821

        while (!last) {
            vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
            i += skip;
2822
            if (i > 63)
2823 2824 2825 2826 2827
                break;
            block[zz_table[i++]] = value;
        }

        /* apply AC prediction if needed */
2828
        if (use_pred) {
2829
            /* scale predictors if needed*/
2830
            if (q2 && q1 != q2) {
2831 2832 2833
                q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

2834 2835
                if (q1 < 1)
                    return AVERROR_INVALIDDATA;
2836 2837
                if (dc_pred_dir) { // left
                    for (k = 1; k < 8; k++)
2838
                        block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
2839 2840
                } else { // top
                    for (k = 1; k < 8; k++)
2841
                        block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
2842 2843
                }
            } else {
2844 2845
                if (dc_pred_dir) { //left
                    for (k = 1; k < 8; k++)
2846
                        block[k << v->left_blk_sh] += ac_val[k];
2847
                } else { //top
2848
                    for (k = 1; k < 8; k++)
2849
                        block[k << v->top_blk_sh] += ac_val[k + 8];
2850 2851 2852 2853
                }
            }
        }
        /* save AC coeffs for further prediction */
2854
        for (k = 1; k < 8; k++) {
2855 2856
            ac_val2[k    ] = block[k << v->left_blk_sh];
            ac_val2[k + 8] = block[k << v->top_blk_sh];
2857 2858 2859
        }

        /* scale AC coeffs */
2860 2861
        for (k = 1; k < 64; k++)
            if (block[k]) {
2862
                block[k] *= scale;
2863
                if (!v->pquantizer)
2864 2865 2866
                    block[k] += (block[k] < 0) ? -mquant : mquant;
            }

2867
        if (use_pred) i = 63;
2868 2869 2870 2871
    } else { // no AC coeffs
        int k;

        memset(ac_val2, 0, 16 * 2);
2872 2873
        if (dc_pred_dir) { // left
            if (use_pred) {
2874
                memcpy(ac_val2, ac_val, 8 * 2);
2875
                if (q2 && q1 != q2) {
2876 2877
                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
2878 2879
                    if (q1 < 1)
                        return AVERROR_INVALIDDATA;
2880
                    for (k = 1; k < 8; k++)
2881 2882 2883
                        ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                }
            }
2884 2885
        } else { // top
            if (use_pred) {
2886
                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);
2887
                if (q2 && q1 != q2) {
2888 2889
                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
2890 2891
                    if (q1 < 1)
                        return AVERROR_INVALIDDATA;
2892
                    for (k = 1; k < 8; k++)
2893 2894 2895 2896 2897 2898
                        ac_val2[k + 8] = (ac_val2[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                }
            }
        }

        /* apply AC prediction if needed */
2899 2900 2901
        if (use_pred) {
            if (dc_pred_dir) { // left
                for (k = 1; k < 8; k++) {
2902
                    block[k << v->left_blk_sh] = ac_val2[k] * scale;
2903
                    if (!v->pquantizer && block[k << v->left_blk_sh])
2904
                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -mquant : mquant;
2905
                }
2906 2907
            } else { // top
                for (k = 1; k < 8; k++) {
2908
                    block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;
2909
                    if (!v->pquantizer && block[k << v->top_blk_sh])
2910
                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -mquant : mquant;
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
                }
            }
            i = 63;
        }
    }
    s->block_last_index[n] = i;

    return 0;
}

/** Decode intra block in inter frames - more generic version than vc1_decode_i_block
 * @param v VC1Context
 * @param block block to decode
 * @param[in] n subblock index
 * @param coded are AC coeffs present or not
 * @param mquant block quantizer
 * @param codingset set of VLC to decode data
 */
2929 2930
static int vc1_decode_intra_block(VC1Context *v, DCTELEM block[64], int n,
                                  int coded, int mquant, int codingset)
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
{
    GetBitContext *gb = &v->s.gb;
    MpegEncContext *s = &v->s;
    int dc_pred_dir = 0; /* Direction of the DC prediction used */
    int i;
    int16_t *dc_val;
    int16_t *ac_val, *ac_val2;
    int dcdiff;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int a_avail = v->a_avail, c_avail = v->c_avail;
    int use_pred = s->ac_pred;
    int scale;
    int q1, q2 = 0;

2945 2946
    s->dsp.clear_block(block);

2947
    /* XXX: Guard against dumb values of mquant */
2948
    mquant = (mquant < 1) ? 0 : ((mquant > 31) ? 31 : mquant);
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959

    /* Set DC scale - y and c use the same */
    s->y_dc_scale = s->y_dc_scale_table[mquant];
    s->c_dc_scale = s->c_dc_scale_table[mquant];

    /* Get DC differential */
    if (n < 4) {
        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
    } else {
        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);
    }
2960
    if (dcdiff < 0) {
2961 2962 2963
        av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");
        return -1;
    }
2964 2965
    if (dcdiff) {
        if (dcdiff == 119 /* ESC index value */) {
2966
            /* TODO: Optimize */
2967
            if (mquant == 1)      dcdiff = get_bits(gb, 10);
2968
            else if (mquant == 2) dcdiff = get_bits(gb, 9);
2969 2970
            else                  dcdiff = get_bits(gb, 8);
        } else {
2971
            if (mquant == 1)
2972
                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;
2973
            else if (mquant == 2)
2974
                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
        }
        if (get_bits1(gb))
            dcdiff = -dcdiff;
    }

    /* Prediction */
    dcdiff += vc1_pred_dc(&v->s, v->overlap, mquant, n, a_avail, c_avail, &dc_val, &dc_pred_dir);
    *dc_val = dcdiff;

    /* Store the quantized DC coeff, used for prediction */

    if (n < 4) {
        block[0] = dcdiff * s->y_dc_scale;
    } else {
        block[0] = dcdiff * s->c_dc_scale;
    }

    //AC Decoding
    i = 1;

    /* check if AC is needed at all and adjust direction if needed */
2996 2997 2998
    if (!a_avail) dc_pred_dir = 1;
    if (!c_avail) dc_pred_dir = 0;
    if (!a_avail && !c_avail) use_pred = 0;
2999 3000 3001 3002 3003
    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;
    ac_val2 = ac_val;

    scale = mquant * 2 + v->halfpq;

3004
    if (dc_pred_dir) //left
3005 3006 3007 3008
        ac_val -= 16;
    else //top
        ac_val -= 16 * s->block_wrap[n];

3009
    q1 = s->current_picture.f.qscale_table[mb_pos];
3010 3011 3012 3013 3014 3015 3016 3017 3018
    if (dc_pred_dir && c_avail && mb_pos)
        q2 = s->current_picture.f.qscale_table[mb_pos - 1];
    if (!dc_pred_dir && a_avail && mb_pos >= s->mb_stride)
        q2 = s->current_picture.f.qscale_table[mb_pos - s->mb_stride];
    if ( dc_pred_dir && n == 1)
        q2 = q1;
    if (!dc_pred_dir && n == 2)
        q2 = q1;
    if (n == 3) q2 = q1;
3019

3020
    if (coded) {
3021 3022 3023 3024 3025 3026
        int last = 0, skip, value;
        int k;

        while (!last) {
            vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);
            i += skip;
3027
            if (i > 63)
3028
                break;
3029
            if (v->fcm == PROGRESSIVE)
3030 3031
                block[v->zz_8x8[0][i++]] = value;
            else {
3032
                if (use_pred && (v->fcm == ILACE_FRAME)) {
3033
                    if (!dc_pred_dir) // top
3034
                        block[v->zz_8x8[2][i++]] = value;
3035
                    else // left
3036 3037 3038 3039 3040
                        block[v->zz_8x8[3][i++]] = value;
                } else {
                    block[v->zzi_8x8[i++]] = value;
                }
            }
3041 3042 3043
        }

        /* apply AC prediction if needed */
3044
        if (use_pred) {
3045
            /* scale predictors if needed*/
3046
            if (q2 && q1 != q2) {
3047 3048 3049
                q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

3050 3051
                if (q1 < 1)
                    return AVERROR_INVALIDDATA;
3052 3053
                if (dc_pred_dir) { // left
                    for (k = 1; k < 8; k++)
3054
                        block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
3055
                } else { //top
3056
                    for (k = 1; k < 8; k++)
3057
                        block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
3058 3059
                }
            } else {
3060 3061
                if (dc_pred_dir) { // left
                    for (k = 1; k < 8; k++)
3062
                        block[k << v->left_blk_sh] += ac_val[k];
3063 3064
                } else { // top
                    for (k = 1; k < 8; k++)
3065
                        block[k << v->top_blk_sh] += ac_val[k + 8];
3066 3067 3068 3069
                }
            }
        }
        /* save AC coeffs for further prediction */
3070
        for (k = 1; k < 8; k++) {
3071 3072
            ac_val2[k    ] = block[k << v->left_blk_sh];
            ac_val2[k + 8] = block[k << v->top_blk_sh];
3073 3074 3075
        }

        /* scale AC coeffs */
3076 3077
        for (k = 1; k < 64; k++)
            if (block[k]) {
3078
                block[k] *= scale;
3079
                if (!v->pquantizer)
3080 3081 3082
                    block[k] += (block[k] < 0) ? -mquant : mquant;
            }

3083
        if (use_pred) i = 63;
3084 3085 3086 3087
    } else { // no AC coeffs
        int k;

        memset(ac_val2, 0, 16 * 2);
3088 3089
        if (dc_pred_dir) { // left
            if (use_pred) {
3090
                memcpy(ac_val2, ac_val, 8 * 2);
3091
                if (q2 && q1 != q2) {
3092 3093
                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
3094 3095
                    if (q1 < 1)
                        return AVERROR_INVALIDDATA;
3096
                    for (k = 1; k < 8; k++)
3097 3098 3099
                        ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                }
            }
3100 3101
        } else { // top
            if (use_pred) {
3102
                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);
3103
                if (q2 && q1 != q2) {
3104 3105
                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;
                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;
3106 3107
                    if (q1 < 1)
                        return AVERROR_INVALIDDATA;
3108
                    for (k = 1; k < 8; k++)
3109 3110 3111 3112 3113 3114
                        ac_val2[k + 8] = (ac_val2[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;
                }
            }
        }

        /* apply AC prediction if needed */
3115 3116 3117
        if (use_pred) {
            if (dc_pred_dir) { // left
                for (k = 1; k < 8; k++) {
3118
                    block[k << v->left_blk_sh] = ac_val2[k] * scale;
3119
                    if (!v->pquantizer && block[k << v->left_blk_sh])
3120
                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -mquant : mquant;
3121
                }
3122 3123
            } else { // top
                for (k = 1; k < 8; k++) {
3124
                    block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;
3125
                    if (!v->pquantizer && block[k << v->top_blk_sh])
3126
                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -mquant : mquant;
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
                }
            }
            i = 63;
        }
    }
    s->block_last_index[n] = i;

    return 0;
}

/** Decode P block
 */
3139 3140 3141 3142
static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n,
                              int mquant, int ttmb, int first_block,
                              uint8_t *dst, int linesize, int skip_block,
                              int *ttmb_out)
3143 3144 3145 3146 3147 3148 3149 3150 3151
{
    MpegEncContext *s = &v->s;
    GetBitContext *gb = &s->gb;
    int i, j;
    int subblkpat = 0;
    int scale, off, idx, last, skip, value;
    int ttblk = ttmb & 7;
    int pat = 0;

3152 3153
    s->dsp.clear_block(block);

3154
    if (ttmb == -1) {
3155 3156
        ttblk = ff_vc1_ttblk_to_tt[v->tt_index][get_vlc2(gb, ff_vc1_ttblk_vlc[v->tt_index].table, VC1_TTBLK_VLC_BITS, 1)];
    }
3157
    if (ttblk == TT_4X4) {
3158 3159
        subblkpat = ~(get_vlc2(gb, ff_vc1_subblkpat_vlc[v->tt_index].table, VC1_SUBBLKPAT_VLC_BITS, 1) + 1);
    }
3160
    if ((ttblk != TT_8X8 && ttblk != TT_4X4)
3161 3162
        && ((v->ttmbf || (ttmb != -1 && (ttmb & 8) && !first_block))
            || (!v->res_rtm_flag && !first_block))) {
3163
        subblkpat = decode012(gb);
3164 3165 3166 3167 3168 3169
        if (subblkpat)
            subblkpat ^= 3; // swap decoded pattern bits
        if (ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM)
            ttblk = TT_8X4;
        if (ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT)
            ttblk = TT_4X8;
3170 3171 3172 3173
    }
    scale = 2 * mquant + ((v->pq == mquant) ? v->halfpq : 0);

    // convert transforms like 8X4_TOP to generic TT and SUBBLKPAT
3174
    if (ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) {
3175
        subblkpat = 2 - (ttblk == TT_8X4_TOP);
3176
        ttblk     = TT_8X4;
3177
    }
3178
    if (ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT) {
3179
        subblkpat = 2 - (ttblk == TT_4X8_LEFT);
3180
        ttblk     = TT_4X8;
3181
    }
3182
    switch (ttblk) {
3183
    case TT_8X8:
3184 3185
        pat  = 0xF;
        i    = 0;
3186 3187 3188 3189
        last = 0;
        while (!last) {
            vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
            i += skip;
3190
            if (i > 63)
3191
                break;
3192
            if (!v->fcm)
3193 3194 3195
                idx = v->zz_8x8[0][i++];
            else
                idx = v->zzi_8x8[i++];
3196
            block[idx] = value * scale;
3197
            if (!v->pquantizer)
3198 3199
                block[idx] += (block[idx] < 0) ? -mquant : mquant;
        }
3200 3201
        if (!skip_block) {
            if (i == 1)
3202
                v->vc1dsp.vc1_inv_trans_8x8_dc(dst, linesize, block);
3203
            else {
3204 3205
                v->vc1dsp.vc1_inv_trans_8x8(block);
                s->dsp.add_pixels_clamped(block, dst, linesize);
3206
            }
3207 3208 3209 3210
        }
        break;
    case TT_4X4:
        pat = ~subblkpat & 0xF;
3211
        for (j = 0; j < 4; j++) {
3212
            last = subblkpat & (1 << (3 - j));
3213 3214
            i    = 0;
            off  = (j & 1) * 4 + (j & 2) * 16;
3215 3216 3217
            while (!last) {
                vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
                i += skip;
3218
                if (i > 15)
3219
                    break;
3220
                if (!v->fcm)
3221 3222 3223
                    idx = ff_vc1_simple_progressive_4x4_zz[i++];
                else
                    idx = ff_vc1_adv_interlaced_4x4_zz[i++];
3224
                block[idx + off] = value * scale;
3225
                if (!v->pquantizer)
3226 3227
                    block[idx + off] += (block[idx + off] < 0) ? -mquant : mquant;
            }
3228 3229 3230
            if (!(subblkpat & (1 << (3 - j))) && !skip_block) {
                if (i == 1)
                    v->vc1dsp.vc1_inv_trans_4x4_dc(dst + (j & 1) * 4 + (j & 2) * 2 * linesize, linesize, block + off);
3231
                else
3232
                    v->vc1dsp.vc1_inv_trans_4x4(dst + (j & 1) * 4 + (j & 2) *  2 * linesize, linesize, block + off);
3233 3234 3235 3236
            }
        }
        break;
    case TT_8X4:
3237 3238
        pat = ~((subblkpat & 2) * 6 + (subblkpat & 1) * 3) & 0xF;
        for (j = 0; j < 2; j++) {
3239
            last = subblkpat & (1 << (1 - j));
3240 3241
            i    = 0;
            off  = j * 32;
3242 3243 3244
            while (!last) {
                vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
                i += skip;
3245
                if (i > 31)
3246
                    break;
3247
                if (!v->fcm)
3248 3249 3250
                    idx = v->zz_8x4[i++] + off;
                else
                    idx = ff_vc1_adv_interlaced_8x4_zz[i++] + off;
3251
                block[idx] = value * scale;
3252
                if (!v->pquantizer)
3253 3254
                    block[idx] += (block[idx] < 0) ? -mquant : mquant;
            }
3255 3256 3257
            if (!(subblkpat & (1 << (1 - j))) && !skip_block) {
                if (i == 1)
                    v->vc1dsp.vc1_inv_trans_8x4_dc(dst + j * 4 * linesize, linesize, block + off);
3258
                else
3259
                    v->vc1dsp.vc1_inv_trans_8x4(dst + j * 4 * linesize, linesize, block + off);
3260 3261 3262 3263
            }
        }
        break;
    case TT_4X8:
3264 3265
        pat = ~(subblkpat * 5) & 0xF;
        for (j = 0; j < 2; j++) {
3266
            last = subblkpat & (1 << (1 - j));
3267 3268
            i    = 0;
            off  = j * 4;
3269 3270 3271
            while (!last) {
                vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);
                i += skip;
3272
                if (i > 31)
3273
                    break;
3274
                if (!v->fcm)
3275 3276 3277
                    idx = v->zz_4x8[i++] + off;
                else
                    idx = ff_vc1_adv_interlaced_4x8_zz[i++] + off;
3278
                block[idx] = value * scale;
3279
                if (!v->pquantizer)
3280 3281
                    block[idx] += (block[idx] < 0) ? -mquant : mquant;
            }
3282 3283 3284
            if (!(subblkpat & (1 << (1 - j))) && !skip_block) {
                if (i == 1)
                    v->vc1dsp.vc1_inv_trans_4x8_dc(dst + j * 4, linesize, block + off);
3285
                else
3286
                    v->vc1dsp.vc1_inv_trans_4x8(dst + j*4, linesize, block + off);
3287 3288 3289 3290
            }
        }
        break;
    }
3291 3292
    if (ttmb_out)
        *ttmb_out |= ttblk << (n * 4);
3293 3294 3295 3296 3297 3298 3299 3300
    return pat;
}

/** @} */ // Macroblock group

static const int size_table  [6] = { 0, 2, 3, 4,  5,  8 };
static const int offset_table[6] = { 0, 1, 3, 7, 15, 31 };

3301 3302
static av_always_inline void vc1_apply_p_v_loop_filter(VC1Context *v, int block_num)
{
3303
    MpegEncContext *s  = &v->s;
3304 3305 3306 3307
    int mb_cbp         = v->cbp[s->mb_x - s->mb_stride],
        block_cbp      = mb_cbp      >> (block_num * 4), bottom_cbp,
        mb_is_intra    = v->is_intra[s->mb_x - s->mb_stride],
        block_is_intra = mb_is_intra >> (block_num * 4), bottom_is_intra;
3308
    int idx, linesize  = block_num > 3 ? s->uvlinesize : s->linesize, ttblk;
3309 3310
    uint8_t *dst;

3311
    if (block_num > 3) {
3312 3313 3314 3315
        dst      = s->dest[block_num - 3];
    } else {
        dst      = s->dest[0] + (block_num & 1) * 8 + ((block_num & 2) * 4 - 8) * linesize;
    }
3316
    if (s->mb_y != s->end_mb_y || block_num < 2) {
3317 3318 3319
        int16_t (*mv)[2];
        int mv_stride;

3320
        if (block_num > 3) {
3321 3322 3323 3324 3325
            bottom_cbp      = v->cbp[s->mb_x]      >> (block_num * 4);
            bottom_is_intra = v->is_intra[s->mb_x] >> (block_num * 4);
            mv              = &v->luma_mv[s->mb_x - s->mb_stride];
            mv_stride       = s->mb_stride;
        } else {
3326 3327 3328 3329
            bottom_cbp      = (block_num < 2) ? (mb_cbp               >> ((block_num + 2) * 4))
                                              : (v->cbp[s->mb_x]      >> ((block_num - 2) * 4));
            bottom_is_intra = (block_num < 2) ? (mb_is_intra          >> ((block_num + 2) * 4))
                                              : (v->is_intra[s->mb_x] >> ((block_num - 2) * 4));
3330
            mv_stride       = s->b8_stride;
3331
            mv              = &s->current_picture.f.motion_val[0][s->block_index[block_num] - 2 * mv_stride];
3332 3333 3334 3335 3336 3337 3338
        }

        if (bottom_is_intra & 1 || block_is_intra & 1 ||
            mv[0][0] != mv[mv_stride][0] || mv[0][1] != mv[mv_stride][1]) {
            v->vc1dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
        } else {
            idx = ((bottom_cbp >> 2) | block_cbp) & 3;
3339
            if (idx == 3) {
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350
                v->vc1dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
            } else if (idx) {
                if (idx == 1)
                    v->vc1dsp.vc1_v_loop_filter4(dst + 4, linesize, v->pq);
                else
                    v->vc1dsp.vc1_v_loop_filter4(dst,     linesize, v->pq);
            }
        }
    }

    dst -= 4 * linesize;
3351
    ttblk = (v->ttblk[s->mb_x - s->mb_stride] >> (block_num * 4)) & 0xF;
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
    if (ttblk == TT_4X4 || ttblk == TT_8X4) {
        idx = (block_cbp | (block_cbp >> 2)) & 3;
        if (idx == 3) {
            v->vc1dsp.vc1_v_loop_filter8(dst, linesize, v->pq);
        } else if (idx) {
            if (idx == 1)
                v->vc1dsp.vc1_v_loop_filter4(dst + 4, linesize, v->pq);
            else
                v->vc1dsp.vc1_v_loop_filter4(dst,     linesize, v->pq);
        }
    }
}

static av_always_inline void vc1_apply_p_h_loop_filter(VC1Context *v, int block_num)
{
3367
    MpegEncContext *s  = &v->s;
3368 3369 3370 3371
    int mb_cbp         = v->cbp[s->mb_x - 1 - s->mb_stride],
        block_cbp      = mb_cbp      >> (block_num * 4), right_cbp,
        mb_is_intra    = v->is_intra[s->mb_x - 1 - s->mb_stride],
        block_is_intra = mb_is_intra >> (block_num * 4), right_is_intra;
3372
    int idx, linesize  = block_num > 3 ? s->uvlinesize : s->linesize, ttblk;
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
    uint8_t *dst;

    if (block_num > 3) {
        dst = s->dest[block_num - 3] - 8 * linesize;
    } else {
        dst = s->dest[0] + (block_num & 1) * 8 + ((block_num & 2) * 4 - 16) * linesize - 8;
    }

    if (s->mb_x != s->mb_width || !(block_num & 5)) {
        int16_t (*mv)[2];

3384
        if (block_num > 3) {
3385 3386 3387
            right_cbp      = v->cbp[s->mb_x - s->mb_stride] >> (block_num * 4);
            right_is_intra = v->is_intra[s->mb_x - s->mb_stride] >> (block_num * 4);
            mv             = &v->luma_mv[s->mb_x - s->mb_stride - 1];
3388 3389 3390 3391 3392
        } else {
            right_cbp      = (block_num & 1) ? (v->cbp[s->mb_x - s->mb_stride]      >> ((block_num - 1) * 4))
                                             : (mb_cbp                              >> ((block_num + 1) * 4));
            right_is_intra = (block_num & 1) ? (v->is_intra[s->mb_x - s->mb_stride] >> ((block_num - 1) * 4))
                                             : (mb_is_intra                         >> ((block_num + 1) * 4));
3393
            mv             = &s->current_picture.f.motion_val[0][s->block_index[block_num] - s->b8_stride * 2 - 2];
3394 3395 3396 3397 3398 3399 3400 3401 3402
        }
        if (block_is_intra & 1 || right_is_intra & 1 || mv[0][0] != mv[1][0] || mv[0][1] != mv[1][1]) {
            v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
        } else {
            idx = ((right_cbp >> 1) | block_cbp) & 5; // FIXME check
            if (idx == 5) {
                v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
            } else if (idx) {
                if (idx == 1)
3403
                    v->vc1dsp.vc1_h_loop_filter4(dst + 4 * linesize, linesize, v->pq);
3404
                else
3405
                    v->vc1dsp.vc1_h_loop_filter4(dst,                linesize, v->pq);
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
            }
        }
    }

    dst -= 4;
    ttblk = (v->ttblk[s->mb_x - s->mb_stride - 1] >> (block_num * 4)) & 0xf;
    if (ttblk == TT_4X4 || ttblk == TT_4X8) {
        idx = (block_cbp | (block_cbp >> 1)) & 5;
        if (idx == 5) {
            v->vc1dsp.vc1_h_loop_filter8(dst, linesize, v->pq);
        } else if (idx) {
            if (idx == 1)
3418
                v->vc1dsp.vc1_h_loop_filter4(dst + linesize * 4, linesize, v->pq);
3419
            else
3420
                v->vc1dsp.vc1_h_loop_filter4(dst,                linesize, v->pq);
3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
        }
    }
}

static void vc1_apply_p_loop_filter(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    int i;

    for (i = 0; i < 6; i++) {
        vc1_apply_p_v_loop_filter(v, i);
    }

3434
    /* V always precedes H, therefore we run H one MB before V;
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
     * at the end of a row, we catch up to complete the row */
    if (s->mb_x) {
        for (i = 0; i < 6; i++) {
            vc1_apply_p_h_loop_filter(v, i);
        }
        if (s->mb_x == s->mb_width - 1) {
            s->mb_x++;
            ff_update_block_index(s);
            for (i = 0; i < 6; i++) {
                vc1_apply_p_h_loop_filter(v, i);
            }
        }
    }
}

3450
/** Decode one P-frame MB
3451 3452 3453 3454 3455
 */
static int vc1_decode_p_mb(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    GetBitContext *gb = &s->gb;
3456
    int i, j;
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int cbp; /* cbp decoding stuff */
    int mqdiff, mquant; /* MB quantization */
    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 1; /* last_flag */
    int dmv_x, dmv_y; /* Differential MV components */
    int index, index1; /* LUT indexes */
    int val, sign; /* temp values */
    int first_block = 1;
    int dst_idx, off;
    int skipped, fourmv;
3469
    int block_cbp = 0, pat, block_tt = 0, block_intra = 0;
3470

3471
    mquant = v->pq; /* lossy initialization */
3472 3473 3474 3475 3476 3477 3478 3479 3480 3481

    if (v->mv_type_is_raw)
        fourmv = get_bits1(gb);
    else
        fourmv = v->mv_type_mb_plane[mb_pos];
    if (v->skip_is_raw)
        skipped = get_bits1(gb);
    else
        skipped = v->s.mbskip_table[mb_pos];

3482 3483
    if (!fourmv) { /* 1MV mode */
        if (!skipped) {
3484 3485 3486
            GET_MVDATA(dmv_x, dmv_y);

            if (s->mb_intra) {
3487 3488
                s->current_picture.f.motion_val[1][s->block_index[0]][0] = 0;
                s->current_picture.f.motion_val[1][s->block_index[0]][1] = 0;
3489
            }
3490
            s->current_picture.f.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16;
3491
            vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0, 0);
3492 3493

            /* FIXME Set DC val for inter block ? */
3494
            if (s->mb_intra && !mb_has_coeffs) {
3495 3496
                GET_MQUANT();
                s->ac_pred = get_bits1(gb);
3497 3498
                cbp        = 0;
            } else if (mb_has_coeffs) {
3499 3500
                if (s->mb_intra)
                    s->ac_pred = get_bits1(gb);
3501 3502
                cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
                GET_MQUANT();
3503
            } else {
3504
                mquant = v->pq;
3505
                cbp    = 0;
3506
            }
3507
            s->current_picture.f.qscale_table[mb_pos] = mquant;
3508 3509 3510 3511

            if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)
                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table,
                                VC1_TTMB_VLC_BITS, 2);
3512
            if (!s->mb_intra) vc1_mc_1mv(v, 0);
3513
            dst_idx = 0;
3514
            for (i = 0; i < 6; i++) {
3515 3516 3517 3518 3519
                s->dc_val[0][s->block_index[i]] = 0;
                dst_idx += i >> 2;
                val = ((cbp >> (5 - i)) & 1);
                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
                v->mb_type[0][s->block_index[i]] = s->mb_intra;
3520
                if (s->mb_intra) {
3521 3522
                    /* check if prediction blocks A and C are available */
                    v->a_avail = v->c_avail = 0;
3523
                    if (i == 2 || i == 3 || !s->first_slice_line)
3524
                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
3525
                    if (i == 1 || i == 3 || s->mb_x)
3526 3527
                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

3528 3529 3530 3531
                    vc1_decode_intra_block(v, s->block[i], i, val, mquant,
                                           (i & 4) ? v->codingset2 : v->codingset);
                    if ((i>3) && (s->flags & CODEC_FLAG_GRAY))
                        continue;
3532
                    v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
3533 3534 3535
                    if (v->rangeredfrm)
                        for (j = 0; j < 64; j++)
                            s->block[i][j] <<= 1;
3536
                    s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
3537 3538
                    if (v->pq >= 9 && v->overlap) {
                        if (v->c_avail)
3539
                            v->vc1dsp.vc1_h_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
3540
                        if (v->a_avail)
3541
                            v->vc1dsp.vc1_v_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
3542
                    }
3543
                    block_cbp   |= 0xF << (i << 2);
3544
                    block_intra |= 1 << i;
3545 3546 3547 3548
                } else if (val) {
                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block,
                                             s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize,
                                             (i & 4) && (s->flags & CODEC_FLAG_GRAY), &block_tt);
3549
                    block_cbp |= pat << (i << 2);
3550 3551
                    if (!v->ttmbf && ttmb < 8)
                        ttmb = -1;
3552 3553 3554
                    first_block = 0;
                }
            }
3555
        } else { // skipped
3556
            s->mb_intra = 0;
3557
            for (i = 0; i < 6; i++) {
3558
                v->mb_type[0][s->block_index[i]] = 0;
3559
                s->dc_val[0][s->block_index[i]]  = 0;
3560
            }
3561
            s->current_picture.f.mb_type[mb_pos]      = MB_TYPE_SKIP;
3562
            s->current_picture.f.qscale_table[mb_pos] = 0;
3563
            vc1_pred_mv(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0, 0);
3564 3565
            vc1_mc_1mv(v, 0);
        }
3566 3567
    } else { // 4MV mode
        if (!skipped /* unskipped MB */) {
3568 3569 3570 3571
            int intra_count = 0, coded_inter = 0;
            int is_intra[6], is_coded[6];
            /* Get CBPCY */
            cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
3572
            for (i = 0; i < 6; i++) {
3573 3574
                val = ((cbp >> (5 - i)) & 1);
                s->dc_val[0][s->block_index[i]] = 0;
3575 3576
                s->mb_intra                     = 0;
                if (i < 4) {
3577
                    dmv_x = dmv_y = 0;
3578
                    s->mb_intra   = 0;
3579
                    mb_has_coeffs = 0;
3580
                    if (val) {
3581 3582
                        GET_MVDATA(dmv_x, dmv_y);
                    }
3583
                    vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], 0, 0);
3584 3585
                    if (!s->mb_intra)
                        vc1_mc_4mv_luma(v, i, 0);
3586
                    intra_count += s->mb_intra;
3587 3588
                    is_intra[i]  = s->mb_intra;
                    is_coded[i]  = mb_has_coeffs;
3589
                }
3590
                if (i & 4) {
3591 3592 3593
                    is_intra[i] = (intra_count >= 3);
                    is_coded[i] = val;
                }
3594 3595
                if (i == 4)
                    vc1_mc_4mv_chroma(v, 0);
3596
                v->mb_type[0][s->block_index[i]] = is_intra[i];
3597 3598
                if (!coded_inter)
                    coded_inter = !is_intra[i] & is_coded[i];
3599 3600 3601
            }
            // if there are no coded blocks then don't do anything more
            dst_idx = 0;
3602
            if (!intra_count && !coded_inter)
3603
                goto end;
3604
            GET_MQUANT();
3605
            s->current_picture.f.qscale_table[mb_pos] = mquant;
3606 3607 3608
            /* test if block is intra and has pred */
            {
                int intrapred = 0;
3609 3610 3611 3612
                for (i = 0; i < 6; i++)
                    if (is_intra[i]) {
                        if (((!s->first_slice_line || (i == 2 || i == 3)) && v->mb_type[0][s->block_index[i] - s->block_wrap[i]])
                            || ((s->mb_x || (i == 1 || i == 3)) && v->mb_type[0][s->block_index[i] - 1])) {
3613 3614 3615 3616
                            intrapred = 1;
                            break;
                        }
                    }
3617 3618 3619 3620
                if (intrapred)
                    s->ac_pred = get_bits1(gb);
                else
                    s->ac_pred = 0;
3621 3622 3623
            }
            if (!v->ttmbf && coded_inter)
                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
3624 3625 3626
            for (i = 0; i < 6; i++) {
                dst_idx    += i >> 2;
                off         = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
3627 3628 3629 3630
                s->mb_intra = is_intra[i];
                if (is_intra[i]) {
                    /* check if prediction blocks A and C are available */
                    v->a_avail = v->c_avail = 0;
3631
                    if (i == 2 || i == 3 || !s->first_slice_line)
3632
                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
3633
                    if (i == 1 || i == 3 || s->mb_x)
3634 3635
                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

3636 3637 3638 3639
                    vc1_decode_intra_block(v, s->block[i], i, is_coded[i], mquant,
                                           (i & 4) ? v->codingset2 : v->codingset);
                    if ((i>3) && (s->flags & CODEC_FLAG_GRAY))
                        continue;
3640
                    v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
3641 3642 3643 3644 3645 3646 3647
                    if (v->rangeredfrm)
                        for (j = 0; j < 64; j++)
                            s->block[i][j] <<= 1;
                    s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off,
                                                     (i & 4) ? s->uvlinesize : s->linesize);
                    if (v->pq >= 9 && v->overlap) {
                        if (v->c_avail)
3648
                            v->vc1dsp.vc1_h_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
3649
                        if (v->a_avail)
3650
                            v->vc1dsp.vc1_v_overlap(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
3651
                    }
3652
                    block_cbp   |= 0xF << (i << 2);
3653
                    block_intra |= 1 << i;
3654 3655 3656 3657 3658 3659
                } else if (is_coded[i]) {
                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
                                             first_block, s->dest[dst_idx] + off,
                                             (i & 4) ? s->uvlinesize : s->linesize,
                                             (i & 4) && (s->flags & CODEC_FLAG_GRAY),
                                             &block_tt);
3660
                    block_cbp |= pat << (i << 2);
3661 3662
                    if (!v->ttmbf && ttmb < 8)
                        ttmb = -1;
3663 3664 3665
                    first_block = 0;
                }
            }
3666 3667
        } else { // skipped MB
            s->mb_intra                               = 0;
3668
            s->current_picture.f.qscale_table[mb_pos] = 0;
3669
            for (i = 0; i < 6; i++) {
3670
                v->mb_type[0][s->block_index[i]] = 0;
3671
                s->dc_val[0][s->block_index[i]]  = 0;
3672
            }
3673
            for (i = 0; i < 4; i++) {
3674 3675
                vc1_pred_mv(v, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0], 0, 0);
                vc1_mc_4mv_luma(v, i, 0);
3676
            }
3677
            vc1_mc_4mv_chroma(v, 0);
3678
            s->current_picture.f.qscale_table[mb_pos] = 0;
3679 3680
        }
    }
3681
end:
3682 3683
    v->cbp[s->mb_x]      = block_cbp;
    v->ttblk[s->mb_x]    = block_tt;
3684
    v->is_intra[s->mb_x] = block_intra;
3685

3686
    return 0;
3687 3688
}

3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
/* Decode one macroblock in an interlaced frame p picture */

static int vc1_decode_p_mb_intfr(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    GetBitContext *gb = &s->gb;
    int i;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int cbp = 0; /* cbp decoding stuff */
    int mqdiff, mquant; /* MB quantization */
    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 1; /* last_flag */
    int dmv_x, dmv_y; /* Differential MV components */
    int val; /* temp value */
    int first_block = 1;
    int dst_idx, off;
    int skipped, fourmv = 0, twomv = 0;
    int block_cbp = 0, pat, block_tt = 0;
    int idx_mbmode = 0, mvbp;
    int stride_y, fieldtx;

Lou Logan's avatar
Lou Logan committed
3711
    mquant = v->pq; /* Lossy initialization */
3712 3713 3714 3715 3716 3717 3718 3719 3720

    if (v->skip_is_raw)
        skipped = get_bits1(gb);
    else
        skipped = v->s.mbskip_table[mb_pos];
    if (!skipped) {
        if (v->fourmvswitch)
            idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_4MV_MBMODE_VLC_BITS, 2); // try getting this done
        else
3721
            idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); // in a single line
3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
        switch (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0]) {
        /* store the motion vector type in a flag (useful later) */
        case MV_PMODE_INTFR_4MV:
            fourmv = 1;
            v->blk_mv_type[s->block_index[0]] = 0;
            v->blk_mv_type[s->block_index[1]] = 0;
            v->blk_mv_type[s->block_index[2]] = 0;
            v->blk_mv_type[s->block_index[3]] = 0;
            break;
        case MV_PMODE_INTFR_4MV_FIELD:
            fourmv = 1;
            v->blk_mv_type[s->block_index[0]] = 1;
            v->blk_mv_type[s->block_index[1]] = 1;
            v->blk_mv_type[s->block_index[2]] = 1;
            v->blk_mv_type[s->block_index[3]] = 1;
            break;
        case MV_PMODE_INTFR_2MV_FIELD:
            twomv = 1;
            v->blk_mv_type[s->block_index[0]] = 1;
            v->blk_mv_type[s->block_index[1]] = 1;
            v->blk_mv_type[s->block_index[2]] = 1;
            v->blk_mv_type[s->block_index[3]] = 1;
            break;
        case MV_PMODE_INTFR_1MV:
            v->blk_mv_type[s->block_index[0]] = 0;
            v->blk_mv_type[s->block_index[1]] = 0;
            v->blk_mv_type[s->block_index[2]] = 0;
            v->blk_mv_type[s->block_index[3]] = 0;
            break;
        }
        if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB
            s->current_picture.f.motion_val[1][s->block_index[0]][0] = 0;
            s->current_picture.f.motion_val[1][s->block_index[0]][1] = 0;
3755
            s->current_picture.f.mb_type[mb_pos]                     = MB_TYPE_INTRA;
3756
            s->mb_intra = v->is_intra[s->mb_x] = 1;
3757 3758
            for (i = 0; i < 6; i++)
                v->mb_type[0][s->block_index[i]] = 1;
3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
            fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb);
            mb_has_coeffs = get_bits1(gb);
            if (mb_has_coeffs)
                cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
            v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);
            GET_MQUANT();
            s->current_picture.f.qscale_table[mb_pos] = mquant;
            /* Set DC scale - y and c use the same (not sure if necessary here) */
            s->y_dc_scale = s->y_dc_scale_table[mquant];
            s->c_dc_scale = s->c_dc_scale_table[mquant];
            dst_idx = 0;
3770
            for (i = 0; i < 6; i++) {
3771 3772 3773 3774 3775
                s->dc_val[0][s->block_index[i]] = 0;
                dst_idx += i >> 2;
                val = ((cbp >> (5 - i)) & 1);
                v->mb_type[0][s->block_index[i]] = s->mb_intra;
                v->a_avail = v->c_avail = 0;
3776
                if (i == 2 || i == 3 || !s->first_slice_line)
3777
                    v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
3778
                if (i == 1 || i == 3 || s->mb_x)
3779 3780
                    v->c_avail = v->mb_type[0][s->block_index[i] - 1];

3781 3782 3783
                vc1_decode_intra_block(v, s->block[i], i, val, mquant,
                                       (i & 4) ? v->codingset2 : v->codingset);
                if ((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;
3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
                v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
                if (i < 4) {
                    stride_y = s->linesize << fieldtx;
                    off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize;
                } else {
                    stride_y = s->uvlinesize;
                    off = 0;
                }
                s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, stride_y);
                //TODO: loop filter
            }

3796
        } else { // inter MB
3797 3798 3799 3800 3801 3802 3803
            mb_has_coeffs = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][3];
            if (mb_has_coeffs)
                cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
            if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {
                v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1);
            } else {
                if ((ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV)
3804
                    || (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV_FIELD)) {
3805 3806 3807 3808
                    v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
                }
            }
            s->mb_intra = v->is_intra[s->mb_x] = 0;
3809 3810
            for (i = 0; i < 6; i++)
                v->mb_type[0][s->block_index[i]] = 0;
3811 3812 3813 3814 3815
            fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][1];
            /* for all motion vector read MVDATA and motion compensate each block */
            dst_idx = 0;
            if (fourmv) {
                mvbp = v->fourmvbp;
3816
                for (i = 0; i < 6; i++) {
3817 3818
                    if (i < 4) {
                        dmv_x = dmv_y = 0;
3819 3820
                        val   = ((mvbp >> (3 - i)) & 1);
                        if (val) {
3821 3822 3823 3824 3825 3826 3827 3828 3829
                            get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
                        }
                        vc1_pred_mv_intfr(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]);
                        vc1_mc_4mv_luma(v, i, 0);
                    } else if (i == 4) {
                        vc1_mc_4mv_chroma4(v);
                    }
                }
            } else if (twomv) {
3830
                mvbp  = v->twomvbp;
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
                dmv_x = dmv_y = 0;
                if (mvbp & 2) {
                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
                }
                vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0]);
                vc1_mc_4mv_luma(v, 0, 0);
                vc1_mc_4mv_luma(v, 1, 0);
                dmv_x = dmv_y = 0;
                if (mvbp & 1) {
                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
                }
                vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0]);
                vc1_mc_4mv_luma(v, 2, 0);
                vc1_mc_4mv_luma(v, 3, 0);
                vc1_mc_4mv_chroma4(v);
            } else {
                mvbp = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][2];
3848
                dmv_x = dmv_y = 0;
3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
                if (mvbp) {
                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);
                }
                vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]);
                vc1_mc_1mv(v, 0);
            }
            if (cbp)
                GET_MQUANT();  // p. 227
            s->current_picture.f.qscale_table[mb_pos] = mquant;
            if (!v->ttmbf && cbp)
                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
3860
            for (i = 0; i < 6; i++) {
3861 3862 3863 3864 3865 3866 3867 3868
                s->dc_val[0][s->block_index[i]] = 0;
                dst_idx += i >> 2;
                val = ((cbp >> (5 - i)) & 1);
                if (!fieldtx)
                    off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
                else
                    off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize));
                if (val) {
3869 3870 3871 3872
                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
                                             first_block, s->dest[dst_idx] + off,
                                             (i & 4) ? s->uvlinesize : (s->linesize << fieldtx),
                                             (i & 4) && (s->flags & CODEC_FLAG_GRAY), &block_tt);
3873 3874 3875 3876 3877 3878 3879 3880 3881
                    block_cbp |= pat << (i << 2);
                    if (!v->ttmbf && ttmb < 8)
                        ttmb = -1;
                    first_block = 0;
                }
            }
        }
    } else { // skipped
        s->mb_intra = v->is_intra[s->mb_x] = 0;
3882
        for (i = 0; i < 6; i++) {
3883 3884 3885
            v->mb_type[0][s->block_index[i]] = 0;
            s->dc_val[0][s->block_index[i]] = 0;
        }
3886
        s->current_picture.f.mb_type[mb_pos]      = MB_TYPE_SKIP;
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914
        s->current_picture.f.qscale_table[mb_pos] = 0;
        v->blk_mv_type[s->block_index[0]] = 0;
        v->blk_mv_type[s->block_index[1]] = 0;
        v->blk_mv_type[s->block_index[2]] = 0;
        v->blk_mv_type[s->block_index[3]] = 0;
        vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]);
        vc1_mc_1mv(v, 0);
    }
    if (s->mb_x == s->mb_width - 1)
        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0])*s->mb_stride);
    return 0;
}

static int vc1_decode_p_mb_intfi(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    GetBitContext *gb = &s->gb;
    int i;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int cbp = 0; /* cbp decoding stuff */
    int mqdiff, mquant; /* MB quantization */
    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 1; /* last_flag */
    int dmv_x, dmv_y; /* Differential MV components */
    int val; /* temp values */
    int first_block = 1;
    int dst_idx, off;
3915
    int pred_flag = 0;
3916 3917 3918
    int block_cbp = 0, pat, block_tt = 0;
    int idx_mbmode = 0;

Lou Logan's avatar
Lou Logan committed
3919
    mquant = v->pq; /* Lossy initialization */
3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931

    idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);
    if (idx_mbmode <= 1) { // intra MB
        s->mb_intra = v->is_intra[s->mb_x] = 1;
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;
        s->current_picture.f.mb_type[mb_pos + v->mb_off] = MB_TYPE_INTRA;
        GET_MQUANT();
        s->current_picture.f.qscale_table[mb_pos] = mquant;
        /* Set DC scale - y and c use the same (not sure if necessary here) */
        s->y_dc_scale = s->y_dc_scale_table[mquant];
        s->c_dc_scale = s->c_dc_scale_table[mquant];
3932
        v->s.ac_pred  = v->acpred_plane[mb_pos] = get_bits1(gb);
3933 3934 3935 3936
        mb_has_coeffs = idx_mbmode & 1;
        if (mb_has_coeffs)
            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2);
        dst_idx = 0;
3937 3938
        for (i = 0; i < 6; i++) {
            s->dc_val[0][s->block_index[i]]  = 0;
3939 3940 3941 3942
            v->mb_type[0][s->block_index[i]] = 1;
            dst_idx += i >> 2;
            val = ((cbp >> (5 - i)) & 1);
            v->a_avail = v->c_avail = 0;
3943
            if (i == 2 || i == 3 || !s->first_slice_line)
3944
                v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
3945
            if (i == 1 || i == 3 || s->mb_x)
3946 3947
                v->c_avail = v->mb_type[0][s->block_index[i] - 1];

3948 3949 3950 3951
            vc1_decode_intra_block(v, s->block[i], i, val, mquant,
                                   (i & 4) ? v->codingset2 : v->codingset);
            if ((i>3) && (s->flags & CODEC_FLAG_GRAY))
                continue;
3952
            v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
3953
            off  = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
3954
            off += v->second_field ? ((i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0]) : 0;
3955
            s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize);
3956
            // TODO: loop filter
3957 3958 3959 3960 3961 3962
        }
    } else {
        s->mb_intra = v->is_intra[s->mb_x] = 0;
        s->current_picture.f.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;
        for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;
        if (idx_mbmode <= 5) { // 1-MV
3963
            dmv_x = dmv_y = pred_flag = 0;
3964 3965 3966 3967 3968 3969 3970 3971
            if (idx_mbmode & 1) {
                get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);
            }
            vc1_pred_mv(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);
            vc1_mc_1mv(v, 0);
            mb_has_coeffs = !(idx_mbmode & 2);
        } else { // 4-MV
            v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
3972
            for (i = 0; i < 6; i++) {
3973 3974
                if (i < 4) {
                    dmv_x = dmv_y = pred_flag = 0;
3975 3976
                    val   = ((v->fourmvbp >> (3 - i)) & 1);
                    if (val) {
3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
                        get_mvdata_interlaced(v, &dmv_x, &dmv_y, &pred_flag);
                    }
                    vc1_pred_mv(v, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0], pred_flag, 0);
                    vc1_mc_4mv_luma(v, i, 0);
                } else if (i == 4)
                    vc1_mc_4mv_chroma(v, 0);
            }
            mb_has_coeffs = idx_mbmode & 1;
        }
        if (mb_has_coeffs)
            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
        if (cbp) {
            GET_MQUANT();
        }
        s->current_picture.f.qscale_table[mb_pos] = mquant;
        if (!v->ttmbf && cbp) {
            ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
        }
        dst_idx = 0;
3996
        for (i = 0; i < 6; i++) {
3997 3998 3999 4000
            s->dc_val[0][s->block_index[i]] = 0;
            dst_idx += i >> 2;
            val = ((cbp >> (5 - i)) & 1);
            off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;
4001
            if (v->second_field)
4002
                off += (i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0];
4003 4004 4005 4006 4007 4008
            if (val) {
                pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
                                         first_block, s->dest[dst_idx] + off,
                                         (i & 4) ? s->uvlinesize : s->linesize,
                                         (i & 4) && (s->flags & CODEC_FLAG_GRAY),
                                         &block_tt);
4009
                block_cbp |= pat << (i << 2);
4010
                if (!v->ttmbf && ttmb < 8) ttmb = -1;
4011 4012 4013 4014 4015
                first_block = 0;
            }
        }
    }
    if (s->mb_x == s->mb_width - 1)
4016
        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);
4017 4018 4019
    return 0;
}

4020 4021 4022 4023 4024 4025
/** Decode one B-frame MB (in Main profile)
 */
static void vc1_decode_b_mb(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    GetBitContext *gb = &s->gb;
4026
    int i, j;
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int cbp = 0; /* cbp decoding stuff */
    int mqdiff, mquant; /* MB quantization */
    int ttmb = v->ttfrm; /* MB Transform type */
    int mb_has_coeffs = 0; /* last_flag */
    int index, index1; /* LUT indexes */
    int val, sign; /* temp values */
    int first_block = 1;
    int dst_idx, off;
    int skipped, direct;
    int dmv_x[2], dmv_y[2];
    int bmvtype = BMV_TYPE_BACKWARD;

4040
    mquant      = v->pq; /* lossy initialization */
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052
    s->mb_intra = 0;

    if (v->dmb_is_raw)
        direct = get_bits1(gb);
    else
        direct = v->direct_mb_plane[mb_pos];
    if (v->skip_is_raw)
        skipped = get_bits1(gb);
    else
        skipped = v->s.mbskip_table[mb_pos];

    dmv_x[0] = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0;
4053
    for (i = 0; i < 6; i++) {
4054
        v->mb_type[0][s->block_index[i]] = 0;
4055
        s->dc_val[0][s->block_index[i]]  = 0;
4056
    }
4057
    s->current_picture.f.qscale_table[mb_pos] = 0;
4058 4059 4060 4061 4062 4063 4064

    if (!direct) {
        if (!skipped) {
            GET_MVDATA(dmv_x[0], dmv_y[0]);
            dmv_x[1] = dmv_x[0];
            dmv_y[1] = dmv_y[0];
        }
4065
        if (skipped || !s->mb_intra) {
4066
            bmvtype = decode012(gb);
4067
            switch (bmvtype) {
4068 4069 4070 4071 4072 4073 4074
            case 0:
                bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD;
                break;
            case 1:
                bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD;
                break;
            case 2:
4075
                bmvtype  = BMV_TYPE_INTERPOLATED;
4076 4077 4078 4079
                dmv_x[0] = dmv_y[0] = 0;
            }
        }
    }
4080
    for (i = 0; i < 6; i++)
4081 4082 4083
        v->mb_type[0][s->block_index[i]] = s->mb_intra;

    if (skipped) {
4084 4085
        if (direct)
            bmvtype = BMV_TYPE_INTERPOLATED;
4086 4087 4088 4089 4090 4091 4092 4093
        vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
        vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
        return;
    }
    if (direct) {
        cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
        GET_MQUANT();
        s->mb_intra = 0;
4094
        s->current_picture.f.qscale_table[mb_pos] = mquant;
4095
        if (!v->ttmbf)
4096 4097 4098 4099 4100
            ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
        dmv_x[0] = dmv_y[0] = dmv_x[1] = dmv_y[1] = 0;
        vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
        vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
    } else {
4101
        if (!mb_has_coeffs && !s->mb_intra) {
4102 4103 4104 4105 4106
            /* no coded blocks - effectively skipped */
            vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
            vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
            return;
        }
4107
        if (s->mb_intra && !mb_has_coeffs) {
4108
            GET_MQUANT();
4109
            s->current_picture.f.qscale_table[mb_pos] = mquant;
4110 4111 4112 4113
            s->ac_pred = get_bits1(gb);
            cbp = 0;
            vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
        } else {
4114
            if (bmvtype == BMV_TYPE_INTERPOLATED) {
4115
                GET_MVDATA(dmv_x[0], dmv_y[0]);
4116
                if (!mb_has_coeffs) {
4117 4118 4119 4120 4121 4122 4123
                    /* interpolated skipped block */
                    vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
                    vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
                    return;
                }
            }
            vc1_pred_b_mv(v, dmv_x, dmv_y, direct, bmvtype);
4124
            if (!s->mb_intra) {
4125 4126
                vc1_b_mc(v, dmv_x, dmv_y, direct, bmvtype);
            }
4127
            if (s->mb_intra)
4128 4129 4130
                s->ac_pred = get_bits1(gb);
            cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
            GET_MQUANT();
4131
            s->current_picture.f.qscale_table[mb_pos] = mquant;
4132
            if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)
4133 4134 4135 4136
                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
        }
    }
    dst_idx = 0;
4137
    for (i = 0; i < 6; i++) {
4138 4139 4140 4141 4142
        s->dc_val[0][s->block_index[i]] = 0;
        dst_idx += i >> 2;
        val = ((cbp >> (5 - i)) & 1);
        off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
        v->mb_type[0][s->block_index[i]] = s->mb_intra;
4143
        if (s->mb_intra) {
4144 4145
            /* check if prediction blocks A and C are available */
            v->a_avail = v->c_avail = 0;
4146
            if (i == 2 || i == 3 || !s->first_slice_line)
4147
                v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
4148
            if (i == 1 || i == 3 || s->mb_x)
4149 4150
                v->c_avail = v->mb_type[0][s->block_index[i] - 1];

4151 4152 4153 4154
            vc1_decode_intra_block(v, s->block[i], i, val, mquant,
                                   (i & 4) ? v->codingset2 : v->codingset);
            if ((i>3) && (s->flags & CODEC_FLAG_GRAY))
                continue;
4155
            v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
4156 4157 4158
            if (v->rangeredfrm)
                for (j = 0; j < 64; j++)
                    s->block[i][j] <<= 1;
4159
            s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize);
4160 4161 4162 4163 4164 4165 4166
        } else if (val) {
            vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
                               first_block, s->dest[dst_idx] + off,
                               (i & 4) ? s->uvlinesize : s->linesize,
                               (i & 4) && (s->flags & CODEC_FLAG_GRAY), NULL);
            if (!v->ttmbf && ttmb < 8)
                ttmb = -1;
4167 4168 4169 4170 4171
            first_block = 0;
        }
    }
}

4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191
/** Decode one B-frame MB (in interlaced field B picture)
 */
static void vc1_decode_b_mb_intfi(VC1Context *v)
{
    MpegEncContext *s = &v->s;
    GetBitContext *gb = &s->gb;
    int i, j;
    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;
    int cbp = 0; /* cbp decoding stuff */
    int mqdiff, mquant; /* MB quantization */
    int ttmb = v->ttfrm; /* MB Transform type */
    int mb_has_coeffs = 0; /* last_flag */
    int val; /* temp value */
    int first_block = 1;
    int dst_idx, off;
    int fwd;
    int dmv_x[2], dmv_y[2], pred_flag[2];
    int bmvtype = BMV_TYPE_BACKWARD;
    int idx_mbmode, interpmvp;

Lou Logan's avatar
Lou Logan committed
4192
    mquant      = v->pq; /* Lossy initialization */
4193 4194 4195 4196 4197 4198 4199
    s->mb_intra = 0;

    idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_IF_MBMODE_VLC_BITS, 2);
    if (idx_mbmode <= 1) { // intra MB
        s->mb_intra = v->is_intra[s->mb_x] = 1;
        s->current_picture.f.motion_val[1][s->block_index[0]][0] = 0;
        s->current_picture.f.motion_val[1][s->block_index[0]][1] = 0;
4200
        s->current_picture.f.mb_type[mb_pos + v->mb_off]         = MB_TYPE_INTRA;
4201 4202 4203 4204 4205
        GET_MQUANT();
        s->current_picture.f.qscale_table[mb_pos] = mquant;
        /* Set DC scale - y and c use the same (not sure if necessary here) */
        s->y_dc_scale = s->y_dc_scale_table[mquant];
        s->c_dc_scale = s->c_dc_scale_table[mquant];
4206
        v->s.ac_pred  = v->acpred_plane[mb_pos] = get_bits1(gb);
4207 4208 4209 4210
        mb_has_coeffs = idx_mbmode & 1;
        if (mb_has_coeffs)
            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_ICBPCY_VLC_BITS, 2);
        dst_idx = 0;
4211
        for (i = 0; i < 6; i++) {
4212 4213 4214 4215
            s->dc_val[0][s->block_index[i]] = 0;
            dst_idx += i >> 2;
            val = ((cbp >> (5 - i)) & 1);
            v->mb_type[0][s->block_index[i]] = s->mb_intra;
4216 4217
            v->a_avail                       = v->c_avail = 0;
            if (i == 2 || i == 3 || !s->first_slice_line)
4218
                v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];
4219
            if (i == 1 || i == 3 || s->mb_x)
4220 4221
                v->c_avail = v->mb_type[0][s->block_index[i] - 1];

4222 4223 4224 4225
            vc1_decode_intra_block(v, s->block[i], i, val, mquant,
                                   (i & 4) ? v->codingset2 : v->codingset);
            if ((i>3) && (s->flags & CODEC_FLAG_GRAY))
                continue;
4226
            v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);
4227 4228 4229 4230
            if (v->rangeredfrm)
                for (j = 0; j < 64; j++)
                    s->block[i][j] <<= 1;
            off  = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);
4231
            off += v->second_field ? ((i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0]) : 0;
4232
            s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i & 4) ? s->uvlinesize : s->linesize);
4233
            // TODO: yet to perform loop filter
4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
        }
    } else {
        s->mb_intra = v->is_intra[s->mb_x] = 0;
        s->current_picture.f.mb_type[mb_pos + v->mb_off] = MB_TYPE_16x16;
        for (i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;
        if (v->fmb_is_raw)
            fwd = v->forward_mb_plane[mb_pos] = get_bits1(gb);
        else
            fwd = v->forward_mb_plane[mb_pos];
        if (idx_mbmode <= 5) { // 1-MV
4244
            dmv_x[0]     = dmv_x[1] = dmv_y[0] = dmv_y[1] = 0;
4245 4246 4247 4248 4249
            pred_flag[0] = pred_flag[1] = 0;
            if (fwd)
                bmvtype = BMV_TYPE_FORWARD;
            else {
                bmvtype = decode012(gb);
4250
                switch (bmvtype) {
4251 4252 4253 4254 4255 4256 4257
                case 0:
                    bmvtype = BMV_TYPE_BACKWARD;
                    break;
                case 1:
                    bmvtype = BMV_TYPE_DIRECT;
                    break;
                case 2:
4258
                    bmvtype   = BMV_TYPE_INTERPOLATED;
4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278
                    interpmvp = get_bits1(gb);
                }
            }
            v->bmvtype = bmvtype;
            if (bmvtype != BMV_TYPE_DIRECT && idx_mbmode & 1) {
                get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD], &dmv_y[bmvtype == BMV_TYPE_BACKWARD], &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);
            }
            if (bmvtype == BMV_TYPE_INTERPOLATED && interpmvp) {
                get_mvdata_interlaced(v, &dmv_x[1], &dmv_y[1], &pred_flag[1]);
            }
            if (bmvtype == BMV_TYPE_DIRECT) {
                dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;
                dmv_x[1] = dmv_y[1] = pred_flag[0] = 0;
            }
            vc1_pred_b_mv_intfi(v, 0, dmv_x, dmv_y, 1, pred_flag);
            vc1_b_mc(v, dmv_x, dmv_y, (bmvtype == BMV_TYPE_DIRECT), bmvtype);
            mb_has_coeffs = !(idx_mbmode & 2);
        } else { // 4-MV
            if (fwd)
                bmvtype = BMV_TYPE_FORWARD;
4279
            v->bmvtype  = bmvtype;
4280
            v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);
4281
            for (i = 0; i < 6; i++) {
4282 4283 4284 4285
                if (i < 4) {
                    dmv_x[0] = dmv_y[0] = pred_flag[0] = 0;
                    dmv_x[1] = dmv_y[1] = pred_flag[1] = 0;
                    val = ((v->fourmvbp >> (3 - i)) & 1);
4286 4287 4288 4289
                    if (val) {
                        get_mvdata_interlaced(v, &dmv_x[bmvtype == BMV_TYPE_BACKWARD],
                                                 &dmv_y[bmvtype == BMV_TYPE_BACKWARD],
                                             &pred_flag[bmvtype == BMV_TYPE_BACKWARD]);
4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307
                    }
                    vc1_pred_b_mv_intfi(v, i, dmv_x, dmv_y, 0, pred_flag);
                    vc1_mc_4mv_luma(v, i, bmvtype == BMV_TYPE_BACKWARD);
                } else if (i == 4)
                    vc1_mc_4mv_chroma(v, bmvtype == BMV_TYPE_BACKWARD);
            }
            mb_has_coeffs = idx_mbmode & 1;
        }
        if (mb_has_coeffs)
            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);
        if (cbp) {
            GET_MQUANT();
        }
        s->current_picture.f.qscale_table[mb_pos] = mquant;
        if (!v->ttmbf && cbp) {
            ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);
        }
        dst_idx = 0;
4308
        for (i = 0; i < 6; i++) {
4309 4310 4311 4312
            s->dc_val[0][s->block_index[i]] = 0;
            dst_idx += i >> 2;
            val = ((cbp >> (5 - i)) & 1);
            off = (i & 4) ? 0 : (i & 1) * 8 + (i & 2) * 4 * s->linesize;
4313
            if (v->second_field)
4314
                off += (i & 4) ? s->current_picture_ptr->f.linesize[1] : s->current_picture_ptr->f.linesize[0];
4315 4316 4317 4318 4319 4320
            if (val) {
                vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,
                                   first_block, s->dest[dst_idx] + off,
                                   (i & 4) ? s->uvlinesize : s->linesize,
                                   (i & 4) && (s->flags & CODEC_FLAG_GRAY), NULL);
                if (!v->ttmbf && ttmb < 8)
4321 4322 4323 4324 4325 4326 4327
                    ttmb = -1;
                first_block = 0;
            }
        }
    }
}

4328 4329 4330 4331
/** Decode blocks of I-frame
 */
static void vc1_decode_i_blocks(VC1Context *v)
{
4332
    int k, j;
4333 4334 4335 4336 4337 4338
    MpegEncContext *s = &v->s;
    int cbp, val;
    uint8_t *coded_val;
    int mb_pos;

    /* select codingmode used for VLC tables selection */
4339
    switch (v->y_ac_table_index) {
4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350
    case 0:
        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
        break;
    case 1:
        v->codingset = CS_HIGH_MOT_INTRA;
        break;
    case 2:
        v->codingset = CS_MID_RATE_INTRA;
        break;
    }

4351
    switch (v->c_ac_table_index) {
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368
    case 0:
        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
        break;
    case 1:
        v->codingset2 = CS_HIGH_MOT_INTER;
        break;
    case 2:
        v->codingset2 = CS_MID_RATE_INTER;
        break;
    }

    /* Set DC scale - y and c use the same */
    s->y_dc_scale = s->y_dc_scale_table[v->pq];
    s->c_dc_scale = s->c_dc_scale_table[v->pq];

    //do frame decode
    s->mb_x = s->mb_y = 0;
4369
    s->mb_intra         = 1;
4370
    s->first_slice_line = 1;
Alberto Delmás's avatar
Alberto Delmás committed
4371
    for (s->mb_y = 0; s->mb_y < s->end_mb_y; s->mb_y++) {
4372 4373
        s->mb_x = 0;
        ff_init_block_index(s);
Alberto Delmás's avatar
Alberto Delmás committed
4374
        for (; s->mb_x < v->end_mb_x; s->mb_x++) {
4375
            uint8_t *dst[6];
4376
            ff_update_block_index(s);
4377 4378 4379 4380 4381 4382
            dst[0] = s->dest[0];
            dst[1] = dst[0] + 8;
            dst[2] = s->dest[0] + s->linesize * 8;
            dst[3] = dst[2] + 8;
            dst[4] = s->dest[1];
            dst[5] = s->dest[2];
4383 4384
            s->dsp.clear_blocks(s->block[0]);
            mb_pos = s->mb_x + s->mb_y * s->mb_width;
4385 4386
            s->current_picture.f.mb_type[mb_pos]                     = MB_TYPE_INTRA;
            s->current_picture.f.qscale_table[mb_pos]                = v->pq;
4387 4388
            s->current_picture.f.motion_val[1][s->block_index[0]][0] = 0;
            s->current_picture.f.motion_val[1][s->block_index[0]][1] = 0;
4389 4390 4391 4392 4393

            // do actual MB decoding and displaying
            cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);
            v->s.ac_pred = get_bits1(&v->s.gb);

4394
            for (k = 0; k < 6; k++) {
4395 4396 4397
                val = ((cbp >> (5 - k)) & 1);

                if (k < 4) {
4398 4399
                    int pred   = vc1_coded_block_pred(&v->s, k, &coded_val);
                    val        = val ^ pred;
4400 4401 4402 4403
                    *coded_val = val;
                }
                cbp |= val << (5 - k);

4404
                vc1_decode_i_block(v, s->block[k], k, val, (k < 4) ? v->codingset : v->codingset2);
4405

4406 4407
                if (k > 3 && (s->flags & CODEC_FLAG_GRAY))
                    continue;
4408
                v->vc1dsp.vc1_inv_trans_8x8(s->block[k]);
4409 4410 4411 4412
                if (v->pq >= 9 && v->overlap) {
                    if (v->rangeredfrm)
                        for (j = 0; j < 64; j++)
                            s->block[k][j] <<= 1;
4413 4414
                    s->dsp.put_signed_pixels_clamped(s->block[k], dst[k], k & 4 ? s->uvlinesize : s->linesize);
                } else {
4415 4416 4417
                    if (v->rangeredfrm)
                        for (j = 0; j < 64; j++)
                            s->block[k][j] = (s->block[k][j] - 64) << 1;
4418 4419
                    s->dsp.put_pixels_clamped(s->block[k], dst[k], k & 4 ? s->uvlinesize : s->linesize);
                }
4420 4421
            }

4422 4423
            if (v->pq >= 9 && v->overlap) {
                if (s->mb_x) {
4424 4425
                    v->vc1dsp.vc1_h_overlap(s->dest[0], s->linesize);
                    v->vc1dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
4426
                    if (!(s->flags & CODEC_FLAG_GRAY)) {
4427 4428
                        v->vc1dsp.vc1_h_overlap(s->dest[1], s->uvlinesize);
                        v->vc1dsp.vc1_h_overlap(s->dest[2], s->uvlinesize);
4429 4430
                    }
                }
4431 4432
                v->vc1dsp.vc1_h_overlap(s->dest[0] + 8, s->linesize);
                v->vc1dsp.vc1_h_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
4433
                if (!s->first_slice_line) {
4434 4435
                    v->vc1dsp.vc1_v_overlap(s->dest[0], s->linesize);
                    v->vc1dsp.vc1_v_overlap(s->dest[0] + 8, s->linesize);
4436
                    if (!(s->flags & CODEC_FLAG_GRAY)) {
4437 4438
                        v->vc1dsp.vc1_v_overlap(s->dest[1], s->uvlinesize);
                        v->vc1dsp.vc1_v_overlap(s->dest[2], s->uvlinesize);
4439 4440
                    }
                }
4441 4442
                v->vc1dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize, s->linesize);
                v->vc1dsp.vc1_v_overlap(s->dest[0] + 8 * s->linesize + 8, s->linesize);
4443
            }
4444
            if (v->s.loop_filter) vc1_loop_filter_iblk(v, v->pq);
4445

4446
            if (get_bits_count(&s->gb) > v->bits) {
4447
                ff_er_add_slice(s, 0, 0, s->mb_x, s->mb_y, ER_MB_ERROR);
4448 4449
                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n",
                       get_bits_count(&s->gb), v->bits);
4450 4451 4452
                return;
            }
        }
4453 4454 4455
        if (!v->s.loop_filter)
            ff_draw_horiz_band(s, s->mb_y * 16, 16);
        else if (s->mb_y)
4456
            ff_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
4457

4458 4459
        s->first_slice_line = 0;
    }
4460
    if (v->s.loop_filter)
Alberto Delmás's avatar
Alberto Delmás committed
4461 4462 4463 4464
        ff_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);

    /* This is intentionally mb_height and not end_mb_y - unlike in advanced
     * profile, these only differ are when decoding MSS2 rectangles. */
4465
    ff_er_add_slice(s, 0, 0, s->mb_width - 1, s->mb_height - 1, ER_MB_END);
4466 4467 4468 4469
}

/** Decode blocks of I-frame for advanced profile
 */
4470
static void vc1_decode_i_blocks_adv(VC1Context *v)
4471
{
4472
    int k;
4473 4474 4475 4476 4477 4478 4479 4480 4481
    MpegEncContext *s = &v->s;
    int cbp, val;
    uint8_t *coded_val;
    int mb_pos;
    int mquant = v->pq;
    int mqdiff;
    GetBitContext *gb = &s->gb;

    /* select codingmode used for VLC tables selection */
4482
    switch (v->y_ac_table_index) {
4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493
    case 0:
        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
        break;
    case 1:
        v->codingset = CS_HIGH_MOT_INTRA;
        break;
    case 2:
        v->codingset = CS_MID_RATE_INTRA;
        break;
    }

4494
    switch (v->c_ac_table_index) {
4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
    case 0:
        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
        break;
    case 1:
        v->codingset2 = CS_HIGH_MOT_INTER;
        break;
    case 2:
        v->codingset2 = CS_MID_RATE_INTER;
        break;
    }

4506 4507 4508
    // do frame decode
    s->mb_x             = s->mb_y = 0;
    s->mb_intra         = 1;
4509
    s->first_slice_line = 1;
4510
    s->mb_y             = s->start_mb_y;
4511
    if (s->start_mb_y) {
Ronald S. Bultje's avatar
Ronald S. Bultje committed
4512 4513
        s->mb_x = 0;
        ff_init_block_index(s);
4514
        memset(&s->coded_block[s->block_index[0] - s->b8_stride], 0,
4515
               (1 + s->b8_stride) * sizeof(*s->coded_block));
Ronald S. Bultje's avatar
Ronald S. Bultje committed
4516
    }
4517
    for (; s->mb_y < s->end_mb_y; s->mb_y++) {
4518 4519
        s->mb_x = 0;
        ff_init_block_index(s);
4520
        for (;s->mb_x < s->mb_width; s->mb_x++) {
4521
            DCTELEM (*block)[64] = v->block[v->cur_blk_idx];
4522
            ff_update_block_index(s);
4523
            s->dsp.clear_blocks(block[0]);
4524
            mb_pos = s->mb_x + s->mb_y * s->mb_stride;
4525
            s->current_picture.f.mb_type[mb_pos + v->mb_off]                         = MB_TYPE_INTRA;
4526 4527
            s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;
            s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;
4528 4529

            // do actual MB decoding and displaying
4530 4531
            if (v->fieldtx_is_raw)
                v->fieldtx_plane[mb_pos] = get_bits1(&v->s.gb);
4532
            cbp = get_vlc2(&v->s.gb, ff_msmp4_mb_i_vlc.table, MB_INTRA_VLC_BITS, 2);
4533
            if ( v->acpred_is_raw)
4534 4535 4536 4537
                v->s.ac_pred = get_bits1(&v->s.gb);
            else
                v->s.ac_pred = v->acpred_plane[mb_pos];

4538 4539
            if (v->condover == CONDOVER_SELECT && v->overflg_is_raw)
                v->over_flags_plane[mb_pos] = get_bits1(&v->s.gb);
4540 4541 4542

            GET_MQUANT();

4543
            s->current_picture.f.qscale_table[mb_pos] = mquant;
4544 4545 4546 4547
            /* Set DC scale - y and c use the same */
            s->y_dc_scale = s->y_dc_scale_table[mquant];
            s->c_dc_scale = s->c_dc_scale_table[mquant];

4548
            for (k = 0; k < 6; k++) {
4549 4550 4551
                val = ((cbp >> (5 - k)) & 1);

                if (k < 4) {
4552 4553
                    int pred   = vc1_coded_block_pred(&v->s, k, &coded_val);
                    val        = val ^ pred;
4554 4555 4556 4557
                    *coded_val = val;
                }
                cbp |= val << (5 - k);

4558 4559
                v->a_avail = !s->first_slice_line || (k == 2 || k == 3);
                v->c_avail = !!s->mb_x || (k == 1 || k == 3);
4560

4561 4562
                vc1_decode_i_block_adv(v, block[k], k, val,
                                       (k < 4) ? v->codingset : v->codingset2, mquant);
4563

4564 4565
                if (k > 3 && (s->flags & CODEC_FLAG_GRAY))
                    continue;
4566
                v->vc1dsp.vc1_inv_trans_8x8(block[k]);
4567 4568
            }

4569 4570
            vc1_smooth_overlap_filter_iblk(v);
            vc1_put_signed_blocks_clamped(v);
4571
            if (v->s.loop_filter) vc1_loop_filter_iblk_delayed(v, v->pq);
4572

4573
            if (get_bits_count(&s->gb) > v->bits) {
4574
                // TODO: may need modification to handle slice coding
4575
                ff_er_add_slice(s, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);
4576 4577
                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i\n",
                       get_bits_count(&s->gb), v->bits);
4578 4579 4580
                return;
            }
        }
4581 4582 4583 4584
        if (!v->s.loop_filter)
            ff_draw_horiz_band(s, s->mb_y * 16, 16);
        else if (s->mb_y)
            ff_draw_horiz_band(s, (s->mb_y-1) * 16, 16);
4585 4586
        s->first_slice_line = 0;
    }
4587 4588 4589 4590

    /* raw bottom MB row */
    s->mb_x = 0;
    ff_init_block_index(s);
4591
    for (;s->mb_x < s->mb_width; s->mb_x++) {
4592 4593
        ff_update_block_index(s);
        vc1_put_signed_blocks_clamped(v);
4594 4595
        if (v->s.loop_filter)
            vc1_loop_filter_iblk_delayed(v, v->pq);
4596
    }
4597
    if (v->s.loop_filter)
4598
        ff_draw_horiz_band(s, (s->end_mb_y-1)*16, 16);
4599
    ff_er_add_slice(s, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
4600
                    (s->end_mb_y << v->field_mode) - 1, ER_MB_END);
4601 4602
}

4603
static void vc1_decode_p_blocks(VC1Context *v)
4604 4605
{
    MpegEncContext *s = &v->s;
4606
    int apply_loop_filter;
4607 4608

    /* select codingmode used for VLC tables selection */
4609
    switch (v->c_ac_table_index) {
4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620
    case 0:
        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
        break;
    case 1:
        v->codingset = CS_HIGH_MOT_INTRA;
        break;
    case 2:
        v->codingset = CS_MID_RATE_INTRA;
        break;
    }

4621
    switch (v->c_ac_table_index) {
4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632
    case 0:
        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
        break;
    case 1:
        v->codingset2 = CS_HIGH_MOT_INTER;
        break;
    case 2:
        v->codingset2 = CS_MID_RATE_INTER;
        break;
    }

4633
    apply_loop_filter   = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY);
4634 4635
    s->first_slice_line = 1;
    memset(v->cbp_base, 0, sizeof(v->cbp_base[0])*2*s->mb_stride);
4636
    for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
4637 4638
        s->mb_x = 0;
        ff_init_block_index(s);
4639
        for (; s->mb_x < s->mb_width; s->mb_x++) {
4640 4641
            ff_update_block_index(s);

4642
            if (v->fcm == ILACE_FIELD)
4643
                vc1_decode_p_mb_intfi(v);
4644
            else if (v->fcm == ILACE_FRAME)
4645 4646
                vc1_decode_p_mb_intfr(v);
            else vc1_decode_p_mb(v);
4647
            if (s->mb_y != s->start_mb_y && apply_loop_filter && v->fcm == PROGRESSIVE)
4648
                vc1_apply_p_loop_filter(v);
4649
            if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {
4650
                // TODO: may need modification to handle slice coding
4651
                ff_er_add_slice(s, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);
4652 4653
                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n",
                       get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y);
4654 4655 4656
                return;
            }
        }
4657 4658 4659 4660 4661
        memmove(v->cbp_base,      v->cbp,      sizeof(v->cbp_base[0])      * s->mb_stride);
        memmove(v->ttblk_base,    v->ttblk,    sizeof(v->ttblk_base[0])    * s->mb_stride);
        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);
        memmove(v->luma_mv_base,  v->luma_mv,  sizeof(v->luma_mv_base[0])  * s->mb_stride);
        if (s->mb_y != s->start_mb_y) ff_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
4662 4663
        s->first_slice_line = 0;
    }
4664
    if (apply_loop_filter && v->fcm == PROGRESSIVE) {
4665 4666 4667 4668 4669 4670 4671
        s->mb_x = 0;
        ff_init_block_index(s);
        for (; s->mb_x < s->mb_width; s->mb_x++) {
            ff_update_block_index(s);
            vc1_apply_p_loop_filter(v);
        }
    }
4672
    if (s->end_mb_y >= s->start_mb_y)
4673 4674
        ff_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
    ff_er_add_slice(s, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
4675
                    (s->end_mb_y << v->field_mode) - 1, ER_MB_END);
4676 4677
}

4678
static void vc1_decode_b_blocks(VC1Context *v)
4679 4680 4681 4682
{
    MpegEncContext *s = &v->s;

    /* select codingmode used for VLC tables selection */
4683
    switch (v->c_ac_table_index) {
4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694
    case 0:
        v->codingset = (v->pqindex <= 8) ? CS_HIGH_RATE_INTRA : CS_LOW_MOT_INTRA;
        break;
    case 1:
        v->codingset = CS_HIGH_MOT_INTRA;
        break;
    case 2:
        v->codingset = CS_MID_RATE_INTRA;
        break;
    }

4695
    switch (v->c_ac_table_index) {
4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707
    case 0:
        v->codingset2 = (v->pqindex <= 8) ? CS_HIGH_RATE_INTER : CS_LOW_MOT_INTER;
        break;
    case 1:
        v->codingset2 = CS_HIGH_MOT_INTER;
        break;
    case 2:
        v->codingset2 = CS_MID_RATE_INTER;
        break;
    }

    s->first_slice_line = 1;
4708
    for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
4709 4710
        s->mb_x = 0;
        ff_init_block_index(s);
4711
        for (; s->mb_x < s->mb_width; s->mb_x++) {
4712 4713
            ff_update_block_index(s);

4714
            if (v->fcm == ILACE_FIELD)
4715 4716 4717
                vc1_decode_b_mb_intfi(v);
            else
                vc1_decode_b_mb(v);
4718
            if (get_bits_count(&s->gb) > v->bits || get_bits_count(&s->gb) < 0) {
4719
                // TODO: may need modification to handle slice coding
4720
                ff_er_add_slice(s, 0, s->start_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR);
4721 4722
                av_log(s->avctx, AV_LOG_ERROR, "Bits overconsumption: %i > %i at %ix%i\n",
                       get_bits_count(&s->gb), v->bits, s->mb_x, s->mb_y);
4723 4724
                return;
            }
4725
            if (v->s.loop_filter) vc1_loop_filter_iblk(v, v->pq);
4726
        }
4727 4728 4729
        if (!v->s.loop_filter)
            ff_draw_horiz_band(s, s->mb_y * 16, 16);
        else if (s->mb_y)
4730
            ff_draw_horiz_band(s, (s->mb_y - 1) * 16, 16);
4731 4732
        s->first_slice_line = 0;
    }
4733
    if (v->s.loop_filter)
4734 4735
        ff_draw_horiz_band(s, (s->end_mb_y - 1) * 16, 16);
    ff_er_add_slice(s, 0, s->start_mb_y << v->field_mode, s->mb_width - 1,
4736
                    (s->end_mb_y << v->field_mode) - 1, ER_MB_END);
4737 4738 4739 4740 4741 4742
}

static void vc1_decode_skip_blocks(VC1Context *v)
{
    MpegEncContext *s = &v->s;

4743
    ff_er_add_slice(s, 0, s->start_mb_y, s->mb_width - 1, s->end_mb_y - 1, ER_MB_END);
4744
    s->first_slice_line = 1;
4745
    for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
4746 4747 4748
        s->mb_x = 0;
        ff_init_block_index(s);
        ff_update_block_index(s);
4749 4750 4751 4752 4753
        if (s->last_picture.f.data[0]) {
            memcpy(s->dest[0], s->last_picture.f.data[0] + s->mb_y * 16 * s->linesize,   s->linesize   * 16);
            memcpy(s->dest[1], s->last_picture.f.data[1] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);
            memcpy(s->dest[2], s->last_picture.f.data[2] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);
        }
4754 4755 4756
        ff_draw_horiz_band(s, s->mb_y * 16, 16);
        s->first_slice_line = 0;
    }
4757
    s->pict_type = AV_PICTURE_TYPE_P;
4758 4759
}

4760
void ff_vc1_decode_blocks(VC1Context *v)
4761 4762 4763
{

    v->s.esc3_level_length = 0;
4764 4765 4766 4767 4768 4769 4770 4771
    if (v->x8_type) {
        ff_intrax8_decode_picture(&v->x8, 2*v->pq + v->halfpq, v->pq * !v->pquantizer);
    } else {
        v->cur_blk_idx     =  0;
        v->left_blk_idx    = -1;
        v->topleft_blk_idx =  1;
        v->top_blk_idx     =  2;
        switch (v->s.pict_type) {
4772
        case AV_PICTURE_TYPE_I:
4773
            if (v->profile == PROFILE_ADVANCED)
4774
                vc1_decode_i_blocks_adv(v);
4775 4776 4777
            else
                vc1_decode_i_blocks(v);
            break;
4778
        case AV_PICTURE_TYPE_P:
4779
            if (v->p_frame_skipped)
4780 4781
                vc1_decode_skip_blocks(v);
            else
4782
                vc1_decode_p_blocks(v);
4783
            break;
4784
        case AV_PICTURE_TYPE_B:
4785 4786
            if (v->bi_type) {
                if (v->profile == PROFILE_ADVANCED)
4787
                    vc1_decode_i_blocks_adv(v);
4788 4789
                else
                    vc1_decode_i_blocks(v);
4790
            } else
4791
                vc1_decode_b_blocks(v);
4792 4793 4794 4795 4796
            break;
        }
    }
}

4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818
#if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER

typedef struct {
    /**
     * Transform coefficients for both sprites in 16.16 fixed point format,
     * in the order they appear in the bitstream:
     *  x scale
     *  rotation 1 (unused)
     *  x offset
     *  rotation 2 (unused)
     *  y scale
     *  y offset
     *  alpha
     */
    int coefs[2][7];

    int effect_type, effect_flag;
    int effect_pcount1, effect_pcount2;   ///< amount of effect parameters stored in effect_params
    int effect_params1[15], effect_params2[10]; ///< effect parameters in 16.16 fixed point format
} SpriteData;

static inline int get_fp_val(GetBitContext* gb)
4819
{
4820
    return (get_bits_long(gb, 30) - (1 << 29)) << 1;
4821 4822
}

4823
static void vc1_sprite_parse_transform(GetBitContext* gb, int c[7])
4824
{
4825
    c[1] = c[3] = 0;
4826 4827 4828

    switch (get_bits(gb, 2)) {
    case 0:
4829
        c[0] = 1 << 16;
4830
        c[2] = get_fp_val(gb);
4831
        c[4] = 1 << 16;
4832 4833
        break;
    case 1:
4834 4835
        c[0] = c[4] = get_fp_val(gb);
        c[2] = get_fp_val(gb);
4836 4837
        break;
    case 2:
4838 4839 4840
        c[0] = get_fp_val(gb);
        c[2] = get_fp_val(gb);
        c[4] = get_fp_val(gb);
4841 4842
        break;
    case 3:
4843 4844 4845 4846 4847
        c[0] = get_fp_val(gb);
        c[1] = get_fp_val(gb);
        c[2] = get_fp_val(gb);
        c[3] = get_fp_val(gb);
        c[4] = get_fp_val(gb);
4848 4849
        break;
    }
4850
    c[5] = get_fp_val(gb);
4851
    if (get_bits1(gb))
4852
        c[6] = get_fp_val(gb);
4853
    else
4854
        c[6] = 1 << 16;
4855 4856
}

4857
static void vc1_parse_sprites(VC1Context *v, GetBitContext* gb, SpriteData* sd)
4858
{
4859 4860 4861 4862 4863 4864 4865 4866
    AVCodecContext *avctx = v->s.avctx;
    int sprite, i;

    for (sprite = 0; sprite <= v->two_sprites; sprite++) {
        vc1_sprite_parse_transform(gb, sd->coefs[sprite]);
        if (sd->coefs[sprite][1] || sd->coefs[sprite][3])
            av_log_ask_for_sample(avctx, "Rotation coefficients are not zero");
        av_log(avctx, AV_LOG_DEBUG, sprite ? "S2:" : "S1:");
4867
        for (i = 0; i < 7; i++)
4868 4869
            av_log(avctx, AV_LOG_DEBUG, " %d.%.3d",
                   sd->coefs[sprite][i] / (1<<16),
4870
                   (abs(sd->coefs[sprite][i]) & 0xFFFF) * 1000 / (1 << 16));
4871
        av_log(avctx, AV_LOG_DEBUG, "\n");
4872
    }
4873

4874
    skip_bits(gb, 2);
4875 4876
    if (sd->effect_type = get_bits_long(gb, 30)) {
        switch (sd->effect_pcount1 = get_bits(gb, 4)) {
4877
        case 7:
4878
            vc1_sprite_parse_transform(gb, sd->effect_params1);
4879 4880
            break;
        case 14:
4881 4882
            vc1_sprite_parse_transform(gb, sd->effect_params1);
            vc1_sprite_parse_transform(gb, sd->effect_params1 + 7);
4883 4884
            break;
        default:
4885 4886
            for (i = 0; i < sd->effect_pcount1; i++)
                sd->effect_params1[i] = get_fp_val(gb);
4887
        }
4888
        if (sd->effect_type != 13 || sd->effect_params1[0] != sd->coefs[0][6]) {
4889
            // effect 13 is simple alpha blending and matches the opacity above
4890 4891 4892
            av_log(avctx, AV_LOG_DEBUG, "Effect: %d; params: ", sd->effect_type);
            for (i = 0; i < sd->effect_pcount1; i++)
                av_log(avctx, AV_LOG_DEBUG, " %d.%.2d",
4893 4894
                       sd->effect_params1[i] / (1 << 16),
                       (abs(sd->effect_params1[i]) & 0xFFFF) * 1000 / (1 << 16));
4895
            av_log(avctx, AV_LOG_DEBUG, "\n");
4896 4897
        }

4898 4899 4900
        sd->effect_pcount2 = get_bits(gb, 16);
        if (sd->effect_pcount2 > 10) {
            av_log(avctx, AV_LOG_ERROR, "Too many effect parameters\n");
4901
            return;
4902 4903 4904
        } else if (sd->effect_pcount2) {
            i = -1;
            av_log(avctx, AV_LOG_DEBUG, "Effect params 2: ");
4905
            while (++i < sd->effect_pcount2) {
4906 4907
                sd->effect_params2[i] = get_fp_val(gb);
                av_log(avctx, AV_LOG_DEBUG, " %d.%.2d",
4908 4909
                       sd->effect_params2[i] / (1 << 16),
                       (abs(sd->effect_params2[i]) & 0xFFFF) * 1000 / (1 << 16));
4910
            }
4911
            av_log(avctx, AV_LOG_DEBUG, "\n");
4912 4913
        }
    }
4914 4915
    if (sd->effect_flag = get_bits1(gb))
        av_log(avctx, AV_LOG_DEBUG, "Effect flag set\n");
4916 4917

    if (get_bits_count(gb) >= gb->size_in_bits +
4918
       (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE ? 64 : 0))
4919
        av_log(avctx, AV_LOG_ERROR, "Buffer overrun\n");
4920
    if (get_bits_count(gb) < gb->size_in_bits - 8)
4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935
        av_log(avctx, AV_LOG_WARNING, "Buffer not fully read\n");
}

static void vc1_draw_sprites(VC1Context *v, SpriteData* sd)
{
    int i, plane, row, sprite;
    int sr_cache[2][2] = { { -1, -1 }, { -1, -1 } };
    uint8_t* src_h[2][2];
    int xoff[2], xadv[2], yoff[2], yadv[2], alpha;
    int ysub[2];
    MpegEncContext *s = &v->s;

    for (i = 0; i < 2; i++) {
        xoff[i] = av_clip(sd->coefs[i][2], 0, v->sprite_width-1 << 16);
        xadv[i] = sd->coefs[i][0];
4936
        if (xadv[i] != 1<<16 || (v->sprite_width << 16) - (v->output_width << 16) - xoff[i])
4937 4938 4939
            xadv[i] = av_clip(xadv[i], 0, ((v->sprite_width<<16) - xoff[i] - 1) / v->output_width);

        yoff[i] = av_clip(sd->coefs[i][5], 0, v->sprite_height-1 << 16);
4940
        yadv[i] = av_clip(sd->coefs[i][4], 0, ((v->sprite_height << 16) - yoff[i]) / v->output_height);
4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953
    }
    alpha = av_clip(sd->coefs[1][6], 0, (1<<16) - 1);

    for (plane = 0; plane < (s->flags&CODEC_FLAG_GRAY ? 1 : 3); plane++) {
        int width = v->output_width>>!!plane;

        for (row = 0; row < v->output_height>>!!plane; row++) {
            uint8_t *dst = v->sprite_output_frame.data[plane] +
                           v->sprite_output_frame.linesize[plane] * row;

            for (sprite = 0; sprite <= v->two_sprites; sprite++) {
                uint8_t *iplane = s->current_picture.f.data[plane];
                int      iline  = s->current_picture.f.linesize[plane];
4954 4955
                int      ycoord = yoff[sprite] + yadv[sprite] * row;
                int      yline  = ycoord >> 16;
4956
                int      next_line;
4957
                ysub[sprite] = ycoord & 0xFFFF;
4958 4959 4960 4961
                if (sprite) {
                    iplane = s->last_picture.f.data[plane];
                    iline  = s->last_picture.f.linesize[plane];
                }
4962
                next_line = FFMIN(yline + 1, (v->sprite_height >> !!plane) - 1) * iline;
4963 4964
                if (!(xoff[sprite] & 0xFFFF) && xadv[sprite] == 1 << 16) {
                        src_h[sprite][0] = iplane + (xoff[sprite] >> 16) +  yline      * iline;
4965
                    if (ysub[sprite])
4966
                        src_h[sprite][1] = iplane + (xoff[sprite] >> 16) + next_line;
4967 4968 4969 4970 4971 4972
                } else {
                    if (sr_cache[sprite][0] != yline) {
                        if (sr_cache[sprite][1] == yline) {
                            FFSWAP(uint8_t*, v->sr_rows[sprite][0], v->sr_rows[sprite][1]);
                            FFSWAP(int,        sr_cache[sprite][0],   sr_cache[sprite][1]);
                        } else {
4973
                            v->vc1dsp.sprite_h(v->sr_rows[sprite][0], iplane + yline * iline, xoff[sprite], xadv[sprite], width);
4974 4975 4976 4977
                            sr_cache[sprite][0] = yline;
                        }
                    }
                    if (ysub[sprite] && sr_cache[sprite][1] != yline + 1) {
4978 4979 4980
                        v->vc1dsp.sprite_h(v->sr_rows[sprite][1],
                                           iplane + next_line, xoff[sprite],
                                           xadv[sprite], width);
4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
                        sr_cache[sprite][1] = yline + 1;
                    }
                    src_h[sprite][0] = v->sr_rows[sprite][0];
                    src_h[sprite][1] = v->sr_rows[sprite][1];
                }
            }

            if (!v->two_sprites) {
                if (ysub[0]) {
                    v->vc1dsp.sprite_v_single(dst, src_h[0][0], src_h[0][1], ysub[0], width);
                } else {
                    memcpy(dst, src_h[0][0], width);
                }
            } else {
                if (ysub[0] && ysub[1]) {
                    v->vc1dsp.sprite_v_double_twoscale(dst, src_h[0][0], src_h[0][1], ysub[0],
                                                       src_h[1][0], src_h[1][1], ysub[1], alpha, width);
                } else if (ysub[0]) {
                    v->vc1dsp.sprite_v_double_onescale(dst, src_h[0][0], src_h[0][1], ysub[0],
                                                       src_h[1][0], alpha, width);
                } else if (ysub[1]) {
                    v->vc1dsp.sprite_v_double_onescale(dst, src_h[1][0], src_h[1][1], ysub[1],
                                                       src_h[0][0], (1<<16)-1-alpha, width);
                } else {
                    v->vc1dsp.sprite_v_double_noscale(dst, src_h[0][0], src_h[1][0], alpha, width);
                }
            }
        }

        if (!plane) {
            for (i = 0; i < 2; i++) {
                xoff[i] >>= 1;
                yoff[i] >>= 1;
            }
        }

    }
}


static int vc1_decode_sprites(VC1Context *v, GetBitContext* gb)
{
5023
    MpegEncContext *s     = &v->s;
5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043
    AVCodecContext *avctx = s->avctx;
    SpriteData sd;

    vc1_parse_sprites(v, gb, &sd);

    if (!s->current_picture.f.data[0]) {
        av_log(avctx, AV_LOG_ERROR, "Got no sprites\n");
        return -1;
    }

    if (v->two_sprites && (!s->last_picture_ptr || !s->last_picture.f.data[0])) {
        av_log(avctx, AV_LOG_WARNING, "Need two sprites, only got one\n");
        v->two_sprites = 0;
    }

    if (v->sprite_output_frame.data[0])
        avctx->release_buffer(avctx, &v->sprite_output_frame);

    v->sprite_output_frame.buffer_hints = FF_BUFFER_HINTS_VALID;
    v->sprite_output_frame.reference = 0;
5044
    if (ff_get_buffer(avctx, &v->sprite_output_frame) < 0) {
5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return -1;
    }

    vc1_draw_sprites(v, &sd);

    return 0;
}

static void vc1_sprite_flush(AVCodecContext *avctx)
{
5056
    VC1Context *v     = avctx->priv_data;
5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067
    MpegEncContext *s = &v->s;
    AVFrame *f = &s->current_picture.f;
    int plane, i;

    /* Windows Media Image codecs have a convergence interval of two keyframes.
       Since we can't enforce it, clear to black the missing sprite. This is
       wrong but it looks better than doing nothing. */

    if (f->data[0])
        for (plane = 0; plane < (s->flags&CODEC_FLAG_GRAY ? 1 : 3); plane++)
            for (i = 0; i < v->sprite_height>>!!plane; i++)
5068
                memset(f->data[plane] + i * f->linesize[plane],
5069
                       plane ? 128 : 0, f->linesize[plane]);
5070 5071
}

5072 5073
#endif

5074
av_cold int ff_vc1_decode_init_alloc_tables(VC1Context *v)
5075 5076 5077 5078 5079
{
    MpegEncContext *s = &v->s;
    int i;

    /* Allocate mb bitplanes */
5080 5081 5082 5083 5084 5085
    v->mv_type_mb_plane = av_malloc (s->mb_stride * s->mb_height);
    v->direct_mb_plane  = av_malloc (s->mb_stride * s->mb_height);
    v->forward_mb_plane = av_malloc (s->mb_stride * s->mb_height);
    v->fieldtx_plane    = av_mallocz(s->mb_stride * s->mb_height);
    v->acpred_plane     = av_malloc (s->mb_stride * s->mb_height);
    v->over_flags_plane = av_malloc (s->mb_stride * s->mb_height);
5086 5087

    v->n_allocated_blks = s->mb_width + 2;
5088 5089 5090 5091 5092 5093 5094 5095 5096
    v->block            = av_malloc(sizeof(*v->block) * v->n_allocated_blks);
    v->cbp_base         = av_malloc(sizeof(v->cbp_base[0]) * 2 * s->mb_stride);
    v->cbp              = v->cbp_base + s->mb_stride;
    v->ttblk_base       = av_malloc(sizeof(v->ttblk_base[0]) * 2 * s->mb_stride);
    v->ttblk            = v->ttblk_base + s->mb_stride;
    v->is_intra_base    = av_mallocz(sizeof(v->is_intra_base[0]) * 2 * s->mb_stride);
    v->is_intra         = v->is_intra_base + s->mb_stride;
    v->luma_mv_base     = av_malloc(sizeof(v->luma_mv_base[0]) * 2 * s->mb_stride);
    v->luma_mv          = v->luma_mv_base + s->mb_stride;
5097 5098 5099

    /* allocate block type info in that way so it could be used with s->block_index[] */
    v->mb_type_base = av_malloc(s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);
5100 5101 5102
    v->mb_type[0]   = v->mb_type_base + s->b8_stride + 1;
    v->mb_type[1]   = v->mb_type_base + s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride + 1;
    v->mb_type[2]   = v->mb_type[1] + s->mb_stride * (s->mb_height + 1);
5103

5104
    /* allocate memory to store block level MV info */
5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115
    v->blk_mv_type_base = av_mallocz(     s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);
    v->blk_mv_type      = v->blk_mv_type_base + s->b8_stride + 1;
    v->mv_f_base        = av_mallocz(2 * (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2));
    v->mv_f[0]          = v->mv_f_base + s->b8_stride + 1;
    v->mv_f[1]          = v->mv_f[0] + (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);
    v->mv_f_last_base   = av_mallocz(2 * (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2));
    v->mv_f_last[0]     = v->mv_f_last_base + s->b8_stride + 1;
    v->mv_f_last[1]     = v->mv_f_last[0] + (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);
    v->mv_f_next_base   = av_mallocz(2 * (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2));
    v->mv_f_next[0]     = v->mv_f_next_base + s->b8_stride + 1;
    v->mv_f_next[1]     = v->mv_f_next[0] + (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);
5116

5117
    /* Init coded blocks info */
5118
    if (v->profile == PROFILE_ADVANCED) {
5119 5120 5121 5122 5123 5124 5125 5126
//        if (alloc_bitplane(&v->over_flags_plane, s->mb_width, s->mb_height) < 0)
//            return -1;
//        if (alloc_bitplane(&v->ac_pred_plane, s->mb_width, s->mb_height) < 0)
//            return -1;
    }

    ff_intrax8_common_init(&v->x8,s);

5127
    if (s->avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || s->avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
5128
        for (i = 0; i < 4; i++)
5129
            if (!(v->sr_rows[i >> 1][i & 1] = av_malloc(v->output_width))) return -1;
5130 5131 5132 5133 5134 5135 5136 5137 5138 5139
    }

    if (!v->mv_type_mb_plane || !v->direct_mb_plane || !v->acpred_plane || !v->over_flags_plane ||
        !v->block || !v->cbp_base || !v->ttblk_base || !v->is_intra_base || !v->luma_mv_base ||
        !v->mb_type_base)
            return -1;

    return 0;
}

5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
av_cold void ff_vc1_init_transposed_scantables(VC1Context *v)
{
    int i;
    for (i = 0; i < 64; i++) {
#define transpose(x) ((x >> 3) | ((x & 7) << 3))
        v->zz_8x8[0][i] = transpose(ff_wmv1_scantable[0][i]);
        v->zz_8x8[1][i] = transpose(ff_wmv1_scantable[1][i]);
        v->zz_8x8[2][i] = transpose(ff_wmv1_scantable[2][i]);
        v->zz_8x8[3][i] = transpose(ff_wmv1_scantable[3][i]);
        v->zzi_8x8[i]   = transpose(ff_vc1_adv_interlaced_8x8_zz[i]);
    }
    v->left_blk_sh = 0;
    v->top_blk_sh  = 3;
}

5155 5156 5157 5158 5159 5160 5161 5162 5163 5164
/** Initialize a VC1/WMV3 decoder
 * @todo TODO: Handle VC-1 IDUs (Transport level?)
 * @todo TODO: Decypher remaining bits in extra_data
 */
static av_cold int vc1_decode_init(AVCodecContext *avctx)
{
    VC1Context *v = avctx->priv_data;
    MpegEncContext *s = &v->s;
    GetBitContext gb;

5165 5166 5167 5168
    /* save the container output size for WMImage */
    v->output_width  = avctx->width;
    v->output_height = avctx->height;

5169 5170
    if (!avctx->extradata_size || !avctx->extradata)
        return -1;
5171 5172 5173
    if (!(avctx->flags & CODEC_FLAG_GRAY))
        avctx->pix_fmt = avctx->get_format(avctx, avctx->codec->pix_fmts);
    else
5174
        avctx->pix_fmt = AV_PIX_FMT_GRAY8;
5175 5176 5177
    avctx->hwaccel = ff_find_hwaccel(avctx->codec->id, avctx->pix_fmt);
    v->s.avctx = avctx;
    avctx->flags |= CODEC_FLAG_EMU_EDGE;
5178
    v->s.flags   |= CODEC_FLAG_EMU_EDGE;
5179

5180 5181
    if (avctx->idct_algo == FF_IDCT_AUTO) {
        avctx->idct_algo = FF_IDCT_WMV2;
5182 5183
    }

5184
    if (ff_vc1_init_common(v) < 0)
5185
        return -1;
5186 5187 5188 5189 5190 5191 5192 5193 5194
    // ensure static VLC tables are initialized
    if (ff_msmpeg4_decode_init(avctx) < 0)
        return -1;
    if (ff_vc1_decode_init_alloc_tables(v) < 0)
        return -1;
    // Hack to ensure the above functions will be called
    // again once we know all necessary settings.
    // That this is necessary might indicate a bug.
    ff_vc1_decode_end(avctx);
5195
    ff_vc1dsp_init(&v->vc1dsp);
5196

5197
    if (avctx->codec_id == AV_CODEC_ID_WMV3 || avctx->codec_id == AV_CODEC_ID_WMV3IMAGE) {
5198 5199 5200 5201 5202 5203 5204 5205 5206
        int count = 0;

        // looks like WMV3 has a sequence header stored in the extradata
        // advanced sequence header may be before the first frame
        // the last byte of the extradata is a version number, 1 for the
        // samples we can decode

        init_get_bits(&gb, avctx->extradata, avctx->extradata_size*8);

5207
        if (ff_vc1_decode_sequence_header(avctx, v, &gb) < 0)
5208 5209 5210
          return -1;

        count = avctx->extradata_size*8 - get_bits_count(&gb);
5211
        if (count > 0) {
5212 5213
            av_log(avctx, AV_LOG_INFO, "Extra data: %i bits left, value: %X\n",
                   count, get_bits(&gb, count));
5214
        } else if (count < 0) {
5215 5216
            av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count);
        }
5217
    } else { // VC1/WVC1/WVP2
5218 5219 5220 5221 5222 5223 5224
        const uint8_t *start = avctx->extradata;
        uint8_t *end = avctx->extradata + avctx->extradata_size;
        const uint8_t *next;
        int size, buf2_size;
        uint8_t *buf2 = NULL;
        int seq_initialized = 0, ep_initialized = 0;

5225
        if (avctx->extradata_size < 16) {
5226 5227 5228 5229
            av_log(avctx, AV_LOG_ERROR, "Extradata size too small: %i\n", avctx->extradata_size);
            return -1;
        }

5230
        buf2  = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
5231
        start = find_next_marker(start, end); // in WVC1 extradata first byte is its size, but can be 0 in mkv
5232 5233
        next  = start;
        for (; next < end; start = next) {
5234 5235
            next = find_next_marker(start + 4, end);
            size = next - start - 4;
5236 5237
            if (size <= 0)
                continue;
5238 5239
            buf2_size = vc1_unescape_buffer(start + 4, size, buf2);
            init_get_bits(&gb, buf2, buf2_size * 8);
5240
            switch (AV_RB32(start)) {
5241
            case VC1_CODE_SEQHDR:
5242
                if (ff_vc1_decode_sequence_header(avctx, v, &gb) < 0) {
5243 5244 5245 5246 5247 5248
                    av_free(buf2);
                    return -1;
                }
                seq_initialized = 1;
                break;
            case VC1_CODE_ENTRYPOINT:
5249
                if (ff_vc1_decode_entry_point(avctx, v, &gb) < 0) {
5250 5251 5252 5253 5254 5255 5256 5257
                    av_free(buf2);
                    return -1;
                }
                ep_initialized = 1;
                break;
            }
        }
        av_free(buf2);
5258
        if (!seq_initialized || !ep_initialized) {
5259 5260 5261
            av_log(avctx, AV_LOG_ERROR, "Incomplete extradata\n");
            return -1;
        }
5262
        v->res_sprite = (avctx->codec_tag == MKTAG('W','V','P','2'));
5263
    }
5264

5265 5266 5267 5268
    avctx->profile = v->profile;
    if (v->profile == PROFILE_ADVANCED)
        avctx->level = v->level;

5269
    avctx->has_b_frames = !!avctx->max_b_frames;
5270

5271 5272
    s->mb_width  = (avctx->coded_width  + 15) >> 4;
    s->mb_height = (avctx->coded_height + 15) >> 4;
5273

5274
    if (v->profile == PROFILE_ADVANCED || v->res_fasttx) {
5275
        ff_vc1_init_transposed_scantables(v);
5276
    } else {
5277
        memcpy(v->zz_8x8, ff_wmv1_scantable, 4*64);
5278 5279 5280 5281
        v->left_blk_sh = 3;
        v->top_blk_sh  = 0;
    }

5282
    if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
5283 5284 5285 5286 5287 5288 5289
        v->sprite_width  = avctx->coded_width;
        v->sprite_height = avctx->coded_height;

        avctx->coded_width  = avctx->width  = v->output_width;
        avctx->coded_height = avctx->height = v->output_height;

        // prevent 16.16 overflows
5290 5291 5292 5293
        if (v->sprite_width  > 1 << 14 ||
            v->sprite_height > 1 << 14 ||
            v->output_width  > 1 << 14 ||
            v->output_height > 1 << 14) return -1;
5294
    }
5295 5296 5297
    return 0;
}

5298 5299 5300
/** Close a VC1/WMV3 decoder
 * @warning Initial try at using MpegEncContext stuff
 */
5301
av_cold int ff_vc1_decode_end(AVCodecContext *avctx)
5302 5303 5304 5305
{
    VC1Context *v = avctx->priv_data;
    int i;

5306
    if ((avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE)
5307 5308 5309
        && v->sprite_output_frame.data[0])
        avctx->release_buffer(avctx, &v->sprite_output_frame);
    for (i = 0; i < 4; i++)
5310
        av_freep(&v->sr_rows[i >> 1][i & 1]);
5311 5312
    av_freep(&v->hrd_rate);
    av_freep(&v->hrd_buffer);
5313
    ff_MPV_common_end(&v->s);
5314 5315
    av_freep(&v->mv_type_mb_plane);
    av_freep(&v->direct_mb_plane);
5316 5317
    av_freep(&v->forward_mb_plane);
    av_freep(&v->fieldtx_plane);
5318 5319 5320
    av_freep(&v->acpred_plane);
    av_freep(&v->over_flags_plane);
    av_freep(&v->mb_type_base);
5321 5322 5323 5324
    av_freep(&v->blk_mv_type_base);
    av_freep(&v->mv_f_base);
    av_freep(&v->mv_f_last_base);
    av_freep(&v->mv_f_next_base);
5325 5326 5327 5328 5329 5330 5331 5332 5333
    av_freep(&v->block);
    av_freep(&v->cbp_base);
    av_freep(&v->ttblk_base);
    av_freep(&v->is_intra_base); // FIXME use v->mb_type[]
    av_freep(&v->luma_mv_base);
    ff_intrax8_common_end(&v->x8);
    return 0;
}

5334 5335 5336 5337

/** Decode a VC1/WMV3 frame
 * @todo TODO: Handle VC-1 IDUs (Transport level?)
 */
5338
static int vc1_decode_frame(AVCodecContext *avctx, void *data,
5339
                            int *got_frame, AVPacket *avpkt)
5340 5341
{
    const uint8_t *buf = avpkt->data;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5342
    int buf_size = avpkt->size, n_slices = 0, i;
5343 5344 5345 5346
    VC1Context *v = avctx->priv_data;
    MpegEncContext *s = &v->s;
    AVFrame *pict = data;
    uint8_t *buf2 = NULL;
5347
    const uint8_t *buf_start = buf, *buf_start_second_field = NULL;
5348
    int mb_height, n_slices1=-1;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5349 5350 5351 5352
    struct {
        uint8_t *buf;
        GetBitContext gb;
        int mby_start;
5353
    } *slices = NULL, *tmp;
5354

5355 5356
    v->second_field = 0;

Mean's avatar
Mean committed
5357 5358 5359
    if(s->flags & CODEC_FLAG_LOW_DELAY)
        s->low_delay = 1;

5360
    /* no supplementary picture */
5361
    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == VC1_CODE_ENDOFSEQ)) {
5362
        /* special case for last picture */
5363
        if (s->low_delay == 0 && s->next_picture_ptr) {
5364
            *pict = s->next_picture_ptr->f;
5365
            s->next_picture_ptr = NULL;
5366

5367
            *got_frame = 1;
5368 5369
        }

5370
        return buf_size;
5371 5372
    }

5373
    if (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) {
5374
        if (v->profile < PROFILE_ADVANCED)
5375
            avctx->pix_fmt = AV_PIX_FMT_VDPAU_WMV3;
5376
        else
5377
            avctx->pix_fmt = AV_PIX_FMT_VDPAU_VC1;
5378 5379 5380
    }

    //for advanced profile we may need to parse and unescape data
5381
    if (avctx->codec_id == AV_CODEC_ID_VC1 || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
5382 5383 5384
        int buf_size2 = 0;
        buf2 = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

5385
        if (IS_MARKER(AV_RB32(buf))) { /* frame starts with marker and needs to be parsed */
5386 5387 5388 5389
            const uint8_t *start, *end, *next;
            int size;

            next = buf;
5390
            for (start = buf, end = buf + buf_size; next < end; start = next) {
5391 5392
                next = find_next_marker(start + 4, end);
                size = next - start - 4;
5393 5394
                if (size <= 0) continue;
                switch (AV_RB32(start)) {
5395 5396 5397 5398 5399 5400
                case VC1_CODE_FRAME:
                    if (avctx->hwaccel ||
                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
                        buf_start = start;
                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);
                    break;
5401 5402
                case VC1_CODE_FIELD: {
                    int buf_size3;
5403 5404 5405
                    if (avctx->hwaccel ||
                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
                        buf_start_second_field = start;
5406 5407
                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                    if (!tmp)
5408
                        goto err;
5409
                    slices = tmp;
5410
                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
5411 5412
                    if (!slices[n_slices].buf)
                        goto err;
5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423
                    buf_size3 = vc1_unescape_buffer(start + 4, size,
                                                    slices[n_slices].buf);
                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                                  buf_size3 << 3);
                    /* assuming that the field marker is at the exact middle,
                       hope it's correct */
                    slices[n_slices].mby_start = s->mb_height >> 1;
                    n_slices1 = n_slices - 1; // index of the last slice of the first field
                    n_slices++;
                    break;
                }
5424 5425
                case VC1_CODE_ENTRYPOINT: /* it should be before frame data */
                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);
5426
                    init_get_bits(&s->gb, buf2, buf_size2 * 8);
5427
                    ff_vc1_decode_entry_point(avctx, v, &s->gb);
5428
                    break;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5429 5430
                case VC1_CODE_SLICE: {
                    int buf_size3;
5431 5432
                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                    if (!tmp)
5433
                        goto err;
5434
                    slices = tmp;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5435
                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
5436 5437
                    if (!slices[n_slices].buf)
                        goto err;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5438 5439 5440 5441 5442 5443 5444 5445
                    buf_size3 = vc1_unescape_buffer(start + 4, size,
                                                    slices[n_slices].buf);
                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                                  buf_size3 << 3);
                    slices[n_slices].mby_start = get_bits(&slices[n_slices].gb, 9);
                    n_slices++;
                    break;
                }
5446 5447
                }
            }
5448
        } else if (v->interlace && ((buf[0] & 0xC0) == 0xC0)) { /* WVC1 interlaced stores both fields divided by marker */
5449
            const uint8_t *divider;
5450
            int buf_size3;
5451 5452

            divider = find_next_marker(buf, buf + buf_size);
5453
            if ((divider == (buf + buf_size)) || AV_RB32(divider) != VC1_CODE_FIELD) {
5454
                av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");
5455
                goto err;
5456
            } else { // found field marker, unescape second field
5457 5458 5459
                if (avctx->hwaccel ||
                    s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
                    buf_start_second_field = divider;
5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472
                tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                if (!tmp)
                    goto err;
                slices = tmp;
                slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
                if (!slices[n_slices].buf)
                    goto err;
                buf_size3 = vc1_unescape_buffer(divider + 4, buf + buf_size - divider - 4, slices[n_slices].buf);
                init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                              buf_size3 << 3);
                slices[n_slices].mby_start = s->mb_height >> 1;
                n_slices1 = n_slices - 1;
                n_slices++;
5473 5474
            }
            buf_size2 = vc1_unescape_buffer(buf, divider - buf, buf2);
5475
        } else {
5476 5477 5478 5479 5480
            buf_size2 = vc1_unescape_buffer(buf, buf_size, buf2);
        }
        init_get_bits(&s->gb, buf2, buf_size2*8);
    } else
        init_get_bits(&s->gb, buf, buf_size*8);
5481 5482

    if (v->res_sprite) {
5483 5484
        v->new_sprite  = !get_bits1(&s->gb);
        v->two_sprites =  get_bits1(&s->gb);
5485
        /* res_sprite means a Windows Media Image stream, AV_CODEC_ID_*IMAGE means
5486 5487 5488
           we're using the sprite compositor. These are intentionally kept separate
           so you can get the raw sprites by using the wmv3 decoder for WMVP or
           the vc1 one for WVP2 */
5489
        if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
5490 5491 5492 5493 5494 5495 5496 5497
            if (v->new_sprite) {
                // switch AVCodecContext parameters to those of the sprites
                avctx->width  = avctx->coded_width  = v->sprite_width;
                avctx->height = avctx->coded_height = v->sprite_height;
            } else {
                goto image;
            }
        }
5498 5499
    }

5500 5501 5502
    if (s->context_initialized &&
        (s->width  != avctx->coded_width ||
         s->height != avctx->coded_height)) {
5503
        ff_vc1_decode_end(avctx);
5504 5505 5506
    }

    if (!s->context_initialized) {
5507
        if (ff_msmpeg4_decode_init(avctx) < 0 || ff_vc1_decode_init_alloc_tables(v) < 0)
5508
            goto err;
5509 5510 5511 5512

        s->low_delay = !avctx->has_b_frames || v->res_sprite;

        if (v->profile == PROFILE_ADVANCED) {
5513 5514
            if(avctx->coded_width<=1 || avctx->coded_height<=1)
                goto err;
5515 5516 5517 5518 5519 5520 5521 5522
            s->h_edge_pos = avctx->coded_width;
            s->v_edge_pos = avctx->coded_height;
        }
    }

    /* We need to set current_picture_ptr before reading the header,
     * otherwise we cannot store anything in there. */
    if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {
5523
        int i = ff_find_unused_picture(s, 0);
5524 5525
        if (i < 0)
            goto err;
5526
        s->current_picture_ptr = &s->picture[i];
5527 5528
    }

5529
    // do parse frame header
5530
    v->pic_header_flag = 0;
5531
    v->first_pic_header_flag = 1;
5532
    if (v->profile < PROFILE_ADVANCED) {
5533
        if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {
5534
            goto err;
5535 5536
        }
    } else {
5537
        if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
5538
            goto err;
5539 5540
        }
    }
5541
    v->first_pic_header_flag = 0;
5542

5543 5544 5545
    if (avctx->debug & FF_DEBUG_PICT_INFO)
        av_log(v->s.avctx, AV_LOG_DEBUG, "pict_type: %c\n", av_get_picture_type_char(s->pict_type));

5546
    if ((avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE)
5547
        && s->pict_type != AV_PICTURE_TYPE_I) {
5548 5549
        av_log(v->s.avctx, AV_LOG_ERROR, "Sprite decoder: expected I-frame\n");
        goto err;
5550 5551
    }

5552 5553 5554 5555 5556
    if ((s->mb_height >> v->field_mode) == 0) {
        av_log(v->s.avctx, AV_LOG_ERROR, "image too short\n");
        goto err;
    }

5557
    // process pulldown flags
5558
    s->current_picture_ptr->f.repeat_pict = 0;
5559 5560
    // Pulldown flags are only valid when 'broadcast' has been set.
    // So ticks_per_frame will be 2
5561
    if (v->rff) {
5562
        // repeat field
5563
        s->current_picture_ptr->f.repeat_pict = 1;
5564
    } else if (v->rptfrm) {
5565
        // repeat frames
5566
        s->current_picture_ptr->f.repeat_pict = v->rptfrm * 2;
5567 5568
    }

5569
    // for skipping the frame
5570 5571
    s->current_picture.f.pict_type = s->pict_type;
    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
5572 5573

    /* skip B-frames if we don't have reference frames */
5574
    if (s->last_picture_ptr == NULL && (s->pict_type == AV_PICTURE_TYPE_B || s->dropable)) {
5575
        goto err;
5576
    }
5577 5578 5579
    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||
        (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||
         avctx->skip_frame >= AVDISCARD_ALL) {
5580
        goto end;
5581 5582
    }

5583 5584
    if (s->next_p_frame_damaged) {
        if (s->pict_type == AV_PICTURE_TYPE_B)
5585
            goto end;
5586
        else
5587
            s->next_p_frame_damaged = 0;
5588 5589
    }

5590
    if (ff_MPV_frame_start(s, avctx) < 0) {
5591
        goto err;
5592 5593
    }

5594 5595 5596
    v->s.current_picture_ptr->f.interlaced_frame = (v->fcm != PROGRESSIVE);
    v->s.current_picture_ptr->f.top_field_first  = v->tff;

5597 5598
    s->me.qpel_put = s->dsp.put_qpel_pixels_tab;
    s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;
5599

5600
    if ((CONFIG_VC1_VDPAU_DECODER)
5601 5602 5603
        &&s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
        ff_vdpau_vc1_decode_picture(s, buf_start, (buf + buf_size) - buf_start);
    else if (avctx->hwaccel) {
5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639
        if (v->field_mode && buf_start_second_field) {
            // decode first field
            s->picture_structure = PICT_BOTTOM_FIELD - v->tff;
            if (avctx->hwaccel->start_frame(avctx, buf_start, buf_start_second_field - buf_start) < 0)
                goto err;
            if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_start_second_field - buf_start) < 0)
                goto err;
            if (avctx->hwaccel->end_frame(avctx) < 0)
                goto err;

            // decode second field
            s->gb = slices[n_slices1 + 1].gb;
            s->picture_structure = PICT_TOP_FIELD + v->tff;
            v->second_field = 1;
            v->pic_header_flag = 0;
            if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
                av_log(avctx, AV_LOG_ERROR, "parsing header for second field failed");
                goto err;
            }
            v->s.current_picture_ptr->f.pict_type = v->s.pict_type;

            if (avctx->hwaccel->start_frame(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
                goto err;
            if (avctx->hwaccel->decode_slice(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
                goto err;
            if (avctx->hwaccel->end_frame(avctx) < 0)
                goto err;
        } else {
            s->picture_structure = PICT_FRAME;
            if (avctx->hwaccel->start_frame(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
                goto err;
            if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
                goto err;
            if (avctx->hwaccel->end_frame(avctx) < 0)
                goto err;
        }
5640
    } else {
5641 5642 5643
        if (v->fcm == ILACE_FRAME && s->pict_type == AV_PICTURE_TYPE_B)
            goto err; // This codepath is still incomplete thus it is disabled

5644 5645 5646
        ff_er_frame_start(s);

        v->bits = buf_size * 8;
Alberto Delmás's avatar
Alberto Delmás committed
5647
        v->end_mb_x = s->mb_width;
5648 5649 5650 5651 5652
        if (v->field_mode) {
            uint8_t *tmp[2];
            s->current_picture.f.linesize[0] <<= 1;
            s->current_picture.f.linesize[1] <<= 1;
            s->current_picture.f.linesize[2] <<= 1;
5653 5654 5655 5656
            s->linesize                      <<= 1;
            s->uvlinesize                    <<= 1;
            tmp[0]          = v->mv_f_last[0];
            tmp[1]          = v->mv_f_last[1];
5657 5658 5659 5660 5661 5662 5663 5664
            v->mv_f_last[0] = v->mv_f_next[0];
            v->mv_f_last[1] = v->mv_f_next[1];
            v->mv_f_next[0] = v->mv_f[0];
            v->mv_f_next[1] = v->mv_f[1];
            v->mv_f[0] = tmp[0];
            v->mv_f[1] = tmp[1];
        }
        mb_height = s->mb_height >> v->field_mode;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5665
        for (i = 0; i <= n_slices; i++) {
5666
            if (i > 0 &&  slices[i - 1].mby_start >= mb_height) {
5667 5668 5669 5670
                if (v->field_mode <= 0) {
                    av_log(v->s.avctx, AV_LOG_ERROR, "Slice %d starts beyond "
                           "picture boundary (%d >= %d)\n", i,
                           slices[i - 1].mby_start, mb_height);
5671 5672
                    continue;
                }
5673
                v->second_field = 1;
5674
                v->blocks_off   = s->mb_width  * s->mb_height << 1;
5675 5676 5677 5678 5679 5680 5681 5682
                v->mb_off       = s->mb_stride * s->mb_height >> 1;
            } else {
                v->second_field = 0;
                v->blocks_off   = 0;
                v->mb_off       = 0;
            }
            if (i) {
                v->pic_header_flag = 0;
5683 5684
                if (v->field_mode && i == n_slices1 + 2) {
                    if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
5685
                        av_log(v->s.avctx, AV_LOG_ERROR, "Field header damaged\n");
5686 5687 5688
                        continue;
                    }
                } else if (get_bits1(&s->gb)) {
5689
                    v->pic_header_flag = 1;
5690
                    if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
5691
                        av_log(v->s.avctx, AV_LOG_ERROR, "Slice header damaged\n");
5692 5693
                        continue;
                    }
5694 5695 5696 5697 5698
                }
            }
            s->start_mb_y = (i == 0) ? 0 : FFMAX(0, slices[i-1].mby_start % mb_height);
            if (!v->field_mode || v->second_field)
                s->end_mb_y = (i == n_slices     ) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
5699 5700 5701 5702 5703
            else {
                if (i >= n_slices) {
                    av_log(v->s.avctx, AV_LOG_ERROR, "first field slice count too large\n");
                    continue;
                }
5704
                s->end_mb_y = (i <= n_slices1 + 1) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
5705
            }
5706 5707 5708 5709
            if (s->end_mb_y <= s->start_mb_y) {
                av_log(v->s.avctx, AV_LOG_ERROR, "end mb y %d %d invalid\n", s->end_mb_y, s->start_mb_y);
                continue;
            }
5710
            ff_vc1_decode_blocks(v);
5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722
            if (i != n_slices)
                s->gb = slices[i].gb;
        }
        if (v->field_mode) {
            v->second_field = 0;
            if (s->pict_type == AV_PICTURE_TYPE_B) {
                memcpy(v->mv_f_base, v->mv_f_next_base,
                       2 * (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2));
            }
            s->current_picture.f.linesize[0] >>= 1;
            s->current_picture.f.linesize[1] >>= 1;
            s->current_picture.f.linesize[2] >>= 1;
5723 5724
            s->linesize                      >>= 1;
            s->uvlinesize                    >>= 1;
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5725
        }
5726 5727
        av_dlog(s->avctx, "Consumed %i/%i bits\n",
                get_bits_count(&s->gb), s->gb.size_in_bits);
5728
//  if (get_bits_count(&s->gb) > buf_size * 8)
5729
//      return -1;
5730
        if(s->error_occurred && s->pict_type == AV_PICTURE_TYPE_B)
5731
            goto err;
5732 5733
        if(!v->field_mode)
            ff_er_frame_end(s);
5734 5735
    }

5736
    ff_MPV_frame_end(s);
5737

5738
    if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
5739 5740 5741
image:
        avctx->width  = avctx->coded_width  = v->output_width;
        avctx->height = avctx->coded_height = v->output_height;
5742 5743
        if (avctx->skip_frame >= AVDISCARD_NONREF)
            goto end;
5744
#if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER
5745 5746
        if (vc1_decode_sprites(v, &s->gb))
            goto err;
5747
#endif
5748
        *pict      = v->sprite_output_frame;
5749
        *got_frame = 1;
5750
    } else {
5751
        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
5752
            *pict = s->current_picture_ptr->f;
5753
        } else if (s->last_picture_ptr != NULL) {
5754
            *pict = s->last_picture_ptr->f;
5755 5756
        }
        if (s->last_picture_ptr || s->low_delay) {
5757
            *got_frame = 1;
5758 5759
            ff_print_debug_info(s, pict);
        }
5760 5761
    }

5762
end:
5763
    av_free(buf2);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5764 5765 5766
    for (i = 0; i < n_slices; i++)
        av_free(slices[i].buf);
    av_free(slices);
5767
    return buf_size;
5768 5769 5770

err:
    av_free(buf2);
Ronald S. Bultje's avatar
Ronald S. Bultje committed
5771 5772 5773
    for (i = 0; i < n_slices; i++)
        av_free(slices[i].buf);
    av_free(slices);
5774
    return -1;
5775 5776 5777
}


5778 5779 5780 5781 5782 5783 5784
static const AVProfile profiles[] = {
    { FF_PROFILE_VC1_SIMPLE,   "Simple"   },
    { FF_PROFILE_VC1_MAIN,     "Main"     },
    { FF_PROFILE_VC1_COMPLEX,  "Complex"  },
    { FF_PROFILE_VC1_ADVANCED, "Advanced" },
    { FF_PROFILE_UNKNOWN },
};
5785

5786
AVCodec ff_vc1_decoder = {
5787 5788
    .name           = "vc1",
    .type           = AVMEDIA_TYPE_VIDEO,
5789
    .id             = AV_CODEC_ID_VC1,
5790 5791
    .priv_data_size = sizeof(VC1Context),
    .init           = vc1_decode_init,
5792
    .close          = ff_vc1_decode_end,
5793
    .decode         = vc1_decode_frame,
5794
    .flush          = ff_mpeg_flush,
5795
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
5796 5797 5798
    .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1"),
    .pix_fmts       = ff_hwaccel_pixfmt_list_420,
    .profiles       = NULL_IF_CONFIG_SMALL(profiles)
5799 5800
};

5801
#if CONFIG_WMV3_DECODER
5802
AVCodec ff_wmv3_decoder = {
5803 5804
    .name           = "wmv3",
    .type           = AVMEDIA_TYPE_VIDEO,
5805
    .id             = AV_CODEC_ID_WMV3,
5806 5807
    .priv_data_size = sizeof(VC1Context),
    .init           = vc1_decode_init,
5808
    .close          = ff_vc1_decode_end,
5809
    .decode         = vc1_decode_frame,
5810
    .flush          = ff_mpeg_flush,
5811
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
5812 5813 5814
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9"),
    .pix_fmts       = ff_hwaccel_pixfmt_list_420,
    .profiles       = NULL_IF_CONFIG_SMALL(profiles)
5815
};
5816
#endif
5817 5818

#if CONFIG_WMV3_VDPAU_DECODER
5819
AVCodec ff_wmv3_vdpau_decoder = {
5820 5821
    .name           = "wmv3_vdpau",
    .type           = AVMEDIA_TYPE_VIDEO,
5822
    .id             = AV_CODEC_ID_WMV3,
5823 5824
    .priv_data_size = sizeof(VC1Context),
    .init           = vc1_decode_init,
5825
    .close          = ff_vc1_decode_end,
5826 5827
    .decode         = vc1_decode_frame,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5828
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 VDPAU"),
5829
    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_VDPAU_WMV3, AV_PIX_FMT_NONE },
5830
    .profiles       = NULL_IF_CONFIG_SMALL(profiles)
5831 5832 5833 5834
};
#endif

#if CONFIG_VC1_VDPAU_DECODER
5835
AVCodec ff_vc1_vdpau_decoder = {
5836 5837
    .name           = "vc1_vdpau",
    .type           = AVMEDIA_TYPE_VIDEO,
5838
    .id             = AV_CODEC_ID_VC1,
5839 5840
    .priv_data_size = sizeof(VC1Context),
    .init           = vc1_decode_init,
5841
    .close          = ff_vc1_decode_end,
5842 5843
    .decode         = vc1_decode_frame,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5844
    .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 VDPAU"),
5845
    .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_VDPAU_VC1, AV_PIX_FMT_NONE },
5846
    .profiles       = NULL_IF_CONFIG_SMALL(profiles)
5847 5848
};
#endif
5849 5850 5851 5852 5853

#if CONFIG_WMV3IMAGE_DECODER
AVCodec ff_wmv3image_decoder = {
    .name           = "wmv3image",
    .type           = AVMEDIA_TYPE_VIDEO,
5854
    .id             = AV_CODEC_ID_WMV3IMAGE,
5855 5856
    .priv_data_size = sizeof(VC1Context),
    .init           = vc1_decode_init,
5857
    .close          = ff_vc1_decode_end,
5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869
    .decode         = vc1_decode_frame,
    .capabilities   = CODEC_CAP_DR1,
    .flush          = vc1_sprite_flush,
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 Image"),
    .pix_fmts       = ff_pixfmt_list_420
};
#endif

#if CONFIG_VC1IMAGE_DECODER
AVCodec ff_vc1image_decoder = {
    .name           = "vc1image",
    .type           = AVMEDIA_TYPE_VIDEO,
5870
    .id             = AV_CODEC_ID_VC1IMAGE,
5871 5872
    .priv_data_size = sizeof(VC1Context),
    .init           = vc1_decode_init,
5873
    .close          = ff_vc1_decode_end,
5874 5875 5876 5877 5878 5879 5880
    .decode         = vc1_decode_frame,
    .capabilities   = CODEC_CAP_DR1,
    .flush          = vc1_sprite_flush,
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 Image v2"),
    .pix_fmts       = ff_pixfmt_list_420
};
#endif