+static void h265_metadata_guess_level(AVBSFContext *bsf,
+ const CodedBitstreamFragment *au)
+{
+ H265MetadataContext *ctx = bsf->priv_data;
+ const H265LevelDescriptor *desc;
+ const H265RawProfileTierLevel *ptl = NULL;
+ const H265RawHRDParameters *hrd = NULL;
+ int64_t bit_rate = 0;
+ int width = 0, height = 0;
+ int tile_cols = 0, tile_rows = 0;
+ int max_dec_pic_buffering = 0;
+ int i;
+
+ for (i = 0; i < au->nb_units; i++) {
+ const CodedBitstreamUnit *unit = &au->units[i];
+
+ if (unit->type == HEVC_NAL_VPS) {
+ const H265RawVPS *vps = unit->content;
+
+ ptl = &vps->profile_tier_level;
+ max_dec_pic_buffering = vps->vps_max_dec_pic_buffering_minus1[0] + 1;
+
+ if (vps->vps_num_hrd_parameters > 0)
+ hrd = &vps->hrd_parameters[0];
+
+ } else if (unit->type == HEVC_NAL_SPS) {
+ const H265RawSPS *sps = unit->content;
+
+ ptl = &sps->profile_tier_level;
+ max_dec_pic_buffering = sps->sps_max_dec_pic_buffering_minus1[0] + 1;
+
+ width = sps->pic_width_in_luma_samples;
+ height = sps->pic_height_in_luma_samples;
+
+ if (sps->vui.vui_hrd_parameters_present_flag)
+ hrd = &sps->vui.hrd_parameters;
+
+ } else if (unit->type == HEVC_NAL_PPS) {
+ const H265RawPPS *pps = unit->content;
+
+ if (pps->tiles_enabled_flag) {
+ tile_cols = pps->num_tile_columns_minus1 + 1;
+ tile_rows = pps->num_tile_rows_minus1 + 1;
+ }
+ }
+ }
+
+ if (hrd) {
+ if (hrd->nal_hrd_parameters_present_flag) {
+ bit_rate = (hrd->nal_sub_layer_hrd_parameters[0].bit_rate_value_minus1[0] + 1) *
+ (INT64_C(1) << hrd->bit_rate_scale + 6);
+ } else if (hrd->vcl_hrd_parameters_present_flag) {
+ bit_rate = (hrd->vcl_sub_layer_hrd_parameters[0].bit_rate_value_minus1[0] + 1) *
+ (INT64_C(1) << hrd->bit_rate_scale + 6);
+ // Adjust for VCL vs. NAL limits.
+ bit_rate = bit_rate * 11 / 10;
+ }
+ }
+
+ desc = ff_h265_guess_level(ptl, bit_rate, width, height,
+ 0, tile_rows, tile_cols,
+ max_dec_pic_buffering);
+ if (desc) {
+ av_log(bsf, AV_LOG_DEBUG, "Stream appears to conform to "
+ "level %s.\n", desc->name);
+ ctx->level_guess = desc->level_idc;
+ }
+}
+
+static void h265_metadata_update_level(AVBSFContext *bsf,
+ uint8_t *level_idc)
+{
+ H265MetadataContext *ctx = bsf->priv_data;
+
+ if (ctx->level != LEVEL_UNSET) {
+ if (ctx->level == LEVEL_AUTO) {
+ if (ctx->level_guess) {
+ *level_idc = ctx->level_guess;
+ } else {
+ if (!ctx->level_warned) {
+ av_log(bsf, AV_LOG_WARNING, "Unable to determine level "
+ "of stream: using level 8.5.\n");
+ ctx->level_warned = 1;
+ }
+ *level_idc = 255;
+ }
+ } else {
+ *level_idc = ctx->level;
+ }
+ }
+}
+