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