Coverage Report

Created: 2026-09-14 08:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/h264_refs.c
Line
Count
Source
1
/*
2
 * H.26L/H.264/AVC/JVT/14496-10/... reference picture handling
3
 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
/**
23
 * @file
24
 * H.264 / AVC / MPEG-4 part10  reference picture handling.
25
 * @author Michael Niedermayer <michaelni@gmx.at>
26
 */
27
28
#include <inttypes.h>
29
30
#include "libavutil/avassert.h"
31
#include "avcodec.h"
32
#include "h264.h"
33
#include "h264dec.h"
34
#include "golomb.h"
35
#include "mpegutils.h"
36
37
#include <assert.h>
38
39
static void pic_as_field(H264Ref *pic, const int parity)
40
1.58M
{
41
6.32M
    for (int i = 0; i < FF_ARRAY_ELEMS(pic->data); ++i) {
42
4.74M
        if (parity == PICT_BOTTOM_FIELD)
43
1.69M
            pic->data[i]   += pic->linesize[i];
44
4.74M
        pic->reference      = parity;
45
4.74M
        pic->linesize[i] *= 2;
46
4.74M
    }
47
1.58M
    pic->poc = pic->parent->field_poc[parity == PICT_BOTTOM_FIELD];
48
1.58M
}
49
50
static void ref_from_h264pic(H264Ref *dst, const H264Picture *src)
51
6.20M
{
52
6.20M
    memcpy(dst->data,     src->f->data,     sizeof(dst->data));
53
6.20M
    memcpy(dst->linesize, src->f->linesize, sizeof(dst->linesize));
54
6.20M
    dst->reference = src->reference;
55
6.20M
    dst->poc       = src->poc;
56
6.20M
    dst->pic_id    = src->pic_id;
57
6.20M
    dst->parent = src;
58
6.20M
}
59
60
static int split_field_copy(H264Ref *dest, const H264Picture *src,
61
                            int parity, int id_add)
62
6.15M
{
63
6.15M
    int match = !!(src->reference & parity);
64
65
6.15M
    if (match) {
66
6.15M
        ref_from_h264pic(dest, src);
67
6.15M
        if (parity != PICT_FRAME) {
68
1.56M
            pic_as_field(dest, parity);
69
1.56M
            dest->pic_id *= 2;
70
1.56M
            dest->pic_id += id_add;
71
1.56M
        }
72
6.15M
    }
73
74
6.15M
    return match;
75
6.15M
}
76
77
static int build_def_list(H264Ref *def, int def_len,
78
                          H264Picture * const *in, int len, int is_long, int sel)
79
6.26M
{
80
6.26M
    int  i[2] = { 0 };
81
6.26M
    int index = 0;
82
83
15.3M
    while (i[0] < len || i[1] < len) {
84
58.3M
        while (i[0] < len && !(in[i[0]] && (in[i[0]]->reference & sel)))
85
49.2M
            i[0]++;
86
64.0M
        while (i[1] < len && !(in[i[1]] && (in[i[1]]->reference & (sel ^ 3))))
87
54.9M
            i[1]++;
88
9.10M
        if (i[0] < len) {
89
5.93M
            av_assert0(index < def_len);
90
5.93M
            in[i[0]]->pic_id = is_long ? i[0] : in[i[0]]->frame_num;
91
5.93M
            split_field_copy(&def[index++], in[i[0]++], sel, 1);
92
5.93M
        }
93
9.10M
        if (i[1] < len) {
94
221k
            av_assert0(index < def_len);
95
221k
            in[i[1]]->pic_id = is_long ? i[1] : in[i[1]]->frame_num;
96
221k
            split_field_copy(&def[index++], in[i[1]++], sel ^ 3, 0);
97
221k
        }
98
9.10M
    }
99
100
6.26M
    return index;
101
6.26M
}
102
103
static int add_sorted(H264Picture **sorted, H264Picture * const *src,
104
                      int len, int limit, int dir)
105
2.73M
{
106
2.73M
    int out_i = 0;
107
108
5.47M
    for (;;) {
109
5.47M
        int best_poc = dir ? INT_MIN : INT_MAX;
110
111
23.5M
        for (int i = 0; i < len; i++) {
112
18.0M
            const int poc = src[i]->poc;
113
18.0M
            if (((poc > limit) ^ dir) && ((poc < best_poc) ^ dir)) {
114
4.69M
                best_poc      = poc;
115
4.69M
                sorted[out_i] = src[i];
116
4.69M
            }
117
18.0M
        }
118
5.47M
        if (best_poc == (dir ? INT_MIN : INT_MAX))
119
2.73M
            break;
120
2.73M
        limit = sorted[out_i++]->poc - dir;
121
2.73M
    }
122
2.73M
    return out_i;
123
2.73M
}
124
125
static int mismatches_ref(const H264Context *h, const H264Picture *pic)
126
3.59M
{
127
3.59M
    const AVFrame *f = pic->f;
128
3.59M
    return (h->cur_pic_ptr->f->width  != f->width ||
129
3.59M
            h->cur_pic_ptr->f->height != f->height ||
130
3.59M
            h->cur_pic_ptr->f->format != f->format);
131
3.59M
}
132
133
static void h264_initialise_ref_list(H264Context *h, H264SliceContext *sl)
134
2.44M
{
135
2.44M
    int len;
136
137
2.44M
    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
138
684k
        H264Picture *sorted[32];
139
684k
        int cur_poc;
140
684k
        int lens[2];
141
142
684k
        if (FIELD_PICTURE(h))
143
158k
            cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure == PICT_BOTTOM_FIELD];
144
525k
        else
145
525k
            cur_poc = h->cur_pic_ptr->poc;
146
147
2.05M
        for (int list = 0; list < 2; list++) {
148
1.36M
            len  = add_sorted(sorted,       h->short_ref, h->short_ref_count, cur_poc, 1 ^ list);
149
1.36M
            len += add_sorted(sorted + len, h->short_ref, h->short_ref_count, cur_poc, 0 ^ list);
150
1.36M
            av_assert0(len <= 32);
151
152
1.36M
            len  = build_def_list(sl->ref_list[list], FF_ARRAY_ELEMS(sl->ref_list[0]),
153
1.36M
                                  sorted, len, 0, h->picture_structure);
154
1.36M
            len += build_def_list(sl->ref_list[list] + len,
155
1.36M
                                  FF_ARRAY_ELEMS(sl->ref_list[0]) - len,
156
1.36M
                                  h->long_ref, 16, 1, h->picture_structure);
157
1.36M
            av_assert0(len <= 32);
158
159
1.36M
            memset(&sl->ref_list[list][len], 0, sizeof(H264Ref) * (32 - len));
160
1.36M
            lens[list] = len;
161
1.36M
        }
162
163
684k
        if (lens[0] == lens[1] && lens[1] > 1) {
164
386k
            int i;
165
1.78M
            for (i = 0; i < lens[0] &&
166
1.41M
                        sl->ref_list[0][i].parent->f->buf[0]->buffer ==
167
1.41M
                        sl->ref_list[1][i].parent->f->buf[0]->buffer; i++);
168
386k
            if (i == lens[0]) {
169
371k
                FFSWAP(H264Ref, sl->ref_list[1][0], sl->ref_list[1][1]);
170
371k
            }
171
386k
        }
172
1.76M
    } else {
173
1.76M
        len  = build_def_list(sl->ref_list[0], FF_ARRAY_ELEMS(sl->ref_list[0]),
174
1.76M
                              h->short_ref, h->short_ref_count, 0, h->picture_structure);
175
1.76M
        len += build_def_list(sl->ref_list[0] + len,
176
1.76M
                              FF_ARRAY_ELEMS(sl->ref_list[0]) - len,
177
1.76M
                              h-> long_ref, 16, 1, h->picture_structure);
178
1.76M
        av_assert0(len <= 32);
179
180
1.76M
        memset(&sl->ref_list[0][len], 0, sizeof(H264Ref) * (32 - len));
181
1.76M
    }
182
#ifdef TRACE
183
    for (int i = 0; i < sl->ref_count[0]; i++) {
184
        ff_tlog(h->avctx, "List0: %s fn:%d 0x%p\n",
185
                (sl->ref_list[0][i].parent ? (sl->ref_list[0][i].parent->long_ref ? "LT" : "ST") : "??"),
186
                sl->ref_list[0][i].pic_id,
187
                sl->ref_list[0][i].data[0]);
188
    }
189
    if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
190
        for (int i = 0; i < sl->ref_count[1]; i++) {
191
            ff_tlog(h->avctx, "List1: %s fn:%d 0x%p\n",
192
                    (sl->ref_list[1][i].parent ? (sl->ref_list[1][i].parent->long_ref ? "LT" : "ST") : "??"),
193
                    sl->ref_list[1][i].pic_id,
194
                    sl->ref_list[1][i].data[0]);
195
        }
196
    }
197
#endif
198
199
5.58M
    for (int j = 0; j < 1 + (sl->slice_type_nos == AV_PICTURE_TYPE_B); j++) {
200
11.4M
        for (int i = 0; i < sl->ref_count[j]; i++) {
201
8.31M
            if (sl->ref_list[j][i].parent) {
202
3.54M
                if (mismatches_ref(h, sl->ref_list[j][i].parent)) {
203
0
                    av_log(h->avctx, AV_LOG_ERROR, "Discarding mismatching reference\n");
204
0
                    memset(&sl->ref_list[j][i], 0, sizeof(sl->ref_list[j][i]));
205
0
                }
206
3.54M
            }
207
8.31M
        }
208
3.13M
    }
209
4.61M
    for (int i = 0; i < sl->list_count; i++)
210
2.16M
        h->default_ref[i] = sl->ref_list[i][0];
211
2.44M
}
212
213
/**
214
 * print short term list
215
 */
216
static void print_short_term(const H264Context *h)
217
5.47M
{
218
5.47M
    if (h->avctx->debug & FF_DEBUG_MMCO) {
219
0
        av_log(h->avctx, AV_LOG_DEBUG, "short term list:\n");
220
0
        for (uint32_t i = 0; i < h->short_ref_count; i++) {
221
0
            H264Picture *pic = h->short_ref[i];
222
0
            av_log(h->avctx, AV_LOG_DEBUG, "%"PRIu32" fn:%d poc:%d %p\n",
223
0
                   i, pic->frame_num, pic->poc, pic->f->data[0]);
224
0
        }
225
0
    }
226
5.47M
}
227
228
/**
229
 * print long term list
230
 */
231
static void print_long_term(const H264Context *h)
232
5.47M
{
233
5.47M
    if (h->avctx->debug & FF_DEBUG_MMCO) {
234
0
        av_log(h->avctx, AV_LOG_DEBUG, "long term list:\n");
235
0
        for (uint32_t i = 0; i < 16; i++) {
236
0
            H264Picture *pic = h->long_ref[i];
237
0
            if (pic) {
238
0
                av_log(h->avctx, AV_LOG_DEBUG, "%"PRIu32" fn:%d poc:%d %p\n",
239
0
                       i, pic->frame_num, pic->poc, pic->f->data[0]);
240
0
            }
241
0
        }
242
0
    }
243
5.47M
}
244
245
/**
246
 * Extract structure information about the picture described by pic_num in
247
 * the current decoding context (frame or field). Note that pic_num is
248
 * picture number without wrapping (so, 0<=pic_num<max_pic_num).
249
 * @param pic_num picture number for which to extract structure information
250
 * @param structure one of PICT_XXX describing structure of picture
251
 *                      with pic_num
252
 * @return frame number (short term) or long term index of picture
253
 *         described by pic_num
254
 */
255
static int pic_num_extract(const H264Context *h, int pic_num, int *structure)
256
1.04M
{
257
1.04M
    *structure = h->picture_structure;
258
1.04M
    if (FIELD_PICTURE(h)) {
259
398k
        if (!(pic_num & 1))
260
            /* opposite field */
261
274k
            *structure ^= PICT_FRAME;
262
398k
        pic_num >>= 1;
263
398k
    }
264
265
1.04M
    return pic_num;
266
1.04M
}
267
268
static void h264_fill_mbaff_ref_list(H264SliceContext *sl)
269
740k
{
270
1.40M
    for (int list = 0; list < sl->list_count; list++) {
271
3.25M
        for (int i = 0; i < sl->ref_count[list]; i++) {
272
2.59M
            const H264Ref *frame = &sl->ref_list[list][i];
273
2.59M
            H264Ref *field = &sl->ref_list[list][16 + 2 * i];
274
275
2.59M
            field[0] = *frame;
276
277
10.3M
            for (int j = 0; j < 3; j++)
278
7.77M
                field[0].linesize[j] <<= 1;
279
2.59M
            field[0].reference = PICT_TOP_FIELD;
280
2.59M
            field[0].poc       = field[0].parent->field_poc[0];
281
282
2.59M
            field[1] = field[0];
283
284
10.3M
            for (int j = 0; j < 3; j++)
285
7.77M
                field[1].data[j] += frame->parent->f->linesize[j];
286
2.59M
            field[1].reference = PICT_BOTTOM_FIELD;
287
2.59M
            field[1].poc       = field[1].parent->field_poc[1];
288
2.59M
        }
289
663k
    }
290
740k
}
291
292
int ff_h264_build_ref_list(H264Context *h, H264SliceContext *sl)
293
2.44M
{
294
2.44M
    print_short_term(h);
295
2.44M
    print_long_term(h);
296
297
2.44M
    h264_initialise_ref_list(h, sl);
298
299
4.60M
    for (int list = 0; list < sl->list_count; list++) {
300
2.16M
        int pred = sl->curr_pic_num;
301
302
2.53M
        for (int index = 0; index < sl->nb_ref_modifications[list]; index++) {
303
380k
            unsigned int modification_of_pic_nums_idc = sl->ref_modifications[list][index].op;
304
380k
            unsigned int                          val = sl->ref_modifications[list][index].val;
305
380k
            unsigned int pic_id;
306
380k
            int i, pic_structure;
307
380k
            H264Picture *ref = NULL;
308
309
380k
            switch (modification_of_pic_nums_idc) {
310
287k
            case 0:
311
301k
            case 1: {
312
301k
                const unsigned int abs_diff_pic_num = val + 1;
313
301k
                int frame_num;
314
315
301k
                if (abs_diff_pic_num > sl->max_pic_num) {
316
2.55k
                    av_log(h->avctx, AV_LOG_ERROR,
317
2.55k
                           "abs_diff_pic_num overflow\n");
318
2.55k
                    return AVERROR_INVALIDDATA;
319
2.55k
                }
320
321
299k
                if (modification_of_pic_nums_idc == 0)
322
285k
                    pred -= abs_diff_pic_num;
323
13.7k
                else
324
13.7k
                    pred += abs_diff_pic_num;
325
299k
                pred &= sl->max_pic_num - 1;
326
327
299k
                frame_num = pic_num_extract(h, pred, &pic_structure);
328
329
662k
                for (i = h->short_ref_count - 1; i >= 0; i--) {
330
413k
                    ref = h->short_ref[i];
331
413k
                    assert(ref->reference);
332
413k
                    assert(!ref->long_ref);
333
413k
                    if (ref->frame_num == frame_num &&
334
51.7k
                        (ref->reference & pic_structure))
335
50.1k
                        break;
336
413k
                }
337
299k
                if (i >= 0)
338
50.1k
                    pic_id = pred;
339
299k
                break;
340
301k
            }
341
79.0k
            case 2: {
342
79.0k
                int long_idx;
343
79.0k
                pic_id = val; // long_term_pic_idx
344
345
79.0k
                long_idx = pic_num_extract(h, pic_id, &pic_structure);
346
347
79.0k
                if (long_idx > 31U) {
348
45
                    av_log(h->avctx, AV_LOG_ERROR,
349
45
                           "long_term_pic_idx overflow\n");
350
45
                    return AVERROR_INVALIDDATA;
351
45
                }
352
78.9k
                ref = h->long_ref[long_idx];
353
78.9k
                assert(!(ref && !ref->reference));
354
78.9k
                if (ref && (ref->reference & pic_structure)) {
355
719
                    assert(ref->long_ref);
356
719
                    i = 0;
357
78.2k
                } else {
358
78.2k
                    i = -1;
359
78.2k
                }
360
78.9k
                break;
361
79.0k
            }
362
0
            default:
363
0
                av_assert0(0);
364
380k
            }
365
366
377k
            if (i < 0 || mismatches_ref(h, ref)) {
367
327k
                av_log(h->avctx, AV_LOG_ERROR,
368
327k
                       i < 0 ? "reference picture missing during reorder\n" :
369
327k
                               "mismatching reference\n"
370
327k
                      );
371
327k
                if (h->avctx->err_recognition & AV_EF_EXPLODE) {
372
9.92k
                    return AVERROR_INVALIDDATA;
373
9.92k
                }
374
317k
                memset(&sl->ref_list[list][index], 0, sizeof(sl->ref_list[0][0])); // FIXME
375
317k
            } else {
376
104k
                for (i = index; i + 1 < sl->ref_count[list]; i++) {
377
74.8k
                    if (sl->ref_list[list][i].parent &&
378
65.9k
                        ref->long_ref == sl->ref_list[list][i].parent->long_ref &&
379
64.0k
                        pic_id        == sl->ref_list[list][i].pic_id)
380
21.3k
                        break;
381
74.8k
                }
382
104k
                for (; i > index; i--) {
383
53.4k
                    sl->ref_list[list][i] = sl->ref_list[list][i - 1];
384
53.4k
                }
385
50.8k
                ref_from_h264pic(&sl->ref_list[list][index], ref);
386
50.8k
                if (FIELD_PICTURE(h)) {
387
11.5k
                    pic_as_field(&sl->ref_list[list][index], pic_structure);
388
11.5k
                }
389
50.8k
            }
390
377k
        }
391
2.16M
    }
392
4.43M
    for (int list = 0; list < sl->list_count; list++) {
393
9.79M
        for (int index = 0; index < sl->ref_count[list]; index++) {
394
7.80M
            if (   !sl->ref_list[list][index].parent
395
4.63M
                || (!FIELD_PICTURE(h) && (sl->ref_list[list][index].reference&3) != 3)) {
396
4.63M
                if (h->avctx->err_recognition & AV_EF_EXPLODE) {
397
17.4k
                    av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture\n");
398
17.4k
                    return AVERROR_INVALIDDATA;
399
17.4k
                }
400
4.61M
                av_log(h->avctx, AV_LOG_ERROR, "Missing reference picture, default is %d\n", h->default_ref[list].poc);
401
402
78.4M
                for (int i = 0; i < FF_ARRAY_ELEMS(h->last_pocs); i++)
403
73.8M
                    h->last_pocs[i] = INT_MIN;
404
4.61M
                if (h->default_ref[list].parent
405
4.54M
                    && !(!FIELD_PICTURE(h) && (h->default_ref[list].reference&3) != 3))
406
4.52M
                    sl->ref_list[list][index] = h->default_ref[list];
407
94.7k
                else
408
94.7k
                    return -1;
409
4.61M
            }
410
7.68M
            if (h->noref_gray>0 && sl->ref_list[list][index].parent->gray && h->non_gray) {
411
1.04M
                for (int j=0; j<sl->list_count; j++) {
412
652k
                    int list2 = (list+j)&1;
413
652k
                    if (h->default_ref[list2].parent && !h->default_ref[list2].parent->gray
414
3.96k
                        && !(!FIELD_PICTURE(h) && (h->default_ref[list2].reference&3) != 3)) {
415
3.83k
                        sl->ref_list[list][index] = h->default_ref[list2];
416
3.83k
                        av_log(h->avctx, AV_LOG_DEBUG, "replacement of gray gap frame\n");
417
3.83k
                        break;
418
3.83k
                    }
419
652k
                }
420
400k
            }
421
7.68M
            av_assert0(av_buffer_get_ref_count(sl->ref_list[list][index].parent->f->buf[0]) > 0);
422
7.68M
        }
423
2.10M
    }
424
425
2.32M
    if (FRAME_MBAFF(h))
426
740k
        h264_fill_mbaff_ref_list(sl);
427
428
2.32M
    return 0;
429
2.43M
}
430
431
int ff_h264_decode_ref_pic_list_reordering(H264SliceContext *sl, void *logctx)
432
2.26M
{
433
2.26M
    sl->nb_ref_modifications[0] = 0;
434
2.26M
    sl->nb_ref_modifications[1] = 0;
435
436
5.07M
    for (int list = 0; list < sl->list_count; list++) {
437
3.10M
        if (!get_bits1(&sl->gb))    // ref_pic_list_modification_flag_l[01]
438
2.39M
            continue;
439
440
1.43M
        for (int index = 0; ; index++) {
441
1.43M
            unsigned int op = get_ue_golomb_31(&sl->gb);
442
443
1.43M
            if (op == 3)
444
417k
                break;
445
446
1.01M
            if (index >= sl->ref_count[list]) {
447
153k
                av_log(logctx, AV_LOG_ERROR, "reference count overflow\n");
448
153k
                return AVERROR_INVALIDDATA;
449
863k
            } else if (op > 2) {
450
131k
                av_log(logctx, AV_LOG_ERROR,
451
131k
                       "illegal modification_of_pic_nums_idc %u\n",
452
131k
                       op);
453
131k
                return AVERROR_INVALIDDATA;
454
131k
            }
455
732k
            sl->ref_modifications[list][index].val = get_ue_golomb_long(&sl->gb);
456
732k
            sl->ref_modifications[list][index].op  = op;
457
732k
            sl->nb_ref_modifications[list]++;
458
732k
        }
459
702k
    }
460
461
1.97M
    return 0;
462
2.26M
}
463
464
/**
465
 * Mark a picture as no longer needed for reference. The refmask
466
 * argument allows unreferencing of individual fields or the whole frame.
467
 * If the picture becomes entirely unreferenced, but is being held for
468
 * display purposes, it is marked as such.
469
 * @param refmask mask of fields to unreference; the mask is bitwise
470
 *                anded with the reference marking of pic
471
 * @return non-zero if pic becomes entirely unreferenced (except possibly
472
 *         for display purposes) zero if one of the fields remains in
473
 *         reference
474
 */
475
static inline int unreference_pic(H264Context *h, H264Picture *pic, int refmask)
476
3.57M
{
477
3.57M
    if (pic->reference &= refmask) {
478
101k
        return 0;
479
3.47M
    } else {
480
7.97M
        for (int i = 0; h->delayed_pic[i]; i++)
481
5.34M
            if(pic == h->delayed_pic[i]){
482
851k
                pic->reference = DELAYED_PIC_REF;
483
851k
                break;
484
851k
            }
485
3.47M
        return 1;
486
3.47M
    }
487
3.57M
}
488
489
/**
490
 * Find a H264Picture in the short term reference list by frame number.
491
 * @param frame_num frame number to search for
492
 * @param idx the index into h->short_ref where returned picture is found
493
 *            undefined if no picture found.
494
 * @return pointer to the found picture, or NULL if no pic with the provided
495
 *                 frame number is found
496
 */
497
static H264Picture *find_short(H264Context *h, int frame_num, int *idx)
498
3.90M
{
499
11.0M
    for (int i = 0; i < h->short_ref_count; i++) {
500
8.84M
        H264Picture *pic = h->short_ref[i];
501
8.84M
        if (h->avctx->debug & FF_DEBUG_MMCO)
502
0
            av_log(h->avctx, AV_LOG_DEBUG, "%d %d %p\n", i, pic->frame_num, pic);
503
8.84M
        if (pic->frame_num == frame_num) {
504
1.67M
            *idx = i;
505
1.67M
            return pic;
506
1.67M
        }
507
8.84M
    }
508
2.22M
    return NULL;
509
3.90M
}
510
511
/**
512
 * Remove a picture from the short term reference list by its index in
513
 * that list.  This does no checking on the provided index; it is assumed
514
 * to be valid. Other list entries are shifted down.
515
 * @param i index into h->short_ref of picture to remove.
516
 */
517
static void remove_short_at_index(H264Context *h, int i)
518
1.16M
{
519
1.16M
    assert(i >= 0 && i < h->short_ref_count);
520
1.16M
    h->short_ref[i] = NULL;
521
1.16M
    if (--h->short_ref_count)
522
647k
        memmove(&h->short_ref[i], &h->short_ref[i + 1],
523
647k
                (h->short_ref_count - i) * sizeof(H264Picture*));
524
1.16M
}
525
526
/**
527
 * @return the removed picture or NULL if an error occurs
528
 */
529
static H264Picture *remove_short(H264Context *h, int frame_num, int ref_mask)
530
3.34M
{
531
3.34M
    H264Picture *pic;
532
3.34M
    int i;
533
534
3.34M
    if (h->avctx->debug & FF_DEBUG_MMCO)
535
0
        av_log(h->avctx, AV_LOG_DEBUG, "remove short %d count %d\n", frame_num, h->short_ref_count);
536
537
3.34M
    pic = find_short(h, frame_num, &i);
538
3.34M
    if (pic) {
539
1.25M
        if (unreference_pic(h, pic, ref_mask))
540
1.15M
            remove_short_at_index(h, i);
541
1.25M
    }
542
543
3.34M
    return pic;
544
3.34M
}
545
546
/**
547
 * Remove a picture from the long term reference list by its index in
548
 * that list.
549
 * @return the removed picture or NULL if an error occurs
550
 */
551
static H264Picture *remove_long(H264Context *h, int i, int ref_mask)
552
28.9M
{
553
28.9M
    H264Picture *pic;
554
555
28.9M
    pic = h->long_ref[i];
556
28.9M
    if (pic) {
557
939k
        if (unreference_pic(h, pic, ref_mask)) {
558
938k
            assert(h->long_ref[i]->long_ref == 1);
559
938k
            h->long_ref[i]->long_ref = 0;
560
938k
            h->long_ref[i]           = NULL;
561
938k
            h->long_ref_count--;
562
938k
        }
563
939k
    }
564
565
28.9M
    return pic;
566
28.9M
}
567
568
void ff_h264_remove_all_refs(H264Context *h)
569
1.68M
{
570
28.5M
    for (int i = 0; i < 16; i++)
571
26.9M
        remove_long(h, i, 0);
572
1.68M
    assert(h->long_ref_count == 0);
573
574
1.68M
    if (h->short_ref_count && !h->last_pic_for_ec.f->data[0]) {
575
682k
        ff_h264_unref_picture(&h->last_pic_for_ec);
576
682k
        ff_h264_ref_picture(&h->last_pic_for_ec, h->short_ref[0]);
577
682k
    }
578
579
3.06M
    for (int i = 0; i < h->short_ref_count; i++) {
580
1.38M
        unreference_pic(h, h->short_ref[i], 0);
581
1.38M
        h->short_ref[i] = NULL;
582
1.38M
    }
583
1.68M
    h->short_ref_count = 0;
584
585
1.68M
    memset(h->default_ref, 0, sizeof(h->default_ref));
586
1.68M
}
587
588
static void generate_sliding_window_mmcos(H264Context *h)
589
1.84M
{
590
1.84M
    MMCO *mmco = h->mmco;
591
1.84M
    int nb_mmco = 0;
592
593
1.84M
    if (h->short_ref_count &&
594
1.44M
        h->long_ref_count + h->short_ref_count >= h->ps.sps->ref_frame_count &&
595
308k
        !(FIELD_PICTURE(h) && !h->first_field && h->cur_pic_ptr->reference)) {
596
307k
        mmco[0].opcode        = MMCO_SHORT2UNUSED;
597
307k
        mmco[0].short_pic_num = h->short_ref[h->short_ref_count - 1]->frame_num;
598
307k
        nb_mmco               = 1;
599
307k
        if (FIELD_PICTURE(h)) {
600
58.4k
            mmco[0].short_pic_num *= 2;
601
58.4k
            mmco[1].opcode         = MMCO_SHORT2UNUSED;
602
58.4k
            mmco[1].short_pic_num  = mmco[0].short_pic_num + 1;
603
58.4k
            nb_mmco                = 2;
604
58.4k
        }
605
307k
    }
606
607
1.84M
    h->nb_mmco = nb_mmco;
608
1.84M
}
609
610
int ff_h264_execute_ref_pic_marking(H264Context *h)
611
3.02M
{
612
3.02M
    MMCO *mmco = h->mmco;
613
3.02M
    int mmco_count;
614
3.02M
    int pps_ref_count[2] = {0};
615
3.02M
    int current_ref_assigned = 0, err = 0;
616
617
3.02M
    if (!h->ps.sps) {
618
0
        av_log(h->avctx, AV_LOG_ERROR, "SPS is unset\n");
619
0
        err = AVERROR_INVALIDDATA;
620
0
        goto out;
621
0
    }
622
623
3.02M
    if (!h->explicit_ref_marking)
624
1.84M
        generate_sliding_window_mmcos(h);
625
3.02M
    mmco_count = h->nb_mmco;
626
627
3.02M
    if ((h->avctx->debug & FF_DEBUG_MMCO) && mmco_count == 0)
628
0
        av_log(h->avctx, AV_LOG_DEBUG, "no mmco here\n");
629
630
4.65M
    for (int i = 0; i < mmco_count; i++) {
631
1.63M
        if (h->avctx->debug & FF_DEBUG_MMCO)
632
0
            av_log(h->avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode,
633
0
                   h->mmco[i].short_pic_num, h->mmco[i].long_arg);
634
635
1.63M
        switch (mmco[i].opcode) {
636
519k
        case MMCO_SHORT2UNUSED:
637
563k
        case MMCO_SHORT2LONG: {
638
563k
            int structure, j;
639
563k
            int frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);
640
563k
            H264Picture *pic = find_short(h, frame_num, &j);
641
642
563k
            if (!pic) {
643
138k
                if (mmco[i].opcode != MMCO_SHORT2LONG ||
644
33.5k
                    !h->long_ref[mmco[i].long_arg]    ||
645
134k
                    h->long_ref[mmco[i].long_arg]->frame_num != frame_num) {
646
134k
                    av_log(h->avctx, h->short_ref_count ? AV_LOG_ERROR : AV_LOG_DEBUG, "mmco: unref short failure\n");
647
134k
                    err = AVERROR_INVALIDDATA;
648
134k
                }
649
138k
                continue;
650
138k
            }
651
425k
            if (mmco[i].opcode == MMCO_SHORT2UNUSED) {
652
415k
                if (h->avctx->debug & FF_DEBUG_MMCO)
653
0
                    av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n",
654
0
                           h->mmco[i].short_pic_num, h->short_ref_count);
655
415k
                remove_short(h, frame_num, structure ^ PICT_FRAME);
656
415k
            } else {
657
9.85k
                if (h->long_ref[mmco[i].long_arg] != pic)
658
9.85k
                    remove_long(h, mmco[i].long_arg, 0);
659
660
9.85k
                remove_short_at_index(h, j);
661
9.85k
                h->long_ref[ mmco[i].long_arg ] = pic;
662
9.85k
                if (h->long_ref[mmco[i].long_arg]) {
663
9.85k
                    h->long_ref[mmco[i].long_arg]->long_ref = 1;
664
9.85k
                    h->long_ref_count++;
665
9.85k
                }
666
9.85k
            }
667
425k
            break;
668
563k
        }
669
100k
        case MMCO_LONG2UNUSED: {
670
100k
            int structure, j = pic_num_extract(h, mmco[i].long_arg, &structure);
671
100k
            H264Picture *pic = h->long_ref[j];
672
100k
            if (pic) {
673
3.60k
                remove_long(h, j, structure ^ PICT_FRAME);
674
97.1k
            } else if (h->avctx->debug & FF_DEBUG_MMCO)
675
0
                av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");
676
100k
            break;
677
563k
        }
678
928k
        case MMCO_LONG:
679
                    // Comment below left from previous code as it is an interesting note.
680
                    /* First field in pair is in short term list or
681
                     * at a different long term index.
682
                     * This is not allowed; see 7.4.3.3, notes 2 and 3.
683
                     * Report the problem and keep the pair where it is,
684
                     * and mark this field valid.
685
                     */
686
928k
            if (h->short_ref[0] == h->cur_pic_ptr) {
687
211
                av_log(h->avctx, AV_LOG_ERROR, "mmco: cannot assign current picture to short and long at the same time\n");
688
211
                remove_short_at_index(h, 0);
689
211
            }
690
691
            /* make sure the current picture is not already assigned as a long ref */
692
928k
            if (h->cur_pic_ptr->long_ref) {
693
15.6M
                for (int j = 0; j < FF_ARRAY_ELEMS(h->long_ref); j++) {
694
15.2M
                    if (h->long_ref[j] == h->cur_pic_ptr) {
695
475k
                        if (j != mmco[i].long_arg)
696
20.1k
                            av_log(h->avctx, AV_LOG_ERROR, "mmco: cannot assign current picture to 2 long term references\n");
697
475k
                        remove_long(h, j, 0);
698
475k
                    }
699
15.2M
                }
700
475k
            }
701
702
928k
            if (h->long_ref[mmco[i].long_arg] != h->cur_pic_ptr) {
703
928k
                av_assert0(!h->cur_pic_ptr->long_ref);
704
928k
                remove_long(h, mmco[i].long_arg, 0);
705
706
928k
                h->long_ref[mmco[i].long_arg]           = h->cur_pic_ptr;
707
928k
                h->long_ref[mmco[i].long_arg]->long_ref = 1;
708
928k
                h->long_ref_count++;
709
928k
            }
710
711
928k
            h->cur_pic_ptr->reference |= h->picture_structure;
712
928k
            current_ref_assigned = 1;
713
928k
            break;
714
15.6k
        case MMCO_SET_MAX_LONG:
715
15.6k
            assert(mmco[i].long_arg <= 16);
716
            // just remove the long term which index is greater than new max
717
221k
            for (int j = mmco[i].long_arg; j < 16; j++)
718
205k
                remove_long(h, j, 0);
719
15.6k
            break;
720
27.2k
        case MMCO_RESET:
721
59.0k
            while (h->short_ref_count) {
722
31.8k
                remove_short(h, h->short_ref[0]->frame_num, 0);
723
31.8k
            }
724
462k
            for (int j = 0; j < 16; j++)
725
435k
                remove_long(h, j, 0);
726
27.2k
            h->poc.frame_num = h->cur_pic_ptr->frame_num = 0;
727
27.2k
            h->mmco_reset = 1;
728
27.2k
            h->cur_pic_ptr->mmco_reset = 1;
729
462k
            for (int j = 0; j < FF_ARRAY_ELEMS(h->last_pocs); j++)
730
435k
                h->last_pocs[j] = INT_MIN;
731
27.2k
            break;
732
0
        default: av_assert0(0);
733
1.63M
        }
734
1.63M
    }
735
736
3.02M
    if (!current_ref_assigned) {
737
        /* Second field of complementary field pair; the first field of
738
         * which is already referenced. If short referenced, it
739
         * should be first entry in short_ref. If not, it must exist
740
         * in long_ref; trying to put it on the short list here is an
741
         * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).
742
         */
743
2.56M
        if (h->short_ref_count && h->short_ref[0] == h->cur_pic_ptr) {
744
            /* Just mark the second field valid */
745
18.0k
            h->cur_pic_ptr->reference |= h->picture_structure;
746
2.54M
        } else if (h->cur_pic_ptr->long_ref) {
747
315
            av_log(h->avctx, AV_LOG_ERROR, "illegal short term reference "
748
315
                                           "assignment for second field "
749
315
                                           "in complementary field pair "
750
315
                                           "(first field is long term)\n");
751
315
            err = AVERROR_INVALIDDATA;
752
2.54M
        } else {
753
2.54M
            H264Picture *pic = remove_short(h, h->cur_pic_ptr->frame_num, 0);
754
2.54M
            if (pic) {
755
455k
                av_log(h->avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");
756
455k
                err = AVERROR_INVALIDDATA;
757
455k
            }
758
759
2.54M
            if (h->short_ref_count)
760
1.34M
                memmove(&h->short_ref[1], &h->short_ref[0],
761
1.34M
                        h->short_ref_count * sizeof(H264Picture*));
762
763
2.54M
            h->short_ref[0] = h->cur_pic_ptr;
764
2.54M
            h->short_ref_count++;
765
2.54M
            h->cur_pic_ptr->reference |= h->picture_structure;
766
2.54M
        }
767
2.56M
    }
768
769
3.02M
    if (h->long_ref_count + h->short_ref_count > FFMAX(h->ps.sps->ref_frame_count, 1)) {
770
771
        /* We have too many reference frames, probably due to corrupted
772
         * stream. Need to discard one frame. Prevents overrun of the
773
         * short_ref and long_ref buffers.
774
         */
775
151k
        av_log(h->avctx, AV_LOG_ERROR,
776
151k
               "number of reference frames (%d+%d) exceeds max (%d; probably "
777
151k
               "corrupt input), discarding one\n",
778
151k
               h->long_ref_count, h->short_ref_count, h->ps.sps->ref_frame_count);
779
151k
        err = AVERROR_INVALIDDATA;
780
781
151k
        if (h->long_ref_count && !h->short_ref_count) {
782
2.49k
            int i;
783
7.37k
            for (i = 0; i < 16; ++i)
784
7.37k
                if (h->long_ref[i])
785
2.49k
                    break;
786
787
2.49k
            assert(i < 16);
788
2.49k
            remove_long(h, i, 0);
789
148k
        } else {
790
148k
            H264Picture *pic = h->short_ref[h->short_ref_count - 1];
791
148k
            remove_short(h, pic->frame_num, 0);
792
148k
        }
793
151k
    }
794
795
10.1M
    for (int i = 0; i < h->short_ref_count; i++) {
796
7.07M
        H264Picture *pic = h->short_ref[i];
797
7.07M
        if (pic->invalid_gap) {
798
5.01M
            int d = av_zero_extend(h->cur_pic_ptr->frame_num - pic->frame_num, h->ps.sps->log2_max_frame_num);
799
5.01M
            if (d > h->ps.sps->ref_frame_count)
800
200k
                remove_short(h, pic->frame_num, 0);
801
5.01M
        }
802
7.07M
    }
803
804
3.02M
    print_short_term(h);
805
3.02M
    print_long_term(h);
806
807
777M
    for (int i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {
808
774M
        if (h->ps.pps_list[i]) {
809
3.46M
            const PPS *pps = h->ps.pps_list[i];
810
3.46M
            pps_ref_count[0] = FFMAX(pps_ref_count[0], pps->ref_count[0]);
811
3.46M
            pps_ref_count[1] = FFMAX(pps_ref_count[1], pps->ref_count[1]);
812
3.46M
        }
813
774M
    }
814
815
    // Detect unmarked random access points
816
3.02M
    if (   err >= 0
817
2.38M
        && h->long_ref_count==0
818
1.70M
        && (   h->short_ref_count<=2
819
669k
            || pps_ref_count[0] <= 2 && pps_ref_count[1] <= 1 && h->avctx->has_b_frames
820
603k
            || pps_ref_count[0] <= 1 + (h->picture_structure != PICT_FRAME) && pps_ref_count[1] <= 1)
821
1.12M
        && pps_ref_count[0]<=2 + (h->picture_structure != PICT_FRAME) + (2*!h->has_recovery_point)
822
443k
        && h->cur_pic_ptr->f->pict_type == AV_PICTURE_TYPE_I){
823
238k
        h->cur_pic_ptr->recovered |= FRAME_RECOVERED_HEURISTIC;
824
238k
        if(!h->avctx->has_b_frames)
825
73.3k
            h->frame_recovered |= FRAME_RECOVERED_HEURISTIC;
826
238k
    }
827
828
3.02M
out:
829
3.02M
    return (h->avctx->err_recognition & AV_EF_EXPLODE) ? err : 0;
830
3.02M
}
831
832
int ff_h264_decode_ref_pic_marking(H264SliceContext *sl, GetBitContext *gb,
833
                                   const H2645NAL *nal, void *logctx)
834
1.97M
{
835
1.97M
    MMCO *mmco = sl->mmco;
836
1.97M
    int nb_mmco = 0;
837
838
1.97M
    if (nal->type == H264_NAL_IDR_SLICE) { // FIXME fields
839
1.07M
        skip_bits1(gb); // broken_link
840
1.07M
        if (get_bits1(gb)) {
841
457k
            mmco[0].opcode   = MMCO_LONG;
842
457k
            mmco[0].long_arg = 0;
843
457k
            nb_mmco          = 1;
844
457k
        }
845
1.07M
        sl->explicit_ref_marking = 1;
846
1.07M
    } else {
847
897k
        sl->explicit_ref_marking = get_bits1(gb);
848
897k
        if (sl->explicit_ref_marking) {
849
367k
            int i;
850
1.44M
            for (i = 0; i < FF_ARRAY_ELEMS(sl->mmco); i++) {
851
1.44M
                MMCOOpcode opcode = get_ue_golomb_31(gb);
852
853
1.44M
                mmco[i].opcode = opcode;
854
1.44M
                if (opcode == MMCO_SHORT2UNUSED || opcode == MMCO_SHORT2LONG) {
855
248k
                    mmco[i].short_pic_num =
856
248k
                        (sl->curr_pic_num - get_ue_golomb_long(gb) - 1) &
857
248k
                            (sl->max_pic_num - 1);
858
248k
                }
859
1.44M
                if (opcode == MMCO_SHORT2LONG || opcode == MMCO_LONG2UNUSED ||
860
1.23M
                    opcode == MMCO_LONG || opcode == MMCO_SET_MAX_LONG) {
861
861k
                    unsigned int long_arg = get_ue_golomb_31(gb);
862
861k
                    if (long_arg >= 32 ||
863
851k
                        (long_arg >= 16 && !(opcode == MMCO_SET_MAX_LONG &&
864
1.76k
                                             long_arg == 16) &&
865
13.5k
                         !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE(sl)))) {
866
13.5k
                        av_log(logctx, AV_LOG_ERROR,
867
13.5k
                               "illegal long ref in memory management control "
868
13.5k
                               "operation %d\n", opcode);
869
13.5k
                        sl->nb_mmco = i;
870
13.5k
                        return -1;
871
13.5k
                    }
872
848k
                    mmco[i].long_arg = long_arg;
873
848k
                }
874
875
1.42M
                if (opcode > (unsigned) MMCO_LONG) {
876
90.3k
                    av_log(logctx, AV_LOG_ERROR,
877
90.3k
                           "illegal memory management control operation %d\n",
878
90.3k
                           opcode);
879
90.3k
                    sl->nb_mmco = i;
880
90.3k
                    return -1;
881
90.3k
                }
882
1.33M
                if (opcode == MMCO_END)
883
259k
                    break;
884
1.33M
            }
885
263k
            nb_mmco = i;
886
263k
        }
887
897k
    }
888
889
1.87M
    sl->nb_mmco = nb_mmco;
890
891
1.87M
    return 0;
892
1.97M
}