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