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