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