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