hevc: inline cabac in hls_mvd_coding(cherry picked from commit ad387195ad04e8a005a1bf...
[ffmpeg.git] / libavcodec / hevc.c
1 /*
2  * HEVC video Decoder
3  *
4  * Copyright (C) 2012 - 2013 Guillaume Martres
5  * Copyright (C) 2012 - 2013 Mickael Raulet
6  * Copyright (C) 2012 - 2013 Gildas Cocherel
7  * Copyright (C) 2012 - 2013 Wassim Hamidouche
8  *
9  * This file is part of FFmpeg.
10  *
11  * FFmpeg is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * FFmpeg is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with FFmpeg; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25
26 #include "libavutil/attributes.h"
27 #include "libavutil/common.h"
28 #include "libavutil/internal.h"
29 #include "libavutil/md5.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/pixdesc.h"
32
33 #include "bytestream.h"
34 #include "cabac_functions.h"
35 #include "dsputil.h"
36 #include "golomb.h"
37 #include "hevc.h"
38
39 const uint8_t ff_hevc_qpel_extra_before[4] = { 0, 3, 3, 2 };
40 const uint8_t ff_hevc_qpel_extra_after[4]  = { 0, 3, 4, 4 };
41 const uint8_t ff_hevc_qpel_extra[4]        = { 0, 6, 7, 6 };
42
43 /**
44  * NOTE: Each function hls_foo correspond to the function foo in the
45  * specification (HLS stands for High Level Syntax).
46  */
47
48 /**
49  * Section 5.7
50  */
51
52 /* free everything allocated  by pic_arrays_init() */
53 static void pic_arrays_free(HEVCContext *s)
54 {
55     av_freep(&s->sao);
56     av_freep(&s->deblock);
57     av_freep(&s->split_cu_flag);
58
59     av_freep(&s->skip_flag);
60     av_freep(&s->tab_ct_depth);
61
62     av_freep(&s->tab_ipm);
63     av_freep(&s->cbf_luma);
64     av_freep(&s->is_pcm);
65
66     av_freep(&s->qp_y_tab);
67     av_freep(&s->tab_slice_address);
68     av_freep(&s->filter_slice_edges);
69
70     av_freep(&s->horizontal_bs);
71     av_freep(&s->vertical_bs);
72
73     av_buffer_pool_uninit(&s->tab_mvf_pool);
74     av_buffer_pool_uninit(&s->rpl_tab_pool);
75 }
76
77 /* allocate arrays that depend on frame dimensions */
78 static int pic_arrays_init(HEVCContext *s)
79 {
80     int log2_min_cb_size     = s->sps->log2_min_coding_block_size;
81     int width                = s->sps->width;
82     int height               = s->sps->height;
83     int pic_size             = width * height;
84     int pic_size_in_ctb      = ((width  >> log2_min_cb_size) + 1) *
85                                ((height >> log2_min_cb_size) + 1);
86     int ctb_count            = s->sps->ctb_width * s->sps->ctb_height;
87     int pic_width_in_min_pu  = width  >> s->sps->log2_min_pu_size;
88     int pic_height_in_min_pu = height >> s->sps->log2_min_pu_size;
89     int pic_size_in_min_pu   = pic_width_in_min_pu * pic_height_in_min_pu;
90     int pic_width_in_min_tu  = width  >> s->sps->log2_min_transform_block_size;
91     int pic_height_in_min_tu = height >> s->sps->log2_min_transform_block_size;
92
93     s->bs_width  = width  >> 3;
94     s->bs_height = height >> 3;
95
96     s->sao           = av_mallocz_array(ctb_count, sizeof(*s->sao));
97     s->deblock       = av_mallocz_array(ctb_count, sizeof(*s->deblock));
98     s->split_cu_flag = av_malloc(pic_size);
99     if (!s->sao || !s->deblock || !s->split_cu_flag)
100         goto fail;
101
102     s->skip_flag    = av_malloc(pic_size_in_ctb);
103     s->tab_ct_depth = av_malloc(s->sps->min_cb_height * s->sps->min_cb_width);
104     if (!s->skip_flag || !s->tab_ct_depth)
105         goto fail;
106
107     s->tab_ipm  = av_malloc(pic_size_in_min_pu);
108     s->cbf_luma = av_malloc(pic_width_in_min_tu * pic_height_in_min_tu);
109     s->is_pcm   = av_malloc(pic_size_in_min_pu);
110     if (!s->tab_ipm || !s->cbf_luma || !s->is_pcm)
111         goto fail;
112
113     s->filter_slice_edges = av_malloc(ctb_count);
114     s->tab_slice_address = av_malloc(pic_size_in_ctb * sizeof(*s->tab_slice_address));
115     s->qp_y_tab = av_malloc(pic_size_in_ctb * sizeof(*s->qp_y_tab));
116     if (!s->qp_y_tab || !s->filter_slice_edges || !s->tab_slice_address)
117         goto fail;
118
119     s->horizontal_bs = av_mallocz(2 * s->bs_width * (s->bs_height + 1));
120     s->vertical_bs   = av_mallocz(2 * s->bs_width * (s->bs_height + 1));
121     if (!s->horizontal_bs || !s->vertical_bs)
122         goto fail;
123
124     s->tab_mvf_pool = av_buffer_pool_init(pic_size_in_min_pu * sizeof(MvField),
125                                           av_buffer_alloc);
126     if (!s->tab_mvf_pool)
127         goto fail;
128
129     s->rpl_tab_pool = av_buffer_pool_init(ctb_count * sizeof(RefPicListTab),
130                                           av_buffer_allocz);
131     if (!s->rpl_tab_pool)
132         goto fail;
133
134     return 0;
135 fail:
136     pic_arrays_free(s);
137     return AVERROR(ENOMEM);
138 }
139
140 static void pred_weight_table(HEVCContext *s, GetBitContext *gb)
141 {
142     int i = 0;
143     int j = 0;
144     uint8_t luma_weight_l0_flag[16];
145     uint8_t chroma_weight_l0_flag[16];
146     uint8_t luma_weight_l1_flag[16];
147     uint8_t chroma_weight_l1_flag[16];
148
149     s->sh.luma_log2_weight_denom = get_ue_golomb_long(gb);
150     if (s->sps->chroma_format_idc != 0) {
151         int delta = get_se_golomb(gb);
152         s->sh.chroma_log2_weight_denom = av_clip_c(s->sh.luma_log2_weight_denom + delta, 0, 7);
153     }
154
155     for (i = 0; i < s->sh.nb_refs[L0]; i++) {
156         luma_weight_l0_flag[i] = get_bits1(gb);
157         if (!luma_weight_l0_flag[i]) {
158             s->sh.luma_weight_l0[i] = 1 << s->sh.luma_log2_weight_denom;
159             s->sh.luma_offset_l0[i] = 0;
160         }
161     }
162     if (s->sps->chroma_format_idc != 0) { //fix me ! invert "if" and "for"
163         for (i = 0; i < s->sh.nb_refs[L0]; i++) {
164             chroma_weight_l0_flag[i] = get_bits1(gb);
165         }
166     } else {
167         for (i = 0; i < s->sh.nb_refs[L0]; i++) {
168             chroma_weight_l0_flag[i] = 0;
169         }
170     }
171     for (i = 0; i < s->sh.nb_refs[L0]; i++) {
172         if (luma_weight_l0_flag[i]) {
173             int delta_luma_weight_l0 = get_se_golomb(gb);
174             s->sh.luma_weight_l0[i] = (1 << s->sh.luma_log2_weight_denom) + delta_luma_weight_l0;
175             s->sh.luma_offset_l0[i] = get_se_golomb(gb);
176         }
177         if (chroma_weight_l0_flag[i]) {
178             for (j = 0; j < 2; j++) {
179                 int delta_chroma_weight_l0 = get_se_golomb(gb);
180                 int delta_chroma_offset_l0 = get_se_golomb(gb);
181                 s->sh.chroma_weight_l0[i][j] = (1 << s->sh.chroma_log2_weight_denom) + delta_chroma_weight_l0;
182                 s->sh.chroma_offset_l0[i][j] = av_clip_c((delta_chroma_offset_l0 - ((128 * s->sh.chroma_weight_l0[i][j])
183                                                                                      >> s->sh.chroma_log2_weight_denom) + 128), -128, 127);
184             }
185         } else {
186             s->sh.chroma_weight_l0[i][0] = 1 << s->sh.chroma_log2_weight_denom;
187             s->sh.chroma_offset_l0[i][0] = 0;
188             s->sh.chroma_weight_l0[i][1] = 1 << s->sh.chroma_log2_weight_denom;
189             s->sh.chroma_offset_l0[i][1] = 0;
190         }
191     }
192     if (s->sh.slice_type == B_SLICE) {
193         for (i = 0; i < s->sh.nb_refs[L1]; i++) {
194             luma_weight_l1_flag[i] = get_bits1(gb);
195             if (!luma_weight_l1_flag[i]) {
196                 s->sh.luma_weight_l1[i] = 1 << s->sh.luma_log2_weight_denom;
197                 s->sh.luma_offset_l1[i] = 0;
198             }
199         }
200         if (s->sps->chroma_format_idc != 0) {
201             for (i = 0; i < s->sh.nb_refs[L1]; i++) {
202                 chroma_weight_l1_flag[i] = get_bits1(gb);
203             }
204         } else {
205             for (i = 0; i < s->sh.nb_refs[L1]; i++) {
206                 chroma_weight_l1_flag[i] = 0;
207             }
208         }
209         for (i = 0; i < s->sh.nb_refs[L1]; i++) {
210             if (luma_weight_l1_flag[i]) {
211                 int delta_luma_weight_l1 = get_se_golomb(gb);
212                 s->sh.luma_weight_l1[i] = (1 << s->sh.luma_log2_weight_denom) + delta_luma_weight_l1;
213                 s->sh.luma_offset_l1[i] = get_se_golomb(gb);
214             }
215             if (chroma_weight_l1_flag[i]) {
216                 for (j = 0; j < 2; j++) {
217                     int delta_chroma_weight_l1 = get_se_golomb(gb);
218                     int delta_chroma_offset_l1 = get_se_golomb(gb);
219                     s->sh.chroma_weight_l1[i][j] = (1 << s->sh.chroma_log2_weight_denom) + delta_chroma_weight_l1;
220                     s->sh.chroma_offset_l1[i][j] = av_clip_c((delta_chroma_offset_l1 - ((128 * s->sh.chroma_weight_l1[i][j])
221                                                                                          >> s->sh.chroma_log2_weight_denom) + 128), -128, 127);
222                 }
223             } else {
224                 s->sh.chroma_weight_l1[i][0] = 1 << s->sh.chroma_log2_weight_denom;
225                 s->sh.chroma_offset_l1[i][0] = 0;
226                 s->sh.chroma_weight_l1[i][1] = 1 << s->sh.chroma_log2_weight_denom;
227                 s->sh.chroma_offset_l1[i][1] = 0;
228             }
229         }
230     }
231 }
232
233 static int decode_lt_rps(HEVCContext *s, LongTermRPS *rps, GetBitContext *gb)
234 {
235     const HEVCSPS *sps = s->sps;
236     int max_poc_lsb = 1 << sps->log2_max_poc_lsb;
237     int prev_delta_msb = 0;
238     int nb_sps = 0, nb_sh;
239     int i;
240
241     rps->nb_refs = 0;
242     if (!sps->long_term_ref_pics_present_flag)
243         return 0;
244
245     if (sps->num_long_term_ref_pics_sps > 0)
246         nb_sps = get_ue_golomb_long(gb);
247     nb_sh = get_ue_golomb_long(gb);
248
249     if (nb_sh + nb_sps > FF_ARRAY_ELEMS(rps->poc))
250         return AVERROR_INVALIDDATA;
251
252     rps->nb_refs = nb_sh + nb_sps;
253
254     for (i = 0; i < rps->nb_refs; i++) {
255         uint8_t delta_poc_msb_present;
256
257         if (i < nb_sps) {
258             uint8_t lt_idx_sps = 0;
259
260             if (sps->num_long_term_ref_pics_sps > 1)
261                 lt_idx_sps = get_bits(gb, av_ceil_log2(sps->num_long_term_ref_pics_sps));
262
263             rps->poc[i]  = sps->lt_ref_pic_poc_lsb_sps[lt_idx_sps];
264             rps->used[i] = sps->used_by_curr_pic_lt_sps_flag[lt_idx_sps];
265         } else {
266             rps->poc[i]  = get_bits(gb, sps->log2_max_poc_lsb);
267             rps->used[i] = get_bits1(gb);
268         }
269
270         delta_poc_msb_present = get_bits1(gb);
271         if (delta_poc_msb_present) {
272             int delta = get_ue_golomb_long(gb);
273
274             if (i && i != nb_sps)
275                 delta += prev_delta_msb;
276
277             rps->poc[i] += s->poc - delta * max_poc_lsb - s->sh.pic_order_cnt_lsb;
278             prev_delta_msb = delta;
279         }
280     }
281
282     return 0;
283 }
284
285 static int hls_slice_header(HEVCContext *s)
286 {
287     GetBitContext *gb = &s->HEVClc.gb;
288     SliceHeader   *sh = &s->sh;
289     int i, ret;
290
291     // Coded parameters
292     sh->first_slice_in_pic_flag = get_bits1(gb);
293     if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) {
294         s->seq_decode = (s->seq_decode + 1) & 0xff;
295         s->max_ra = INT_MAX;
296         if (IS_IDR(s))
297             ff_hevc_clear_refs(s);
298     }
299     if (s->nal_unit_type >= 16 && s->nal_unit_type <= 23)
300         sh->no_output_of_prior_pics_flag = get_bits1(gb);
301
302     sh->pps_id = get_ue_golomb_long(gb);
303     if (sh->pps_id >= MAX_PPS_COUNT || !s->pps_list[sh->pps_id]) {
304         av_log(s->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);
305         return AVERROR_INVALIDDATA;
306     }
307     s->pps = (HEVCPPS*)s->pps_list[sh->pps_id]->data;
308
309     if (s->sps != (HEVCSPS*)s->sps_list[s->pps->sps_id]->data) {
310         s->sps = (HEVCSPS*)s->sps_list[s->pps->sps_id]->data;
311         s->vps = s->vps_list[s->sps->vps_id];
312
313         pic_arrays_free(s);
314         ret = pic_arrays_init(s);
315         if (ret < 0) {
316             s->sps = NULL;
317             return AVERROR(ENOMEM);
318         }
319
320         s->width  = s->sps->width;
321         s->height = s->sps->height;
322
323         s->avctx->coded_width  = s->sps->width;
324         s->avctx->coded_height = s->sps->height;
325         s->avctx->width        = s->sps->output_width;
326         s->avctx->height       = s->sps->output_height;
327         s->avctx->pix_fmt      = s->sps->pix_fmt;
328         s->avctx->sample_aspect_ratio = s->sps->vui.sar;
329         s->avctx->has_b_frames = s->sps->temporal_layer[s->sps->max_sub_layers - 1].num_reorder_pics;
330
331         if (s->sps->chroma_format_idc == 0 || s->sps->separate_colour_plane_flag) {
332             av_log(s->avctx, AV_LOG_ERROR,
333                    "TODO: s->sps->chroma_format_idc == 0 || "
334                    "s->sps->separate_colour_plane_flag\n");
335             return AVERROR_PATCHWELCOME;
336         }
337
338         ff_hevc_pred_init(&s->hpc,     s->sps->bit_depth);
339         ff_hevc_dsp_init (&s->hevcdsp, s->sps->bit_depth);
340         ff_videodsp_init (&s->vdsp,    s->sps->bit_depth);
341
342         if (s->sps->sao_enabled) {
343             av_frame_unref(s->tmp_frame);
344             ret = ff_get_buffer(s->avctx, s->tmp_frame, 0);
345             if (ret < 0)
346                 return ret;
347             s->frame = s->tmp_frame;
348         }
349     }
350
351     sh->dependent_slice_segment_flag = 0;
352     if (!sh->first_slice_in_pic_flag) {
353         int slice_address_length;
354
355         if (s->pps->dependent_slice_segments_enabled_flag)
356             sh->dependent_slice_segment_flag = get_bits1(gb);
357
358         slice_address_length = av_ceil_log2(s->sps->ctb_width *
359                                               s->sps->ctb_height);
360         sh->slice_segment_addr = get_bits(gb, slice_address_length);
361         if (sh->slice_segment_addr >= s->sps->ctb_width * s->sps->ctb_height) {
362             av_log(s->avctx, AV_LOG_ERROR, "Invalid slice segment address: %u.\n",
363                    sh->slice_segment_addr);
364             return AVERROR_INVALIDDATA;
365         }
366
367         if (!sh->dependent_slice_segment_flag) {
368             sh->slice_addr = sh->slice_segment_addr;
369             s->slice_idx++;
370         }
371     } else {
372         sh->slice_segment_addr = sh->slice_addr = 0;
373         s->slice_idx = 0;
374         s->slice_initialized = 0;
375     }
376
377     if (!sh->dependent_slice_segment_flag) {
378         s->slice_initialized = 0;
379
380         for (i = 0; i < s->pps->num_extra_slice_header_bits; i++)
381             skip_bits(gb, 1); // slice_reserved_undetermined_flag[]
382
383         sh->slice_type = get_ue_golomb_long(gb);
384         if (!(sh->slice_type == I_SLICE || sh->slice_type == P_SLICE ||
385               sh->slice_type == B_SLICE)) {
386             av_log(s->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",
387                    sh->slice_type);
388             return AVERROR_INVALIDDATA;
389         }
390
391         if (s->pps->output_flag_present_flag)
392             sh->pic_output_flag = get_bits1(gb);
393
394         if (s->sps->separate_colour_plane_flag)
395             sh->colour_plane_id = get_bits(gb, 2);
396
397         if (!IS_IDR(s)) {
398             int short_term_ref_pic_set_sps_flag;
399             int poc;
400
401             sh->pic_order_cnt_lsb = get_bits(gb, s->sps->log2_max_poc_lsb);
402             poc = ff_hevc_compute_poc(s, sh->pic_order_cnt_lsb);
403             if (!sh->first_slice_in_pic_flag && poc != s->poc) {
404                 av_log(s->avctx, AV_LOG_WARNING,
405                        "Ignoring POC change between slices: %d -> %d\n", s->poc, poc);
406                 if (s->avctx->err_recognition & AV_EF_EXPLODE)
407                     return AVERROR_INVALIDDATA;
408                 poc = s->poc;
409             }
410             s->poc = poc;
411
412             short_term_ref_pic_set_sps_flag = get_bits1(gb);
413             if (!short_term_ref_pic_set_sps_flag) {
414                 ret = ff_hevc_decode_short_term_rps(s, &sh->slice_rps, s->sps, 1);
415                 if (ret < 0)
416                     return ret;
417
418                 sh->short_term_rps = &sh->slice_rps;
419             } else {
420                 int numbits, rps_idx;
421
422                 if (!s->sps->nb_st_rps) {
423                     av_log(s->avctx, AV_LOG_ERROR, "No ref lists in the SPS.\n");
424                     return AVERROR_INVALIDDATA;
425                 }
426
427                 numbits = av_ceil_log2(s->sps->nb_st_rps);
428                 rps_idx = (numbits > 0) ? get_bits(gb, numbits) : 0;
429                 sh->short_term_rps = &s->sps->st_rps[rps_idx];
430             }
431
432             ret = decode_lt_rps(s, &sh->long_term_rps, gb);
433             if (ret < 0) {
434                 av_log(s->avctx, AV_LOG_WARNING, "Invalid long term RPS.\n");
435                 if (s->avctx->err_recognition & AV_EF_EXPLODE)
436                     return AVERROR_INVALIDDATA;
437             }
438
439             if (s->sps->sps_temporal_mvp_enabled_flag)
440                 sh->slice_temporal_mvp_enabled_flag = get_bits1(gb);
441             else
442                 sh->slice_temporal_mvp_enabled_flag = 0;
443         } else {
444             s->sh.short_term_rps = NULL;
445             s->poc = 0;
446         }
447
448         if (s->temporal_id == 0 &&
449             s->nal_unit_type != NAL_TRAIL_N &&
450             s->nal_unit_type != NAL_TSA_N &&
451             s->nal_unit_type != NAL_STSA_N &&
452             s->nal_unit_type != NAL_TRAIL_N &&
453             s->nal_unit_type != NAL_RADL_N &&
454             s->nal_unit_type != NAL_RADL_R &&
455             s->nal_unit_type != NAL_RASL_R)
456             s->pocTid0 = s->poc;
457
458         if (s->sps->sao_enabled) {
459             sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb);
460             sh->slice_sample_adaptive_offset_flag[2] =
461             sh->slice_sample_adaptive_offset_flag[1] = get_bits1(gb);
462         } else {
463             sh->slice_sample_adaptive_offset_flag[0] = 0;
464             sh->slice_sample_adaptive_offset_flag[1] = 0;
465             sh->slice_sample_adaptive_offset_flag[2] = 0;
466         }
467
468         sh->nb_refs[L0] = sh->nb_refs[L1] = 0;
469         if (sh->slice_type == P_SLICE || sh->slice_type == B_SLICE) {
470             int nb_refs;
471
472             sh->nb_refs[L0] = s->pps->num_ref_idx_l0_default_active;
473             if (sh->slice_type == B_SLICE)
474                 sh->nb_refs[L1] = s->pps->num_ref_idx_l1_default_active;
475
476             if (get_bits1(gb)) { // num_ref_idx_active_override_flag
477                 sh->nb_refs[L0] = get_ue_golomb_long(gb) + 1;
478                 if (sh->slice_type == B_SLICE)
479                     sh->nb_refs[L1] = get_ue_golomb_long(gb) + 1;
480             }
481             if (sh->nb_refs[L0] > MAX_REFS || sh->nb_refs[L1] > MAX_REFS) {
482                 av_log(s->avctx, AV_LOG_ERROR, "Too many refs: %d/%d.\n",
483                        sh->nb_refs[L0], sh->nb_refs[L1]);
484                 return AVERROR_INVALIDDATA;
485             }
486
487             sh->rpl_modification_flag[0] = 0;
488             sh->rpl_modification_flag[1] = 0;
489             nb_refs = ff_hevc_frame_nb_refs(s);
490             if (!nb_refs) {
491                 av_log(s->avctx, AV_LOG_ERROR, "Zero refs for a frame with P or B slices.\n");
492                 return AVERROR_INVALIDDATA;
493             }
494
495             if (s->pps->lists_modification_present_flag && nb_refs > 1) {
496                 sh->rpl_modification_flag[0] = get_bits1(gb);
497                 if (sh->rpl_modification_flag[0]) {
498                     for (i = 0; i < sh->nb_refs[L0]; i++)
499                         sh->list_entry_lx[0][i] = get_bits(gb, av_ceil_log2(nb_refs));
500                 }
501
502                 if (sh->slice_type == B_SLICE) {
503                     sh->rpl_modification_flag[1] = get_bits1(gb);
504                     if (sh->rpl_modification_flag[1] == 1)
505                         for (i = 0; i < sh->nb_refs[L1]; i++)
506                             sh->list_entry_lx[1][i] = get_bits(gb, av_ceil_log2(nb_refs));
507                 }
508             }
509
510             if (sh->slice_type == B_SLICE)
511                 sh->mvd_l1_zero_flag = get_bits1(gb);
512
513             if (s->pps->cabac_init_present_flag)
514                 sh->cabac_init_flag = get_bits1(gb);
515             else
516                 sh->cabac_init_flag = 0;
517
518             sh->collocated_ref_idx = 0;
519             if (sh->slice_temporal_mvp_enabled_flag) {
520                 sh->collocated_list = L0;
521                 if (sh->slice_type == B_SLICE)
522                     sh->collocated_list = !get_bits1(gb);
523
524                 if (sh->nb_refs[sh->collocated_list] > 1) {
525                     sh->collocated_ref_idx = get_ue_golomb_long(gb);
526                     if (sh->collocated_ref_idx >= sh->nb_refs[sh->collocated_list]) {
527                         av_log(s->avctx, AV_LOG_ERROR,
528                                "Invalid collocated_ref_idx: %d.\n", sh->collocated_ref_idx);
529                         return AVERROR_INVALIDDATA;
530                     }
531                 }
532             }
533
534             if ((s->pps->weighted_pred_flag   && sh->slice_type == P_SLICE) ||
535                 (s->pps->weighted_bipred_flag && sh->slice_type == B_SLICE)) {
536                 pred_weight_table(s, gb);
537             }
538
539             sh->max_num_merge_cand = 5 - get_ue_golomb_long(gb);
540         }
541
542         sh->slice_qp_delta = get_se_golomb(gb);
543         if (s->pps->pic_slice_level_chroma_qp_offsets_present_flag) {
544             sh->slice_cb_qp_offset = get_se_golomb(gb);
545             sh->slice_cr_qp_offset = get_se_golomb(gb);
546         } else {
547             sh->slice_cb_qp_offset = 0;
548             sh->slice_cr_qp_offset = 0;
549         }
550
551         if (s->pps->deblocking_filter_control_present_flag) {
552             int deblocking_filter_override_flag = 0;
553
554             if (s->pps->deblocking_filter_override_enabled_flag)
555                 deblocking_filter_override_flag = get_bits1(gb);
556
557             if (deblocking_filter_override_flag) {
558                 sh->disable_deblocking_filter_flag = get_bits1(gb);
559                 if (!sh->disable_deblocking_filter_flag) {
560                     sh->beta_offset = get_se_golomb(gb) * 2;
561                     sh->tc_offset   = get_se_golomb(gb) * 2;
562                 }
563             } else {
564                 sh->disable_deblocking_filter_flag = s->pps->pps_disable_deblocking_filter_flag;
565                 sh->beta_offset = s->pps->beta_offset;
566                 sh->tc_offset = s->pps->tc_offset;
567             }
568         } else {
569             sh->disable_deblocking_filter_flag = 0;
570             sh->beta_offset = 0;
571             sh->tc_offset = 0;
572         }
573
574
575         if (s->pps->seq_loop_filter_across_slices_enabled_flag &&
576             (sh->slice_sample_adaptive_offset_flag[0] ||
577              sh->slice_sample_adaptive_offset_flag[1] ||
578              !sh->disable_deblocking_filter_flag)) {
579             sh->slice_loop_filter_across_slices_enabled_flag = get_bits1(gb);
580         } else {
581             sh->slice_loop_filter_across_slices_enabled_flag = s->pps->seq_loop_filter_across_slices_enabled_flag;
582         }
583     } else if (!s->slice_initialized) {
584         av_log(s->avctx, AV_LOG_ERROR, "Independent slice segment missing.\n");
585         return AVERROR_INVALIDDATA;
586     }
587
588     sh->num_entry_point_offsets = 0;
589     if (s->pps->tiles_enabled_flag || s->pps->entropy_coding_sync_enabled_flag) {
590         sh->num_entry_point_offsets = get_ue_golomb_long(gb);
591         if (sh->num_entry_point_offsets > 0) {
592             int offset_len = get_ue_golomb_long(gb) + 1;
593
594             for (i = 0; i < sh->num_entry_point_offsets; i++)
595                 skip_bits(gb, offset_len);
596         }
597     }
598
599     if (s->pps->slice_header_extension_present_flag) {
600         int length = get_ue_golomb_long(gb);
601         for (i = 0; i < length; i++)
602             skip_bits(gb, 8); // slice_header_extension_data_byte
603     }
604
605     // Inferred parameters
606     sh->slice_qp = 26 + s->pps->pic_init_qp_minus26 + sh->slice_qp_delta;
607     sh->slice_ctb_addr_rs = sh->slice_segment_addr;
608
609     s->HEVClc.first_qp_group = !s->sh.dependent_slice_segment_flag;
610
611     if (!s->pps->cu_qp_delta_enabled_flag)
612         s->HEVClc.qp_y = ((s->sh.slice_qp + 52 + 2 * s->sps->qp_bd_offset) %
613                           (52 + s->sps->qp_bd_offset)) - s->sps->qp_bd_offset;
614
615     s->slice_initialized = 1;
616
617     return 0;
618 }
619
620 #define CTB(tab, x, y) ((tab)[(y) * s->sps->ctb_width + (x)])
621
622 #define SET_SAO(elem, value)                            \
623 do {                                                    \
624     if (!sao_merge_up_flag && !sao_merge_left_flag)     \
625         sao->elem = value;                              \
626     else if (sao_merge_left_flag)                       \
627         sao->elem = CTB(s->sao, rx-1, ry).elem;         \
628     else if (sao_merge_up_flag)                         \
629         sao->elem = CTB(s->sao, rx, ry-1).elem;         \
630     else                                                \
631         sao->elem = 0;                                  \
632 } while (0)
633
634 static void hls_sao_param(HEVCContext *s, int rx, int ry)
635 {
636     HEVCLocalContext *lc = &s->HEVClc;
637     int sao_merge_left_flag = 0;
638     int sao_merge_up_flag   = 0;
639     int shift = s->sps->bit_depth - FFMIN(s->sps->bit_depth, 10);
640     SAOParams *sao = &CTB(s->sao, rx, ry);
641     int c_idx, i;
642
643     if (s->sh.slice_sample_adaptive_offset_flag[0] ||
644         s->sh.slice_sample_adaptive_offset_flag[1]) {
645         if (rx > 0) {
646             if (lc->ctb_left_flag)
647                 sao_merge_left_flag = ff_hevc_sao_merge_flag_decode(s);
648         }
649         if (ry > 0 && !sao_merge_left_flag) {
650             if (lc->ctb_up_flag)
651                 sao_merge_up_flag = ff_hevc_sao_merge_flag_decode(s);
652         }
653     }
654
655     for (c_idx = 0; c_idx < 3; c_idx++) {
656         if (!s->sh.slice_sample_adaptive_offset_flag[c_idx]) {
657             sao->type_idx[c_idx] = SAO_NOT_APPLIED;
658             continue;
659         }
660
661         if (c_idx == 2) {
662             sao->type_idx[2] = sao->type_idx[1];
663             sao->eo_class[2] = sao->eo_class[1];
664         } else {
665             SET_SAO(type_idx[c_idx], ff_hevc_sao_type_idx_decode(s));
666         }
667
668         if (sao->type_idx[c_idx] == SAO_NOT_APPLIED)
669             continue;
670
671         for (i = 0; i < 4; i++)
672             SET_SAO(offset_abs[c_idx][i], ff_hevc_sao_offset_abs_decode(s));
673
674         if (sao->type_idx[c_idx] == SAO_BAND) {
675             for (i = 0; i < 4; i++) {
676                 if (sao->offset_abs[c_idx][i]) {
677                     SET_SAO(offset_sign[c_idx][i], ff_hevc_sao_offset_sign_decode(s));
678                 } else {
679                     sao->offset_sign[c_idx][i] = 0;
680                 }
681             }
682             SET_SAO(band_position[c_idx], ff_hevc_sao_band_position_decode(s));
683         } else if (c_idx != 2) {
684             SET_SAO(eo_class[c_idx], ff_hevc_sao_eo_class_decode(s));
685         }
686
687         // Inferred parameters
688         sao->offset_val[c_idx][0] = 0;   //avoid undefined values
689         for (i = 0; i < 4; i++) {
690             sao->offset_val[c_idx][i + 1] = sao->offset_abs[c_idx][i] << shift;
691             if (sao->type_idx[c_idx] == SAO_EDGE) {
692                 if (i > 1)
693                     sao->offset_val[c_idx][i + 1] = -sao->offset_val[c_idx][i + 1];
694             } else if (sao->offset_sign[c_idx][i]) {
695                 sao->offset_val[c_idx][i + 1] = -sao->offset_val[c_idx][i + 1];
696             }
697         }
698     }
699 }
700
701 #undef SET_SAO
702 #undef CTB
703
704
705 static void hls_transform_unit(HEVCContext *s, int x0, int  y0, int xBase, int yBase, int cb_xBase, int cb_yBase,
706                                int log2_cb_size, int log2_trafo_size, int trafo_depth, int blk_idx)
707 {
708     HEVCLocalContext *lc = &s->HEVClc;
709     int scan_idx = SCAN_DIAG;
710     int scan_idx_c = SCAN_DIAG;
711
712     if (lc->cu.pred_mode == MODE_INTRA) {
713         int trafo_size = 1 << log2_trafo_size;
714         ff_hevc_set_neighbour_available(s, x0, y0, trafo_size, trafo_size);
715
716         s->hpc.intra_pred(s, x0, y0, log2_trafo_size, 0);
717         if (log2_trafo_size > 2) {
718             trafo_size = trafo_size<<(s->sps->hshift[1]-1);
719             ff_hevc_set_neighbour_available(s, x0, y0, trafo_size, trafo_size);
720             s->hpc.intra_pred(s, x0, y0, log2_trafo_size - 1, 1);
721             s->hpc.intra_pred(s, x0, y0, log2_trafo_size - 1, 2);
722         } else if (blk_idx == 3) {
723             trafo_size = trafo_size<<(s->sps->hshift[1]);
724             ff_hevc_set_neighbour_available(s, xBase, yBase, trafo_size, trafo_size);
725             s->hpc.intra_pred(s, xBase, yBase, log2_trafo_size, 1);
726             s->hpc.intra_pred(s, xBase, yBase, log2_trafo_size, 2);
727         }
728     }
729
730     if (lc->tt.cbf_luma ||
731         SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) ||
732         SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0)) {
733         if (s->pps->cu_qp_delta_enabled_flag && !lc->tu.is_cu_qp_delta_coded) {
734             lc->tu.cu_qp_delta = ff_hevc_cu_qp_delta_abs(s);
735             if (lc->tu.cu_qp_delta != 0)
736                 if (ff_hevc_cu_qp_delta_sign_flag(s) == 1)
737                     lc->tu.cu_qp_delta = -lc->tu.cu_qp_delta;
738             lc->tu.is_cu_qp_delta_coded = 1;
739             ff_hevc_set_qPy(s, x0, y0, cb_xBase, cb_yBase, log2_cb_size);
740         }
741
742         if (lc->cu.pred_mode == MODE_INTRA && log2_trafo_size < 4) {
743             if (lc->tu.cur_intra_pred_mode >= 6 &&
744                 lc->tu.cur_intra_pred_mode <= 14) {
745                 scan_idx = SCAN_VERT;
746             } else if (lc->tu.cur_intra_pred_mode >= 22 &&
747                        lc->tu.cur_intra_pred_mode <= 30) {
748                 scan_idx = SCAN_HORIZ;
749             }
750
751             if (lc->pu.intra_pred_mode_c >= 6 &&
752                 lc->pu.intra_pred_mode_c <= 14) {
753                 scan_idx_c = SCAN_VERT;
754             } else if (lc->pu.intra_pred_mode_c >= 22 &&
755                        lc->pu.intra_pred_mode_c <= 30) {
756                 scan_idx_c = SCAN_HORIZ;
757             }
758         }
759
760         if (lc->tt.cbf_luma)
761             ff_hevc_hls_residual_coding(s, x0, y0, log2_trafo_size, scan_idx, 0);
762         if (log2_trafo_size > 2) {
763             if (SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0))
764                 ff_hevc_hls_residual_coding(s, x0, y0, log2_trafo_size - 1, scan_idx_c, 1);
765             if (SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0))
766                 ff_hevc_hls_residual_coding(s, x0, y0, log2_trafo_size - 1, scan_idx_c, 2);
767         } else if (blk_idx == 3) {
768             if (SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], xBase, yBase))
769                 ff_hevc_hls_residual_coding(s, xBase, yBase, log2_trafo_size, scan_idx_c, 1);
770             if (SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], xBase, yBase))
771                 ff_hevc_hls_residual_coding(s, xBase, yBase, log2_trafo_size, scan_idx_c, 2);
772         }
773     }
774 }
775
776 static void set_deblocking_bypass(HEVCContext *s, int x0, int y0, int log2_cb_size)
777 {
778     int cb_size = 1 << log2_cb_size;
779     int log2_min_pu_size = s->sps->log2_min_pu_size;
780
781     int pic_width_in_min_pu = s->sps->width >> s->sps->log2_min_pu_size;
782     int x_end = FFMIN(x0 + cb_size, s->sps->width);
783     int y_end = FFMIN(y0 + cb_size, s->sps->height);
784     int i, j;
785
786     for (j = (y0 >> log2_min_pu_size); j < (y_end >> log2_min_pu_size); j++)
787         for (i = (x0 >> log2_min_pu_size); i < (x_end >> log2_min_pu_size); i++)
788             s->is_pcm[i + j * pic_width_in_min_pu] = 2;
789 }
790
791 static void hls_transform_tree(HEVCContext *s, int x0, int y0, int xBase, int yBase, int cb_xBase, int cb_yBase,
792                                int log2_cb_size, int log2_trafo_size, int trafo_depth, int blk_idx)
793 {
794     HEVCLocalContext *lc = &s->HEVClc;
795     uint8_t split_transform_flag;
796
797     if (trafo_depth > 0 && log2_trafo_size == 2) {
798         SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =
799             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth - 1], xBase, yBase);
800         SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) =
801             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth - 1], xBase, yBase);
802     } else {
803         SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =
804             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) = 0;
805     }
806
807     if (lc->cu.intra_split_flag) {
808         if (trafo_depth == 1)
809             lc->tu.cur_intra_pred_mode = lc->pu.intra_pred_mode[blk_idx];
810     } else {
811         lc->tu.cur_intra_pred_mode = lc->pu.intra_pred_mode[0];
812     }
813
814     lc->tt.cbf_luma = 1;
815
816     lc->tt.inter_split_flag = (s->sps->max_transform_hierarchy_depth_inter == 0 &&
817                                lc->cu.pred_mode == MODE_INTER &&
818                                lc->cu.part_mode != PART_2Nx2N && trafo_depth == 0);
819
820     if (log2_trafo_size <= s->sps->log2_max_trafo_size &&
821         log2_trafo_size > s->sps->log2_min_transform_block_size &&
822         trafo_depth < lc->cu.max_trafo_depth &&
823         !(lc->cu.intra_split_flag && trafo_depth == 0)) {
824         split_transform_flag = ff_hevc_split_transform_flag_decode(s, log2_trafo_size);
825     } else {
826         split_transform_flag = (log2_trafo_size > s->sps->log2_max_trafo_size ||
827                                (lc->cu.intra_split_flag && (trafo_depth == 0)) ||
828                                lc->tt.inter_split_flag);
829     }
830
831     if (log2_trafo_size > 2) {
832         if (trafo_depth == 0 ||
833             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth - 1], xBase, yBase)) {
834             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =
835                 ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
836         }
837
838         if (trafo_depth == 0 || SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth - 1], xBase, yBase)) {
839             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) =
840                 ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
841         }
842     }
843
844     if (split_transform_flag) {
845         int x1 = x0 + ((1 << log2_trafo_size) >> 1);
846         int y1 = y0 + ((1 << log2_trafo_size) >> 1);
847
848         hls_transform_tree(s, x0, y0, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
849                            log2_trafo_size - 1, trafo_depth + 1, 0);
850         hls_transform_tree(s, x1, y0, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
851                            log2_trafo_size - 1, trafo_depth + 1, 1);
852         hls_transform_tree(s, x0, y1, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
853                            log2_trafo_size - 1, trafo_depth + 1, 2);
854         hls_transform_tree(s, x1, y1, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
855                            log2_trafo_size - 1, trafo_depth + 1, 3);
856     } else {
857         int min_tu_size = 1 << s->sps->log2_min_transform_block_size;
858         int log2_min_tu_size = s->sps->log2_min_transform_block_size;
859         int pic_width_in_min_tu = s->sps->width >> log2_min_tu_size;
860         int i, j;
861
862         if (lc->cu.pred_mode == MODE_INTRA || trafo_depth != 0 ||
863             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) ||
864             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0)) {
865             lc->tt.cbf_luma = ff_hevc_cbf_luma_decode(s, trafo_depth);
866         }
867
868         hls_transform_unit(s, x0, y0, xBase, yBase, cb_xBase, cb_yBase,
869                 log2_cb_size, log2_trafo_size, trafo_depth, blk_idx);
870
871         // TODO: store cbf_luma somewhere else
872         if (lc->tt.cbf_luma)
873             for (i = 0; i < (1 << log2_trafo_size); i += min_tu_size)
874                 for (j = 0; j < (1 << log2_trafo_size); j += min_tu_size) {
875                     int x_tu = (x0 + j) >> log2_min_tu_size;
876                     int y_tu = (y0 + i) >> log2_min_tu_size;
877                     s->cbf_luma[y_tu * pic_width_in_min_tu + x_tu] = 1;
878                 }
879         if (!s->sh.disable_deblocking_filter_flag) {
880             ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_trafo_size,
881                                                   lc->slice_or_tiles_up_boundary,
882                                                   lc->slice_or_tiles_left_boundary);
883             if (s->pps->transquant_bypass_enable_flag && lc->cu.cu_transquant_bypass_flag)
884                 set_deblocking_bypass(s, x0, y0, log2_trafo_size);
885         }
886     }
887 }
888
889 static int hls_pcm_sample(HEVCContext *s, int x0, int y0, int log2_cb_size)
890 {
891     //TODO: non-4:2:0 support
892     HEVCLocalContext *lc = &s->HEVClc;
893     GetBitContext gb;
894     int cb_size = 1 << log2_cb_size;
895     int    stride0 = s->frame->linesize[0];
896     uint8_t *dst0 = &s->frame->data[0][y0 * stride0 + (x0 << s->sps->pixel_shift)];
897     int   stride1 = s->frame->linesize[1];
898     uint8_t *dst1 = &s->frame->data[1][(y0 >> s->sps->vshift[1]) * stride1 + ((x0 >> s->sps->hshift[1]) << s->sps->pixel_shift)];
899     int   stride2 = s->frame->linesize[2];
900     uint8_t *dst2 = &s->frame->data[2][(y0 >> s->sps->vshift[2]) * stride2 + ((x0 >> s->sps->hshift[2]) << s->sps->pixel_shift)];
901
902     int length = cb_size * cb_size * s->sps->pcm.bit_depth + ((cb_size * cb_size) >> 1) * s->sps->pcm.bit_depth;
903     const uint8_t *pcm = skip_bytes(&s->HEVClc.cc, (length + 7) >> 3);
904     int ret;
905
906     ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size,
907                                           lc->slice_or_tiles_up_boundary,
908                                           lc->slice_or_tiles_left_boundary);
909
910     ret = init_get_bits(&gb, pcm, length);
911     if (ret < 0)
912         return ret;
913
914     s->hevcdsp.put_pcm(dst0, stride0, cb_size, &gb, s->sps->pcm.bit_depth);
915     s->hevcdsp.put_pcm(dst1, stride1, cb_size / 2, &gb, s->sps->pcm.bit_depth_chroma);
916     s->hevcdsp.put_pcm(dst2, stride2, cb_size / 2, &gb, s->sps->pcm.bit_depth_chroma);
917     return 0;
918 }
919
920 /**
921  * 8.5.3.2.2.1 Luma sample interpolation process
922  *
923  * @param s HEVC decoding context
924  * @param dst target buffer for block data at block position
925  * @param dststride stride of the dst buffer
926  * @param ref reference picture buffer at origin (0, 0)
927  * @param mv motion vector (relative to block position) to get pixel data from
928  * @param x_off horizontal position of block from origin (0, 0)
929  * @param y_off vertical position of block from origin (0, 0)
930  * @param block_w width of block
931  * @param block_h height of block
932  */
933 static void luma_mc(HEVCContext *s, int16_t *dst, ptrdiff_t dststride, AVFrame *ref,
934                     const Mv *mv, int x_off, int y_off, int block_w, int block_h)
935 {
936     HEVCLocalContext *lc = &s->HEVClc;
937     uint8_t *src = ref->data[0];
938     ptrdiff_t srcstride = ref->linesize[0];
939     int pic_width = s->sps->width;
940     int pic_height = s->sps->height;
941
942     int mx = mv->x & 3;
943     int my = mv->y & 3;
944     int extra_left = ff_hevc_qpel_extra_before[mx];
945     int extra_top  = ff_hevc_qpel_extra_before[my];
946
947     x_off += mv->x >> 2;
948     y_off += mv->y >> 2;
949     src   += y_off * srcstride + (x_off << s->sps->pixel_shift);
950
951     if (x_off < extra_left || x_off >= pic_width - block_w - ff_hevc_qpel_extra_after[mx] ||
952         y_off < extra_top || y_off >= pic_height - block_h - ff_hevc_qpel_extra_after[my]) {
953         int offset = extra_top * srcstride + (extra_left << s->sps->pixel_shift);
954
955         s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, srcstride, src - offset, srcstride,
956                                  block_w + ff_hevc_qpel_extra[mx], block_h + ff_hevc_qpel_extra[my],
957                                  x_off - extra_left, y_off - extra_top,
958                                  pic_width, pic_height);
959         src = lc->edge_emu_buffer + offset;
960     }
961     s->hevcdsp.put_hevc_qpel[my][mx](dst, dststride, src, srcstride, block_w,
962                                      block_h, lc->mc_buffer);
963 }
964
965 /**
966  * 8.5.3.2.2.2 Chroma sample interpolation process
967  *
968  * @param s HEVC decoding context
969  * @param dst1 target buffer for block data at block position (U plane)
970  * @param dst2 target buffer for block data at block position (V plane)
971  * @param dststride stride of the dst1 and dst2 buffers
972  * @param ref reference picture buffer at origin (0, 0)
973  * @param mv motion vector (relative to block position) to get pixel data from
974  * @param x_off horizontal position of block from origin (0, 0)
975  * @param y_off vertical position of block from origin (0, 0)
976  * @param block_w width of block
977  * @param block_h height of block
978  */
979 static void chroma_mc(HEVCContext *s, int16_t *dst1, int16_t *dst2, ptrdiff_t dststride, AVFrame *ref,
980                       const Mv *mv, int x_off, int y_off, int block_w, int block_h)
981 {
982     HEVCLocalContext *lc = &s->HEVClc;
983     uint8_t *src1 = ref->data[1];
984     uint8_t *src2 = ref->data[2];
985     ptrdiff_t src1stride = ref->linesize[1];
986     ptrdiff_t src2stride = ref->linesize[2];
987     int pic_width  = s->sps->width >> 1;
988     int pic_height = s->sps->height >> 1;
989
990     int mx = mv->x & 7;
991     int my = mv->y & 7;
992
993     x_off += mv->x >> 3;
994     y_off += mv->y >> 3;
995     src1 += y_off * src1stride + (x_off << s->sps->pixel_shift);
996     src2 += y_off * src2stride + (x_off << s->sps->pixel_shift);
997
998     if (x_off < EPEL_EXTRA_BEFORE || x_off >= pic_width - block_w - EPEL_EXTRA_AFTER ||
999         y_off < EPEL_EXTRA_AFTER || y_off >= pic_height - block_h - EPEL_EXTRA_AFTER) {
1000         int offset1 = EPEL_EXTRA_BEFORE * (src1stride + (1 << s->sps->pixel_shift));
1001         int offset2 = EPEL_EXTRA_BEFORE * (src2stride + (1 << s->sps->pixel_shift));
1002
1003         s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src1stride, src1 - offset1, src1stride,
1004                                  block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
1005                                  x_off - EPEL_EXTRA_BEFORE, y_off - EPEL_EXTRA_BEFORE,
1006                                  pic_width, pic_height);
1007
1008         src1 = lc->edge_emu_buffer + offset1;
1009         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst1, dststride, src1, src1stride,
1010                                              block_w, block_h, mx, my, lc->mc_buffer);
1011
1012         s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src2stride, src2 - offset2, src2stride,
1013                                  block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
1014                                  x_off - EPEL_EXTRA_BEFORE, y_off - EPEL_EXTRA_BEFORE,
1015                                  pic_width, pic_height);
1016         src2 = lc->edge_emu_buffer + offset2;
1017         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst2, dststride, src2, src2stride,
1018                                              block_w, block_h, mx, my, lc->mc_buffer);
1019     } else {
1020         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst1, dststride, src1, src1stride,
1021                                              block_w, block_h, mx, my, lc->mc_buffer);
1022         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst2, dststride, src2, src2stride,
1023                                              block_w, block_h, mx, my, lc->mc_buffer);
1024     }
1025 }
1026
1027 static void hevc_await_progress(HEVCContext *s, HEVCFrame *ref,
1028                                 const Mv *mv, int y0)
1029 {
1030     int y = (mv->y >> 2) + y0;
1031
1032     //ff_thread_await_progress(&ref->tf, FFMIN(s->height, y), 0);
1033     ff_thread_await_progress(&ref->tf, INT_MAX, 0);
1034 }
1035
1036 static void hls_prediction_unit(HEVCContext *s, int x0, int y0, int nPbW, int nPbH, int log2_cb_size, int partIdx)
1037 {
1038 #define POS(c_idx, x, y)                                                              \
1039     &s->frame->data[c_idx][((y) >> s->sps->vshift[c_idx]) * s->frame->linesize[c_idx] + \
1040                            (((x) >> s->sps->hshift[c_idx]) << s->sps->pixel_shift)]
1041     HEVCLocalContext *lc = &s->HEVClc;
1042     int merge_idx = 0;
1043     enum InterPredIdc inter_pred_idc = PRED_L0;
1044     struct MvField current_mv = {{{ 0 }}};
1045
1046     int pic_width_in_min_pu = s->sps->width >> s->sps->log2_min_pu_size;
1047
1048     MvField *tab_mvf = s->ref->tab_mvf;
1049     RefPicList  *refPicList = s->ref->refPicList;
1050     HEVCFrame *ref0, *ref1;
1051
1052     int tmpstride = MAX_PB_SIZE;
1053
1054     uint8_t *dst0 = POS(0, x0, y0);
1055     uint8_t *dst1 = POS(1, x0, y0);
1056     uint8_t *dst2 = POS(2, x0, y0);
1057     int log2_min_cb_size = s->sps->log2_min_coding_block_size;
1058     int pic_width_in_ctb = s->sps->width>>log2_min_cb_size;
1059     int x_cb             = x0 >> log2_min_cb_size;
1060     int y_cb             = y0 >> log2_min_cb_size;
1061     int ref_idx[2];
1062     int mvp_flag[2];
1063     int x_pu, y_pu;
1064     int i, j;
1065
1066     if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) {
1067         if (s->sh.max_num_merge_cand > 1)
1068             merge_idx = ff_hevc_merge_idx_decode(s);
1069         else
1070             merge_idx = 0;
1071
1072         ff_hevc_luma_mv_merge_mode(s, x0, y0, 1 << log2_cb_size, 1 << log2_cb_size,
1073                                    log2_cb_size, partIdx, merge_idx, &current_mv);
1074         x_pu = x0 >> s->sps->log2_min_pu_size;
1075         y_pu = y0 >> s->sps->log2_min_pu_size;
1076
1077         for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)
1078             for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)
1079                 tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i] = current_mv;
1080     } else { /* MODE_INTER */
1081         lc->pu.merge_flag = ff_hevc_merge_flag_decode(s);
1082         if (lc->pu.merge_flag) {
1083             if (s->sh.max_num_merge_cand > 1)
1084                 merge_idx = ff_hevc_merge_idx_decode(s);
1085             else
1086                 merge_idx = 0;
1087
1088             ff_hevc_luma_mv_merge_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
1089                                        partIdx, merge_idx, &current_mv);
1090             x_pu = x0 >> s->sps->log2_min_pu_size;
1091             y_pu = y0 >> s->sps->log2_min_pu_size;
1092
1093             for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)
1094                 for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)
1095                     tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i] = current_mv;
1096         } else {
1097             ff_hevc_set_neighbour_available(s, x0, y0, nPbW, nPbH);
1098             if (s->sh.slice_type == B_SLICE)
1099                 inter_pred_idc = ff_hevc_inter_pred_idc_decode(s, nPbW, nPbH);
1100
1101             if (inter_pred_idc != PRED_L1) {
1102                 if (s->sh.nb_refs[L0]) {
1103                     ref_idx[0] = ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L0]);
1104                     current_mv.ref_idx[0] = ref_idx[0];
1105                 }
1106                 current_mv.pred_flag[0] = 1;
1107                 ff_hevc_hls_mvd_coding(s, x0, y0, 0);
1108                 mvp_flag[0] = ff_hevc_mvp_lx_flag_decode(s);
1109                 ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
1110                                          partIdx, merge_idx, &current_mv, mvp_flag[0], 0);
1111                 current_mv.mv[0].x += lc->pu.mvd.x;
1112                 current_mv.mv[0].y += lc->pu.mvd.y;
1113             }
1114
1115             if (inter_pred_idc != PRED_L0) {
1116                 if (s->sh.nb_refs[L1]) {
1117                     ref_idx[1] = ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L1]);
1118                     current_mv.ref_idx[1] = ref_idx[1];
1119                 }
1120
1121                 if (s->sh.mvd_l1_zero_flag == 1 && inter_pred_idc == PRED_BI) {
1122                     lc->pu.mvd.x = 0;
1123                     lc->pu.mvd.y = 0;
1124                 } else {
1125                     ff_hevc_hls_mvd_coding(s, x0, y0, 1);
1126                 }
1127
1128                 current_mv.pred_flag[1] = 1;
1129                 mvp_flag[1] = ff_hevc_mvp_lx_flag_decode(s);
1130                 ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
1131                                          partIdx, merge_idx, &current_mv, mvp_flag[1], 1);
1132                 current_mv.mv[1].x += lc->pu.mvd.x;
1133                 current_mv.mv[1].y += lc->pu.mvd.y;
1134             }
1135
1136             x_pu = x0 >> s->sps->log2_min_pu_size;
1137             y_pu = y0 >> s->sps->log2_min_pu_size;
1138
1139             for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)
1140                 for(j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)
1141                     tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i] = current_mv;
1142         }
1143     }
1144
1145     if (current_mv.pred_flag[0]) {
1146         ref0 = refPicList[0].ref[current_mv.ref_idx[0]];
1147         if (!ref0)
1148             return;
1149         hevc_await_progress(s, ref0, &current_mv.mv[0], y0);
1150     }
1151     if (current_mv.pred_flag[1]) {
1152         ref1 = refPicList[1].ref[current_mv.ref_idx[1]];
1153         if (!ref1)
1154             return;
1155         hevc_await_progress(s, ref1, &current_mv.mv[1], y0);
1156     }
1157
1158     if (current_mv.pred_flag[0] && !current_mv.pred_flag[1]) {
1159         DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
1160         DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]);
1161
1162         luma_mc(s, tmp, tmpstride, ref0->frame,
1163                 &current_mv.mv[0], x0, y0, nPbW, nPbH);
1164
1165         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
1166             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
1167             s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom,
1168                                      s->sh.luma_weight_l0[current_mv.ref_idx[0]],
1169                                      s->sh.luma_offset_l0[current_mv.ref_idx[0]],
1170                                      dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH);
1171         } else {
1172             s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH);
1173         }
1174         chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame,
1175                   &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2);
1176
1177         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
1178             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
1179             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
1180                                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0],
1181                                      s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0],
1182                                      dst1, s->frame->linesize[1], tmp, tmpstride,
1183                                      nPbW / 2, nPbH / 2);
1184             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
1185                                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1],
1186                                      s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1],
1187                                      dst2, s->frame->linesize[2], tmp2, tmpstride,
1188                                      nPbW / 2, nPbH / 2);
1189         } else {
1190             s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2);
1191             s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2);
1192         }
1193     } else if (!current_mv.pred_flag[0] && current_mv.pred_flag[1]) {
1194         DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
1195         DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]);
1196
1197         if (!ref1)
1198             return;
1199
1200         luma_mc(s, tmp, tmpstride, ref1->frame,
1201                 &current_mv.mv[1], x0, y0, nPbW, nPbH);
1202
1203         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
1204             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
1205             s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom,
1206                                       s->sh.luma_weight_l1[current_mv.ref_idx[1]],
1207                                       s->sh.luma_offset_l1[current_mv.ref_idx[1]],
1208                                       dst0, s->frame->linesize[0], tmp, tmpstride,
1209                                       nPbW, nPbH);
1210         } else {
1211             s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH);
1212         }
1213
1214         chroma_mc(s, tmp, tmp2, tmpstride, ref1->frame,
1215                   &current_mv.mv[1], x0/2, y0/2, nPbW/2, nPbH/2);
1216
1217         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
1218             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
1219             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
1220                                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0],
1221                                      s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0],
1222                                      dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2);
1223             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
1224                                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1],
1225                                      s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1],
1226                                      dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2);
1227         } else {
1228             s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2);
1229             s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2);
1230         }
1231     } else if (current_mv.pred_flag[0] && current_mv.pred_flag[1]) {
1232         DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
1233         DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]);
1234         DECLARE_ALIGNED(16, int16_t, tmp3[MAX_PB_SIZE * MAX_PB_SIZE]);
1235         DECLARE_ALIGNED(16, int16_t, tmp4[MAX_PB_SIZE * MAX_PB_SIZE]);
1236         HEVCFrame *ref0 = refPicList[0].ref[current_mv.ref_idx[0]];
1237         HEVCFrame *ref1 = refPicList[1].ref[current_mv.ref_idx[1]];
1238
1239         if (!ref0 || !ref1)
1240             return;
1241
1242         luma_mc(s, tmp, tmpstride, ref0->frame,
1243                 &current_mv.mv[0], x0, y0, nPbW, nPbH);
1244         luma_mc(s, tmp2, tmpstride, ref1->frame,
1245                 &current_mv.mv[1], x0, y0, nPbW, nPbH);
1246
1247         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
1248             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)){
1249             s->hevcdsp.weighted_pred_avg(s->sh.luma_log2_weight_denom,
1250                                          s->sh.luma_weight_l0[current_mv.ref_idx[0]],
1251                                          s->sh.luma_weight_l1[current_mv.ref_idx[1]],
1252                                          s->sh.luma_offset_l0[current_mv.ref_idx[0]],
1253                                          s->sh.luma_offset_l1[current_mv.ref_idx[1]],
1254                                          dst0, s->frame->linesize[0], tmp, tmp2, tmpstride, nPbW, nPbH);
1255         } else {
1256             s->hevcdsp.put_weighted_pred_avg(dst0, s->frame->linesize[0], tmp, tmp2, tmpstride, nPbW, nPbH);
1257         }
1258
1259         chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame,
1260                   &current_mv.mv[0], x0/2, y0/2, nPbW/2, nPbH/2);
1261         chroma_mc(s, tmp3, tmp4, tmpstride, ref1->frame,
1262                   &current_mv.mv[1], x0/2, y0/2, nPbW/2, nPbH/2);
1263
1264         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
1265             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
1266             s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom ,
1267                                          s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0],
1268                                          s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0],
1269                                          s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0],
1270                                          s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0],
1271                                          dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW/2, nPbH/2);
1272             s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom ,
1273                                          s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1],
1274                                          s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1],
1275                                          s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1],
1276                                          s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1],
1277                                          dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW/2, nPbH/2);
1278         } else {
1279             s->hevcdsp.put_weighted_pred_avg(dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW/2, nPbH/2);
1280             s->hevcdsp.put_weighted_pred_avg(dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW/2, nPbH/2);
1281         }
1282     }
1283 }
1284
1285 /**
1286  * 8.4.1
1287  */
1288 static int luma_intra_pred_mode(HEVCContext *s, int x0, int y0, int pu_size,
1289                                 int prev_intra_luma_pred_flag)
1290 {
1291     HEVCLocalContext *lc = &s->HEVClc;
1292     int x_pu = x0 >> s->sps->log2_min_pu_size;
1293     int y_pu = y0 >> s->sps->log2_min_pu_size;
1294     int pic_width_in_min_pu = s->sps->width >> s->sps->log2_min_pu_size;
1295     int size_in_pus = pu_size >> s->sps->log2_min_pu_size;
1296     int x0b = x0 & ((1 << s->sps->log2_ctb_size) - 1);
1297     int y0b = y0 & ((1 << s->sps->log2_ctb_size) - 1);
1298
1299     int cand_up   = (lc->ctb_up_flag || y0b) ? s->tab_ipm[(y_pu-1)*pic_width_in_min_pu+x_pu] : INTRA_DC ;
1300     int cand_left = (lc->ctb_left_flag || x0b) ? s->tab_ipm[y_pu*pic_width_in_min_pu+x_pu-1] : INTRA_DC ;
1301
1302     int y_ctb = (y0 >> (s->sps->log2_ctb_size)) << (s->sps->log2_ctb_size);
1303     MvField *tab_mvf = s->ref->tab_mvf;
1304     int intra_pred_mode;
1305     int candidate[3];
1306     int i, j;
1307
1308     // intra_pred_mode prediction does not cross vertical CTB boundaries
1309     if ((y0 - 1) < y_ctb)
1310         cand_up = INTRA_DC;
1311
1312     if (cand_left == cand_up) {
1313         if (cand_left < 2) {
1314             candidate[0] = INTRA_PLANAR;
1315             candidate[1] = INTRA_DC;
1316             candidate[2] = INTRA_ANGULAR_26;
1317         } else {
1318             candidate[0] = cand_left;
1319             candidate[1] = 2 + ((cand_left - 2 - 1 + 32) & 31);
1320             candidate[2] = 2 + ((cand_left - 2 + 1) & 31);
1321         }
1322     } else {
1323         candidate[0] = cand_left;
1324         candidate[1] = cand_up;
1325         if (candidate[0] != INTRA_PLANAR && candidate[1] != INTRA_PLANAR) {
1326             candidate[2] = INTRA_PLANAR;
1327         } else if (candidate[0] != INTRA_DC && candidate[1] != INTRA_DC) {
1328             candidate[2] = INTRA_DC;
1329         } else {
1330             candidate[2] = INTRA_ANGULAR_26;
1331         }
1332     }
1333
1334     if (prev_intra_luma_pred_flag) {
1335         intra_pred_mode = candidate[lc->pu.mpm_idx];
1336     } else {
1337         if (candidate[0] > candidate[1])
1338             FFSWAP(uint8_t, candidate[0], candidate[1]);
1339         if (candidate[0] > candidate[2])
1340             FFSWAP(uint8_t, candidate[0], candidate[2]);
1341         if (candidate[1] > candidate[2])
1342             FFSWAP(uint8_t, candidate[1], candidate[2]);
1343
1344         intra_pred_mode = lc->pu.rem_intra_luma_pred_mode;
1345         for (i = 0; i < 3; i++) {
1346             if (intra_pred_mode >= candidate[i])
1347                 intra_pred_mode++;
1348         }
1349     }
1350
1351     /* write the intra prediction units into the mv array */
1352     if(!size_in_pus)
1353         size_in_pus = 1;
1354     for (i = 0; i < size_in_pus; i++) {
1355         memset(&s->tab_ipm[(y_pu + i) * pic_width_in_min_pu + x_pu],
1356                intra_pred_mode, size_in_pus);
1357
1358         for (j = 0; j < size_in_pus; j++) {
1359             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].is_intra     = 1;
1360             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].pred_flag[0] = 0;
1361             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].pred_flag[1] = 0;
1362             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].ref_idx[0]   = 0;
1363             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].ref_idx[1]   = 0;
1364             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].mv[0].x      = 0;
1365             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].mv[0].y      = 0;
1366             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].mv[1].x      = 0;
1367             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + i].mv[1].y      = 0;
1368         }
1369     }
1370
1371     return intra_pred_mode;
1372 }
1373
1374 static av_always_inline void set_ct_depth(HEVCContext *s, int x0, int y0,
1375                                           int log2_cb_size, int ct_depth)
1376 {
1377     int length = (1 << log2_cb_size) >> s->sps->log2_min_coding_block_size;
1378     int x_cb = x0 >> s->sps->log2_min_coding_block_size;
1379     int y_cb = y0 >> s->sps->log2_min_coding_block_size;
1380     int y;
1381
1382     for (y = 0; y < length; y++)
1383         memset(&s->tab_ct_depth[(y_cb + y) * s->sps->min_cb_width + x_cb],
1384                ct_depth, length);
1385 }
1386
1387 static void intra_prediction_unit(HEVCContext *s, int x0, int y0, int log2_cb_size)
1388 {
1389     HEVCLocalContext *lc = &s->HEVClc;
1390     static const uint8_t intra_chroma_table[4] = {0, 26, 10, 1};
1391     uint8_t prev_intra_luma_pred_flag[4];
1392     int split   = lc->cu.part_mode == PART_NxN;
1393     int pb_size = (1 << log2_cb_size) >> split;
1394     int side    = split + 1;
1395     int chroma_mode;
1396     int i, j;
1397
1398     for (i = 0; i < side; i++)
1399         for (j = 0; j < side; j++)
1400             prev_intra_luma_pred_flag[2 * i + j] = ff_hevc_prev_intra_luma_pred_flag_decode(s);
1401
1402     for (i = 0; i < side; i++) {
1403         for (j = 0; j < side; j++) {
1404             if (prev_intra_luma_pred_flag[2*i+j])
1405                 lc->pu.mpm_idx = ff_hevc_mpm_idx_decode(s);
1406             else
1407                 lc->pu.rem_intra_luma_pred_mode = ff_hevc_rem_intra_luma_pred_mode_decode(s);
1408
1409             lc->pu.intra_pred_mode[2 * i + j] =
1410                 luma_intra_pred_mode(s, x0 + pb_size * j, y0 + pb_size * i, pb_size,
1411                                      prev_intra_luma_pred_flag[2 * i + j]);
1412         }
1413     }
1414
1415     chroma_mode = ff_hevc_intra_chroma_pred_mode_decode(s);
1416     if (chroma_mode != 4) {
1417         if (lc->pu.intra_pred_mode[0] == intra_chroma_table[chroma_mode])
1418             lc->pu.intra_pred_mode_c = 34;
1419         else
1420             lc->pu.intra_pred_mode_c = intra_chroma_table[chroma_mode];
1421     } else {
1422         lc->pu.intra_pred_mode_c = lc->pu.intra_pred_mode[0];
1423     }
1424 }
1425
1426 static void intra_prediction_unit_default_value(HEVCContext *s, int x0, int y0, int log2_cb_size)
1427 {
1428     HEVCLocalContext *lc = &s->HEVClc;
1429     int pb_size = 1 << log2_cb_size;
1430     int size_in_pus = pb_size >> s->sps->log2_min_pu_size;
1431     int pic_width_in_min_pu = s->sps->width >> s->sps->log2_min_pu_size;
1432     MvField *tab_mvf = s->ref->tab_mvf;
1433     int x_pu = x0 >> s->sps->log2_min_pu_size;
1434     int y_pu = y0 >> s->sps->log2_min_pu_size;
1435     int j, k;
1436
1437     if (size_in_pus == 0)
1438         size_in_pus = 1;
1439     for (j = 0; j < size_in_pus; j++) {
1440         memset(&s->tab_ipm[(y_pu + j) * pic_width_in_min_pu + x_pu], INTRA_DC, size_in_pus);
1441         for (k = 0; k <size_in_pus; k++)
1442             tab_mvf[(y_pu + j) * pic_width_in_min_pu + x_pu + k].is_intra = lc->cu.pred_mode == MODE_INTRA;
1443     }
1444 }
1445
1446 static int hls_coding_unit(HEVCContext *s, int x0, int y0, int log2_cb_size)
1447 {
1448     int cb_size          = 1 << log2_cb_size;
1449     HEVCLocalContext *lc = &s->HEVClc;
1450     int log2_min_cb_size = s->sps->log2_min_coding_block_size;
1451     int length           = cb_size >> log2_min_cb_size;
1452     int pic_width_in_ctb = s->sps->width >> log2_min_cb_size;
1453     int x_cb             = x0 >> log2_min_cb_size;
1454     int y_cb             = y0 >> log2_min_cb_size;
1455     int x, y;
1456
1457     lc->cu.x = x0;
1458     lc->cu.y = y0;
1459     lc->cu.rqt_root_cbf = 1;
1460
1461     lc->cu.pred_mode        = MODE_INTRA;
1462     lc->cu.part_mode        = PART_2Nx2N;
1463     lc->cu.intra_split_flag = 0;
1464     lc->cu.pcm_flag         = 0;
1465     SAMPLE_CTB(s->skip_flag, x_cb, y_cb) = 0;
1466     for (x = 0; x < 4; x++)
1467         lc->pu.intra_pred_mode[x] = 1;
1468     if (s->pps->transquant_bypass_enable_flag) {
1469         lc->cu.cu_transquant_bypass_flag = ff_hevc_cu_transquant_bypass_flag_decode(s);
1470         if (lc->cu.cu_transquant_bypass_flag)
1471             set_deblocking_bypass(s, x0, y0, log2_cb_size);
1472     } else
1473         lc->cu.cu_transquant_bypass_flag = 0;
1474
1475
1476     if (s->sh.slice_type != I_SLICE) {
1477         uint8_t skip_flag = ff_hevc_skip_flag_decode(s, x0, y0, x_cb, y_cb);
1478
1479         lc->cu.pred_mode = MODE_SKIP;
1480         x = y_cb * pic_width_in_ctb + x_cb;
1481         for (y = 0; y < length; y++) {
1482             memset(&s->skip_flag[x], skip_flag, length);
1483             x += pic_width_in_ctb;
1484         }
1485         lc->cu.pred_mode = skip_flag ? MODE_SKIP : MODE_INTER;
1486     }
1487
1488     if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) {
1489         hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0);
1490         intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
1491
1492         if (!s->sh.disable_deblocking_filter_flag)
1493             ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size,
1494                                                   lc->slice_or_tiles_up_boundary,
1495                                                   lc->slice_or_tiles_left_boundary);
1496     } else {
1497         if (s->sh.slice_type != I_SLICE)
1498             lc->cu.pred_mode = ff_hevc_pred_mode_decode(s);
1499         if (lc->cu.pred_mode != MODE_INTRA ||
1500             log2_cb_size == s->sps->log2_min_coding_block_size) {
1501             lc->cu.part_mode = ff_hevc_part_mode_decode(s, log2_cb_size);
1502             lc->cu.intra_split_flag = lc->cu.part_mode == PART_NxN &&
1503                                       lc->cu.pred_mode == MODE_INTRA;
1504         }
1505
1506         if (lc->cu.pred_mode == MODE_INTRA) {
1507             if (lc->cu.part_mode == PART_2Nx2N && s->sps->pcm_enabled_flag &&
1508                 log2_cb_size >= s->sps->pcm.log2_min_pcm_cb_size &&
1509                 log2_cb_size <= s->sps->pcm.log2_max_pcm_cb_size) {
1510                 lc->cu.pcm_flag = ff_hevc_pcm_flag_decode(s);
1511             }
1512             if (lc->cu.pcm_flag) {
1513                 int ret;
1514                 intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
1515                 ret = hls_pcm_sample(s, x0, y0, log2_cb_size);
1516                 if(s->sps->pcm.loop_filter_disable_flag)
1517                     set_deblocking_bypass(s, x0, y0, log2_cb_size);
1518
1519                 if (ret < 0)
1520                     return ret;
1521             } else {
1522                 intra_prediction_unit(s, x0, y0, log2_cb_size);
1523             }
1524         } else {
1525             intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
1526             switch (lc->cu.part_mode) {
1527             case PART_2Nx2N:
1528                 hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0);
1529                 break;
1530             case PART_2NxN:
1531                 hls_prediction_unit(s, x0, y0, cb_size, cb_size / 2, log2_cb_size, 0);
1532                 hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size, cb_size/2, log2_cb_size, 1);
1533                 break;
1534             case PART_Nx2N:
1535                 hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size, log2_cb_size, 0);
1536                 hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size, log2_cb_size, 1);
1537                 break;
1538             case PART_2NxnU:
1539                 hls_prediction_unit(s, x0, y0, cb_size, cb_size / 4, log2_cb_size, 0);
1540                 hls_prediction_unit(s, x0, y0 + cb_size / 4, cb_size, cb_size * 3 / 4, log2_cb_size, 1);
1541                 break;
1542             case PART_2NxnD:
1543                 hls_prediction_unit(s, x0, y0, cb_size, cb_size * 3 / 4, log2_cb_size, 0);
1544                 hls_prediction_unit(s, x0, y0 + cb_size * 3 / 4, cb_size, cb_size / 4, log2_cb_size, 1);
1545                 break;
1546             case PART_nLx2N:
1547                 hls_prediction_unit(s, x0, y0, cb_size / 4, cb_size, log2_cb_size,0);
1548                 hls_prediction_unit(s, x0 + cb_size / 4, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 1);
1549                 break;
1550             case PART_nRx2N:
1551                 hls_prediction_unit(s, x0, y0, cb_size * 3 / 4, cb_size, log2_cb_size,0);
1552                 hls_prediction_unit(s, x0 + cb_size * 3 / 4, y0, cb_size/4, cb_size, log2_cb_size, 1);
1553                 break;
1554             case PART_NxN:
1555                 hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size / 2, log2_cb_size, 0);
1556                 hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size / 2, log2_cb_size, 1);
1557                 hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 2);
1558                 hls_prediction_unit(s, x0 + cb_size / 2, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 3);
1559                 break;
1560             }
1561         }
1562
1563         if (!lc->cu.pcm_flag) {
1564             if (lc->cu.pred_mode != MODE_INTRA &&
1565                 !(lc->cu.part_mode == PART_2Nx2N && lc->pu.merge_flag)) {
1566                 lc->cu.rqt_root_cbf = ff_hevc_no_residual_syntax_flag_decode(s);
1567             }
1568             if (lc->cu.rqt_root_cbf) {
1569                 lc->cu.max_trafo_depth = lc->cu.pred_mode == MODE_INTRA ?
1570                                         s->sps->max_transform_hierarchy_depth_intra + lc->cu.intra_split_flag :
1571                                         s->sps->max_transform_hierarchy_depth_inter;
1572                 hls_transform_tree(s, x0, y0, x0, y0, x0, y0, log2_cb_size,
1573                                    log2_cb_size, 0, 0);
1574             } else {
1575                 if (!s->sh.disable_deblocking_filter_flag)
1576                     ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size,
1577                                                           lc->slice_or_tiles_up_boundary,
1578                                                           lc->slice_or_tiles_left_boundary);
1579             }
1580         }
1581     }
1582
1583     if (s->pps->cu_qp_delta_enabled_flag && lc->tu.is_cu_qp_delta_coded == 0)
1584         ff_hevc_set_qPy(s, x0, y0, x0, y0, log2_cb_size);
1585
1586     x = y_cb * pic_width_in_ctb + x_cb;
1587     for (y = 0; y < length; y++) {
1588         memset(&s->qp_y_tab[x], lc->qp_y, length);
1589         x += pic_width_in_ctb;
1590     }
1591
1592     set_ct_depth(s, x0, y0, log2_cb_size, lc->ct.depth);
1593
1594     return 0;
1595 }
1596
1597 static int hls_coding_quadtree(HEVCContext *s, int x0, int y0, int log2_cb_size, int cb_depth)
1598 {
1599     HEVCLocalContext *lc = &s->HEVClc;
1600     int ret;
1601
1602     lc->ct.depth = cb_depth;
1603     if ((x0 + (1 << log2_cb_size) <= s->sps->width) &&
1604         (y0 + (1 << log2_cb_size) <= s->sps->height) &&
1605         log2_cb_size > s->sps->log2_min_coding_block_size) {
1606         SAMPLE(s->split_cu_flag, x0, y0) =
1607             ff_hevc_split_coding_unit_flag_decode(s, cb_depth, x0, y0);
1608     } else {
1609         SAMPLE(s->split_cu_flag, x0, y0) =
1610             (log2_cb_size > s->sps->log2_min_coding_block_size);
1611     }
1612     if (s->pps->cu_qp_delta_enabled_flag &&
1613         log2_cb_size >= s->sps->log2_ctb_size - s->pps->diff_cu_qp_delta_depth) {
1614         lc->tu.is_cu_qp_delta_coded = 0;
1615         lc->tu.cu_qp_delta          = 0;
1616     }
1617
1618     if (SAMPLE(s->split_cu_flag, x0, y0)) {
1619         int more_data = 0;
1620         int cb_size = (1 << (log2_cb_size)) >> 1;
1621         int x1 = x0 + cb_size;
1622         int y1 = y0 + cb_size;
1623
1624         more_data = hls_coding_quadtree(s, x0, y0, log2_cb_size - 1, cb_depth + 1);
1625         if (more_data < 0)
1626             return more_data;
1627
1628         if (more_data && x1 < s->sps->width)
1629             more_data = hls_coding_quadtree(s, x1, y0, log2_cb_size - 1, cb_depth + 1);
1630         if (more_data && y1 < s->sps->height)
1631             more_data = hls_coding_quadtree(s, x0, y1, log2_cb_size - 1, cb_depth + 1);
1632         if (more_data && x1 < s->sps->width &&
1633             y1 < s->sps->height) {
1634             return hls_coding_quadtree(s, x1, y1, log2_cb_size - 1, cb_depth + 1);
1635         }
1636         if (more_data)
1637             return ((x1 + cb_size) < s->sps->width ||
1638                     (y1 + cb_size) < s->sps->height);
1639         else
1640             return 0;
1641     } else {
1642         ret = hls_coding_unit(s, x0, y0, log2_cb_size);
1643         if (ret < 0)
1644             return ret;
1645         if ((!((x0 + (1 << log2_cb_size)) %
1646                (1 << (s->sps->log2_ctb_size))) ||
1647              (x0 + (1 << log2_cb_size) >= s->sps->width)) &&
1648             (!((y0 + (1 << log2_cb_size)) %
1649                (1 << (s->sps->log2_ctb_size))) ||
1650              (y0 + (1 << log2_cb_size) >= s->sps->height))) {
1651             int end_of_slice_flag = ff_hevc_end_of_slice_flag_decode(s);
1652             return !end_of_slice_flag;
1653         } else {
1654             return 1;
1655         }
1656     }
1657
1658     return 0;
1659 }
1660
1661 /**
1662  * 7.3.4
1663  */
1664
1665 static void hls_decode_neighbour(HEVCContext *s, int x_ctb, int y_ctb, int ctb_addr_ts)
1666 {
1667     HEVCLocalContext *lc  = &s->HEVClc;
1668     int ctb_size          = 1 << s->sps->log2_ctb_size;
1669     int ctb_addr_rs       = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts];
1670     int ctb_addr_in_slice = ctb_addr_rs - s->sh.slice_addr;
1671
1672     int tile_left_boundary;
1673     int tile_up_boundary;
1674     int slice_left_boundary;
1675     int slice_up_boundary;
1676
1677     s->tab_slice_address[ctb_addr_rs] = s->sh.slice_addr;
1678
1679
1680     if (s->pps->entropy_coding_sync_enabled_flag) {
1681         if (x_ctb == 0 && (y_ctb & (ctb_size - 1)) == 0)
1682             lc->first_qp_group = 1;
1683         lc->end_of_tiles_x = s->sps->width;
1684     } else if (s->pps->tiles_enabled_flag) {
1685         if (ctb_addr_ts && s->pps->tile_id[ctb_addr_ts] != s->pps->tile_id[ctb_addr_ts - 1]) {
1686             int idxX = s->pps->col_idxX[x_ctb >> s->sps->log2_ctb_size];
1687             lc->start_of_tiles_x = x_ctb;
1688             lc->end_of_tiles_x   = x_ctb + (s->pps->column_width[idxX]<< s->sps->log2_ctb_size);
1689             lc->first_qp_group   = 1;
1690         }
1691     } else {
1692         lc->end_of_tiles_x = s->sps->width;
1693     }
1694
1695     lc->end_of_tiles_y = FFMIN(y_ctb + ctb_size, s->sps->height);
1696
1697     if (s->pps->tiles_enabled_flag) {
1698         tile_left_boundary = ((x_ctb > 0) &&
1699                               (s->pps->tile_id[ctb_addr_ts] == s->pps->tile_id[s->pps->ctb_addr_rs_to_ts[ctb_addr_rs-1]]));
1700         slice_left_boundary = ((x_ctb > 0) &&
1701                                (s->tab_slice_address[ctb_addr_rs] == s->tab_slice_address[ctb_addr_rs - 1]));
1702         tile_up_boundary = ((y_ctb > 0) &&
1703                             (s->pps->tile_id[ctb_addr_ts] == s->pps->tile_id[s->pps->ctb_addr_rs_to_ts[ctb_addr_rs - s->sps->ctb_width]]));
1704         slice_up_boundary = ((y_ctb > 0) &&
1705                              (s->tab_slice_address[ctb_addr_rs] == s->tab_slice_address[ctb_addr_rs - s->sps->ctb_width]));
1706     } else {
1707         tile_left_boundary =
1708         tile_up_boundary = 1;
1709         slice_left_boundary = ctb_addr_in_slice > 0;
1710         slice_up_boundary = ctb_addr_in_slice >= s->sps->ctb_width;
1711     }
1712     lc->slice_or_tiles_left_boundary = (!slice_left_boundary) + (!tile_left_boundary << 1);
1713     lc->slice_or_tiles_up_boundary   = (!slice_up_boundary + (!tile_up_boundary << 1));
1714     lc->ctb_left_flag = ((x_ctb > 0) && (ctb_addr_in_slice > 0) && tile_left_boundary);
1715     lc->ctb_up_flag   = ((y_ctb > 0) && (ctb_addr_in_slice >= s->sps->ctb_width) && tile_up_boundary);
1716     lc->ctb_up_right_flag = ((y_ctb > 0)  && (ctb_addr_in_slice+1 >= s->sps->ctb_width) && (s->pps->tile_id[ctb_addr_ts] == s->pps->tile_id[s->pps->ctb_addr_rs_to_ts[ctb_addr_rs+1 - s->sps->ctb_width]]));
1717     lc->ctb_up_left_flag = ((x_ctb > 0) && (y_ctb > 0)  && (ctb_addr_in_slice-1 >= s->sps->ctb_width) && (s->pps->tile_id[ctb_addr_ts] == s->pps->tile_id[s->pps->ctb_addr_rs_to_ts[ctb_addr_rs-1 - s->sps->ctb_width]]));
1718 }
1719
1720 static int hls_slice_data(HEVCContext *s)
1721 {
1722     int ctb_size    = 1 << s->sps->log2_ctb_size;
1723     int more_data   = 1;
1724     int x_ctb       = 0;
1725     int y_ctb       = 0;
1726     int ctb_addr_ts = s->pps->ctb_addr_rs_to_ts[s->sh.slice_ctb_addr_rs];
1727
1728     while (more_data && ctb_addr_ts < s->sps->ctb_size) {
1729         int ctb_addr_rs = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts];
1730
1731         x_ctb = (ctb_addr_rs % ((s->sps->width + (ctb_size - 1)) >> s->sps->log2_ctb_size)) << s->sps->log2_ctb_size;
1732         y_ctb = (ctb_addr_rs / ((s->sps->width + (ctb_size - 1)) >> s->sps->log2_ctb_size)) << s->sps->log2_ctb_size;
1733         hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);
1734
1735         ff_hevc_cabac_init(s, ctb_addr_ts);
1736
1737         hls_sao_param(s, x_ctb >> s->sps->log2_ctb_size, y_ctb >> s->sps->log2_ctb_size);
1738
1739         s->deblock[ctb_addr_rs].disable     = s->sh.disable_deblocking_filter_flag;
1740         s->deblock[ctb_addr_rs].beta_offset = s->sh.beta_offset;
1741         s->deblock[ctb_addr_rs].tc_offset   = s->sh.tc_offset;
1742         s->filter_slice_edges[ctb_addr_rs]  = s->sh.slice_loop_filter_across_slices_enabled_flag;
1743
1744         more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->sps->log2_ctb_size, 0);
1745         if (more_data < 0)
1746             return more_data;
1747
1748         ctb_addr_ts++;
1749         ff_hevc_save_states(s, ctb_addr_ts);
1750         ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);
1751     }
1752
1753     if (x_ctb + ctb_size >= s->sps->width &&
1754         y_ctb + ctb_size >= s->sps->height)
1755         ff_hevc_hls_filter(s, x_ctb, y_ctb);
1756
1757     return ctb_addr_ts;
1758 }
1759
1760 /**
1761  * @return AVERROR_INVALIDDATA if the packet is not a valid NAL unit,
1762  * 0 if the unit should be skipped, 1 otherwise
1763  */
1764 static int hls_nal_unit(HEVCContext *s)
1765 {
1766     GetBitContext *gb = &s->HEVClc.gb;
1767     int nuh_layer_id;
1768
1769     if (get_bits1(gb) != 0)
1770         return AVERROR_INVALIDDATA;
1771
1772     s->nal_unit_type = get_bits(gb, 6);
1773
1774     nuh_layer_id   = get_bits(gb, 6);
1775     s->temporal_id = get_bits(gb, 3) - 1;
1776     if (s->temporal_id < 0)
1777         return AVERROR_INVALIDDATA;
1778
1779     av_log(s->avctx, AV_LOG_DEBUG,
1780            "nal_unit_type: %d, nuh_layer_id: %dtemporal_id: %d\n",
1781            s->nal_unit_type, nuh_layer_id, s->temporal_id);
1782
1783     return (nuh_layer_id == 0);
1784 }
1785
1786 static void restore_tqb_pixels(HEVCContext *s)
1787 {
1788     int pic_width_in_min_pu  = s->sps->width >> s->sps->log2_min_pu_size;
1789     int pic_height_in_min_pu = s->sps->height >> s->sps->log2_min_pu_size;
1790     int min_pu_size = 1 << s->sps->log2_min_pu_size;
1791     int x, y, c_idx;
1792
1793     for (c_idx = 0; c_idx < 3; c_idx++) {
1794         ptrdiff_t stride = s->frame->linesize[c_idx];
1795         int hshift = s->sps->hshift[c_idx];
1796         int vshift = s->sps->vshift[c_idx];
1797         for (y = 0; y < pic_height_in_min_pu; y++) {
1798             for (x = 0; x < pic_width_in_min_pu; x++) {
1799                 if (s->is_pcm[y*pic_width_in_min_pu+x]) {
1800                     int n;
1801                     int len = min_pu_size >> hshift;
1802                     uint8_t *src = &s->frame->data[c_idx][((y << s->sps->log2_min_pu_size) >> vshift) * stride + (((x << s->sps->log2_min_pu_size) >> hshift) << s->sps->pixel_shift)];
1803                     uint8_t *dst = &s->sao_frame->data[c_idx][((y << s->sps->log2_min_pu_size) >> vshift) * stride + (((x << s->sps->log2_min_pu_size) >> hshift) << s->sps->pixel_shift)];
1804                     for (n = 0;n < (min_pu_size >> vshift); n++) {
1805                        memcpy(dst,src,len);
1806                        src += stride;
1807                        dst += stride;
1808                     }
1809                 }
1810             }
1811         }
1812     }
1813 }
1814
1815 static int hevc_frame_start(HEVCContext *s)
1816 {
1817     HEVCLocalContext *lc     = &s->HEVClc;
1818     int pic_width_in_min_pu  = s->sps->width  >> s->sps->log2_min_pu_size;
1819     int pic_height_in_min_pu = s->sps->height >> s->sps->log2_min_pu_size;
1820     int pic_width_in_min_tu  = s->sps->width  >> s->sps->log2_min_transform_block_size;
1821     int pic_height_in_min_tu = s->sps->height >> s->sps->log2_min_transform_block_size;
1822     int ret;
1823
1824     memset(s->horizontal_bs, 0, 2 * s->bs_width * (s->bs_height + 1));
1825     memset(s->vertical_bs,   0, 2 * s->bs_width * (s->bs_height + 1));
1826     memset(s->cbf_luma,      0, pic_width_in_min_tu * pic_height_in_min_tu);
1827     memset(s->is_pcm,        0, pic_width_in_min_pu * pic_height_in_min_pu);
1828
1829     lc->start_of_tiles_x = 0;
1830     s->is_decoded        = 0;
1831
1832     if (s->pps->tiles_enabled_flag)
1833         lc->end_of_tiles_x   = s->pps->column_width[0] << s->sps->log2_ctb_size;
1834
1835     ret = ff_hevc_set_new_ref(s, s->sps->sao_enabled ? &s->sao_frame : &s->frame,
1836                               s->poc);
1837     if (ret < 0)
1838         goto fail;
1839
1840     av_fast_malloc(&lc->edge_emu_buffer, &lc->edge_emu_buffer_size,
1841                    (MAX_PB_SIZE + 7) * s->ref->frame->linesize[0]);
1842     if (!lc->edge_emu_buffer) {
1843         ret = AVERROR(ENOMEM);
1844         goto fail;
1845     }
1846
1847     ret = ff_hevc_frame_rps(s);
1848     if (ret < 0) {
1849         av_log(s->avctx, AV_LOG_ERROR, "Error constructing the frame RPS.\n");
1850         goto fail;
1851     }
1852
1853     av_frame_unref(s->output_frame);
1854     ret = ff_hevc_output_frame(s, s->output_frame, 0);
1855     if (ret < 0)
1856         goto fail;
1857
1858     ff_thread_finish_setup(s->avctx);
1859
1860     return 0;
1861 fail:
1862     if (s->ref)
1863         ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);
1864     s->ref = NULL;
1865     return ret;
1866 }
1867
1868 static int decode_nal_unit(HEVCContext *s, const uint8_t *nal, int length)
1869 {
1870     HEVCLocalContext *lc = &s->HEVClc;
1871     GetBitContext *gb = &lc->gb;
1872     int ctb_addr_ts;
1873     int ret;
1874
1875     ret = init_get_bits8(gb, nal, length);
1876     if (ret < 0)
1877         return ret;
1878
1879     ret = hls_nal_unit(s);
1880     if (ret < 0) {
1881         av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",
1882                 s->nal_unit_type);
1883         if (s->avctx->err_recognition & AV_EF_EXPLODE)
1884             return ret;
1885         return 0;
1886     } else if (!ret)
1887         return 0;
1888
1889     switch (s->nal_unit_type) {
1890     case NAL_VPS:
1891         ret = ff_hevc_decode_nal_vps(s);
1892         if (ret < 0)
1893             return ret;
1894         break;
1895     case NAL_SPS:
1896         ret = ff_hevc_decode_nal_sps(s);
1897         if (ret < 0)
1898             return ret;
1899         break;
1900     case NAL_PPS:
1901         ret = ff_hevc_decode_nal_pps(s);
1902         if (ret < 0)
1903             return ret;
1904         break;
1905     case NAL_SEI_PREFIX:
1906     case NAL_SEI_SUFFIX:
1907         ret = ff_hevc_decode_nal_sei(s);
1908         if (ret < 0)
1909             return ret;
1910         break;
1911     case NAL_TRAIL_R:
1912     case NAL_TRAIL_N:
1913     case NAL_TSA_N:
1914     case NAL_TSA_R:
1915     case NAL_STSA_N:
1916     case NAL_STSA_R:
1917     case NAL_BLA_W_LP:
1918     case NAL_BLA_W_RADL:
1919     case NAL_BLA_N_LP:
1920     case NAL_IDR_W_RADL:
1921     case NAL_IDR_N_LP:
1922     case NAL_CRA_NUT:
1923     case NAL_RADL_N:
1924     case NAL_RADL_R:
1925     case NAL_RASL_N:
1926     case NAL_RASL_R:
1927         ret = hls_slice_header(s);
1928         if (ret < 0)
1929             return ret;
1930
1931         if (s->max_ra == INT_MAX) {
1932             if (s->nal_unit_type == NAL_CRA_NUT  ||
1933                 s->nal_unit_type == NAL_BLA_W_LP ||
1934                 s->nal_unit_type == NAL_BLA_N_LP ||
1935                 s->nal_unit_type == NAL_BLA_N_LP) {
1936                 s->max_ra = s->poc;
1937             } else {
1938                 if (IS_IDR(s))
1939                     s->max_ra = INT_MIN;
1940             }
1941         }
1942
1943         if ((s->nal_unit_type == NAL_RASL_R || s->nal_unit_type == NAL_RASL_N) &&
1944             s->poc <= s->max_ra) {
1945             s->is_decoded = 0;
1946             break;
1947         } else {
1948             if (s->nal_unit_type == NAL_RASL_R && s->poc > s->max_ra)
1949                 s->max_ra = INT_MIN;
1950         }
1951
1952         if (s->sh.first_slice_in_pic_flag) {
1953             ret = hevc_frame_start(s);
1954             if (ret < 0)
1955                 return ret;
1956         } else if (!s->ref) {
1957             av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n");
1958             return AVERROR_INVALIDDATA;
1959         }
1960
1961         if (!s->sh.dependent_slice_segment_flag &&
1962             s->sh.slice_type != I_SLICE) {
1963             ret = ff_hevc_slice_rpl(s);
1964             if (ret < 0) {
1965                 av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference "
1966                        "lists for the current slice.\n");
1967                 if (s->avctx->err_recognition & AV_EF_EXPLODE)
1968                     return ret;
1969             }
1970         }
1971
1972         ctb_addr_ts = hls_slice_data(s);
1973         if (ctb_addr_ts >= (s->sps->ctb_width * s->sps->ctb_height)) {
1974             s->is_decoded = 1;
1975             if ((s->pps->transquant_bypass_enable_flag ||
1976                  (s->sps->pcm.loop_filter_disable_flag && s->sps->pcm_enabled_flag)) &&
1977                 s->sps->sao_enabled)
1978                 restore_tqb_pixels(s);
1979         }
1980
1981         if (ctb_addr_ts < 0)
1982             return ctb_addr_ts;
1983         break;
1984     case NAL_EOS_NUT:
1985     case NAL_EOB_NUT:
1986         s->seq_decode = (s->seq_decode + 1) & 0xff;
1987         s->max_ra     = INT_MAX;
1988         break;
1989     case NAL_AUD:
1990     case NAL_FD_NUT:
1991         break;
1992     default:
1993         av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type);
1994     }
1995
1996     return 0;
1997 }
1998
1999 /* FIXME: This is adapted from ff_h264_decode_nal, avoiding duplication
2000    between these functions would be nice. */
2001 static int extract_rbsp(const uint8_t *src, int length,
2002                         HEVCNAL *nal)
2003 {
2004     int i, si, di;
2005     uint8_t *dst;
2006
2007 #define STARTCODE_TEST                                                  \
2008         if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {     \
2009             if (src[i + 2] != 3) {                                      \
2010                 /* startcode, so we must be past the end */             \
2011                 length = i;                                             \
2012             }                                                           \
2013             break;                                                      \
2014         }
2015 #if HAVE_FAST_UNALIGNED
2016 #define FIND_FIRST_ZERO                                                 \
2017         if (i > 0 && !src[i])                                           \
2018             i--;                                                        \
2019         while (src[i])                                                  \
2020             i++
2021 #if HAVE_FAST_64BIT
2022     for (i = 0; i + 1 < length; i += 9) {
2023         if (!((~AV_RN64A(src + i) &
2024                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
2025               0x8000800080008080ULL))
2026             continue;
2027         FIND_FIRST_ZERO;
2028         STARTCODE_TEST;
2029         i -= 7;
2030     }
2031 #else
2032     for (i = 0; i + 1 < length; i += 5) {
2033         if (!((~AV_RN32A(src + i) &
2034                (AV_RN32A(src + i) - 0x01000101U)) &
2035               0x80008080U))
2036             continue;
2037         FIND_FIRST_ZERO;
2038         STARTCODE_TEST;
2039         i -= 3;
2040     }
2041 #endif
2042 #else
2043     for (i = 0; i + 1 < length; i += 2) {
2044         if (src[i])
2045             continue;
2046         if (i > 0 && src[i - 1] == 0)
2047             i--;
2048         STARTCODE_TEST;
2049     }
2050 #endif
2051
2052     if (i >= length - 1) { // no escaped 0
2053         nal->data = src;
2054         nal->size = length;
2055         return length;
2056     }
2057
2058     av_fast_malloc(&nal->rbsp_buffer, &nal->rbsp_buffer_size,
2059                    length + FF_INPUT_BUFFER_PADDING_SIZE);
2060     if (!nal->rbsp_buffer)
2061         return AVERROR(ENOMEM);
2062
2063     dst = nal->rbsp_buffer;
2064
2065     memcpy(dst, src, i);
2066     si = di = i;
2067     while (si + 2 < length) {
2068         // remove escapes (very rare 1:2^22)
2069         if (src[si + 2] > 3) {
2070             dst[di++] = src[si++];
2071             dst[di++] = src[si++];
2072         } else if (src[si] == 0 && src[si + 1] == 0) {
2073             if (src[si + 2] == 3) { // escape
2074                 dst[di++]  = 0;
2075                 dst[di++]  = 0;
2076                 si        += 3;
2077
2078                 continue;
2079             } else // next start code
2080                 goto nsc;
2081         }
2082
2083         dst[di++] = src[si++];
2084     }
2085     while (si < length)
2086         dst[di++] = src[si++];
2087 nsc:
2088
2089     memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2090
2091     nal->data = dst;
2092     nal->size = di;
2093     return si;
2094 }
2095
2096 static int decode_nal_units(HEVCContext *s, const uint8_t *buf, int length)
2097 {
2098     int i, consumed, ret = 0;
2099
2100     s->ref = NULL;
2101     s->eos = 0;
2102
2103     /* split the input packet into NAL units, so we know the upper bound on the
2104      * number of slices in the frame */
2105     s->nb_nals = 0;
2106     while (length >= 4) {
2107         HEVCNAL *nal;
2108         int extract_length = 0;
2109
2110         if (s->disable_au == 0) {
2111             if (s->is_nalff) {
2112                 int i;
2113                 for (i = 0; i < s->nal_length_size; i++)
2114                     extract_length = (extract_length << 8) | buf[i];
2115                 buf    += s->nal_length_size;
2116                 length -= s->nal_length_size;
2117
2118                 if (extract_length > length) {
2119                     av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit size.\n");
2120                     ret = AVERROR_INVALIDDATA;
2121                     goto fail;
2122                 }
2123             } else {
2124                 if (buf[2] == 0) {
2125                     length--;
2126                     buf++;
2127                     continue;
2128                 }
2129                 if (buf[0] != 0 || buf[1] != 0 || buf[2] != 1) {
2130                     ret = AVERROR_INVALIDDATA;
2131                     goto fail;
2132                 }
2133
2134                 buf    += 3;
2135                 length -= 3;
2136             }
2137         }
2138         if (!s->is_nalff || s->disable_au)
2139             extract_length = length;
2140
2141         if (s->nals_allocated < s->nb_nals + 1) {
2142             int new_size = s->nals_allocated + 1;
2143             HEVCNAL *tmp = av_realloc_array(s->nals, new_size, sizeof(*tmp));
2144             if (!tmp) {
2145                 ret = AVERROR(ENOMEM);
2146                 goto fail;
2147             }
2148             s->nals = tmp;
2149             memset(s->nals + s->nals_allocated, 0, (new_size - s->nals_allocated) * sizeof(*tmp));
2150             s->nals_allocated = new_size;
2151         }
2152         nal = &s->nals[s->nb_nals++];
2153
2154         consumed = extract_rbsp(buf, extract_length, nal);
2155         if (consumed < 0) {
2156             ret = consumed;
2157             goto fail;
2158         }
2159
2160         ret = init_get_bits8(&s->HEVClc.gb, nal->data, nal->size);
2161         if (ret < 0)
2162             goto fail;
2163         hls_nal_unit(s);
2164
2165         if (s->nal_unit_type == NAL_EOS_NUT || s->nal_unit_type == NAL_EOB_NUT)
2166             s->eos = 1;
2167
2168         buf    += consumed;
2169         length -= consumed;
2170     }
2171
2172     /* parse the NAL units */
2173     for (i = 0; i < s->nb_nals; i++) {
2174         int ret = decode_nal_unit(s, s->nals[i].data, s->nals[i].size);
2175         if (ret < 0) {
2176             av_log(s->avctx, AV_LOG_WARNING, "Error parsing NAL unit #%d.\n", i);
2177             if (s->avctx->err_recognition & AV_EF_EXPLODE)
2178                 goto fail;
2179         }
2180     }
2181
2182 fail:
2183     if (s->ref)
2184         ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);
2185
2186     return ret;
2187 }
2188
2189 static void print_md5(void *log_ctx, int level,  uint8_t md5[16])
2190 {
2191     int i;
2192     for (i = 0; i < 16; i++)
2193         av_log(log_ctx, level, "%02"PRIx8, md5[i]);
2194 }
2195
2196 static int verify_md5(HEVCContext *s, AVFrame *frame)
2197 {
2198     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
2199     int pixel_shift = desc->comp[0].depth_minus1 > 7;
2200     int i, j;
2201
2202     if (!desc)
2203         return AVERROR(EINVAL);
2204
2205     av_log(s->avctx, AV_LOG_DEBUG, "Verifying checksum for frame with POC %d: ",
2206            s->poc);
2207
2208     /* the checksums are LE, so we have to byteswap for >8bpp formats
2209      * on BE arches */
2210 #if HAVE_BIGENDIAN
2211     if (pixel_shift && !s->checksum_buf) {
2212         av_fast_malloc(&s->checksum_buf, &s->checksum_buf_size,
2213                        FFMAX3(frame->linesize[0], frame->linesize[1],
2214                               frame->linesize[2]));
2215         if (!s->checksum_buf)
2216             return AVERROR(ENOMEM);
2217     }
2218 #endif
2219
2220     for (i = 0; frame->data[i]; i++) {
2221         int width  = s->avctx->coded_width;
2222         int height = s->avctx->coded_height;
2223         int w = (i == 1 || i == 2) ? (width  >> desc->log2_chroma_w) : width;
2224         int h = (i == 1 || i == 2) ? (height >> desc->log2_chroma_h) : height;
2225         uint8_t md5[16];
2226
2227         av_md5_init(s->md5_ctx);
2228         for (j = 0; j < h; j++) {
2229             const uint8_t *src = frame->data[i] + j * frame->linesize[i];
2230 #if HAVE_BIGENDIAN
2231             if (pixel_shift) {
2232                 s->dsp.bswap16_buf((uint16_t*)s->checksum_buf,
2233                                    (const uint16_t*)src, w);
2234                 src = s->checksum_buf;
2235             }
2236 #endif
2237             av_md5_update(s->md5_ctx, src, w << pixel_shift);
2238         }
2239         av_md5_final(s->md5_ctx, md5);
2240
2241         if (!memcmp(md5, s->md5[i], 16)) {
2242             av_log   (s->avctx, AV_LOG_DEBUG, "plane %d - correct ", i);
2243             print_md5(s->avctx, AV_LOG_DEBUG, md5);
2244             av_log   (s->avctx, AV_LOG_DEBUG, "; ");
2245         } else {
2246             av_log   (s->avctx, AV_LOG_ERROR, "mismatching checksum of plane %d - ", i);
2247             print_md5(s->avctx, AV_LOG_ERROR, md5);
2248             av_log   (s->avctx, AV_LOG_ERROR, " != ");
2249             print_md5(s->avctx, AV_LOG_ERROR, s->md5[i]);
2250             av_log   (s->avctx, AV_LOG_ERROR, "\n");
2251             return AVERROR_INVALIDDATA;
2252         }
2253     }
2254
2255     av_log(s->avctx, AV_LOG_DEBUG, "\n");
2256
2257     return 0;
2258 }
2259
2260 static int hevc_decode_frame(AVCodecContext *avctx, void *data, int *got_output,
2261                              AVPacket *avpkt)
2262 {
2263     int ret;
2264     HEVCContext *s = avctx->priv_data;
2265
2266     //av_log(avctx, AV_LOG_WARNING, "decode size %d\n", avpkt->size);
2267
2268     if (!avpkt->size) {
2269         ret = ff_hevc_output_frame(s, data, 1);
2270         if (ret < 0)
2271             return ret;
2272
2273         *got_output = ret;
2274         return 0;
2275     }
2276
2277     s->ref = NULL;
2278     ret = decode_nal_units(s, avpkt->data, avpkt->size);
2279     if (ret < 0)
2280         return ret;
2281
2282     /* verify the SEI checksum */
2283     if (avctx->err_recognition & AV_EF_CRCCHECK && s->is_decoded &&
2284         s->is_md5) {
2285         ret = verify_md5(s, s->ref->frame);
2286         if (ret < 0 && avctx->err_recognition & AV_EF_EXPLODE) {
2287             ff_hevc_unref_frame(s, s->ref, ~0);
2288             return ret;
2289         }
2290     }
2291     s->is_md5 = 0;
2292
2293     if (s->is_decoded) {
2294         av_log(avctx, AV_LOG_DEBUG, "Decoded frame with POC %d.\n", s->poc);
2295         s->is_decoded = 0;
2296     }
2297
2298     if (s->output_frame->buf[0]) {
2299         av_frame_move_ref(data, s->output_frame);
2300         *got_output = 1;
2301     }
2302
2303     return avpkt->size;
2304 }
2305
2306 static int hevc_ref_frame(HEVCContext *s, HEVCFrame *dst, HEVCFrame *src)
2307 {
2308     int ret;
2309
2310     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
2311     if (ret < 0)
2312         return ret;
2313
2314     dst->tab_mvf_buf = av_buffer_ref(src->tab_mvf_buf);
2315     if (!dst->tab_mvf_buf)
2316         goto fail;
2317     dst->tab_mvf = src->tab_mvf;
2318
2319     dst->rpl_tab_buf = av_buffer_ref(src->rpl_tab_buf);
2320     if (!dst->rpl_tab_buf)
2321         goto fail;
2322     dst->rpl_tab = src->rpl_tab;
2323
2324     dst->rpl_buf = av_buffer_ref(src->rpl_buf);
2325     if (!dst->rpl_buf)
2326         goto fail;
2327
2328     dst->poc        = src->poc;
2329     dst->ctb_count  = src->ctb_count;
2330     dst->window     = src->window;
2331     dst->flags      = src->flags;
2332     dst->sequence   = src->sequence;
2333
2334     return 0;
2335 fail:
2336     ff_hevc_unref_frame(s, dst, ~0);
2337     return AVERROR(ENOMEM);
2338 }
2339
2340 static av_cold int hevc_decode_free(AVCodecContext *avctx)
2341 {
2342     HEVCContext       *s = avctx->priv_data;
2343     HEVCLocalContext *lc = &s->HEVClc;
2344     int i;
2345
2346     pic_arrays_free(s);
2347
2348     av_freep(&lc->edge_emu_buffer);
2349     av_freep(&s->md5_ctx);
2350
2351     av_frame_free(&s->tmp_frame);
2352     av_frame_free(&s->output_frame);
2353
2354     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
2355         ff_hevc_unref_frame(s, &s->DPB[i], ~0);
2356         av_frame_free(&s->DPB[i].frame);
2357     }
2358
2359     for (i = 0; i < FF_ARRAY_ELEMS(s->vps_list); i++)
2360         av_freep(&s->vps_list[i]);
2361     for (i = 0; i < FF_ARRAY_ELEMS(s->sps_list); i++)
2362         av_buffer_unref(&s->sps_list[i]);
2363     for (i = 0; i < FF_ARRAY_ELEMS(s->pps_list); i++)
2364         av_buffer_unref(&s->pps_list[i]);
2365
2366     for (i = 0; i < s->nals_allocated; i++)
2367         av_freep(&s->nals[i].rbsp_buffer);
2368     av_freep(&s->nals);
2369     s->nals_allocated = 0;
2370
2371     return 0;
2372 }
2373
2374 static av_cold int hevc_init_context(AVCodecContext *avctx)
2375 {
2376     HEVCContext *s = avctx->priv_data;
2377     int i;
2378
2379     s->avctx = avctx;
2380
2381     s->tmp_frame = av_frame_alloc();
2382     if (!s->tmp_frame)
2383         goto fail;
2384
2385     s->output_frame = av_frame_alloc();
2386     if (!s->output_frame)
2387         goto fail;
2388
2389     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
2390         s->DPB[i].frame = av_frame_alloc();
2391         if (!s->DPB[i].frame)
2392             goto fail;
2393         s->DPB[i].tf.f = s->DPB[i].frame;
2394     }
2395
2396     s->max_ra = INT_MAX;
2397
2398     s->md5_ctx = av_md5_alloc();
2399     if (!s->md5_ctx)
2400         goto fail;
2401
2402     ff_dsputil_init(&s->dsp, avctx);
2403
2404     s->context_initialized = 1;
2405
2406     return 0;
2407 fail:
2408     hevc_decode_free(avctx);
2409     return AVERROR(ENOMEM);
2410 }
2411
2412 static int hevc_update_thread_context(AVCodecContext *dst,
2413                                       const AVCodecContext *src)
2414 {
2415     HEVCContext *s  = dst->priv_data;
2416     HEVCContext *s0 = src->priv_data;
2417     int i, ret;
2418
2419     if (!s->context_initialized) {
2420         ret = hevc_init_context(dst);
2421         if (ret < 0)
2422             return ret;
2423     }
2424
2425     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
2426         ff_hevc_unref_frame(s, &s->DPB[i], ~0);
2427         if (s0->DPB[i].frame->buf[0]) {
2428             ret = hevc_ref_frame(s, &s->DPB[i], &s0->DPB[i]);
2429             if (ret < 0)
2430                 return ret;
2431         }
2432     }
2433
2434     for (i = 0; i < FF_ARRAY_ELEMS(s->sps_list); i++) {
2435         av_buffer_unref(&s->sps_list[i]);
2436         if (s0->sps_list[i]) {
2437             s->sps_list[i] = av_buffer_ref(s0->sps_list[i]);
2438             if (!s->sps_list[i])
2439                 return AVERROR(ENOMEM);
2440         }
2441     }
2442
2443     for (i = 0; i < FF_ARRAY_ELEMS(s->pps_list); i++) {
2444         av_buffer_unref(&s->pps_list[i]);
2445         if (s0->pps_list[i]) {
2446             s->pps_list[i] = av_buffer_ref(s0->pps_list[i]);
2447             if (!s->pps_list[i])
2448                 return AVERROR(ENOMEM);
2449         }
2450     }
2451
2452     s->seq_decode = s0->seq_decode;
2453     s->seq_output = s0->seq_output;
2454     s->pocTid0    = s0->pocTid0;
2455     s->max_ra     = s0->max_ra;
2456
2457     s->is_nalff        = s0->is_nalff;
2458     s->nal_length_size = s0->nal_length_size;
2459
2460
2461     if (s0->eos) {
2462         s->seq_decode = (s->seq_decode + 1) & 0xff;
2463         s->max_ra = INT_MAX;
2464     }
2465
2466     return 0;
2467 }
2468
2469 static int hevc_decode_extradata(HEVCContext *s)
2470 {
2471     AVCodecContext *avctx = s->avctx;
2472     GetByteContext gb;
2473     int ret;
2474
2475     bytestream2_init(&gb, avctx->extradata, avctx->extradata_size);
2476
2477     if (avctx->extradata_size > 3 &&
2478         (avctx->extradata[0] || avctx->extradata[1] ||
2479          avctx->extradata[2] > 1)) {
2480         /* It seems the extradata is encoded as hvcC format.
2481          * Temporarily, we support configurationVersion==0 until 14496-15 3rd finalized.
2482          * When finalized, configurationVersion will be 1 and we can recognize hvcC by
2483          * checking if avctx->extradata[0]==1 or not. */
2484         int i, j, num_arrays;
2485         int nal_len_size;
2486
2487         s->is_nalff = 1;
2488
2489         bytestream2_skip(&gb, 21);
2490         nal_len_size = (bytestream2_get_byte(&gb) & 3) + 1;
2491         num_arrays   = bytestream2_get_byte(&gb);
2492
2493         /* nal units in the hvcC always have length coded with 2 bytes,
2494          * so put a fake nal_length_size = 2 while parsing them */
2495         s->nal_length_size = 2;
2496
2497         /* Decode nal units from hvcC. */
2498         for (i = 0; i < num_arrays; i++) {
2499             int type = bytestream2_get_byte(&gb) & 0x3f;
2500             int cnt  = bytestream2_get_be16(&gb);
2501
2502             for (j = 0; j < cnt; j++) {
2503                 // +2 for the nal size field
2504                 int nalsize = bytestream2_peek_be16(&gb) + 2;
2505                 if (bytestream2_get_bytes_left(&gb) < nalsize) {
2506                     av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit size in extradata.\n");
2507                     return AVERROR_INVALIDDATA;
2508                 }
2509
2510                 ret = decode_nal_units(s, gb.buffer, nalsize);
2511                 if (ret < 0) {
2512                     av_log(avctx, AV_LOG_ERROR,
2513                            "Decoding nal unit %d %d from hvcC failed\n", type, i);
2514                     return ret;
2515                 }
2516                 bytestream2_skip(&gb, nalsize);
2517             }
2518         }
2519
2520         /* Now store right nal length size, that will be used to parse all other nals */
2521         s->nal_length_size = nal_len_size;
2522     } else {
2523         s->is_nalff = 0;
2524         ret = decode_nal_units(s, avctx->extradata, avctx->extradata_size);
2525         if (ret < 0)
2526             return ret;
2527     }
2528     return 0;
2529 }
2530
2531 static av_cold int hevc_decode_init(AVCodecContext *avctx)
2532 {
2533     HEVCContext *s = avctx->priv_data;
2534     int ret;
2535
2536     ff_init_cabac_states();
2537
2538     avctx->internal->allocate_progress = 1;
2539
2540     ret = hevc_init_context(avctx);
2541     if (ret < 0)
2542         return ret;
2543
2544     if (avctx->extradata_size > 0 && avctx->extradata) {
2545         ret = hevc_decode_extradata(s);
2546         if (ret < 0) {
2547             hevc_decode_free(avctx);
2548             return ret;
2549         }
2550     }
2551
2552     return 0;
2553 }
2554
2555 static av_cold int hevc_init_thread_copy(AVCodecContext *avctx)
2556 {
2557     HEVCContext *s = avctx->priv_data;
2558     int ret;
2559
2560     memset(s, 0, sizeof(*s));
2561
2562     ret = hevc_init_context(avctx);
2563     if (ret < 0)
2564         return ret;
2565
2566     return 0;
2567 }
2568
2569 static void hevc_decode_flush(AVCodecContext *avctx)
2570 {
2571     HEVCContext *s = avctx->priv_data;
2572     ff_hevc_flush_dpb(s);
2573     s->max_ra = INT_MAX;
2574 }
2575
2576 #define OFFSET(x) offsetof(HEVCContext, x)
2577 #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
2578 static const AVOption options[] = {
2579     { "disable-au", "disable read frame AU by AU", OFFSET(disable_au),
2580         AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, PAR },
2581     { "strict-displaywin", "stricly apply default display window size", OFFSET(strict_def_disp_win),
2582         AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, PAR },
2583     { NULL },
2584 };
2585
2586 static const AVClass hevc_decoder_class = {
2587     .class_name = "HEVC decoder",
2588     .item_name  = av_default_item_name,
2589     .option     = options,
2590     .version    = LIBAVUTIL_VERSION_INT,
2591 };
2592
2593 AVCodec ff_hevc_decoder = {
2594     .name                  = "hevc",
2595     .long_name             = NULL_IF_CONFIG_SMALL("HEVC (High Efficiency Video Coding)"),
2596     .type                  = AVMEDIA_TYPE_VIDEO,
2597     .id                    = AV_CODEC_ID_HEVC,
2598     .priv_data_size        = sizeof(HEVCContext),
2599     .priv_class            = &hevc_decoder_class,
2600     .init                  = hevc_decode_init,
2601     .close                 = hevc_decode_free,
2602     .decode                = hevc_decode_frame,
2603     .flush                 = hevc_decode_flush,
2604     .update_thread_context = hevc_update_thread_context,
2605     .init_thread_copy      = hevc_init_thread_copy,
2606     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_FRAME_THREADS | CODEC_CAP_EXPERIMENTAL,
2607 };