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