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