1/*
2 * HEVC video decoder
3 *
4 * Copyright (C) 2012 - 2013 Guillaume Martres
5 * Copyright (C) 2012 - 2013 Gildas Cocherel
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#include "libavutil/pixdesc.h"
25
26#include "internal.h"
27#include "thread.h"
28#include "hevc.h"
29
30void ff_hevc_unref_frame(HEVCContext *s, HEVCFrame *frame, int flags)
31{
32    /* frame->frame can be NULL if context init failed */
33    if (!frame->frame || !frame->frame->buf[0])
34        return;
35
36    frame->flags &= ~flags;
37    if (!frame->flags) {
38        ff_thread_release_buffer(s->avctx, &frame->tf);
39
40        av_buffer_unref(&frame->tab_mvf_buf);
41        frame->tab_mvf = NULL;
42
43        av_buffer_unref(&frame->rpl_buf);
44        av_buffer_unref(&frame->rpl_tab_buf);
45        frame->rpl_tab    = NULL;
46        frame->refPicList = NULL;
47
48        frame->collocated_ref = NULL;
49    }
50}
51
52RefPicList *ff_hevc_get_ref_list(HEVCContext *s, HEVCFrame *ref, int x0, int y0)
53{
54    if (x0 < 0 || y0 < 0) {
55        return s->ref->refPicList;
56    } else {
57        int x_cb         = x0 >> s->sps->log2_ctb_size;
58        int y_cb         = y0 >> s->sps->log2_ctb_size;
59        int pic_width_cb = (s->sps->width + (1 << s->sps->log2_ctb_size) - 1) >>
60                           s->sps->log2_ctb_size;
61        int ctb_addr_ts  = s->pps->ctb_addr_rs_to_ts[y_cb * pic_width_cb + x_cb];
62        return (RefPicList *)ref->rpl_tab[ctb_addr_ts];
63    }
64}
65
66void ff_hevc_clear_refs(HEVCContext *s)
67{
68    int i;
69    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++)
70        ff_hevc_unref_frame(s, &s->DPB[i],
71                            HEVC_FRAME_FLAG_SHORT_REF |
72                            HEVC_FRAME_FLAG_LONG_REF);
73}
74
75void ff_hevc_flush_dpb(HEVCContext *s)
76{
77    int i;
78    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++)
79        ff_hevc_unref_frame(s, &s->DPB[i], ~0);
80}
81
82static HEVCFrame *alloc_frame(HEVCContext *s)
83{
84    int i, j, ret;
85    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
86        HEVCFrame *frame = &s->DPB[i];
87        if (frame->frame->buf[0])
88            continue;
89
90        ret = ff_thread_get_buffer(s->avctx, &frame->tf,
91                                   AV_GET_BUFFER_FLAG_REF);
92        if (ret < 0)
93            return NULL;
94
95        frame->rpl_buf = av_buffer_allocz(s->nb_nals * sizeof(RefPicListTab));
96        if (!frame->rpl_buf)
97            goto fail;
98
99        frame->tab_mvf_buf = av_buffer_pool_get(s->tab_mvf_pool);
100        if (!frame->tab_mvf_buf)
101            goto fail;
102        frame->tab_mvf = (MvField *)frame->tab_mvf_buf->data;
103
104        frame->rpl_tab_buf = av_buffer_pool_get(s->rpl_tab_pool);
105        if (!frame->rpl_tab_buf)
106            goto fail;
107        frame->rpl_tab   = (RefPicListTab **)frame->rpl_tab_buf->data;
108        frame->ctb_count = s->sps->ctb_width * s->sps->ctb_height;
109        for (j = 0; j < frame->ctb_count; j++)
110            frame->rpl_tab[j] = (RefPicListTab *)frame->rpl_buf->data;
111
112        frame->frame->top_field_first  = s->picture_struct == AV_PICTURE_STRUCTURE_TOP_FIELD;
113        frame->frame->interlaced_frame = (s->picture_struct == AV_PICTURE_STRUCTURE_TOP_FIELD) || (s->picture_struct == AV_PICTURE_STRUCTURE_BOTTOM_FIELD);
114        return frame;
115fail:
116        ff_hevc_unref_frame(s, frame, ~0);
117        return NULL;
118    }
119    av_log(s->avctx, AV_LOG_ERROR, "Error allocating frame, DPB full.\n");
120    return NULL;
121}
122
123int ff_hevc_set_new_ref(HEVCContext *s, AVFrame **frame, int poc)
124{
125    HEVCFrame *ref;
126    int i;
127
128    /* check that this POC doesn't already exist */
129    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
130        HEVCFrame *frame = &s->DPB[i];
131
132        if (frame->frame->buf[0] && frame->sequence == s->seq_decode &&
133            frame->poc == poc) {
134            av_log(s->avctx, AV_LOG_ERROR, "Duplicate POC in a sequence: %d.\n",
135                   poc);
136            return AVERROR_INVALIDDATA;
137        }
138    }
139
140    ref = alloc_frame(s);
141    if (!ref)
142        return AVERROR(ENOMEM);
143
144    *frame = ref->frame;
145    s->ref = ref;
146
147    if (s->sh.pic_output_flag)
148        ref->flags = HEVC_FRAME_FLAG_OUTPUT | HEVC_FRAME_FLAG_SHORT_REF;
149    else
150        ref->flags = HEVC_FRAME_FLAG_SHORT_REF;
151
152    ref->poc      = poc;
153    ref->sequence = s->seq_decode;
154    ref->window   = s->sps->output_window;
155
156    return 0;
157}
158
159int ff_hevc_output_frame(HEVCContext *s, AVFrame *out, int flush)
160{
161    do {
162        int nb_output = 0;
163        int min_poc   = INT_MAX;
164        int i, min_idx, ret;
165
166        if (s->sh.no_output_of_prior_pics_flag == 1) {
167            for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
168                HEVCFrame *frame = &s->DPB[i];
169                if ((frame->flags & HEVC_FRAME_FLAG_OUTPUT) && frame->poc != s->poc &&
170                        frame->sequence == s->seq_output) {
171                    frame->flags &= ~(HEVC_FRAME_FLAG_OUTPUT);
172                }
173            }
174        }
175
176        for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
177            HEVCFrame *frame = &s->DPB[i];
178            if ((frame->flags & HEVC_FRAME_FLAG_OUTPUT) &&
179                frame->sequence == s->seq_output) {
180                nb_output++;
181                if (frame->poc < min_poc) {
182                    min_poc = frame->poc;
183                    min_idx = i;
184                }
185            }
186        }
187
188        /* wait for more frames before output */
189        if (!flush && s->seq_output == s->seq_decode && s->sps &&
190            nb_output <= s->sps->temporal_layer[s->sps->max_sub_layers - 1].num_reorder_pics)
191            return 0;
192
193        if (nb_output) {
194            HEVCFrame *frame = &s->DPB[min_idx];
195            AVFrame *dst = out;
196            AVFrame *src = frame->frame;
197            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
198            int pixel_shift = !!(desc->comp[0].depth_minus1 > 7);
199
200            ret = av_frame_ref(out, src);
201            ff_hevc_unref_frame(s, frame, HEVC_FRAME_FLAG_OUTPUT);
202            if (ret < 0)
203                return ret;
204
205            for (i = 0; i < 3; i++) {
206                int hshift = (i > 0) ? desc->log2_chroma_w : 0;
207                int vshift = (i > 0) ? desc->log2_chroma_h : 0;
208                int off = ((frame->window.left_offset >> hshift) << pixel_shift) +
209                          (frame->window.top_offset   >> vshift) * dst->linesize[i];
210                dst->data[i] += off;
211            }
212            av_log(s->avctx, AV_LOG_DEBUG,
213                   "Output frame with POC %d.\n", frame->poc);
214            return 1;
215        }
216
217        if (s->seq_output != s->seq_decode)
218            s->seq_output = (s->seq_output + 1) & 0xff;
219        else
220            break;
221    } while (1);
222
223    return 0;
224}
225
226static int init_slice_rpl(HEVCContext *s)
227{
228    HEVCFrame *frame = s->ref;
229    int ctb_count    = frame->ctb_count;
230    int ctb_addr_ts  = s->pps->ctb_addr_rs_to_ts[s->sh.slice_segment_addr];
231    int i;
232
233    if (s->slice_idx >= frame->rpl_buf->size / sizeof(RefPicListTab))
234        return AVERROR_INVALIDDATA;
235
236    for (i = ctb_addr_ts; i < ctb_count; i++)
237        frame->rpl_tab[i] = (RefPicListTab *)frame->rpl_buf->data + s->slice_idx;
238
239    frame->refPicList = (RefPicList *)frame->rpl_tab[ctb_addr_ts];
240
241    return 0;
242}
243
244int ff_hevc_slice_rpl(HEVCContext *s)
245{
246    SliceHeader *sh = &s->sh;
247
248    uint8_t nb_list = sh->slice_type == B_SLICE ? 2 : 1;
249    uint8_t list_idx;
250    int i, j, ret;
251
252    ret = init_slice_rpl(s);
253    if (ret < 0)
254        return ret;
255
256    if (!(s->rps[ST_CURR_BEF].nb_refs + s->rps[ST_CURR_AFT].nb_refs +
257          s->rps[LT_CURR].nb_refs)) {
258        av_log(s->avctx, AV_LOG_ERROR, "Zero refs in the frame RPS.\n");
259        return AVERROR_INVALIDDATA;
260    }
261
262    for (list_idx = 0; list_idx < nb_list; list_idx++) {
263        RefPicList  rpl_tmp = { { 0 } };
264        RefPicList *rpl     = &s->ref->refPicList[list_idx];
265
266        /* The order of the elements is
267         * ST_CURR_BEF - ST_CURR_AFT - LT_CURR for the L0 and
268         * ST_CURR_AFT - ST_CURR_BEF - LT_CURR for the L1 */
269        int cand_lists[3] = { list_idx ? ST_CURR_AFT : ST_CURR_BEF,
270                              list_idx ? ST_CURR_BEF : ST_CURR_AFT,
271                              LT_CURR };
272
273        /* concatenate the candidate lists for the current frame */
274        while (rpl_tmp.nb_refs < sh->nb_refs[list_idx]) {
275            for (i = 0; i < FF_ARRAY_ELEMS(cand_lists); i++) {
276                RefPicList *rps = &s->rps[cand_lists[i]];
277                for (j = 0; j < rps->nb_refs && rpl_tmp.nb_refs < MAX_REFS; j++) {
278                    rpl_tmp.list[rpl_tmp.nb_refs]       = rps->list[j];
279                    rpl_tmp.ref[rpl_tmp.nb_refs]        = rps->ref[j];
280                    rpl_tmp.isLongTerm[rpl_tmp.nb_refs] = i == 2;
281                    rpl_tmp.nb_refs++;
282                }
283            }
284        }
285
286        /* reorder the references if necessary */
287        if (sh->rpl_modification_flag[list_idx]) {
288            for (i = 0; i < sh->nb_refs[list_idx]; i++) {
289                int idx = sh->list_entry_lx[list_idx][i];
290
291                if (idx >= rpl_tmp.nb_refs) {
292                    av_log(s->avctx, AV_LOG_ERROR, "Invalid reference index.\n");
293                    return AVERROR_INVALIDDATA;
294                }
295
296                rpl->list[i]       = rpl_tmp.list[idx];
297                rpl->ref[i]        = rpl_tmp.ref[idx];
298                rpl->isLongTerm[i] = rpl_tmp.isLongTerm[idx];
299                rpl->nb_refs++;
300            }
301        } else {
302            memcpy(rpl, &rpl_tmp, sizeof(*rpl));
303            rpl->nb_refs = FFMIN(rpl->nb_refs, sh->nb_refs[list_idx]);
304        }
305
306        if (sh->collocated_list == list_idx &&
307            sh->collocated_ref_idx < rpl->nb_refs)
308            s->ref->collocated_ref = rpl->ref[sh->collocated_ref_idx];
309    }
310
311    return 0;
312}
313
314static HEVCFrame *find_ref_idx(HEVCContext *s, int poc)
315{
316    int i;
317    int LtMask = (1 << s->sps->log2_max_poc_lsb) - 1;
318
319    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
320        HEVCFrame *ref = &s->DPB[i];
321        if (ref->frame->buf[0] && (ref->sequence == s->seq_decode)) {
322            if ((ref->poc & LtMask) == poc)
323                return ref;
324        }
325    }
326
327    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
328        HEVCFrame *ref = &s->DPB[i];
329        if (ref->frame->buf[0] && ref->sequence == s->seq_decode) {
330            if (ref->poc == poc || (ref->poc & LtMask) == poc)
331                return ref;
332        }
333    }
334
335    av_log(s->avctx, AV_LOG_ERROR,
336           "Could not find ref with POC %d\n", poc);
337    return NULL;
338}
339
340static void mark_ref(HEVCFrame *frame, int flag)
341{
342    frame->flags &= ~(HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF);
343    frame->flags |= flag;
344}
345
346static HEVCFrame *generate_missing_ref(HEVCContext *s, int poc)
347{
348    HEVCFrame *frame;
349    int i, x, y;
350
351    frame = alloc_frame(s);
352    if (!frame)
353        return NULL;
354
355    if (!s->sps->pixel_shift) {
356        for (i = 0; frame->frame->buf[i]; i++)
357            memset(frame->frame->buf[i]->data, 1 << (s->sps->bit_depth - 1),
358                   frame->frame->buf[i]->size);
359    } else {
360        for (i = 0; frame->frame->data[i]; i++)
361            for (y = 0; y < (s->sps->height >> s->sps->vshift[i]); y++)
362                for (x = 0; x < (s->sps->width >> s->sps->hshift[i]); x++) {
363                    AV_WN16(frame->frame->data[i] + y * frame->frame->linesize[i] + 2 * x,
364                            1 << (s->sps->bit_depth - 1));
365                }
366    }
367
368    frame->poc      = poc;
369    frame->sequence = s->seq_decode;
370    frame->flags    = 0;
371
372    if (s->threads_type == FF_THREAD_FRAME)
373        ff_thread_report_progress(&frame->tf, INT_MAX, 0);
374
375    return frame;
376}
377
378/* add a reference with the given poc to the list and mark it as used in DPB */
379static int add_candidate_ref(HEVCContext *s, RefPicList *list,
380                             int poc, int ref_flag)
381{
382    HEVCFrame *ref = find_ref_idx(s, poc);
383
384    if (ref == s->ref)
385        return AVERROR_INVALIDDATA;
386
387    if (!ref) {
388        ref = generate_missing_ref(s, poc);
389        if (!ref)
390            return AVERROR(ENOMEM);
391    }
392
393    list->list[list->nb_refs] = ref->poc;
394    list->ref[list->nb_refs]  = ref;
395    list->nb_refs++;
396
397    mark_ref(ref, ref_flag);
398    return 0;
399}
400
401int ff_hevc_frame_rps(HEVCContext *s)
402{
403    const ShortTermRPS *short_rps = s->sh.short_term_rps;
404    const LongTermRPS  *long_rps  = &s->sh.long_term_rps;
405    RefPicList               *rps = s->rps;
406    int i, ret;
407
408    if (!short_rps) {
409        rps[0].nb_refs = rps[1].nb_refs = 0;
410        return 0;
411    }
412
413    /* clear the reference flags on all frames except the current one */
414    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
415        HEVCFrame *frame = &s->DPB[i];
416
417        if (frame == s->ref)
418            continue;
419
420        mark_ref(frame, 0);
421    }
422
423    for (i = 0; i < NB_RPS_TYPE; i++)
424        rps[i].nb_refs = 0;
425
426    /* add the short refs */
427    for (i = 0; i < short_rps->num_delta_pocs; i++) {
428        int poc = s->poc + short_rps->delta_poc[i];
429        int list;
430
431        if (!short_rps->used[i])
432            list = ST_FOLL;
433        else if (i < short_rps->num_negative_pics)
434            list = ST_CURR_BEF;
435        else
436            list = ST_CURR_AFT;
437
438        ret = add_candidate_ref(s, &rps[list], poc, HEVC_FRAME_FLAG_SHORT_REF);
439        if (ret < 0)
440            return ret;
441    }
442
443    /* add the long refs */
444    for (i = 0; i < long_rps->nb_refs; i++) {
445        int poc  = long_rps->poc[i];
446        int list = long_rps->used[i] ? LT_CURR : LT_FOLL;
447
448        ret = add_candidate_ref(s, &rps[list], poc, HEVC_FRAME_FLAG_LONG_REF);
449        if (ret < 0)
450            return ret;
451    }
452
453    /* release any frames that are now unused */
454    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++)
455        ff_hevc_unref_frame(s, &s->DPB[i], 0);
456
457    return 0;
458}
459
460int ff_hevc_compute_poc(HEVCContext *s, int poc_lsb)
461{
462    int max_poc_lsb  = 1 << s->sps->log2_max_poc_lsb;
463    int prev_poc_lsb = s->pocTid0 % max_poc_lsb;
464    int prev_poc_msb = s->pocTid0 - prev_poc_lsb;
465    int poc_msb;
466
467    if (poc_lsb < prev_poc_lsb && prev_poc_lsb - poc_lsb >= max_poc_lsb / 2)
468        poc_msb = prev_poc_msb + max_poc_lsb;
469    else if (poc_lsb > prev_poc_lsb && poc_lsb - prev_poc_lsb > max_poc_lsb / 2)
470        poc_msb = prev_poc_msb - max_poc_lsb;
471    else
472        poc_msb = prev_poc_msb;
473
474    // For BLA picture types, POCmsb is set to 0.
475    if (s->nal_unit_type == NAL_BLA_W_LP   ||
476        s->nal_unit_type == NAL_BLA_W_RADL ||
477        s->nal_unit_type == NAL_BLA_N_LP)
478        poc_msb = 0;
479
480    return poc_msb + poc_lsb;
481}
482
483int ff_hevc_frame_nb_refs(HEVCContext *s)
484{
485    int ret = 0;
486    int i;
487    const ShortTermRPS *rps = s->sh.short_term_rps;
488    LongTermRPS *long_rps   = &s->sh.long_term_rps;
489
490    if (rps) {
491        for (i = 0; i < rps->num_negative_pics; i++)
492            ret += !!rps->used[i];
493        for (; i < rps->num_delta_pocs; i++)
494            ret += !!rps->used[i];
495    }
496
497    if (long_rps) {
498        for (i = 0; i < long_rps->nb_refs; i++)
499            ret += !!long_rps->used[i];
500    }
501    return ret;
502}
503