h264_refs.c 30.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * H.26L/H.264/AVC/JVT/14496-10/... reference picture handling
 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
 *
 * 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
 */

/**
23
 * @file
24 25 26 27
 * H.264 / AVC / MPEG4 part10  reference picture handling.
 * @author Michael Niedermayer <michaelni@gmx.at>
 */

28
#include "libavutil/avassert.h"
29 30 31 32 33 34 35
#include "internal.h"
#include "avcodec.h"
#include "h264.h"
#include "golomb.h"

#include <assert.h>

36 37 38 39 40 41 42
#define COPY_PICTURE(dst, src) \
do {\
    *(dst) = *(src);\
    (dst)->f.extended_data = (dst)->f.data;\
    (dst)->tf.f = &(dst)->f;\
} while (0)

43 44 45 46 47

static void pic_as_field(Picture *pic, const int parity){
    int i;
    for (i = 0; i < 4; ++i) {
        if (parity == PICT_BOTTOM_FIELD)
48
            pic->f.data[i] += pic->f.linesize[i];
49
        pic->reference      = parity;
50
        pic->f.linesize[i] *= 2;
51 52 53 54
    }
    pic->poc= pic->field_poc[parity == PICT_BOTTOM_FIELD];
}

55 56
static int split_field_copy(Picture *dest, Picture *src, int parity, int id_add)
{
57
    int match = !!(src->reference & parity);
58 59

    if (match) {
60
        COPY_PICTURE(dest, src);
61
        if (parity != PICT_FRAME) {
62 63 64 65 66 67 68 69 70
            pic_as_field(dest, parity);
            dest->pic_id *= 2;
            dest->pic_id += id_add;
        }
    }

    return match;
}

71 72
static int build_def_list(Picture *def, int def_len,
                          Picture **in, int len, int is_long, int sel)
73 74 75
{
    int  i[2] = { 0 };
    int index = 0;
76

77 78
    while (i[0] < len || i[1] < len) {
        while (i[0] < len && !(in[i[0]] && (in[i[0]]->reference & sel)))
79
            i[0]++;
80
        while (i[1] < len && !(in[i[1]] && (in[i[1]]->reference & (sel ^ 3))))
81
            i[1]++;
82
        if (i[0] < len) {
83
            av_assert0(index < def_len);
84 85
            in[i[0]]->pic_id = is_long ? i[0] : in[i[0]]->frame_num;
            split_field_copy(&def[index++], in[i[0]++], sel, 1);
86
        }
87
        if (i[1] < len) {
88
            av_assert0(index < def_len);
89 90
            in[i[1]]->pic_id = is_long ? i[1] : in[i[1]]->frame_num;
            split_field_copy(&def[index++], in[i[1]++], sel ^ 3, 0);
91 92 93 94 95 96
        }
    }

    return index;
}

97 98
static int add_sorted(Picture **sorted, Picture **src, int len, int limit, int dir)
{
99
    int i, best_poc;
100
    int out_i = 0;
101

102 103
    for (;;) {
        best_poc = dir ? INT_MIN : INT_MAX;
104

105 106 107 108 109
        for (i = 0; i < len; i++) {
            const int poc = src[i]->poc;
            if (((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)) {
                best_poc      = poc;
                sorted[out_i] = src[i];
110 111
            }
        }
112
        if (best_poc == (dir ? INT_MIN : INT_MAX))
113
            break;
114
        limit = sorted[out_i++]->poc - dir;
115 116 117 118
    }
    return out_i;
}

119 120
int ff_h264_fill_default_ref_list(H264Context *h)
{
121 122
    int i, len;

123
    if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
124 125 126 127
        Picture *sorted[32];
        int cur_poc, list;
        int lens[2];

128
        if (FIELD_PICTURE(h))
129
            cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure == PICT_BOTTOM_FIELD];
130
        else
131 132 133 134 135
            cur_poc = h->cur_pic_ptr->poc;

        for (list = 0; list < 2; list++) {
            len  = add_sorted(sorted,       h->short_ref, h->short_ref_count, cur_poc, 1 ^ list);
            len += add_sorted(sorted + len, h->short_ref, h->short_ref_count, cur_poc, 0 ^ list);
136
            av_assert0(len <= 32);
137 138 139 140 141 142

            len  = build_def_list(h->default_ref_list[list], FF_ARRAY_ELEMS(h->default_ref_list[0]),
                                  sorted, len, 0, h->picture_structure);
            len += build_def_list(h->default_ref_list[list] + len,
                                  FF_ARRAY_ELEMS(h->default_ref_list[0]) - len,
                                  h->long_ref, 16, 1, h->picture_structure);
143
            av_assert0(len <= 32);
144 145 146 147

            if (len < h->ref_count[list])
                memset(&h->default_ref_list[list][len], 0, sizeof(Picture) * (h->ref_count[list] - len));
            lens[list] = len;
148 149
        }

150
        if (lens[0] == lens[1] && lens[1] > 1) {
151 152 153
            for (i = 0; i < lens[0] &&
                        h->default_ref_list[0][i].f.buf[0]->buffer ==
                        h->default_ref_list[1][i].f.buf[0]->buffer; i++);
154 155 156 157 158 159
            if (i == lens[0]) {
                Picture tmp;
                COPY_PICTURE(&tmp, &h->default_ref_list[1][0]);
                COPY_PICTURE(&h->default_ref_list[1][0], &h->default_ref_list[1][1]);
                COPY_PICTURE(&h->default_ref_list[1][1], &tmp);
            }
160
        }
161
    } else {
162 163 164 165 166
        len  = build_def_list(h->default_ref_list[0], FF_ARRAY_ELEMS(h->default_ref_list[0]),
                              h->short_ref, h->short_ref_count, 0, h->picture_structure);
        len += build_def_list(h->default_ref_list[0] + len,
                              FF_ARRAY_ELEMS(h->default_ref_list[0]) - len,
                              h-> long_ref, 16, 1, h->picture_structure);
167
        av_assert0(len <= 32);
168

169 170
        if (len < h->ref_count[0])
            memset(&h->default_ref_list[0][len], 0, sizeof(Picture) * (h->ref_count[0] - len));
171 172
    }
#ifdef TRACE
173 174 175 176 177
    for (i = 0; i < h->ref_count[0]; i++) {
        tprintf(h->avctx, "List0: %s fn:%d 0x%p\n",
                (h->default_ref_list[0][i].long_ref ? "LT" : "ST"),
                h->default_ref_list[0][i].pic_id,
                h->default_ref_list[0][i].f.data[0]);
178
    }
179 180 181 182 183 184
    if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
        for (i = 0; i < h->ref_count[1]; i++) {
            tprintf(h->avctx, "List1: %s fn:%d 0x%p\n",
                    (h->default_ref_list[1][i].long_ref ? "LT" : "ST"),
                    h->default_ref_list[1][i].pic_id,
                    h->default_ref_list[1][i].f.data[0]);
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        }
    }
#endif
    return 0;
}

static void print_short_term(H264Context *h);
static void print_long_term(H264Context *h);

/**
 * Extract structure information about the picture described by pic_num in
 * the current decoding context (frame or field). Note that pic_num is
 * picture number without wrapping (so, 0<=pic_num<max_pic_num).
 * @param pic_num picture number for which to extract structure information
 * @param structure one of PICT_XXX describing structure of picture
 *                      with pic_num
 * @return frame number (short term) or long term index of picture
 *         described by pic_num
 */
204 205
static int pic_num_extract(H264Context *h, int pic_num, int *structure)
{
206
    *structure = h->picture_structure;
207
    if (FIELD_PICTURE(h)) {
208 209 210 211 212 213 214 215 216
        if (!(pic_num & 1))
            /* opposite field */
            *structure ^= PICT_FRAME;
        pic_num >>= 1;
    }

    return pic_num;
}

217 218
int ff_h264_decode_ref_pic_list_reordering(H264Context *h)
{
219
    int list, index, pic_structure, i;
220 221 222 223

    print_short_term(h);
    print_long_term(h);

224
    for (list = 0; list < h->list_count; list++) {
225 226
        for (i = 0; i < h->ref_count[list]; i++)
            COPY_PICTURE(&h->ref_list[list][i], &h->default_ref_list[list][i]);
227

228 229
        if (get_bits1(&h->gb)) {
            int pred = h->curr_pic_num;
230

231 232
            for (index = 0; ; index++) {
                unsigned int reordering_of_pic_nums_idc = get_ue_golomb_31(&h->gb);
233 234 235 236
                unsigned int pic_id;
                int i;
                Picture *ref = NULL;

237
                if (reordering_of_pic_nums_idc == 3)
238 239
                    break;

240
                if (index >= h->ref_count[list]) {
241
                    av_log(h->avctx, AV_LOG_ERROR, "reference count overflow\n");
242 243 244
                    return -1;
                }

245 246 247
                if (reordering_of_pic_nums_idc < 3) {
                    if (reordering_of_pic_nums_idc < 2) {
                        const unsigned int abs_diff_pic_num = get_ue_golomb(&h->gb) + 1;
248 249
                        int frame_num;

250
                        if (abs_diff_pic_num > h->max_pic_num) {
251
                            av_log(h->avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");
252 253 254
                            return -1;
                        }

255 256 257 258
                        if (reordering_of_pic_nums_idc == 0)
                            pred -= abs_diff_pic_num;
                        else
                            pred += abs_diff_pic_num;
259 260 261 262
                        pred &= h->max_pic_num - 1;

                        frame_num = pic_num_extract(h, pred, &pic_structure);

263
                        for (i = h->short_ref_count - 1; i >= 0; i--) {
264
                            ref = h->short_ref[i];
265
                            assert(ref->reference);
266
                            assert(!ref->long_ref);
267 268
                            if (ref->frame_num == frame_num &&
                                (ref->reference & pic_structure))
269 270
                                break;
                        }
271 272 273
                        if (i >= 0)
                            ref->pic_id = pred;
                    } else {
274
                        int long_idx;
275
                        pic_id = get_ue_golomb(&h->gb); //long_term_pic_idx
276

277
                        long_idx = pic_num_extract(h, pic_id, &pic_structure);
278

279
                        if (long_idx > 31) {
280
                            av_log(h->avctx, AV_LOG_ERROR, "long_term_pic_idx overflow\n");
281 282 283
                            return -1;
                        }
                        ref = h->long_ref[long_idx];
284 285
                        assert(!(ref && !ref->reference));
                        if (ref && (ref->reference & pic_structure)) {
286
                            ref->pic_id = pic_id;
287
                            assert(ref->long_ref);
288 289 290
                            i = 0;
                        } else {
                            i = -1;
291 292 293 294
                        }
                    }

                    if (i < 0) {
295
                        av_log(h->avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");
296 297
                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME
                    } else {
298 299 300
                        for (i = index; i + 1 < h->ref_count[list]; i++) {
                            if (ref->long_ref == h->ref_list[list][i].long_ref &&
                                ref->pic_id   == h->ref_list[list][i].pic_id)
301 302
                                break;
                        }
303
                        for (; i > index; i--) {
304
                            COPY_PICTURE(&h->ref_list[list][i], &h->ref_list[list][i - 1]);
305
                        }
306
                        COPY_PICTURE(&h->ref_list[list][index], ref);
307
                        if (FIELD_PICTURE(h)) {
308 309 310
                            pic_as_field(&h->ref_list[list][index], pic_structure);
                        }
                    }
311
                } else {
312
                    av_log(h->avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");
313 314 315 316 317
                    return -1;
                }
            }
        }
    }
318 319
    for (list = 0; list < h->list_count; list++) {
        for (index = 0; index < h->ref_count[list]; index++) {
320
            if (   !h->ref_list[list][index].f.buf[0]
321
                || (!FIELD_PICTURE(h) && (h->ref_list[list][index].reference&3) != 3)) {
322
                int i;
323
                av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture, default is %d\n", h->default_ref_list[list][0].poc);
324
                for (i = 0; i < FF_ARRAY_ELEMS(h->last_pocs); i++)
325
                    h->last_pocs[i] = INT_MIN;
326
                if (h->default_ref_list[list][0].f.buf[0]
327
                    && !(!FIELD_PICTURE(h) && (h->default_ref_list[list][0].reference&3) != 3))
328
                    COPY_PICTURE(&h->ref_list[list][index], &h->default_ref_list[list][0]);
329 330 331
                else
                    return -1;
            }
332
            av_assert0(av_buffer_get_ref_count(h->ref_list[list][index].f.buf[0]) > 0);
333 334 335 336 337 338
        }
    }

    return 0;
}

339 340
void ff_h264_fill_mbaff_ref_list(H264Context *h)
{
341
    int list, i, j;
342
    for (list = 0; list < h->list_count; list++) {
343
        for (i = 0; i < h->ref_count[list]; i++) {
344
            Picture *frame = &h->ref_list[list][i];
345
            Picture *field = &h->ref_list[list][16 + 2 * i];
346
            COPY_PICTURE(field, frame);
347
            for (j = 0; j < 3; j++)
348
                field[0].f.linesize[j] <<= 1;
349
            field[0].reference = PICT_TOP_FIELD;
350
            field[0].poc       = field[0].field_poc[0];
351
            COPY_PICTURE(field + 1, field);
352
            for (j = 0; j < 3; j++)
353
                field[1].f.data[j] += frame->f.linesize[j];
354
            field[1].reference = PICT_BOTTOM_FIELD;
355
            field[1].poc       = field[1].field_poc[1];
356

357 358 359 360 361
            h->luma_weight[16 + 2 * i][list][0] = h->luma_weight[16 + 2 * i + 1][list][0] = h->luma_weight[i][list][0];
            h->luma_weight[16 + 2 * i][list][1] = h->luma_weight[16 + 2 * i + 1][list][1] = h->luma_weight[i][list][1];
            for (j = 0; j < 2; j++) {
                h->chroma_weight[16 + 2 * i][list][j][0] = h->chroma_weight[16 + 2 * i + 1][list][j][0] = h->chroma_weight[i][list][j][0];
                h->chroma_weight[16 + 2 * i][list][j][1] = h->chroma_weight[16 + 2 * i + 1][list][j][1] = h->chroma_weight[i][list][j][1];
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            }
        }
    }
}

/**
 * Mark a picture as no longer needed for reference. The refmask
 * argument allows unreferencing of individual fields or the whole frame.
 * If the picture becomes entirely unreferenced, but is being held for
 * display purposes, it is marked as such.
 * @param refmask mask of fields to unreference; the mask is bitwise
 *                anded with the reference marking of pic
 * @return non-zero if pic becomes entirely unreferenced (except possibly
 *         for display purposes) zero if one of the fields remains in
 *         reference
 */
378 379
static inline int unreference_pic(H264Context *h, Picture *pic, int refmask)
{
380
    int i;
381
    if (pic->reference &= refmask) {
382 383 384 385
        return 0;
    } else {
        for(i = 0; h->delayed_pic[i]; i++)
            if(pic == h->delayed_pic[i]){
386
                pic->reference = DELAYED_PIC_REF;
387 388 389 390 391 392 393 394 395 396 397 398 399 400
                break;
            }
        return 1;
    }
}

/**
 * Find a Picture in the short term reference list by frame number.
 * @param frame_num frame number to search for
 * @param idx the index into h->short_ref where returned picture is found
 *            undefined if no picture found.
 * @return pointer to the found picture, or NULL if no pic with the provided
 *                 frame number is found
 */
401 402
static Picture *find_short(H264Context *h, int frame_num, int *idx)
{
403 404
    int i;

405 406 407
    for (i = 0; i < h->short_ref_count; i++) {
        Picture *pic = h->short_ref[i];
        if (h->avctx->debug & FF_DEBUG_MMCO)
408
            av_log(h->avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
409
        if (pic->frame_num == frame_num) {
410 411 412 413 414 415 416 417 418 419 420 421 422
            *idx = i;
            return pic;
        }
    }
    return NULL;
}

/**
 * Remove a picture from the short term reference list by its index in
 * that list.  This does no checking on the provided index; it is assumed
 * to be valid. Other list entries are shifted down.
 * @param i index into h->short_ref of picture to remove.
 */
423 424
static void remove_short_at_index(H264Context *h, int i)
{
425
    assert(i >= 0 && i < h->short_ref_count);
426
    h->short_ref[i] = NULL;
427
    if (--h->short_ref_count)
428 429
        memmove(&h->short_ref[i], &h->short_ref[i + 1],
                (h->short_ref_count - i) * sizeof(Picture*));
430 431 432 433 434 435
}

/**
 *
 * @return the removed picture or NULL if an error occurs
 */
436 437
static Picture *remove_short(H264Context *h, int frame_num, int ref_mask)
{
438 439 440
    Picture *pic;
    int i;

441
    if (h->avctx->debug & FF_DEBUG_MMCO)
442
        av_log(h->avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
443 444

    pic = find_short(h, frame_num, &i);
445 446 447
    if (pic) {
        if (unreference_pic(h, pic, ref_mask))
            remove_short_at_index(h, i);
448 449 450 451 452 453 454 455 456 457
    }

    return pic;
}

/**
 * Remove a picture from the long term reference list by its index in
 * that list.
 * @return the removed picture or NULL if an error occurs
 */
458 459
static Picture *remove_long(H264Context *h, int i, int ref_mask)
{
460 461
    Picture *pic;

462 463 464
    pic = h->long_ref[i];
    if (pic) {
        if (unreference_pic(h, pic, ref_mask)) {
465
            assert(h->long_ref[i]->long_ref == 1);
466 467
            h->long_ref[i]->long_ref = 0;
            h->long_ref[i]           = NULL;
468 469 470 471 472 473 474
            h->long_ref_count--;
        }
    }

    return pic;
}

475 476
void ff_h264_remove_all_refs(H264Context *h)
{
477 478
    int i;

479
    for (i = 0; i < 16; i++) {
480 481
        remove_long(h, i, 0);
    }
482
    assert(h->long_ref_count == 0);
483

484
    for (i = 0; i < h->short_ref_count; i++) {
485
        unreference_pic(h, h->short_ref[i], 0);
486
        h->short_ref[i] = NULL;
487
    }
488
    h->short_ref_count = 0;
489 490 491

    memset(h->default_ref_list, 0, sizeof(h->default_ref_list));
    memset(h->ref_list, 0, sizeof(h->ref_list));
492 493 494 495 496
}

/**
 * print short term list
 */
497 498
static void print_short_term(H264Context *h)
{
499
    uint32_t i;
500
    if (h->avctx->debug & FF_DEBUG_MMCO) {
501
        av_log(h->avctx, AV_LOG_DEBUG, "short term list:\n");
502 503
        for (i = 0; i < h->short_ref_count; i++) {
            Picture *pic = h->short_ref[i];
504
            av_log(h->avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n",
505
                   i, pic->frame_num, pic->poc, pic->f.data[0]);
506 507 508 509 510 511 512
        }
    }
}

/**
 * print long term list
 */
513 514
static void print_long_term(H264Context *h)
{
515
    uint32_t i;
516
    if (h->avctx->debug & FF_DEBUG_MMCO) {
517
        av_log(h->avctx, AV_LOG_DEBUG, "long term list:\n");
518 519
        for (i = 0; i < 16; i++) {
            Picture *pic = h->long_ref[i];
520
            if (pic) {
521
                av_log(h->avctx, AV_LOG_DEBUG, "%d fn:%d poc:%d %p\n",
522
                       i, pic->frame_num, pic->poc, pic->f.data[0]);
523 524 525 526 527
            }
        }
    }
}

528 529 530 531 532
static int check_opcodes(MMCO *mmco1, MMCO *mmco2, int n_mmcos)
{
    int i;

    for (i = 0; i < n_mmcos; i++) {
533 534 535
        if (mmco1[i].opcode != mmco2[i].opcode) {
            av_log(NULL, AV_LOG_ERROR, "MMCO opcode [%d, %d] at %d mismatches between slices\n",
                   mmco1[i].opcode, mmco2[i].opcode, i);
536
            return -1;
537
        }
538 539 540 541
    }

    return 0;
}
542

543
int ff_generate_sliding_window_mmcos(H264Context *h, int first_slice)
544 545 546 547 548 549
{
    MMCO mmco_temp[MAX_MMCO_COUNT], *mmco = first_slice ? h->mmco : mmco_temp;
    int mmco_index = 0, i;

    if (h->short_ref_count &&
        h->long_ref_count + h->short_ref_count >= h->sps.ref_frame_count &&
550
        !(FIELD_PICTURE(h) && !h->first_field && h->cur_pic_ptr->reference)) {
551
        mmco[0].opcode        = MMCO_SHORT2UNUSED;
552
        mmco[0].short_pic_num = h->short_ref[h->short_ref_count - 1]->frame_num;
553
        mmco_index            = 1;
554
        if (FIELD_PICTURE(h)) {
555
            mmco[0].short_pic_num *= 2;
556 557 558
            mmco[1].opcode         = MMCO_SHORT2UNUSED;
            mmco[1].short_pic_num  = mmco[0].short_pic_num + 1;
            mmco_index             = 2;
559 560
        }
    }
561 562 563 564 565 566

    if (first_slice) {
        h->mmco_index = mmco_index;
    } else if (!first_slice && mmco_index >= 0 &&
               (mmco_index != h->mmco_index ||
                (i = check_opcodes(h->mmco, mmco_temp, mmco_index)))) {
567
        av_log(h->avctx, AV_LOG_ERROR,
568 569
               "Inconsistent MMCO state between slices [%d, %d]\n",
               mmco_index, h->mmco_index);
570 571
        return AVERROR_INVALIDDATA;
    }
572
    return 0;
573 574
}

575 576
int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count)
{
577
    int i, av_uninit(j);
578
    int pps_count;
579
    int current_ref_assigned = 0, err = 0;
580 581
    Picture *av_uninit(pic);

582
    if ((h->avctx->debug & FF_DEBUG_MMCO) && mmco_count == 0)
583
        av_log(h->avctx, AV_LOG_DEBUG, "no mmco here\n");
584

585
    for (i = 0; i < mmco_count; i++) {
586
        int av_uninit(structure), av_uninit(frame_num);
587 588 589
        if (h->avctx->debug & FF_DEBUG_MMCO)
            av_log(h->avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode,
                   h->mmco[i].short_pic_num, h->mmco[i].long_arg);
590

591 592
        if (mmco[i].opcode == MMCO_SHORT2UNUSED ||
            mmco[i].opcode == MMCO_SHORT2LONG) {
593
            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
594 595 596 597 598
            pic       = find_short(h, frame_num, &j);
            if (!pic) {
                if (mmco[i].opcode != MMCO_SHORT2LONG ||
                    !h->long_ref[mmco[i].long_arg]    ||
                    h->long_ref[mmco[i].long_arg]->frame_num != frame_num) {
599
                    av_log(h->avctx, h->short_ref_count ? AV_LOG_ERROR : AV_LOG_DEBUG, "mmco: unref short failure\n");
600 601
                    err = AVERROR_INVALIDDATA;
                }
602 603 604 605
                continue;
            }
        }

606
        switch (mmco[i].opcode) {
607
        case MMCO_SHORT2UNUSED:
608 609 610
            if (h->avctx->debug & FF_DEBUG_MMCO)
                av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n",
                       h->mmco[i].short_pic_num, h->short_ref_count);
611 612 613 614 615 616 617
            remove_short(h, frame_num, structure ^ PICT_FRAME);
            break;
        case MMCO_SHORT2LONG:
                if (h->long_ref[mmco[i].long_arg] != pic)
                    remove_long(h, mmco[i].long_arg, 0);

                remove_short_at_index(h, j);
618 619 620
                h->long_ref[ mmco[i].long_arg ] = pic;
                if (h->long_ref[mmco[i].long_arg]) {
                    h->long_ref[mmco[i].long_arg]->long_ref = 1;
621 622 623 624
                    h->long_ref_count++;
                }
            break;
        case MMCO_LONG2UNUSED:
625
            j   = pic_num_extract(h, mmco[i].long_arg, &structure);
626 627 628
            pic = h->long_ref[j];
            if (pic) {
                remove_long(h, j, structure ^ PICT_FRAME);
629
            } else if (h->avctx->debug & FF_DEBUG_MMCO)
630
                av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
631 632 633 634 635 636 637 638 639
            break;
        case MMCO_LONG:
                    // Comment below left from previous code as it is an interresting note.
                    /* First field in pair is in short term list or
                     * at a different long term index.
                     * This is not allowed; see 7.4.3.3, notes 2 and 3.
                     * Report the problem and keep the pair where it is,
                     * and mark this field valid.
                     */
640 641
            if (h->short_ref[0] == h->cur_pic_ptr) {
                av_log(h->avctx, AV_LOG_ERROR, "mmco: cannot assign current picture to short and long at the same time\n");
642
                remove_short_at_index(h, 0);
643
            }
644

645
            if (h->long_ref[mmco[i].long_arg] != h->cur_pic_ptr) {
646 647 648 649 650 651 652 653
                if (h->cur_pic_ptr->long_ref) {
                    for(j=0; j<16; j++) {
                        if(h->long_ref[j] == h->cur_pic_ptr) {
                            remove_long(h, j, 0);
                            av_log(h->avctx, AV_LOG_ERROR, "mmco: cannot assign current picture to 2 long term references\n");
                        }
                    }
                }
654
                av_assert0(!h->cur_pic_ptr->long_ref);
655 656
                remove_long(h, mmco[i].long_arg, 0);

657 658
                h->long_ref[mmco[i].long_arg]           = h->cur_pic_ptr;
                h->long_ref[mmco[i].long_arg]->long_ref = 1;
659 660 661
                h->long_ref_count++;
            }

662
            h->cur_pic_ptr->reference |= h->picture_structure;
663
            current_ref_assigned = 1;
664 665 666 667
            break;
        case MMCO_SET_MAX_LONG:
            assert(mmco[i].long_arg <= 16);
            // just remove the long term which index is greater than new max
668
            for (j = mmco[i].long_arg; j < 16; j++) {
669 670 671 672
                remove_long(h, j, 0);
            }
            break;
        case MMCO_RESET:
673
            while (h->short_ref_count) {
674 675
                remove_short(h, h->short_ref[0]->frame_num, 0);
            }
676
            for (j = 0; j < 16; j++) {
677 678
                remove_long(h, j, 0);
            }
679
            h->frame_num  = h->cur_pic_ptr->frame_num = 0;
680
            h->mmco_reset = 1;
681
            h->cur_pic_ptr->mmco_reset = 1;
682 683
            for (j = 0; j < MAX_DELAYED_PIC_COUNT; j++)
                h->last_pocs[j] = INT_MIN;
684 685 686 687 688 689 690 691 692 693 694 695
            break;
        default: assert(0);
        }
    }

    if (!current_ref_assigned) {
        /* Second field of complementary field pair; the first field of
         * which is already referenced. If short referenced, it
         * should be first entry in short_ref. If not, it must exist
         * in long_ref; trying to put it on the short list here is an
         * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
         */
696
        if (h->short_ref_count && h->short_ref[0] == h->cur_pic_ptr) {
697
            /* Just mark the second field valid */
698
            h->cur_pic_ptr->reference = PICT_FRAME;
699 700 701 702 703
        } else if (h->cur_pic_ptr->long_ref) {
            av_log(h->avctx, AV_LOG_ERROR, "illegal short term reference "
                                           "assignment for second field "
                                           "in complementary field pair "
                                           "(first field is long term)\n");
704
            err = AVERROR_INVALIDDATA;
705
        } else {
706 707
            pic = remove_short(h, h->cur_pic_ptr->frame_num, 0);
            if (pic) {
708
                av_log(h->avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
709
                err = AVERROR_INVALIDDATA;
710 711
            }

712 713 714
            if (h->short_ref_count)
                memmove(&h->short_ref[1], &h->short_ref[0],
                        h->short_ref_count * sizeof(Picture*));
715

716
            h->short_ref[0] = h->cur_pic_ptr;
717
            h->short_ref_count++;
718
            h->cur_pic_ptr->reference |= h->picture_structure;
719 720 721
        }
    }

722
    if (h->long_ref_count + h->short_ref_count > FFMAX(h->sps.ref_frame_count, 1)) {
723 724 725 726 727

        /* We have too many reference frames, probably due to corrupted
         * stream. Need to discard one frame. Prevents overrun of the
         * short_ref and long_ref buffers.
         */
728
        av_log(h->avctx, AV_LOG_ERROR,
729 730 731
               "number of reference frames (%d+%d) exceeds max (%d; probably "
               "corrupt input), discarding one\n",
               h->long_ref_count, h->short_ref_count, h->sps.ref_frame_count);
732
        err = AVERROR_INVALIDDATA;
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748

        if (h->long_ref_count && !h->short_ref_count) {
            for (i = 0; i < 16; ++i)
                if (h->long_ref[i])
                    break;

            assert(i < 16);
            remove_long(h, i, 0);
        } else {
            pic = h->short_ref[h->short_ref_count - 1];
            remove_short(h, pic->frame_num, 0);
        }
    }

    print_short_term(h);
    print_long_term(h);
749

750 751 752 753
    pps_count = 0;
    for (i = 0; i < FF_ARRAY_ELEMS(h->pps_buffers); i++)
        pps_count += !!h->pps_buffers[i];

754 755
    if (   err >= 0
        && h->long_ref_count==0
756
        && (h->short_ref_count<=2 || h->pps.ref_count[0] <= 1 && h->pps.ref_count[1] <= 1 && pps_count == 1)
757 758
        && h->pps.ref_count[0]<=2 + (h->picture_structure != PICT_FRAME)
        && h->cur_pic_ptr->f.pict_type == AV_PICTURE_TYPE_I){
759
        h->cur_pic_ptr->recovered |= 1;
760
        if(!h->avctx->has_b_frames)
761
            h->frame_recovered |= FRAME_RECOVERED_SEI;
762 763
    }

764
    return (h->avctx->err_recognition & AV_EF_EXPLODE) ? err : 0;
765 766
}

767 768 769
int ff_h264_decode_ref_pic_marking(H264Context *h, GetBitContext *gb,
                                   int first_slice)
{
770
    int i, ret;
771
    MMCO mmco_temp[MAX_MMCO_COUNT], *mmco = mmco_temp;
772 773
    int mmco_index = 0;

774
    if (h->nal_unit_type == NAL_IDR_SLICE) { // FIXME fields
775
        skip_bits1(gb); // broken_link
776 777
        if (get_bits1(gb)) {
            mmco[0].opcode   = MMCO_LONG;
778
            mmco[0].long_arg = 0;
779
            mmco_index       = 1;
780
        }
781 782 783 784 785 786
    } else {
        if (get_bits1(gb)) { // adaptive_ref_pic_marking_mode_flag
            for (i = 0; i < MAX_MMCO_COUNT; i++) {
                MMCOOpcode opcode = get_ue_golomb_31(gb);

                mmco[i].opcode = opcode;
787
                if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG) {
788 789 790 791 792 793 794 795 796
                    mmco[i].short_pic_num =
                        (h->curr_pic_num - get_ue_golomb(gb) - 1) &
                            (h->max_pic_num - 1);
#if 0
                    if (mmco[i].short_pic_num >= h->short_ref_count ||
                        h->short_ref[ mmco[i].short_pic_num ] == NULL){
                        av_log(s->avctx, AV_LOG_ERROR,
                               "illegal short ref in memory management control "
                               "operation %d\n", mmco);
797
                        return -1;
798 799
                    }
#endif
800
                }
801 802 803 804 805 806
                if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||
                    opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG) {
                    unsigned int long_arg = get_ue_golomb_31(gb);
                    if (long_arg >= 32 ||
                        (long_arg >= 16 && !(opcode == MMCO_SET_MAX_LONG &&
                                             long_arg == 16) &&
807
                         !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE(h)))) {
808
                        av_log(h->avctx, AV_LOG_ERROR,
809 810
                               "illegal long ref in memory management control "
                               "operation %d\n", opcode);
811 812
                        return -1;
                    }
813
                    mmco[i].long_arg = long_arg;
814 815
                }

816
                if (opcode > (unsigned) MMCO_LONG) {
817
                    av_log(h->avctx, AV_LOG_ERROR,
818 819
                           "illegal memory management control operation %d\n",
                           opcode);
820 821
                    return -1;
                }
822
                if (opcode == MMCO_END)
823 824
                    break;
            }
825 826
            mmco_index = i;
        } else {
827 828
            if (first_slice) {
                ret = ff_generate_sliding_window_mmcos(h, first_slice);
829
                if (ret < 0 && h->avctx->err_recognition & AV_EF_EXPLODE)
830 831
                    return ret;
            }
832
            mmco_index = -1;
833 834 835
        }
    }

836
    if (first_slice && mmco_index != -1) {
837
        memcpy(h->mmco, mmco_temp, sizeof(h->mmco));
838 839 840
        h->mmco_index = mmco_index;
    } else if (!first_slice && mmco_index >= 0 &&
               (mmco_index != h->mmco_index ||
841
                check_opcodes(h->mmco, mmco_temp, mmco_index))) {
842
        av_log(h->avctx, AV_LOG_ERROR,
843 844
               "Inconsistent MMCO state between slices [%d, %d]\n",
               mmco_index, h->mmco_index);
845 846 847
        return AVERROR_INVALIDDATA;
    }

848 849
    return 0;
}