Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  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->min_pu_width;
  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,
  822.                                int xBase, int yBase, int cb_xBase, int cb_yBase,
  823.                                int log2_cb_size, int log2_trafo_size,
  824.                                int trafo_depth, int blk_idx)
  825. {
  826.     HEVCLocalContext *lc = s->HEVClc;
  827.     uint8_t split_transform_flag;
  828.  
  829.     if (trafo_depth > 0 && log2_trafo_size == 2) {
  830.         SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =
  831.             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth - 1], xBase, yBase);
  832.         SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) =
  833.             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth - 1], xBase, yBase);
  834.     } else {
  835.         SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =
  836.         SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) = 0;
  837.     }
  838.  
  839.     if (lc->cu.intra_split_flag) {
  840.         if (trafo_depth == 1)
  841.             lc->tu.cur_intra_pred_mode = lc->pu.intra_pred_mode[blk_idx];
  842.     } else {
  843.         lc->tu.cur_intra_pred_mode = lc->pu.intra_pred_mode[0];
  844.     }
  845.  
  846.     lc->tt.cbf_luma = 1;
  847.  
  848.     lc->tt.inter_split_flag = (s->sps->max_transform_hierarchy_depth_inter == 0 &&
  849.                                lc->cu.pred_mode == MODE_INTER &&
  850.                                lc->cu.part_mode != PART_2Nx2N && trafo_depth == 0);
  851.  
  852.     if (log2_trafo_size <= s->sps->log2_max_trafo_size &&
  853.         log2_trafo_size > s->sps->log2_min_tb_size &&
  854.         trafo_depth < lc->cu.max_trafo_depth &&
  855.         !(lc->cu.intra_split_flag && trafo_depth == 0)) {
  856.         split_transform_flag = ff_hevc_split_transform_flag_decode(s, log2_trafo_size);
  857.     } else {
  858.         split_transform_flag = (log2_trafo_size > s->sps->log2_max_trafo_size ||
  859.                                 (lc->cu.intra_split_flag && (trafo_depth == 0)) ||
  860.                                 lc->tt.inter_split_flag);
  861.     }
  862.  
  863.     if (log2_trafo_size > 2) {
  864.         if (trafo_depth == 0 ||
  865.             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth - 1], xBase, yBase)) {
  866.             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =
  867.                 ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
  868.         }
  869.  
  870.         if (trafo_depth == 0 || SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth - 1], xBase, yBase)) {
  871.             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) =
  872.                 ff_hevc_cbf_cb_cr_decode(s, trafo_depth);
  873.         }
  874.     }
  875.  
  876.     if (split_transform_flag) {
  877.         int x1 = x0 + ((1 << log2_trafo_size) >> 1);
  878.         int y1 = y0 + ((1 << log2_trafo_size) >> 1);
  879.  
  880.         hls_transform_tree(s, x0, y0, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
  881.                            log2_trafo_size - 1, trafo_depth + 1, 0);
  882.         hls_transform_tree(s, x1, y0, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
  883.                            log2_trafo_size - 1, trafo_depth + 1, 1);
  884.         hls_transform_tree(s, x0, y1, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
  885.                            log2_trafo_size - 1, trafo_depth + 1, 2);
  886.         hls_transform_tree(s, x1, y1, x0, y0, cb_xBase, cb_yBase, log2_cb_size,
  887.                            log2_trafo_size - 1, trafo_depth + 1, 3);
  888.     } else {
  889.         int min_tu_size      = 1 << s->sps->log2_min_tb_size;
  890.         int log2_min_tu_size = s->sps->log2_min_tb_size;
  891.         int min_tu_width     = s->sps->min_tb_width;
  892.  
  893.         if (lc->cu.pred_mode == MODE_INTRA || trafo_depth != 0 ||
  894.             SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) ||
  895.             SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0)) {
  896.             lc->tt.cbf_luma = ff_hevc_cbf_luma_decode(s, trafo_depth);
  897.         }
  898.  
  899.         hls_transform_unit(s, x0, y0, xBase, yBase, cb_xBase, cb_yBase,
  900.                            log2_cb_size, log2_trafo_size, trafo_depth, blk_idx);
  901.  
  902.         // TODO: store cbf_luma somewhere else
  903.         if (lc->tt.cbf_luma) {
  904.             int i, j;
  905.             for (i = 0; i < (1 << log2_trafo_size); i += min_tu_size)
  906.                 for (j = 0; j < (1 << log2_trafo_size); j += min_tu_size) {
  907.                     int x_tu = (x0 + j) >> log2_min_tu_size;
  908.                     int y_tu = (y0 + i) >> log2_min_tu_size;
  909.                     s->cbf_luma[y_tu * min_tu_width + x_tu] = 1;
  910.                 }
  911.         }
  912.         if (!s->sh.disable_deblocking_filter_flag) {
  913.             ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_trafo_size,
  914.                                                   lc->slice_or_tiles_up_boundary,
  915.                                                   lc->slice_or_tiles_left_boundary);
  916.             if (s->pps->transquant_bypass_enable_flag && lc->cu.cu_transquant_bypass_flag)
  917.                 set_deblocking_bypass(s, x0, y0, log2_trafo_size);
  918.         }
  919.     }
  920. }
  921.  
  922. static int hls_pcm_sample(HEVCContext *s, int x0, int y0, int log2_cb_size)
  923. {
  924.     //TODO: non-4:2:0 support
  925.     HEVCLocalContext *lc = s->HEVClc;
  926.     GetBitContext gb;
  927.     int cb_size   = 1 << log2_cb_size;
  928.     int stride0   = s->frame->linesize[0];
  929.     uint8_t *dst0 = &s->frame->data[0][y0 * stride0 + (x0 << s->sps->pixel_shift)];
  930.     int   stride1 = s->frame->linesize[1];
  931.     uint8_t *dst1 = &s->frame->data[1][(y0 >> s->sps->vshift[1]) * stride1 + ((x0 >> s->sps->hshift[1]) << s->sps->pixel_shift)];
  932.     int   stride2 = s->frame->linesize[2];
  933.     uint8_t *dst2 = &s->frame->data[2][(y0 >> s->sps->vshift[2]) * stride2 + ((x0 >> s->sps->hshift[2]) << s->sps->pixel_shift)];
  934.  
  935.     int length         = cb_size * cb_size * s->sps->pcm.bit_depth + ((cb_size * cb_size) >> 1) * s->sps->pcm.bit_depth;
  936.     const uint8_t *pcm = skip_bytes(&s->HEVClc->cc, (length + 7) >> 3);
  937.     int ret;
  938.  
  939.     ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size,
  940.                                           lc->slice_or_tiles_up_boundary,
  941.                                           lc->slice_or_tiles_left_boundary);
  942.  
  943.     ret = init_get_bits(&gb, pcm, length);
  944.     if (ret < 0)
  945.         return ret;
  946.  
  947.     s->hevcdsp.put_pcm(dst0, stride0, cb_size, &gb, s->sps->pcm.bit_depth);
  948.     s->hevcdsp.put_pcm(dst1, stride1, cb_size / 2, &gb, s->sps->pcm.bit_depth_chroma);
  949.     s->hevcdsp.put_pcm(dst2, stride2, cb_size / 2, &gb, s->sps->pcm.bit_depth_chroma);
  950.     return 0;
  951. }
  952.  
  953. /**
  954.  * 8.5.3.2.2.1 Luma sample interpolation process
  955.  *
  956.  * @param s HEVC decoding context
  957.  * @param dst target buffer for block data at block position
  958.  * @param dststride stride of the dst buffer
  959.  * @param ref reference picture buffer at origin (0, 0)
  960.  * @param mv motion vector (relative to block position) to get pixel data from
  961.  * @param x_off horizontal position of block from origin (0, 0)
  962.  * @param y_off vertical position of block from origin (0, 0)
  963.  * @param block_w width of block
  964.  * @param block_h height of block
  965.  */
  966. static void luma_mc(HEVCContext *s, int16_t *dst, ptrdiff_t dststride,
  967.                     AVFrame *ref, const Mv *mv, int x_off, int y_off,
  968.                     int block_w, int block_h)
  969. {
  970.     HEVCLocalContext *lc = s->HEVClc;
  971.     uint8_t *src         = ref->data[0];
  972.     ptrdiff_t srcstride  = ref->linesize[0];
  973.     int pic_width        = s->sps->width;
  974.     int pic_height       = s->sps->height;
  975.  
  976.     int mx         = mv->x & 3;
  977.     int my         = mv->y & 3;
  978.     int extra_left = ff_hevc_qpel_extra_before[mx];
  979.     int extra_top  = ff_hevc_qpel_extra_before[my];
  980.  
  981.     x_off += mv->x >> 2;
  982.     y_off += mv->y >> 2;
  983.     src   += y_off * srcstride + (x_off << s->sps->pixel_shift);
  984.  
  985.     if (x_off < extra_left || y_off < extra_top ||
  986.         x_off >= pic_width - block_w - ff_hevc_qpel_extra_after[mx] ||
  987.         y_off >= pic_height - block_h - ff_hevc_qpel_extra_after[my]) {
  988.         int offset = extra_top * srcstride + (extra_left << s->sps->pixel_shift);
  989.  
  990.         s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, srcstride, src - offset, srcstride,
  991.                                  block_w + ff_hevc_qpel_extra[mx], block_h + ff_hevc_qpel_extra[my],
  992.                                  x_off - extra_left, y_off - extra_top,
  993.                                  pic_width, pic_height);
  994.         src = lc->edge_emu_buffer + offset;
  995.     }
  996.     s->hevcdsp.put_hevc_qpel[my][mx](dst, dststride, src, srcstride, block_w,
  997.                                      block_h, lc->mc_buffer);
  998. }
  999.  
  1000. /**
  1001.  * 8.5.3.2.2.2 Chroma sample interpolation process
  1002.  *
  1003.  * @param s HEVC decoding context
  1004.  * @param dst1 target buffer for block data at block position (U plane)
  1005.  * @param dst2 target buffer for block data at block position (V plane)
  1006.  * @param dststride stride of the dst1 and dst2 buffers
  1007.  * @param ref reference picture buffer at origin (0, 0)
  1008.  * @param mv motion vector (relative to block position) to get pixel data from
  1009.  * @param x_off horizontal position of block from origin (0, 0)
  1010.  * @param y_off vertical position of block from origin (0, 0)
  1011.  * @param block_w width of block
  1012.  * @param block_h height of block
  1013.  */
  1014. static void chroma_mc(HEVCContext *s, int16_t *dst1, int16_t *dst2, ptrdiff_t dststride, AVFrame *ref,
  1015.                       const Mv *mv, int x_off, int y_off, int block_w, int block_h)
  1016. {
  1017.     HEVCLocalContext *lc = s->HEVClc;
  1018.     uint8_t *src1        = ref->data[1];
  1019.     uint8_t *src2        = ref->data[2];
  1020.     ptrdiff_t src1stride = ref->linesize[1];
  1021.     ptrdiff_t src2stride = ref->linesize[2];
  1022.     int pic_width        = s->sps->width >> 1;
  1023.     int pic_height       = s->sps->height >> 1;
  1024.  
  1025.     int mx = mv->x & 7;
  1026.     int my = mv->y & 7;
  1027.  
  1028.     x_off += mv->x >> 3;
  1029.     y_off += mv->y >> 3;
  1030.     src1  += y_off * src1stride + (x_off << s->sps->pixel_shift);
  1031.     src2  += y_off * src2stride + (x_off << s->sps->pixel_shift);
  1032.  
  1033.     if (x_off < EPEL_EXTRA_BEFORE || y_off < EPEL_EXTRA_AFTER ||
  1034.         x_off >= pic_width - block_w - EPEL_EXTRA_AFTER ||
  1035.         y_off >= pic_height - block_h - EPEL_EXTRA_AFTER) {
  1036.         int offset1 = EPEL_EXTRA_BEFORE * (src1stride + (1 << s->sps->pixel_shift));
  1037.         int offset2 = EPEL_EXTRA_BEFORE * (src2stride + (1 << s->sps->pixel_shift));
  1038.  
  1039.         s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src1stride, src1 - offset1, src1stride,
  1040.                                  block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
  1041.                                  x_off - EPEL_EXTRA_BEFORE,
  1042.                                  y_off - EPEL_EXTRA_BEFORE,
  1043.                                  pic_width, pic_height);
  1044.  
  1045.         src1 = lc->edge_emu_buffer + offset1;
  1046.         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst1, dststride, src1, src1stride,
  1047.                                              block_w, block_h, mx, my, lc->mc_buffer);
  1048.  
  1049.         s->vdsp.emulated_edge_mc(lc->edge_emu_buffer, src2stride, src2 - offset2, src2stride,
  1050.                                  block_w + EPEL_EXTRA, block_h + EPEL_EXTRA,
  1051.                                  x_off - EPEL_EXTRA_BEFORE,
  1052.                                  y_off - EPEL_EXTRA_BEFORE,
  1053.                                  pic_width, pic_height);
  1054.         src2 = lc->edge_emu_buffer + offset2;
  1055.         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst2, dststride, src2, src2stride,
  1056.                                              block_w, block_h, mx, my,
  1057.                                              lc->mc_buffer);
  1058.     } else {
  1059.         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst1, dststride, src1, src1stride,
  1060.                                              block_w, block_h, mx, my,
  1061.                                              lc->mc_buffer);
  1062.         s->hevcdsp.put_hevc_epel[!!my][!!mx](dst2, dststride, src2, src2stride,
  1063.                                              block_w, block_h, mx, my,
  1064.                                              lc->mc_buffer);
  1065.     }
  1066. }
  1067.  
  1068. static void hevc_await_progress(HEVCContext *s, HEVCFrame *ref,
  1069.                                 const Mv *mv, int y0, int height)
  1070. {
  1071.     int y = (mv->y >> 2) + y0 + height + 9;
  1072.  
  1073.     if (s->threads_type == FF_THREAD_FRAME )
  1074.         ff_thread_await_progress(&ref->tf, y, 0);
  1075. }
  1076.  
  1077. static void hls_prediction_unit(HEVCContext *s, int x0, int y0,
  1078.                                 int nPbW, int nPbH,
  1079.                                 int log2_cb_size, int partIdx)
  1080. {
  1081. #define POS(c_idx, x, y)                                                              \
  1082.     &s->frame->data[c_idx][((y) >> s->sps->vshift[c_idx]) * s->frame->linesize[c_idx] + \
  1083.                            (((x) >> s->sps->hshift[c_idx]) << s->sps->pixel_shift)]
  1084.     HEVCLocalContext *lc = s->HEVClc;
  1085.     int merge_idx = 0;
  1086.     struct MvField current_mv = {{{ 0 }}};
  1087.  
  1088.     int min_pu_width = s->sps->min_pu_width;
  1089.  
  1090.     MvField *tab_mvf = s->ref->tab_mvf;
  1091.     RefPicList  *refPicList = s->ref->refPicList;
  1092.     HEVCFrame *ref0, *ref1;
  1093.  
  1094.     int tmpstride = MAX_PB_SIZE;
  1095.  
  1096.     uint8_t *dst0 = POS(0, x0, y0);
  1097.     uint8_t *dst1 = POS(1, x0, y0);
  1098.     uint8_t *dst2 = POS(2, x0, y0);
  1099.     int log2_min_cb_size = s->sps->log2_min_cb_size;
  1100.     int min_cb_width     = s->sps->min_cb_width;
  1101.     int x_cb             = x0 >> log2_min_cb_size;
  1102.     int y_cb             = y0 >> log2_min_cb_size;
  1103.     int ref_idx[2];
  1104.     int mvp_flag[2];
  1105.     int x_pu, y_pu;
  1106.     int i, j;
  1107.  
  1108.     if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) {
  1109.         if (s->sh.max_num_merge_cand > 1)
  1110.             merge_idx = ff_hevc_merge_idx_decode(s);
  1111.         else
  1112.             merge_idx = 0;
  1113.  
  1114.         ff_hevc_luma_mv_merge_mode(s, x0, y0, 1 << log2_cb_size, 1 << log2_cb_size,
  1115.                                    log2_cb_size, partIdx, merge_idx, &current_mv);
  1116.         x_pu = x0 >> s->sps->log2_min_pu_size;
  1117.         y_pu = y0 >> s->sps->log2_min_pu_size;
  1118.  
  1119.         for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)
  1120.             for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)
  1121.                 tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv;
  1122.     } else { /* MODE_INTER */
  1123.         lc->pu.merge_flag = ff_hevc_merge_flag_decode(s);
  1124.         if (lc->pu.merge_flag) {
  1125.             if (s->sh.max_num_merge_cand > 1)
  1126.                 merge_idx = ff_hevc_merge_idx_decode(s);
  1127.             else
  1128.                 merge_idx = 0;
  1129.  
  1130.             ff_hevc_luma_mv_merge_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
  1131.                                        partIdx, merge_idx, &current_mv);
  1132.             x_pu = x0 >> s->sps->log2_min_pu_size;
  1133.             y_pu = y0 >> s->sps->log2_min_pu_size;
  1134.  
  1135.             for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)
  1136.                 for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)
  1137.                     tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv;
  1138.         } else {
  1139.             enum InterPredIdc inter_pred_idc = PRED_L0;
  1140.             ff_hevc_set_neighbour_available(s, x0, y0, nPbW, nPbH);
  1141.             if (s->sh.slice_type == B_SLICE)
  1142.                 inter_pred_idc = ff_hevc_inter_pred_idc_decode(s, nPbW, nPbH);
  1143.  
  1144.             if (inter_pred_idc != PRED_L1) {
  1145.                 if (s->sh.nb_refs[L0]) {
  1146.                     ref_idx[0] = ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L0]);
  1147.                     current_mv.ref_idx[0] = ref_idx[0];
  1148.                 }
  1149.                 current_mv.pred_flag[0] = 1;
  1150.                 ff_hevc_hls_mvd_coding(s, x0, y0, 0);
  1151.                 mvp_flag[0] = ff_hevc_mvp_lx_flag_decode(s);
  1152.                 ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
  1153.                                          partIdx, merge_idx, &current_mv, mvp_flag[0], 0);
  1154.                 current_mv.mv[0].x += lc->pu.mvd.x;
  1155.                 current_mv.mv[0].y += lc->pu.mvd.y;
  1156.             }
  1157.  
  1158.             if (inter_pred_idc != PRED_L0) {
  1159.                 if (s->sh.nb_refs[L1]) {
  1160.                     ref_idx[1] = ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L1]);
  1161.                     current_mv.ref_idx[1] = ref_idx[1];
  1162.                 }
  1163.  
  1164.                 if (s->sh.mvd_l1_zero_flag == 1 && inter_pred_idc == PRED_BI) {
  1165.                     lc->pu.mvd.x = 0;
  1166.                     lc->pu.mvd.y = 0;
  1167.                 } else {
  1168.                     ff_hevc_hls_mvd_coding(s, x0, y0, 1);
  1169.                 }
  1170.  
  1171.                 current_mv.pred_flag[1] = 1;
  1172.                 mvp_flag[1] = ff_hevc_mvp_lx_flag_decode(s);
  1173.                 ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,
  1174.                                          partIdx, merge_idx, &current_mv, mvp_flag[1], 1);
  1175.                 current_mv.mv[1].x += lc->pu.mvd.x;
  1176.                 current_mv.mv[1].y += lc->pu.mvd.y;
  1177.             }
  1178.  
  1179.             x_pu = x0 >> s->sps->log2_min_pu_size;
  1180.             y_pu = y0 >> s->sps->log2_min_pu_size;
  1181.  
  1182.             for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)
  1183.                 for(j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)
  1184.                     tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv;
  1185.         }
  1186.     }
  1187.  
  1188.     if (current_mv.pred_flag[0]) {
  1189.         ref0 = refPicList[0].ref[current_mv.ref_idx[0]];
  1190.         if (!ref0)
  1191.             return;
  1192.         hevc_await_progress(s, ref0, &current_mv.mv[0], y0, nPbH);
  1193.     }
  1194.     if (current_mv.pred_flag[1]) {
  1195.         ref1 = refPicList[1].ref[current_mv.ref_idx[1]];
  1196.         if (!ref1)
  1197.             return;
  1198.         hevc_await_progress(s, ref1, &current_mv.mv[1], y0, nPbH);
  1199.     }
  1200.  
  1201.     if (current_mv.pred_flag[0] && !current_mv.pred_flag[1]) {
  1202.         DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
  1203.         DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]);
  1204.  
  1205.         luma_mc(s, tmp, tmpstride, ref0->frame,
  1206.                 &current_mv.mv[0], x0, y0, nPbW, nPbH);
  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.luma_log2_weight_denom,
  1211.                                      s->sh.luma_weight_l0[current_mv.ref_idx[0]],
  1212.                                      s->sh.luma_offset_l0[current_mv.ref_idx[0]],
  1213.                                      dst0, s->frame->linesize[0], tmp,
  1214.                                      tmpstride, nPbW, nPbH);
  1215.         } else {
  1216.             s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH);
  1217.         }
  1218.         chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame,
  1219.                   &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2);
  1220.  
  1221.         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
  1222.             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
  1223.             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
  1224.                                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0],
  1225.                                      s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0],
  1226.                                      dst1, s->frame->linesize[1], tmp, tmpstride,
  1227.                                      nPbW / 2, nPbH / 2);
  1228.             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
  1229.                                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1],
  1230.                                      s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1],
  1231.                                      dst2, s->frame->linesize[2], tmp2, tmpstride,
  1232.                                      nPbW / 2, nPbH / 2);
  1233.         } else {
  1234.             s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2);
  1235.             s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2);
  1236.         }
  1237.     } else if (!current_mv.pred_flag[0] && current_mv.pred_flag[1]) {
  1238.         DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
  1239.         DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]);
  1240.  
  1241.         if (!ref1)
  1242.             return;
  1243.  
  1244.         luma_mc(s, tmp, tmpstride, ref1->frame,
  1245.                 &current_mv.mv[1], x0, y0, nPbW, nPbH);
  1246.  
  1247.         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
  1248.             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
  1249.             s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom,
  1250.                                       s->sh.luma_weight_l1[current_mv.ref_idx[1]],
  1251.                                       s->sh.luma_offset_l1[current_mv.ref_idx[1]],
  1252.                                       dst0, s->frame->linesize[0], tmp, tmpstride,
  1253.                                       nPbW, nPbH);
  1254.         } else {
  1255.             s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH);
  1256.         }
  1257.  
  1258.         chroma_mc(s, tmp, tmp2, tmpstride, ref1->frame,
  1259.                   &current_mv.mv[1], x0/2, y0/2, nPbW/2, nPbH/2);
  1260.  
  1261.         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
  1262.             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
  1263.             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
  1264.                                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0],
  1265.                                      s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0],
  1266.                                      dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2);
  1267.             s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom,
  1268.                                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1],
  1269.                                      s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1],
  1270.                                      dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2);
  1271.         } else {
  1272.             s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2);
  1273.             s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2);
  1274.         }
  1275.     } else if (current_mv.pred_flag[0] && current_mv.pred_flag[1]) {
  1276.         DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]);
  1277.         DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]);
  1278.         DECLARE_ALIGNED(16, int16_t, tmp3[MAX_PB_SIZE * MAX_PB_SIZE]);
  1279.         DECLARE_ALIGNED(16, int16_t, tmp4[MAX_PB_SIZE * MAX_PB_SIZE]);
  1280.         HEVCFrame *ref0 = refPicList[0].ref[current_mv.ref_idx[0]];
  1281.         HEVCFrame *ref1 = refPicList[1].ref[current_mv.ref_idx[1]];
  1282.  
  1283.         if (!ref0 || !ref1)
  1284.             return;
  1285.  
  1286.         luma_mc(s, tmp, tmpstride, ref0->frame,
  1287.                 &current_mv.mv[0], x0, y0, nPbW, nPbH);
  1288.         luma_mc(s, tmp2, tmpstride, ref1->frame,
  1289.                 &current_mv.mv[1], x0, y0, nPbW, nPbH);
  1290.  
  1291.         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
  1292.             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
  1293.             s->hevcdsp.weighted_pred_avg(s->sh.luma_log2_weight_denom,
  1294.                                          s->sh.luma_weight_l0[current_mv.ref_idx[0]],
  1295.                                          s->sh.luma_weight_l1[current_mv.ref_idx[1]],
  1296.                                          s->sh.luma_offset_l0[current_mv.ref_idx[0]],
  1297.                                          s->sh.luma_offset_l1[current_mv.ref_idx[1]],
  1298.                                          dst0, s->frame->linesize[0],
  1299.                                          tmp, tmp2, tmpstride, nPbW, nPbH);
  1300.         } else {
  1301.             s->hevcdsp.put_weighted_pred_avg(dst0, s->frame->linesize[0],
  1302.                                              tmp, tmp2, tmpstride, nPbW, nPbH);
  1303.         }
  1304.  
  1305.         chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame,
  1306.                   &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2);
  1307.         chroma_mc(s, tmp3, tmp4, tmpstride, ref1->frame,
  1308.                   &current_mv.mv[1], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2);
  1309.  
  1310.         if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) ||
  1311.             (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) {
  1312.             s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom,
  1313.                                          s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0],
  1314.                                          s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0],
  1315.                                          s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0],
  1316.                                          s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0],
  1317.                                          dst1, s->frame->linesize[1], tmp, tmp3,
  1318.                                          tmpstride, nPbW / 2, nPbH / 2);
  1319.             s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom,
  1320.                                          s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1],
  1321.                                          s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1],
  1322.                                          s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1],
  1323.                                          s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1],
  1324.                                          dst2, s->frame->linesize[2], tmp2, tmp4,
  1325.                                          tmpstride, nPbW / 2, nPbH / 2);
  1326.         } else {
  1327.             s->hevcdsp.put_weighted_pred_avg(dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW/2, nPbH/2);
  1328.             s->hevcdsp.put_weighted_pred_avg(dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW/2, nPbH/2);
  1329.         }
  1330.     }
  1331. }
  1332.  
  1333. /**
  1334.  * 8.4.1
  1335.  */
  1336. static int luma_intra_pred_mode(HEVCContext *s, int x0, int y0, int pu_size,
  1337.                                 int prev_intra_luma_pred_flag)
  1338. {
  1339.     HEVCLocalContext *lc = s->HEVClc;
  1340.     int x_pu             = x0 >> s->sps->log2_min_pu_size;
  1341.     int y_pu             = y0 >> s->sps->log2_min_pu_size;
  1342.     int min_pu_width     = s->sps->min_pu_width;
  1343.     int size_in_pus      = pu_size >> s->sps->log2_min_pu_size;
  1344.     int x0b              = x0 & ((1 << s->sps->log2_ctb_size) - 1);
  1345.     int y0b              = y0 & ((1 << s->sps->log2_ctb_size) - 1);
  1346.  
  1347.     int cand_up   = (lc->ctb_up_flag || y0b) ?
  1348.                     s->tab_ipm[(y_pu - 1) * min_pu_width + x_pu] : INTRA_DC;
  1349.     int cand_left = (lc->ctb_left_flag || x0b) ?
  1350.                     s->tab_ipm[y_pu * min_pu_width + x_pu - 1]   : INTRA_DC;
  1351.  
  1352.     int y_ctb = (y0 >> (s->sps->log2_ctb_size)) << (s->sps->log2_ctb_size);
  1353.  
  1354.     MvField *tab_mvf = s->ref->tab_mvf;
  1355.     int intra_pred_mode;
  1356.     int candidate[3];
  1357.     int i, j;
  1358.  
  1359.     // intra_pred_mode prediction does not cross vertical CTB boundaries
  1360.     if ((y0 - 1) < y_ctb)
  1361.         cand_up = INTRA_DC;
  1362.  
  1363.     if (cand_left == cand_up) {
  1364.         if (cand_left < 2) {
  1365.             candidate[0] = INTRA_PLANAR;
  1366.             candidate[1] = INTRA_DC;
  1367.             candidate[2] = INTRA_ANGULAR_26;
  1368.         } else {
  1369.             candidate[0] = cand_left;
  1370.             candidate[1] = 2 + ((cand_left - 2 - 1 + 32) & 31);
  1371.             candidate[2] = 2 + ((cand_left - 2 + 1) & 31);
  1372.         }
  1373.     } else {
  1374.         candidate[0] = cand_left;
  1375.         candidate[1] = cand_up;
  1376.         if (candidate[0] != INTRA_PLANAR && candidate[1] != INTRA_PLANAR) {
  1377.             candidate[2] = INTRA_PLANAR;
  1378.         } else if (candidate[0] != INTRA_DC && candidate[1] != INTRA_DC) {
  1379.             candidate[2] = INTRA_DC;
  1380.         } else {
  1381.             candidate[2] = INTRA_ANGULAR_26;
  1382.         }
  1383.     }
  1384.  
  1385.     if (prev_intra_luma_pred_flag) {
  1386.         intra_pred_mode = candidate[lc->pu.mpm_idx];
  1387.     } else {
  1388.         if (candidate[0] > candidate[1])
  1389.             FFSWAP(uint8_t, candidate[0], candidate[1]);
  1390.         if (candidate[0] > candidate[2])
  1391.             FFSWAP(uint8_t, candidate[0], candidate[2]);
  1392.         if (candidate[1] > candidate[2])
  1393.             FFSWAP(uint8_t, candidate[1], candidate[2]);
  1394.  
  1395.         intra_pred_mode = lc->pu.rem_intra_luma_pred_mode;
  1396.         for (i = 0; i < 3; i++)
  1397.             if (intra_pred_mode >= candidate[i])
  1398.                 intra_pred_mode++;
  1399.     }
  1400.  
  1401.     /* write the intra prediction units into the mv array */
  1402.     if (!size_in_pus)
  1403.         size_in_pus = 1;
  1404.     for (i = 0; i < size_in_pus; i++) {
  1405.         memset(&s->tab_ipm[(y_pu + i) * min_pu_width + x_pu],
  1406.                intra_pred_mode, size_in_pus);
  1407.  
  1408.         for (j = 0; j < size_in_pus; j++) {
  1409.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].is_intra     = 1;
  1410.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].pred_flag[0] = 0;
  1411.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].pred_flag[1] = 0;
  1412.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].ref_idx[0]   = 0;
  1413.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].ref_idx[1]   = 0;
  1414.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].mv[0].x      = 0;
  1415.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].mv[0].y      = 0;
  1416.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].mv[1].x      = 0;
  1417.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + i].mv[1].y      = 0;
  1418.         }
  1419.     }
  1420.  
  1421.     return intra_pred_mode;
  1422. }
  1423.  
  1424. static av_always_inline void set_ct_depth(HEVCContext *s, int x0, int y0,
  1425.                                           int log2_cb_size, int ct_depth)
  1426. {
  1427.     int length = (1 << log2_cb_size) >> s->sps->log2_min_cb_size;
  1428.     int x_cb   = x0 >> s->sps->log2_min_cb_size;
  1429.     int y_cb   = y0 >> s->sps->log2_min_cb_size;
  1430.     int y;
  1431.  
  1432.     for (y = 0; y < length; y++)
  1433.         memset(&s->tab_ct_depth[(y_cb + y) * s->sps->min_cb_width + x_cb],
  1434.                ct_depth, length);
  1435. }
  1436.  
  1437. static void intra_prediction_unit(HEVCContext *s, int x0, int y0,
  1438.                                   int log2_cb_size)
  1439. {
  1440.     HEVCLocalContext *lc = s->HEVClc;
  1441.     static const uint8_t intra_chroma_table[4] = { 0, 26, 10, 1 };
  1442.     uint8_t prev_intra_luma_pred_flag[4];
  1443.     int split   = lc->cu.part_mode == PART_NxN;
  1444.     int pb_size = (1 << log2_cb_size) >> split;
  1445.     int side    = split + 1;
  1446.     int chroma_mode;
  1447.     int i, j;
  1448.  
  1449.     for (i = 0; i < side; i++)
  1450.         for (j = 0; j < side; j++)
  1451.             prev_intra_luma_pred_flag[2 * i + j] = ff_hevc_prev_intra_luma_pred_flag_decode(s);
  1452.  
  1453.     for (i = 0; i < side; i++) {
  1454.         for (j = 0; j < side; j++) {
  1455.             if (prev_intra_luma_pred_flag[2 * i + j])
  1456.                 lc->pu.mpm_idx = ff_hevc_mpm_idx_decode(s);
  1457.             else
  1458.                 lc->pu.rem_intra_luma_pred_mode = ff_hevc_rem_intra_luma_pred_mode_decode(s);
  1459.  
  1460.             lc->pu.intra_pred_mode[2 * i + j] =
  1461.                 luma_intra_pred_mode(s, x0 + pb_size * j, y0 + pb_size * i, pb_size,
  1462.                                      prev_intra_luma_pred_flag[2 * i + j]);
  1463.         }
  1464.     }
  1465.  
  1466.     chroma_mode = ff_hevc_intra_chroma_pred_mode_decode(s);
  1467.     if (chroma_mode != 4) {
  1468.         if (lc->pu.intra_pred_mode[0] == intra_chroma_table[chroma_mode])
  1469.             lc->pu.intra_pred_mode_c = 34;
  1470.         else
  1471.             lc->pu.intra_pred_mode_c = intra_chroma_table[chroma_mode];
  1472.     } else {
  1473.         lc->pu.intra_pred_mode_c = lc->pu.intra_pred_mode[0];
  1474.     }
  1475. }
  1476.  
  1477. static void intra_prediction_unit_default_value(HEVCContext *s,
  1478.                                                 int x0, int y0,
  1479.                                                 int log2_cb_size)
  1480. {
  1481.     HEVCLocalContext *lc = s->HEVClc;
  1482.     int pb_size          = 1 << log2_cb_size;
  1483.     int size_in_pus      = pb_size >> s->sps->log2_min_pu_size;
  1484.     int min_pu_width     = s->sps->min_pu_width;
  1485.     MvField *tab_mvf     = s->ref->tab_mvf;
  1486.     int x_pu             = x0 >> s->sps->log2_min_pu_size;
  1487.     int y_pu             = y0 >> s->sps->log2_min_pu_size;
  1488.     int j, k;
  1489.  
  1490.     if (size_in_pus == 0)
  1491.         size_in_pus = 1;
  1492.     for (j = 0; j < size_in_pus; j++) {
  1493.         memset(&s->tab_ipm[(y_pu + j) * min_pu_width + x_pu], INTRA_DC, size_in_pus);
  1494.         for (k = 0; k < size_in_pus; k++)
  1495.             tab_mvf[(y_pu + j) * min_pu_width + x_pu + k].is_intra = lc->cu.pred_mode == MODE_INTRA;
  1496.     }
  1497. }
  1498.  
  1499. static int hls_coding_unit(HEVCContext *s, int x0, int y0, int log2_cb_size)
  1500. {
  1501.     int cb_size          = 1 << log2_cb_size;
  1502.     HEVCLocalContext *lc = s->HEVClc;
  1503.     int log2_min_cb_size = s->sps->log2_min_cb_size;
  1504.     int length           = cb_size >> log2_min_cb_size;
  1505.     int min_cb_width     = s->sps->min_cb_width;
  1506.     int x_cb             = x0 >> log2_min_cb_size;
  1507.     int y_cb             = y0 >> log2_min_cb_size;
  1508.     int x, y;
  1509.  
  1510.     lc->cu.x            = x0;
  1511.     lc->cu.y            = y0;
  1512.     lc->cu.rqt_root_cbf = 1;
  1513.  
  1514.     lc->cu.pred_mode                     = MODE_INTRA;
  1515.     lc->cu.part_mode                     = PART_2Nx2N;
  1516.     lc->cu.intra_split_flag              = 0;
  1517.     lc->cu.pcm_flag                      = 0;
  1518.     SAMPLE_CTB(s->skip_flag, x_cb, y_cb) = 0;
  1519.     for (x = 0; x < 4; x++)
  1520.         lc->pu.intra_pred_mode[x] = 1;
  1521.     if (s->pps->transquant_bypass_enable_flag) {
  1522.         lc->cu.cu_transquant_bypass_flag = ff_hevc_cu_transquant_bypass_flag_decode(s);
  1523.         if (lc->cu.cu_transquant_bypass_flag)
  1524.             set_deblocking_bypass(s, x0, y0, log2_cb_size);
  1525.     } else
  1526.         lc->cu.cu_transquant_bypass_flag = 0;
  1527.  
  1528.     if (s->sh.slice_type != I_SLICE) {
  1529.         uint8_t skip_flag = ff_hevc_skip_flag_decode(s, x0, y0, x_cb, y_cb);
  1530.  
  1531.         lc->cu.pred_mode = MODE_SKIP;
  1532.         x = y_cb * min_cb_width + x_cb;
  1533.         for (y = 0; y < length; y++) {
  1534.             memset(&s->skip_flag[x], skip_flag, length);
  1535.             x += min_cb_width;
  1536.         }
  1537.         lc->cu.pred_mode = skip_flag ? MODE_SKIP : MODE_INTER;
  1538.     }
  1539.  
  1540.     if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) {
  1541.         hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0);
  1542.         intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
  1543.  
  1544.         if (!s->sh.disable_deblocking_filter_flag)
  1545.             ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size,
  1546.                                                   lc->slice_or_tiles_up_boundary,
  1547.                                                   lc->slice_or_tiles_left_boundary);
  1548.     } else {
  1549.         if (s->sh.slice_type != I_SLICE)
  1550.             lc->cu.pred_mode = ff_hevc_pred_mode_decode(s);
  1551.         if (lc->cu.pred_mode != MODE_INTRA ||
  1552.             log2_cb_size == s->sps->log2_min_cb_size) {
  1553.             lc->cu.part_mode        = ff_hevc_part_mode_decode(s, log2_cb_size);
  1554.             lc->cu.intra_split_flag = lc->cu.part_mode == PART_NxN &&
  1555.                                       lc->cu.pred_mode == MODE_INTRA;
  1556.         }
  1557.  
  1558.         if (lc->cu.pred_mode == MODE_INTRA) {
  1559.             if (lc->cu.part_mode == PART_2Nx2N && s->sps->pcm_enabled_flag &&
  1560.                 log2_cb_size >= s->sps->pcm.log2_min_pcm_cb_size &&
  1561.                 log2_cb_size <= s->sps->pcm.log2_max_pcm_cb_size) {
  1562.                 lc->cu.pcm_flag = ff_hevc_pcm_flag_decode(s);
  1563.             }
  1564.             if (lc->cu.pcm_flag) {
  1565.                 int ret;
  1566.                 intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
  1567.                 ret = hls_pcm_sample(s, x0, y0, log2_cb_size);
  1568.                 if (s->sps->pcm.loop_filter_disable_flag)
  1569.                     set_deblocking_bypass(s, x0, y0, log2_cb_size);
  1570.  
  1571.                 if (ret < 0)
  1572.                     return ret;
  1573.             } else {
  1574.                 intra_prediction_unit(s, x0, y0, log2_cb_size);
  1575.             }
  1576.         } else {
  1577.             intra_prediction_unit_default_value(s, x0, y0, log2_cb_size);
  1578.             switch (lc->cu.part_mode) {
  1579.             case PART_2Nx2N:
  1580.                 hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0);
  1581.                 break;
  1582.             case PART_2NxN:
  1583.                 hls_prediction_unit(s, x0, y0, cb_size, cb_size / 2, log2_cb_size, 0);
  1584.                 hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size, cb_size/2, log2_cb_size, 1);
  1585.                 break;
  1586.             case PART_Nx2N:
  1587.                 hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size, log2_cb_size, 0);
  1588.                 hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size, log2_cb_size, 1);
  1589.                 break;
  1590.             case PART_2NxnU:
  1591.                 hls_prediction_unit(s, x0, y0, cb_size, cb_size / 4, log2_cb_size, 0);
  1592.                 hls_prediction_unit(s, x0, y0 + cb_size / 4, cb_size, cb_size * 3 / 4, log2_cb_size, 1);
  1593.                 break;
  1594.             case PART_2NxnD:
  1595.                 hls_prediction_unit(s, x0, y0, cb_size, cb_size * 3 / 4, log2_cb_size, 0);
  1596.                 hls_prediction_unit(s, x0, y0 + cb_size * 3 / 4, cb_size, cb_size / 4, log2_cb_size, 1);
  1597.                 break;
  1598.             case PART_nLx2N:
  1599.                 hls_prediction_unit(s, x0, y0, cb_size / 4, cb_size, log2_cb_size,0);
  1600.                 hls_prediction_unit(s, x0 + cb_size / 4, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 1);
  1601.                 break;
  1602.             case PART_nRx2N:
  1603.                 hls_prediction_unit(s, x0, y0, cb_size * 3 / 4, cb_size, log2_cb_size,0);
  1604.                 hls_prediction_unit(s, x0 + cb_size * 3 / 4, y0, cb_size/4, cb_size, log2_cb_size, 1);
  1605.                 break;
  1606.             case PART_NxN:
  1607.                 hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size / 2, log2_cb_size, 0);
  1608.                 hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size / 2, log2_cb_size, 1);
  1609.                 hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 2);
  1610.                 hls_prediction_unit(s, x0 + cb_size / 2, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 3);
  1611.                 break;
  1612.             }
  1613.         }
  1614.  
  1615.         if (!lc->cu.pcm_flag) {
  1616.             if (lc->cu.pred_mode != MODE_INTRA &&
  1617.                 !(lc->cu.part_mode == PART_2Nx2N && lc->pu.merge_flag)) {
  1618.                 lc->cu.rqt_root_cbf = ff_hevc_no_residual_syntax_flag_decode(s);
  1619.             }
  1620.             if (lc->cu.rqt_root_cbf) {
  1621.                 lc->cu.max_trafo_depth = lc->cu.pred_mode == MODE_INTRA ?
  1622.                                          s->sps->max_transform_hierarchy_depth_intra + lc->cu.intra_split_flag :
  1623.                                          s->sps->max_transform_hierarchy_depth_inter;
  1624.                 hls_transform_tree(s, x0, y0, x0, y0, x0, y0, log2_cb_size,
  1625.                                    log2_cb_size, 0, 0);
  1626.             } else {
  1627.                 if (!s->sh.disable_deblocking_filter_flag)
  1628.                     ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size,
  1629.                                                           lc->slice_or_tiles_up_boundary,
  1630.                                                           lc->slice_or_tiles_left_boundary);
  1631.             }
  1632.         }
  1633.     }
  1634.  
  1635.     if (s->pps->cu_qp_delta_enabled_flag && lc->tu.is_cu_qp_delta_coded == 0)
  1636.         ff_hevc_set_qPy(s, x0, y0, x0, y0, log2_cb_size);
  1637.  
  1638.     x = y_cb * min_cb_width + x_cb;
  1639.     for (y = 0; y < length; y++) {
  1640.         memset(&s->qp_y_tab[x], lc->qp_y, length);
  1641.         x += min_cb_width;
  1642.     }
  1643.  
  1644.     set_ct_depth(s, x0, y0, log2_cb_size, lc->ct.depth);
  1645.  
  1646.     return 0;
  1647. }
  1648.  
  1649. static int hls_coding_quadtree(HEVCContext *s, int x0, int y0,
  1650.                                int log2_cb_size, int cb_depth)
  1651. {
  1652.     HEVCLocalContext *lc = s->HEVClc;
  1653.     const int cb_size    = 1 << log2_cb_size;
  1654.     int ret;
  1655.  
  1656.     lc->ct.depth = cb_depth;
  1657.     if ((x0 + cb_size <= s->sps->width) &&
  1658.         (y0 + cb_size <= s->sps->height) &&
  1659.         log2_cb_size > s->sps->log2_min_cb_size) {
  1660.         SAMPLE(s->split_cu_flag, x0, y0) =
  1661.             ff_hevc_split_coding_unit_flag_decode(s, cb_depth, x0, y0);
  1662.     } else {
  1663.         SAMPLE(s->split_cu_flag, x0, y0) =
  1664.             (log2_cb_size > s->sps->log2_min_cb_size);
  1665.     }
  1666.     if (s->pps->cu_qp_delta_enabled_flag &&
  1667.         log2_cb_size >= s->sps->log2_ctb_size - s->pps->diff_cu_qp_delta_depth) {
  1668.         lc->tu.is_cu_qp_delta_coded = 0;
  1669.         lc->tu.cu_qp_delta          = 0;
  1670.     }
  1671.  
  1672.     if (SAMPLE(s->split_cu_flag, x0, y0)) {
  1673.         const int cb_size_split = cb_size >> 1;
  1674.         const int x1 = x0 + cb_size_split;
  1675.         const int y1 = y0 + cb_size_split;
  1676.         int more_data = 0;
  1677.  
  1678.         more_data = hls_coding_quadtree(s, x0, y0, log2_cb_size - 1, cb_depth + 1);
  1679.         if (more_data < 0)
  1680.             return more_data;
  1681.  
  1682.         if (more_data && x1 < s->sps->width)
  1683.             more_data = hls_coding_quadtree(s, x1, y0, log2_cb_size - 1, cb_depth + 1);
  1684.         if (more_data && y1 < s->sps->height)
  1685.             more_data = hls_coding_quadtree(s, x0, y1, log2_cb_size - 1, cb_depth + 1);
  1686.         if (more_data && x1 < s->sps->width &&
  1687.             y1 < s->sps->height) {
  1688.             return hls_coding_quadtree(s, x1, y1, log2_cb_size - 1, cb_depth + 1);
  1689.         }
  1690.         if (more_data)
  1691.             return ((x1 + cb_size_split) < s->sps->width ||
  1692.                     (y1 + cb_size_split) < s->sps->height);
  1693.         else
  1694.             return 0;
  1695.     } else {
  1696.         ret = hls_coding_unit(s, x0, y0, log2_cb_size);
  1697.         if (ret < 0)
  1698.             return ret;
  1699.         if ((!((x0 + cb_size) %
  1700.                (1 << (s->sps->log2_ctb_size))) ||
  1701.              (x0 + cb_size >= s->sps->width)) &&
  1702.             (!((y0 + cb_size) %
  1703.                (1 << (s->sps->log2_ctb_size))) ||
  1704.              (y0 + cb_size >= s->sps->height))) {
  1705.             int end_of_slice_flag = ff_hevc_end_of_slice_flag_decode(s);
  1706.             return !end_of_slice_flag;
  1707.         } else {
  1708.             return 1;
  1709.         }
  1710.     }
  1711.  
  1712.     return 0;
  1713. }
  1714.  
  1715. static void hls_decode_neighbour(HEVCContext *s, int x_ctb, int y_ctb, int ctb_addr_ts)
  1716. {
  1717.     HEVCLocalContext *lc  = s->HEVClc;
  1718.     int ctb_size          = 1 << s->sps->log2_ctb_size;
  1719.     int ctb_addr_rs       = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts];
  1720.     int ctb_addr_in_slice = ctb_addr_rs - s->sh.slice_addr;
  1721.  
  1722.     int tile_left_boundary;
  1723.     int tile_up_boundary;
  1724.     int slice_left_boundary;
  1725.     int slice_up_boundary;
  1726.  
  1727.     s->tab_slice_address[ctb_addr_rs] = s->sh.slice_addr;
  1728.  
  1729.     if (s->pps->entropy_coding_sync_enabled_flag) {
  1730.         if (x_ctb == 0 && (y_ctb & (ctb_size - 1)) == 0)
  1731.             lc->first_qp_group = 1;
  1732.         lc->end_of_tiles_x = s->sps->width;
  1733.     } else if (s->pps->tiles_enabled_flag) {
  1734.         if (ctb_addr_ts && s->pps->tile_id[ctb_addr_ts] != s->pps->tile_id[ctb_addr_ts - 1]) {
  1735.             int idxX = s->pps->col_idxX[x_ctb >> s->sps->log2_ctb_size];
  1736.             lc->start_of_tiles_x = x_ctb;
  1737.             lc->end_of_tiles_x   = x_ctb + (s->pps->column_width[idxX] << s->sps->log2_ctb_size);
  1738.             lc->first_qp_group   = 1;
  1739.         }
  1740.     } else {
  1741.         lc->end_of_tiles_x = s->sps->width;
  1742.     }
  1743.  
  1744.     lc->end_of_tiles_y = FFMIN(y_ctb + ctb_size, s->sps->height);
  1745.  
  1746.     if (s->pps->tiles_enabled_flag) {
  1747.         tile_left_boundary  = ((x_ctb > 0) &&
  1748.                                (s->pps->tile_id[ctb_addr_ts] == s->pps->tile_id[s->pps->ctb_addr_rs_to_ts[ctb_addr_rs - 1]]));
  1749.         slice_left_boundary = ((x_ctb > 0) &&
  1750.                                (s->tab_slice_address[ctb_addr_rs] == s->tab_slice_address[ctb_addr_rs - 1]));
  1751.         tile_up_boundary  = ((y_ctb > 0) &&
  1752.                              (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]]));
  1753.         slice_up_boundary = ((y_ctb > 0) &&
  1754.                              (s->tab_slice_address[ctb_addr_rs] == s->tab_slice_address[ctb_addr_rs - s->sps->ctb_width]));
  1755.     } else {
  1756.         tile_left_boundary  =
  1757.         tile_up_boundary    = 1;
  1758.         slice_left_boundary = ctb_addr_in_slice > 0;
  1759.         slice_up_boundary   = ctb_addr_in_slice >= s->sps->ctb_width;
  1760.     }
  1761.     lc->slice_or_tiles_left_boundary = (!slice_left_boundary) + (!tile_left_boundary << 1);
  1762.     lc->slice_or_tiles_up_boundary   = (!slice_up_boundary + (!tile_up_boundary << 1));
  1763.     lc->ctb_left_flag = ((x_ctb > 0) && (ctb_addr_in_slice > 0) && tile_left_boundary);
  1764.     lc->ctb_up_flag   = ((y_ctb > 0) && (ctb_addr_in_slice >= s->sps->ctb_width) && tile_up_boundary);
  1765.     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]]));
  1766.     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]]));
  1767. }
  1768.  
  1769. static int hls_decode_entry(AVCodecContext *avctxt, void *isFilterThread)
  1770. {
  1771.     HEVCContext *s  = avctxt->priv_data;
  1772.     int ctb_size    = 1 << s->sps->log2_ctb_size;
  1773.     int more_data   = 1;
  1774.     int x_ctb       = 0;
  1775.     int y_ctb       = 0;
  1776.     int ctb_addr_ts = s->pps->ctb_addr_rs_to_ts[s->sh.slice_ctb_addr_rs];
  1777.  
  1778.     while (more_data && ctb_addr_ts < s->sps->ctb_size) {
  1779.         int ctb_addr_rs = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts];
  1780.  
  1781.         x_ctb = (ctb_addr_rs % ((s->sps->width + (ctb_size - 1)) >> s->sps->log2_ctb_size)) << s->sps->log2_ctb_size;
  1782.         y_ctb = (ctb_addr_rs / ((s->sps->width + (ctb_size - 1)) >> s->sps->log2_ctb_size)) << s->sps->log2_ctb_size;
  1783.         hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);
  1784.  
  1785.         ff_hevc_cabac_init(s, ctb_addr_ts);
  1786.  
  1787.         hls_sao_param(s, x_ctb >> s->sps->log2_ctb_size, y_ctb >> s->sps->log2_ctb_size);
  1788.  
  1789.         s->deblock[ctb_addr_rs].beta_offset = s->sh.beta_offset;
  1790.         s->deblock[ctb_addr_rs].tc_offset   = s->sh.tc_offset;
  1791.         s->filter_slice_edges[ctb_addr_rs]  = s->sh.slice_loop_filter_across_slices_enabled_flag;
  1792.  
  1793.         more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->sps->log2_ctb_size, 0);
  1794.         if (more_data < 0)
  1795.             return more_data;
  1796.  
  1797.         ctb_addr_ts++;
  1798.         ff_hevc_save_states(s, ctb_addr_ts);
  1799.         ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);
  1800.     }
  1801.  
  1802.     if (x_ctb + ctb_size >= s->sps->width &&
  1803.         y_ctb + ctb_size >= s->sps->height)
  1804.         ff_hevc_hls_filter(s, x_ctb, y_ctb);
  1805.  
  1806.     return ctb_addr_ts;
  1807. }
  1808.  
  1809. static int hls_slice_data(HEVCContext *s)
  1810. {
  1811.     int arg[2];
  1812.     int ret[2];
  1813.  
  1814.     arg[0] = 0;
  1815.     arg[1] = 1;
  1816.  
  1817.     s->avctx->execute(s->avctx, hls_decode_entry, arg, ret , 1, sizeof(int));
  1818.     return ret[0];
  1819. }
  1820. static int hls_decode_entry_wpp(AVCodecContext *avctxt, void *input_ctb_row, int job, int self_id)
  1821. {
  1822.     HEVCContext *s1  = avctxt->priv_data, *s;
  1823.     HEVCLocalContext *lc;
  1824.     int ctb_size    = 1<< s1->sps->log2_ctb_size;
  1825.     int more_data   = 1;
  1826.     int *ctb_row_p    = input_ctb_row;
  1827.     int ctb_row = ctb_row_p[job];
  1828.     int ctb_addr_rs = s1->sh.slice_ctb_addr_rs + ctb_row * ((s1->sps->width + ctb_size - 1) >> s1->sps->log2_ctb_size);
  1829.     int ctb_addr_ts = s1->pps->ctb_addr_rs_to_ts[ctb_addr_rs];
  1830.     int thread = ctb_row % s1->threads_number;
  1831.     int ret;
  1832.  
  1833.     s = s1->sList[self_id];
  1834.     lc = s->HEVClc;
  1835.  
  1836.     if(ctb_row) {
  1837.         ret = init_get_bits8(&lc->gb, s->data + s->sh.offset[ctb_row - 1], s->sh.size[ctb_row - 1]);
  1838.  
  1839.         if (ret < 0)
  1840.             return ret;
  1841.         ff_init_cabac_decoder(&lc->cc, s->data + s->sh.offset[(ctb_row)-1], s->sh.size[ctb_row - 1]);
  1842.     }
  1843.  
  1844.     while(more_data && ctb_addr_ts < s->sps->ctb_size) {
  1845.         int x_ctb = (ctb_addr_rs % s->sps->ctb_width) << s->sps->log2_ctb_size;
  1846.         int y_ctb = (ctb_addr_rs / s->sps->ctb_width) << s->sps->log2_ctb_size;
  1847.  
  1848.         hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);
  1849.  
  1850.         ff_thread_await_progress2(s->avctx, ctb_row, thread, SHIFT_CTB_WPP);
  1851.  
  1852.         if (avpriv_atomic_int_get(&s1->wpp_err)){
  1853.             ff_thread_report_progress2(s->avctx, ctb_row , thread, SHIFT_CTB_WPP);
  1854.             return 0;
  1855.         }
  1856.  
  1857.         ff_hevc_cabac_init(s, ctb_addr_ts);
  1858.         hls_sao_param(s, x_ctb >> s->sps->log2_ctb_size, y_ctb >> s->sps->log2_ctb_size);
  1859.         more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->sps->log2_ctb_size, 0);
  1860.  
  1861.         if (more_data < 0)
  1862.             return more_data;
  1863.  
  1864.         ctb_addr_ts++;
  1865.  
  1866.         ff_hevc_save_states(s, ctb_addr_ts);
  1867.         ff_thread_report_progress2(s->avctx, ctb_row, thread, 1);
  1868.         ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);
  1869.  
  1870.         if (!more_data && (x_ctb+ctb_size) < s->sps->width && ctb_row != s->sh.num_entry_point_offsets) {
  1871.             avpriv_atomic_int_set(&s1->wpp_err,  1);
  1872.             ff_thread_report_progress2(s->avctx, ctb_row ,thread, SHIFT_CTB_WPP);
  1873.             return 0;
  1874.         }
  1875.  
  1876.         if ((x_ctb+ctb_size) >= s->sps->width && (y_ctb+ctb_size) >= s->sps->height ) {
  1877.             ff_hevc_hls_filter(s, x_ctb, y_ctb);
  1878.             ff_thread_report_progress2(s->avctx, ctb_row , thread, SHIFT_CTB_WPP);
  1879.             return ctb_addr_ts;
  1880.         }
  1881.         ctb_addr_rs       = s->pps->ctb_addr_ts_to_rs[ctb_addr_ts];
  1882.         x_ctb+=ctb_size;
  1883.  
  1884.         if(x_ctb >= s->sps->width) {
  1885.             break;
  1886.         }
  1887.     }
  1888.     ff_thread_report_progress2(s->avctx, ctb_row ,thread, SHIFT_CTB_WPP);
  1889.  
  1890.     return 0;
  1891. }
  1892.  
  1893. static int hls_slice_data_wpp(HEVCContext *s, const uint8_t *nal, int length)
  1894. {
  1895.     HEVCLocalContext *lc = s->HEVClc;
  1896.     int *ret = av_malloc((s->sh.num_entry_point_offsets + 1) * sizeof(int));
  1897.     int *arg = av_malloc((s->sh.num_entry_point_offsets + 1) * sizeof(int));
  1898.     int offset;
  1899.     int startheader, cmpt = 0;
  1900.     int i, j, res = 0;
  1901.  
  1902.  
  1903.     if (!s->sList[1]) {
  1904.         ff_alloc_entries(s->avctx, s->sh.num_entry_point_offsets + 1);
  1905.  
  1906.  
  1907.         for (i = 1; i < s->threads_number; i++) {
  1908.             s->sList[i] = av_malloc(sizeof(HEVCContext));
  1909.             memcpy(s->sList[i], s, sizeof(HEVCContext));
  1910.             s->HEVClcList[i] = av_malloc(sizeof(HEVCLocalContext));
  1911.             s->HEVClcList[i]->edge_emu_buffer = av_malloc((MAX_PB_SIZE + 7) * s->frame->linesize[0]);
  1912.             s->sList[i]->HEVClc = s->HEVClcList[i];
  1913.         }
  1914.     }
  1915.  
  1916.     offset = (lc->gb.index >> 3);
  1917.  
  1918.     for (j = 0, cmpt = 0, startheader = offset + s->sh.entry_point_offset[0]; j < s->skipped_bytes; j++) {
  1919.         if (s->skipped_bytes_pos[j] >= offset && s->skipped_bytes_pos[j] < startheader) {
  1920.             startheader--;
  1921.             cmpt++;
  1922.         }
  1923.     }
  1924.  
  1925.     for (i = 1; i < s->sh.num_entry_point_offsets; i++) {
  1926.         offset += (s->sh.entry_point_offset[i - 1] - cmpt);
  1927.         for (j = 0, cmpt = 0, startheader = offset
  1928.              + s->sh.entry_point_offset[i]; j < s->skipped_bytes; j++) {
  1929.             if (s->skipped_bytes_pos[j] >= offset && s->skipped_bytes_pos[j] < startheader) {
  1930.                 startheader--;
  1931.                 cmpt++;
  1932.             }
  1933.         }
  1934.         s->sh.size[i - 1] = s->sh.entry_point_offset[i] - cmpt;
  1935.         s->sh.offset[i - 1] = offset;
  1936.  
  1937.     }
  1938.     if (s->sh.num_entry_point_offsets != 0) {
  1939.         offset += s->sh.entry_point_offset[s->sh.num_entry_point_offsets - 1] - cmpt;
  1940.         s->sh.size[s->sh.num_entry_point_offsets - 1] = length - offset;
  1941.         s->sh.offset[s->sh.num_entry_point_offsets - 1] = offset;
  1942.  
  1943.     }
  1944.     s->data = nal;
  1945.  
  1946.     for (i = 1; i < s->threads_number; i++) {
  1947.         s->sList[i]->HEVClc->first_qp_group = 1;
  1948.         s->sList[i]->HEVClc->qp_y = s->sList[0]->HEVClc->qp_y;
  1949.         memcpy(s->sList[i], s, sizeof(HEVCContext));
  1950.         s->sList[i]->HEVClc = s->HEVClcList[i];
  1951.     }
  1952.  
  1953.     avpriv_atomic_int_set(&s->wpp_err, 0);
  1954.     ff_reset_entries(s->avctx);
  1955.  
  1956.     for (i = 0; i <= s->sh.num_entry_point_offsets; i++) {
  1957.         arg[i] = i;
  1958.         ret[i] = 0;
  1959.     }
  1960.  
  1961.     if (s->pps->entropy_coding_sync_enabled_flag)
  1962.         s->avctx->execute2(s->avctx, (void *) hls_decode_entry_wpp, arg, ret, s->sh.num_entry_point_offsets + 1);
  1963.  
  1964.     for (i = 0; i <= s->sh.num_entry_point_offsets; i++)
  1965.         res += ret[i];
  1966.     av_free(ret);
  1967.     av_free(arg);
  1968.     return res;
  1969. }
  1970.  
  1971. /**
  1972.  * @return AVERROR_INVALIDDATA if the packet is not a valid NAL unit,
  1973.  * 0 if the unit should be skipped, 1 otherwise
  1974.  */
  1975. static int hls_nal_unit(HEVCContext *s)
  1976. {
  1977.     GetBitContext *gb = &s->HEVClc->gb;
  1978.     int nuh_layer_id;
  1979.  
  1980.     if (get_bits1(gb) != 0)
  1981.         return AVERROR_INVALIDDATA;
  1982.  
  1983.     s->nal_unit_type = get_bits(gb, 6);
  1984.  
  1985.     nuh_layer_id   = get_bits(gb, 6);
  1986.     s->temporal_id = get_bits(gb, 3) - 1;
  1987.     if (s->temporal_id < 0)
  1988.         return AVERROR_INVALIDDATA;
  1989.  
  1990.     av_log(s->avctx, AV_LOG_DEBUG,
  1991.            "nal_unit_type: %d, nuh_layer_id: %dtemporal_id: %d\n",
  1992.            s->nal_unit_type, nuh_layer_id, s->temporal_id);
  1993.  
  1994.     return nuh_layer_id == 0;
  1995. }
  1996.  
  1997. static void restore_tqb_pixels(HEVCContext *s)
  1998. {
  1999.     int min_pu_size          = 1 << s->sps->log2_min_pu_size;
  2000.     int x, y, c_idx;
  2001.  
  2002.     for (c_idx = 0; c_idx < 3; c_idx++) {
  2003.         ptrdiff_t stride = s->frame->linesize[c_idx];
  2004.         int hshift       = s->sps->hshift[c_idx];
  2005.         int vshift       = s->sps->vshift[c_idx];
  2006.         for (y = 0; y < s->sps->min_pu_height; y++) {
  2007.             for (x = 0; x < s->sps->min_pu_width; x++) {
  2008.                 if (s->is_pcm[y * s->sps->min_pu_width + x]) {
  2009.                     int n;
  2010.                     int len      = min_pu_size >> hshift;
  2011.                     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)];
  2012.                     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)];
  2013.                     for (n = 0; n < (min_pu_size >> vshift); n++) {
  2014.                         memcpy(dst, src, len);
  2015.                         src += stride;
  2016.                         dst += stride;
  2017.                     }
  2018.                 }
  2019.             }
  2020.         }
  2021.     }
  2022. }
  2023.  
  2024. static int hevc_frame_start(HEVCContext *s)
  2025. {
  2026.     HEVCLocalContext *lc     = s->HEVClc;
  2027.     int ret;
  2028.  
  2029.     memset(s->horizontal_bs, 0, 2 * s->bs_width * (s->bs_height + 1));
  2030.     memset(s->vertical_bs,   0, 2 * s->bs_width * (s->bs_height + 1));
  2031.     memset(s->cbf_luma,      0, s->sps->min_tb_width * s->sps->min_tb_height);
  2032.     memset(s->is_pcm,        0, s->sps->min_pu_width * s->sps->min_pu_height);
  2033.  
  2034.     lc->start_of_tiles_x = 0;
  2035.     s->is_decoded        = 0;
  2036.  
  2037.     if (s->pps->tiles_enabled_flag)
  2038.         lc->end_of_tiles_x = s->pps->column_width[0] << s->sps->log2_ctb_size;
  2039.  
  2040.     ret = ff_hevc_set_new_ref(s, s->sps->sao_enabled ? &s->sao_frame : &s->frame,
  2041.                               s->poc);
  2042.     if (ret < 0)
  2043.         goto fail;
  2044.  
  2045.     av_fast_malloc(&lc->edge_emu_buffer, &lc->edge_emu_buffer_size,
  2046.                    (MAX_PB_SIZE + 7) * s->ref->frame->linesize[0]);
  2047.     if (!lc->edge_emu_buffer) {
  2048.         ret = AVERROR(ENOMEM);
  2049.         goto fail;
  2050.     }
  2051.  
  2052.     ret = ff_hevc_frame_rps(s);
  2053.     if (ret < 0) {
  2054.         av_log(s->avctx, AV_LOG_ERROR, "Error constructing the frame RPS.\n");
  2055.         goto fail;
  2056.     }
  2057.  
  2058.     av_frame_unref(s->output_frame);
  2059.     ret = ff_hevc_output_frame(s, s->output_frame, 0);
  2060.     if (ret < 0)
  2061.         goto fail;
  2062.  
  2063.     ff_thread_finish_setup(s->avctx);
  2064.  
  2065.     return 0;
  2066. fail:
  2067.     if (s->ref && s->threads_type == FF_THREAD_FRAME)
  2068.         ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);
  2069.     s->ref = NULL;
  2070.     return ret;
  2071. }
  2072.  
  2073. static int decode_nal_unit(HEVCContext *s, const uint8_t *nal, int length)
  2074. {
  2075.     HEVCLocalContext *lc = s->HEVClc;
  2076.     GetBitContext *gb    = &lc->gb;
  2077.     int ctb_addr_ts;
  2078.     int ret;
  2079.  
  2080.     ret = init_get_bits8(gb, nal, length);
  2081.     if (ret < 0)
  2082.         return ret;
  2083.  
  2084.     ret = hls_nal_unit(s);
  2085.     if (ret < 0) {
  2086.         av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",
  2087.                s->nal_unit_type);
  2088.         if (s->avctx->err_recognition & AV_EF_EXPLODE)
  2089.             return ret;
  2090.         return 0;
  2091.     } else if (!ret)
  2092.         return 0;
  2093.  
  2094.     switch (s->nal_unit_type) {
  2095.     case NAL_VPS:
  2096.         ret = ff_hevc_decode_nal_vps(s);
  2097.         if (ret < 0)
  2098.             return ret;
  2099.         break;
  2100.     case NAL_SPS:
  2101.         ret = ff_hevc_decode_nal_sps(s);
  2102.         if (ret < 0)
  2103.             return ret;
  2104.         break;
  2105.     case NAL_PPS:
  2106.         ret = ff_hevc_decode_nal_pps(s);
  2107.         if (ret < 0)
  2108.             return ret;
  2109.         break;
  2110.     case NAL_SEI_PREFIX:
  2111.     case NAL_SEI_SUFFIX:
  2112.         ret = ff_hevc_decode_nal_sei(s);
  2113.         if (ret < 0)
  2114.             return ret;
  2115.         break;
  2116.     case NAL_TRAIL_R:
  2117.     case NAL_TRAIL_N:
  2118.     case NAL_TSA_N:
  2119.     case NAL_TSA_R:
  2120.     case NAL_STSA_N:
  2121.     case NAL_STSA_R:
  2122.     case NAL_BLA_W_LP:
  2123.     case NAL_BLA_W_RADL:
  2124.     case NAL_BLA_N_LP:
  2125.     case NAL_IDR_W_RADL:
  2126.     case NAL_IDR_N_LP:
  2127.     case NAL_CRA_NUT:
  2128.     case NAL_RADL_N:
  2129.     case NAL_RADL_R:
  2130.     case NAL_RASL_N:
  2131.     case NAL_RASL_R:
  2132.         ret = hls_slice_header(s);
  2133.         if (ret < 0)
  2134.             return ret;
  2135.  
  2136.         if (s->max_ra == INT_MAX) {
  2137.             if (s->nal_unit_type == NAL_CRA_NUT || IS_BLA(s)) {
  2138.                 s->max_ra = s->poc;
  2139.             } else {
  2140.                 if (IS_IDR(s))
  2141.                     s->max_ra = INT_MIN;
  2142.             }
  2143.         }
  2144.  
  2145.         if ((s->nal_unit_type == NAL_RASL_R || s->nal_unit_type == NAL_RASL_N) &&
  2146.             s->poc <= s->max_ra) {
  2147.             s->is_decoded = 0;
  2148.             break;
  2149.         } else {
  2150.             if (s->nal_unit_type == NAL_RASL_R && s->poc > s->max_ra)
  2151.                 s->max_ra = INT_MIN;
  2152.         }
  2153.  
  2154.         if (s->sh.first_slice_in_pic_flag) {
  2155.             ret = hevc_frame_start(s);
  2156.             if (ret < 0)
  2157.                 return ret;
  2158.         } else if (!s->ref) {
  2159.             av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n");
  2160.             return AVERROR_INVALIDDATA;
  2161.         }
  2162.  
  2163.         if (!s->sh.dependent_slice_segment_flag &&
  2164.             s->sh.slice_type != I_SLICE) {
  2165.             ret = ff_hevc_slice_rpl(s);
  2166.             if (ret < 0) {
  2167.                 av_log(s->avctx, AV_LOG_WARNING,
  2168.                        "Error constructing the reference lists for the current slice.\n");
  2169.                 if (s->avctx->err_recognition & AV_EF_EXPLODE)
  2170.                     return ret;
  2171.             }
  2172.         }
  2173.  
  2174.         if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0)
  2175.             ctb_addr_ts = hls_slice_data_wpp(s, nal, length);
  2176.         else
  2177.             ctb_addr_ts = hls_slice_data(s);
  2178.  
  2179.         if (ctb_addr_ts >= (s->sps->ctb_width * s->sps->ctb_height)) {
  2180.             s->is_decoded = 1;
  2181.             if ((s->pps->transquant_bypass_enable_flag ||
  2182.                  (s->sps->pcm.loop_filter_disable_flag && s->sps->pcm_enabled_flag)) &&
  2183.                 s->sps->sao_enabled)
  2184.                 restore_tqb_pixels(s);
  2185.         }
  2186.  
  2187.         if (ctb_addr_ts < 0)
  2188.             return ctb_addr_ts;
  2189.         break;
  2190.     case NAL_EOS_NUT:
  2191.     case NAL_EOB_NUT:
  2192.         s->seq_decode = (s->seq_decode + 1) & 0xff;
  2193.         s->max_ra     = INT_MAX;
  2194.         break;
  2195.     case NAL_AUD:
  2196.     case NAL_FD_NUT:
  2197.         break;
  2198.     default:
  2199.         av_log(s->avctx, AV_LOG_INFO,
  2200.                "Skipping NAL unit %d\n", s->nal_unit_type);
  2201.     }
  2202.  
  2203.     return 0;
  2204. }
  2205.  
  2206. /* FIXME: This is adapted from ff_h264_decode_nal, avoiding duplication
  2207.    between these functions would be nice. */
  2208. int ff_hevc_extract_rbsp(HEVCContext *s, const uint8_t *src, int length,
  2209.                          HEVCNAL *nal)
  2210. {
  2211.     int i, si, di;
  2212.     uint8_t *dst;
  2213.  
  2214.     s->skipped_bytes = 0;
  2215. #define STARTCODE_TEST                                                  \
  2216.         if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {     \
  2217.             if (src[i + 2] != 3) {                                      \
  2218.                 /* startcode, so we must be past the end */             \
  2219.                 length = i;                                             \
  2220.             }                                                           \
  2221.             break;                                                      \
  2222.         }
  2223. #if HAVE_FAST_UNALIGNED
  2224. #define FIND_FIRST_ZERO                                                 \
  2225.         if (i > 0 && !src[i])                                           \
  2226.             i--;                                                        \
  2227.         while (src[i])                                                  \
  2228.             i++
  2229. #if HAVE_FAST_64BIT
  2230.     for (i = 0; i + 1 < length; i += 9) {
  2231.         if (!((~AV_RN64A(src + i) &
  2232.                (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  2233.               0x8000800080008080ULL))
  2234.             continue;
  2235.         FIND_FIRST_ZERO;
  2236.         STARTCODE_TEST;
  2237.         i -= 7;
  2238.     }
  2239. #else
  2240.     for (i = 0; i + 1 < length; i += 5) {
  2241.         if (!((~AV_RN32A(src + i) &
  2242.                (AV_RN32A(src + i) - 0x01000101U)) &
  2243.               0x80008080U))
  2244.             continue;
  2245.         FIND_FIRST_ZERO;
  2246.         STARTCODE_TEST;
  2247.         i -= 3;
  2248.     }
  2249. #endif
  2250. #else
  2251.     for (i = 0; i + 1 < length; i += 2) {
  2252.         if (src[i])
  2253.             continue;
  2254.         if (i > 0 && src[i - 1] == 0)
  2255.             i--;
  2256.         STARTCODE_TEST;
  2257.     }
  2258. #endif
  2259.  
  2260.     if (i >= length - 1) { // no escaped 0
  2261.         nal->data = src;
  2262.         nal->size = length;
  2263.         return length;
  2264.     }
  2265.  
  2266.     av_fast_malloc(&nal->rbsp_buffer, &nal->rbsp_buffer_size,
  2267.                    length + FF_INPUT_BUFFER_PADDING_SIZE);
  2268.     if (!nal->rbsp_buffer)
  2269.         return AVERROR(ENOMEM);
  2270.  
  2271.     dst = nal->rbsp_buffer;
  2272.  
  2273.     memcpy(dst, src, i);
  2274.     si = di = i;
  2275.     while (si + 2 < length) {
  2276.         // remove escapes (very rare 1:2^22)
  2277.         if (src[si + 2] > 3) {
  2278.             dst[di++] = src[si++];
  2279.             dst[di++] = src[si++];
  2280.         } else if (src[si] == 0 && src[si + 1] == 0) {
  2281.             if (src[si + 2] == 3) { // escape
  2282.                 dst[di++] = 0;
  2283.                 dst[di++] = 0;
  2284.                 si       += 3;
  2285.  
  2286.                 s->skipped_bytes++;
  2287.                 if (s->skipped_bytes_pos_size < s->skipped_bytes) {
  2288.                     s->skipped_bytes_pos_size *= 2;
  2289.                     av_reallocp_array(&s->skipped_bytes_pos,
  2290.                             s->skipped_bytes_pos_size,
  2291.                             sizeof(*s->skipped_bytes_pos));
  2292.                     if (!s->skipped_bytes_pos)
  2293.                         return AVERROR(ENOMEM);
  2294.                 }
  2295.                 if (s->skipped_bytes_pos)
  2296.                     s->skipped_bytes_pos[s->skipped_bytes-1] = di - 1;
  2297.                 continue;
  2298.             } else // next start code
  2299.                 goto nsc;
  2300.         }
  2301.  
  2302.         dst[di++] = src[si++];
  2303.     }
  2304.     while (si < length)
  2305.         dst[di++] = src[si++];
  2306. nsc:
  2307.  
  2308.     memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  2309.  
  2310.     nal->data = dst;
  2311.     nal->size = di;
  2312.     return si;
  2313. }
  2314.  
  2315. static int decode_nal_units(HEVCContext *s, const uint8_t *buf, int length)
  2316. {
  2317.     int i, consumed, ret = 0;
  2318.  
  2319.     s->ref = NULL;
  2320.     s->eos = 0;
  2321.  
  2322.     /* split the input packet into NAL units, so we know the upper bound on the
  2323.      * number of slices in the frame */
  2324.     s->nb_nals = 0;
  2325.     while (length >= 4) {
  2326.         HEVCNAL *nal;
  2327.         int extract_length = 0;
  2328.  
  2329.         if (s->is_nalff) {
  2330.             int i;
  2331.             for (i = 0; i < s->nal_length_size; i++)
  2332.                 extract_length = (extract_length << 8) | buf[i];
  2333.             buf    += s->nal_length_size;
  2334.             length -= s->nal_length_size;
  2335.  
  2336.             if (extract_length > length) {
  2337.                 av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit size.\n");
  2338.                 ret = AVERROR_INVALIDDATA;
  2339.                 goto fail;
  2340.             }
  2341.         } else {
  2342.             /* search start code */
  2343.             while (buf[0] != 0 || buf[1] != 0 || buf[2] != 1) {
  2344.                 ++buf;
  2345.                 --length;
  2346.                 if (length < 4) {
  2347.                     av_log(s->avctx, AV_LOG_ERROR, "No start code is found.\n");
  2348.                     ret = AVERROR_INVALIDDATA;
  2349.                     goto fail;
  2350.                 }
  2351.             }
  2352.  
  2353.             buf    += 3;
  2354.             length -= 3;
  2355.         }
  2356.  
  2357.         if (!s->is_nalff)
  2358.             extract_length = length;
  2359.  
  2360.         if (s->nals_allocated < s->nb_nals + 1) {
  2361.             int new_size = s->nals_allocated + 1;
  2362.             HEVCNAL *tmp = av_realloc_array(s->nals, new_size, sizeof(*tmp));
  2363.             if (!tmp) {
  2364.                 ret = AVERROR(ENOMEM);
  2365.                 goto fail;
  2366.             }
  2367.             s->nals = tmp;
  2368.             memset(s->nals + s->nals_allocated, 0, (new_size - s->nals_allocated) * sizeof(*tmp));
  2369.             av_reallocp_array(&s->skipped_bytes_nal, new_size, sizeof(*s->skipped_bytes_nal));
  2370.             av_reallocp_array(&s->skipped_bytes_pos_size_nal, new_size, sizeof(*s->skipped_bytes_pos_size_nal));
  2371.             av_reallocp_array(&s->skipped_bytes_pos_nal, new_size, sizeof(*s->skipped_bytes_pos_nal));
  2372.             s->skipped_bytes_pos_size_nal[s->nals_allocated] = 1024; // initial buffer size
  2373.             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));
  2374.             s->nals_allocated = new_size;
  2375.         }
  2376.         s->skipped_bytes_pos_size = s->skipped_bytes_pos_size_nal[s->nb_nals];
  2377.         s->skipped_bytes_pos = s->skipped_bytes_pos_nal[s->nb_nals];
  2378.         nal = &s->nals[s->nb_nals];
  2379.  
  2380.         consumed = ff_hevc_extract_rbsp(s, buf, extract_length, nal);
  2381.  
  2382.         s->skipped_bytes_nal[s->nb_nals] = s->skipped_bytes;
  2383.         s->skipped_bytes_pos_size_nal[s->nb_nals] = s->skipped_bytes_pos_size;
  2384.         s->skipped_bytes_pos_nal[s->nb_nals++] = s->skipped_bytes_pos;
  2385.  
  2386.  
  2387.         if (consumed < 0) {
  2388.             ret = consumed;
  2389.             goto fail;
  2390.         }
  2391.  
  2392.         ret = init_get_bits8(&s->HEVClc->gb, nal->data, nal->size);
  2393.         if (ret < 0)
  2394.             goto fail;
  2395.         hls_nal_unit(s);
  2396.  
  2397.         if (s->nal_unit_type == NAL_EOS_NUT ||
  2398.             s->nal_unit_type == NAL_EOB_NUT)
  2399.             s->eos = 1;
  2400.  
  2401.         buf    += consumed;
  2402.         length -= consumed;
  2403.     }
  2404.  
  2405.     /* parse the NAL units */
  2406.     for (i = 0; i < s->nb_nals; i++) {
  2407.         int ret;
  2408.         s->skipped_bytes = s->skipped_bytes_nal[i];
  2409.         s->skipped_bytes_pos = s->skipped_bytes_pos_nal[i];
  2410.  
  2411.         ret = decode_nal_unit(s, s->nals[i].data, s->nals[i].size);
  2412.         if (ret < 0) {
  2413.             av_log(s->avctx, AV_LOG_WARNING,
  2414.                    "Error parsing NAL unit #%d.\n", i);
  2415.             if (s->avctx->err_recognition & AV_EF_EXPLODE)
  2416.                 goto fail;
  2417.         }
  2418.     }
  2419.  
  2420. fail:
  2421.     if (s->ref && s->threads_type == FF_THREAD_FRAME)
  2422.         ff_thread_report_progress(&s->ref->tf, INT_MAX, 0);
  2423.  
  2424.     return ret;
  2425. }
  2426.  
  2427. static void print_md5(void *log_ctx, int level,  uint8_t md5[16])
  2428. {
  2429.     int i;
  2430.     for (i = 0; i < 16; i++)
  2431.         av_log(log_ctx, level, "%02"PRIx8, md5[i]);
  2432. }
  2433.  
  2434. static int verify_md5(HEVCContext *s, AVFrame *frame)
  2435. {
  2436.     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
  2437.     int pixel_shift;
  2438.     int i, j;
  2439.  
  2440.     if (!desc)
  2441.         return AVERROR(EINVAL);
  2442.  
  2443.     pixel_shift = desc->comp[0].depth_minus1 > 7;
  2444.  
  2445.     av_log(s->avctx, AV_LOG_DEBUG, "Verifying checksum for frame with POC %d: ",
  2446.            s->poc);
  2447.  
  2448.     /* the checksums are LE, so we have to byteswap for >8bpp formats
  2449.      * on BE arches */
  2450. #if HAVE_BIGENDIAN
  2451.     if (pixel_shift && !s->checksum_buf) {
  2452.         av_fast_malloc(&s->checksum_buf, &s->checksum_buf_size,
  2453.                        FFMAX3(frame->linesize[0], frame->linesize[1],
  2454.                               frame->linesize[2]));
  2455.         if (!s->checksum_buf)
  2456.             return AVERROR(ENOMEM);
  2457.     }
  2458. #endif
  2459.  
  2460.     for (i = 0; frame->data[i]; i++) {
  2461.         int width  = s->avctx->coded_width;
  2462.         int height = s->avctx->coded_height;
  2463.         int w = (i == 1 || i == 2) ? (width  >> desc->log2_chroma_w) : width;
  2464.         int h = (i == 1 || i == 2) ? (height >> desc->log2_chroma_h) : height;
  2465.         uint8_t md5[16];
  2466.  
  2467.         av_md5_init(s->md5_ctx);
  2468.         for (j = 0; j < h; j++) {
  2469.             const uint8_t *src = frame->data[i] + j * frame->linesize[i];
  2470. #if HAVE_BIGENDIAN
  2471.             if (pixel_shift) {
  2472.                 s->dsp.bswap16_buf((uint16_t*)s->checksum_buf,
  2473.                                    (const uint16_t*)src, w);
  2474.                 src = s->checksum_buf;
  2475.             }
  2476. #endif
  2477.             av_md5_update(s->md5_ctx, src, w << pixel_shift);
  2478.         }
  2479.         av_md5_final(s->md5_ctx, md5);
  2480.  
  2481.         if (!memcmp(md5, s->md5[i], 16)) {
  2482.             av_log   (s->avctx, AV_LOG_DEBUG, "plane %d - correct ", i);
  2483.             print_md5(s->avctx, AV_LOG_DEBUG, md5);
  2484.             av_log   (s->avctx, AV_LOG_DEBUG, "; ");
  2485.         } else {
  2486.             av_log   (s->avctx, AV_LOG_ERROR, "mismatching checksum of plane %d - ", i);
  2487.             print_md5(s->avctx, AV_LOG_ERROR, md5);
  2488.             av_log   (s->avctx, AV_LOG_ERROR, " != ");
  2489.             print_md5(s->avctx, AV_LOG_ERROR, s->md5[i]);
  2490.             av_log   (s->avctx, AV_LOG_ERROR, "\n");
  2491.             return AVERROR_INVALIDDATA;
  2492.         }
  2493.     }
  2494.  
  2495.     av_log(s->avctx, AV_LOG_DEBUG, "\n");
  2496.  
  2497.     return 0;
  2498. }
  2499.  
  2500. static int hevc_decode_frame(AVCodecContext *avctx, void *data, int *got_output,
  2501.                              AVPacket *avpkt)
  2502. {
  2503.     int ret;
  2504.     HEVCContext *s = avctx->priv_data;
  2505.  
  2506.     if (!avpkt->size) {
  2507.         ret = ff_hevc_output_frame(s, data, 1);
  2508.         if (ret < 0)
  2509.             return ret;
  2510.  
  2511.         *got_output = ret;
  2512.         return 0;
  2513.     }
  2514.  
  2515.     s->ref = NULL;
  2516.     ret = decode_nal_units(s, avpkt->data, avpkt->size);
  2517.     if (ret < 0)
  2518.         return ret;
  2519.  
  2520.     /* verify the SEI checksum */
  2521.     if (avctx->err_recognition & AV_EF_CRCCHECK && s->is_decoded &&
  2522.         avctx->err_recognition & AV_EF_EXPLODE &&
  2523.         s->is_md5) {
  2524.         ret = verify_md5(s, s->ref->frame);
  2525.         if (ret < 0) {
  2526.             ff_hevc_unref_frame(s, s->ref, ~0);
  2527.             return ret;
  2528.         }
  2529.     }
  2530.     s->is_md5 = 0;
  2531.  
  2532.     if (s->is_decoded) {
  2533.         av_log(avctx, AV_LOG_DEBUG, "Decoded frame with POC %d.\n", s->poc);
  2534.         s->is_decoded = 0;
  2535.     }
  2536.  
  2537.     if (s->output_frame->buf[0]) {
  2538.         av_frame_move_ref(data, s->output_frame);
  2539.         *got_output = 1;
  2540.     }
  2541.  
  2542.     return avpkt->size;
  2543. }
  2544.  
  2545. static int hevc_ref_frame(HEVCContext *s, HEVCFrame *dst, HEVCFrame *src)
  2546. {
  2547.     int ret;
  2548.  
  2549.     ret = ff_thread_ref_frame(&dst->tf, &src->tf);
  2550.     if (ret < 0)
  2551.         return ret;
  2552.  
  2553.     dst->tab_mvf_buf = av_buffer_ref(src->tab_mvf_buf);
  2554.     if (!dst->tab_mvf_buf)
  2555.         goto fail;
  2556.     dst->tab_mvf = src->tab_mvf;
  2557.  
  2558.     dst->rpl_tab_buf = av_buffer_ref(src->rpl_tab_buf);
  2559.     if (!dst->rpl_tab_buf)
  2560.         goto fail;
  2561.     dst->rpl_tab = src->rpl_tab;
  2562.  
  2563.     dst->rpl_buf = av_buffer_ref(src->rpl_buf);
  2564.     if (!dst->rpl_buf)
  2565.         goto fail;
  2566.  
  2567.     dst->poc        = src->poc;
  2568.     dst->ctb_count  = src->ctb_count;
  2569.     dst->window     = src->window;
  2570.     dst->flags      = src->flags;
  2571.     dst->sequence   = src->sequence;
  2572.  
  2573.     return 0;
  2574. fail:
  2575.     ff_hevc_unref_frame(s, dst, ~0);
  2576.     return AVERROR(ENOMEM);
  2577. }
  2578.  
  2579. static av_cold int hevc_decode_free(AVCodecContext *avctx)
  2580. {
  2581.     HEVCContext       *s = avctx->priv_data;
  2582.     HEVCLocalContext *lc = s->HEVClc;
  2583.     int i;
  2584.  
  2585.     pic_arrays_free(s);
  2586.  
  2587.     av_freep(&lc->edge_emu_buffer);
  2588.     av_freep(&s->md5_ctx);
  2589.  
  2590.     for(i=0; i < s->nals_allocated; i++) {
  2591.         av_freep(&s->skipped_bytes_pos_nal[i]);
  2592.     }
  2593.     av_freep(&s->skipped_bytes_pos_size_nal);
  2594.     av_freep(&s->skipped_bytes_nal);
  2595.     av_freep(&s->skipped_bytes_pos_nal);
  2596.  
  2597.     av_freep(&s->cabac_state);
  2598.  
  2599.     av_frame_free(&s->tmp_frame);
  2600.     av_frame_free(&s->output_frame);
  2601.  
  2602.     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
  2603.         ff_hevc_unref_frame(s, &s->DPB[i], ~0);
  2604.         av_frame_free(&s->DPB[i].frame);
  2605.     }
  2606.  
  2607.     for (i = 0; i < FF_ARRAY_ELEMS(s->vps_list); i++)
  2608.         av_freep(&s->vps_list[i]);
  2609.     for (i = 0; i < FF_ARRAY_ELEMS(s->sps_list); i++)
  2610.         av_buffer_unref(&s->sps_list[i]);
  2611.     for (i = 0; i < FF_ARRAY_ELEMS(s->pps_list); i++)
  2612.         av_buffer_unref(&s->pps_list[i]);
  2613.  
  2614.     av_freep(&s->sh.entry_point_offset);
  2615.     av_freep(&s->sh.offset);
  2616.     av_freep(&s->sh.size);
  2617.  
  2618.     for (i = 1; i < s->threads_number; i++) {
  2619.         lc = s->HEVClcList[i];
  2620.         if (lc) {
  2621.             av_freep(&lc->edge_emu_buffer);
  2622.  
  2623.             av_freep(&s->HEVClcList[i]);
  2624.             av_freep(&s->sList[i]);
  2625.         }
  2626.     }
  2627.     av_freep(&s->HEVClcList[0]);
  2628.  
  2629.     for (i = 0; i < s->nals_allocated; i++)
  2630.         av_freep(&s->nals[i].rbsp_buffer);
  2631.     av_freep(&s->nals);
  2632.     s->nals_allocated = 0;
  2633.  
  2634.     return 0;
  2635. }
  2636.  
  2637. static av_cold int hevc_init_context(AVCodecContext *avctx)
  2638. {
  2639.     HEVCContext *s = avctx->priv_data;
  2640.     int i;
  2641.  
  2642.     s->avctx = avctx;
  2643.  
  2644.     s->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
  2645.     if (!s->HEVClc)
  2646.         goto fail;
  2647.     s->HEVClcList[0] = s->HEVClc;
  2648.     s->sList[0] = s;
  2649.  
  2650.     s->cabac_state = av_malloc(HEVC_CONTEXTS);
  2651.     if (!s->cabac_state)
  2652.         goto fail;
  2653.  
  2654.     s->tmp_frame = av_frame_alloc();
  2655.     if (!s->tmp_frame)
  2656.         goto fail;
  2657.  
  2658.     s->output_frame = av_frame_alloc();
  2659.     if (!s->output_frame)
  2660.         goto fail;
  2661.  
  2662.     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
  2663.         s->DPB[i].frame = av_frame_alloc();
  2664.         if (!s->DPB[i].frame)
  2665.             goto fail;
  2666.         s->DPB[i].tf.f = s->DPB[i].frame;
  2667.     }
  2668.  
  2669.     s->max_ra = INT_MAX;
  2670.  
  2671.     s->md5_ctx = av_md5_alloc();
  2672.     if (!s->md5_ctx)
  2673.         goto fail;
  2674.  
  2675.     ff_dsputil_init(&s->dsp, avctx);
  2676.  
  2677.     s->context_initialized = 1;
  2678.  
  2679.     return 0;
  2680. fail:
  2681.     hevc_decode_free(avctx);
  2682.     return AVERROR(ENOMEM);
  2683. }
  2684.  
  2685. static int hevc_update_thread_context(AVCodecContext *dst,
  2686.                                       const AVCodecContext *src)
  2687. {
  2688.     HEVCContext *s  = dst->priv_data;
  2689.     HEVCContext *s0 = src->priv_data;
  2690.     int i, ret;
  2691.  
  2692.     if (!s->context_initialized) {
  2693.         ret = hevc_init_context(dst);
  2694.         if (ret < 0)
  2695.             return ret;
  2696.     }
  2697.  
  2698.     for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
  2699.         ff_hevc_unref_frame(s, &s->DPB[i], ~0);
  2700.         if (s0->DPB[i].frame->buf[0]) {
  2701.             ret = hevc_ref_frame(s, &s->DPB[i], &s0->DPB[i]);
  2702.             if (ret < 0)
  2703.                 return ret;
  2704.         }
  2705.     }
  2706.  
  2707.     for (i = 0; i < FF_ARRAY_ELEMS(s->sps_list); i++) {
  2708.         av_buffer_unref(&s->sps_list[i]);
  2709.         if (s0->sps_list[i]) {
  2710.             s->sps_list[i] = av_buffer_ref(s0->sps_list[i]);
  2711.             if (!s->sps_list[i])
  2712.                 return AVERROR(ENOMEM);
  2713.         }
  2714.     }
  2715.  
  2716.     for (i = 0; i < FF_ARRAY_ELEMS(s->pps_list); i++) {
  2717.         av_buffer_unref(&s->pps_list[i]);
  2718.         if (s0->pps_list[i]) {
  2719.             s->pps_list[i] = av_buffer_ref(s0->pps_list[i]);
  2720.             if (!s->pps_list[i])
  2721.                 return AVERROR(ENOMEM);
  2722.         }
  2723.     }
  2724.  
  2725.     s->seq_decode = s0->seq_decode;
  2726.     s->seq_output = s0->seq_output;
  2727.     s->pocTid0    = s0->pocTid0;
  2728.     s->max_ra     = s0->max_ra;
  2729.  
  2730.     s->is_nalff        = s0->is_nalff;
  2731.     s->nal_length_size = s0->nal_length_size;
  2732.  
  2733.     s->threads_number      = s0->threads_number;
  2734.     s->threads_type        = s0->threads_type;
  2735.  
  2736.     if (s0->eos) {
  2737.         s->seq_decode = (s->seq_decode + 1) & 0xff;
  2738.         s->max_ra = INT_MAX;
  2739.     }
  2740.  
  2741.     return 0;
  2742. }
  2743.  
  2744. static int hevc_decode_extradata(HEVCContext *s)
  2745. {
  2746.     AVCodecContext *avctx = s->avctx;
  2747.     GetByteContext gb;
  2748.     int ret;
  2749.  
  2750.     bytestream2_init(&gb, avctx->extradata, avctx->extradata_size);
  2751.  
  2752.     if (avctx->extradata_size > 3 &&
  2753.         (avctx->extradata[0] || avctx->extradata[1] ||
  2754.          avctx->extradata[2] > 1)) {
  2755.         /* It seems the extradata is encoded as hvcC format.
  2756.          * Temporarily, we support configurationVersion==0 until 14496-15 3rd finalized.
  2757.          * When finalized, configurationVersion will be 1 and we can recognize hvcC by
  2758.          * checking if avctx->extradata[0]==1 or not. */
  2759.         int i, j, num_arrays;
  2760.         int nal_len_size;
  2761.  
  2762.         s->is_nalff = 1;
  2763.  
  2764.         bytestream2_skip(&gb, 21);
  2765.         nal_len_size = (bytestream2_get_byte(&gb) & 3) + 1;
  2766.         num_arrays   = bytestream2_get_byte(&gb);
  2767.  
  2768.         /* nal units in the hvcC always have length coded with 2 bytes,
  2769.          * so put a fake nal_length_size = 2 while parsing them */
  2770.         s->nal_length_size = 2;
  2771.  
  2772.         /* Decode nal units from hvcC. */
  2773.         for (i = 0; i < num_arrays; i++) {
  2774.             int type = bytestream2_get_byte(&gb) & 0x3f;
  2775.             int cnt  = bytestream2_get_be16(&gb);
  2776.  
  2777.             for (j = 0; j < cnt; j++) {
  2778.                 // +2 for the nal size field
  2779.                 int nalsize = bytestream2_peek_be16(&gb) + 2;
  2780.                 if (bytestream2_get_bytes_left(&gb) < nalsize) {
  2781.                     av_log(s->avctx, AV_LOG_ERROR,
  2782.                            "Invalid NAL unit size in extradata.\n");
  2783.                     return AVERROR_INVALIDDATA;
  2784.                 }
  2785.  
  2786.                 ret = decode_nal_units(s, gb.buffer, nalsize);
  2787.                 if (ret < 0) {
  2788.                     av_log(avctx, AV_LOG_ERROR,
  2789.                            "Decoding nal unit %d %d from hvcC failed\n", type, i);
  2790.                     return ret;
  2791.                 }
  2792.                 bytestream2_skip(&gb, nalsize);
  2793.             }
  2794.         }
  2795.  
  2796.         /* Now store right nal length size, that will be used to parse all other nals */
  2797.         s->nal_length_size = nal_len_size;
  2798.     } else {
  2799.         s->is_nalff = 0;
  2800.         ret = decode_nal_units(s, avctx->extradata, avctx->extradata_size);
  2801.         if (ret < 0)
  2802.             return ret;
  2803.     }
  2804.     return 0;
  2805. }
  2806.  
  2807. static av_cold int hevc_decode_init(AVCodecContext *avctx)
  2808. {
  2809.     HEVCContext *s = avctx->priv_data;
  2810.     int ret;
  2811.  
  2812.     ff_init_cabac_states();
  2813.  
  2814.     avctx->internal->allocate_progress = 1;
  2815.  
  2816.     ret = hevc_init_context(avctx);
  2817.     if (ret < 0)
  2818.         return ret;
  2819.  
  2820.     s->enable_parallel_tiles = 0;
  2821.  
  2822.     if(avctx->active_thread_type & FF_THREAD_SLICE)
  2823.         s->threads_number = avctx->thread_count;
  2824.     else
  2825.         s->threads_number = 1;
  2826.  
  2827.     if (avctx->extradata_size > 0 && avctx->extradata) {
  2828.         ret = hevc_decode_extradata(s);
  2829.         if (ret < 0) {
  2830.             hevc_decode_free(avctx);
  2831.             return ret;
  2832.         }
  2833.     }
  2834.  
  2835.     if((avctx->active_thread_type & FF_THREAD_FRAME) && avctx->thread_count > 1)
  2836.             s->threads_type = FF_THREAD_FRAME;
  2837.         else
  2838.             s->threads_type = FF_THREAD_SLICE;
  2839.  
  2840.     return 0;
  2841. }
  2842.  
  2843. static av_cold int hevc_init_thread_copy(AVCodecContext *avctx)
  2844. {
  2845.     HEVCContext *s = avctx->priv_data;
  2846.     int ret;
  2847.  
  2848.     memset(s, 0, sizeof(*s));
  2849.  
  2850.     ret = hevc_init_context(avctx);
  2851.     if (ret < 0)
  2852.         return ret;
  2853.  
  2854.     return 0;
  2855. }
  2856.  
  2857. static void hevc_decode_flush(AVCodecContext *avctx)
  2858. {
  2859.     HEVCContext *s = avctx->priv_data;
  2860.     ff_hevc_flush_dpb(s);
  2861.     s->max_ra = INT_MAX;
  2862. }
  2863.  
  2864. #define OFFSET(x) offsetof(HEVCContext, x)
  2865. #define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_VIDEO_PARAM)
  2866. static const AVOption options[] = {
  2867.     { "strict-displaywin", "stricly apply default display window size", OFFSET(strict_def_disp_win),
  2868.         AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, PAR },
  2869.     { NULL },
  2870. };
  2871.  
  2872. static const AVClass hevc_decoder_class = {
  2873.     .class_name = "HEVC decoder",
  2874.     .item_name  = av_default_item_name,
  2875.     .option     = options,
  2876.     .version    = LIBAVUTIL_VERSION_INT,
  2877. };
  2878.  
  2879. AVCodec ff_hevc_decoder = {
  2880.     .name                  = "hevc",
  2881.     .long_name             = NULL_IF_CONFIG_SMALL("HEVC (High Efficiency Video Coding)"),
  2882.     .type                  = AVMEDIA_TYPE_VIDEO,
  2883.     .id                    = AV_CODEC_ID_HEVC,
  2884.     .priv_data_size        = sizeof(HEVCContext),
  2885.     .priv_class            = &hevc_decoder_class,
  2886.     .init                  = hevc_decode_init,
  2887.     .close                 = hevc_decode_free,
  2888.     .decode                = hevc_decode_frame,
  2889.     .flush                 = hevc_decode_flush,
  2890.     .update_thread_context = hevc_update_thread_context,
  2891.     .init_thread_copy      = hevc_init_thread_copy,
  2892.     .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS,
  2893. };
  2894.