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