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