1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18 
19 #include "libavutil/common.h"
20 #include "libavutil/opt.h"
21 
22 #include "bsf.h"
23 #include "bsf_internal.h"
24 #include "cbs.h"
25 #include "cbs_bsf.h"
26 #include "cbs_h265.h"
27 #include "hevc.h"
28 #include "h265_profile_level.h"
29 
30 enum {
31     LEVEL_UNSET = -2,
32     LEVEL_AUTO  = -1,
33 };
34 
35 typedef struct H265MetadataContext {
36     CBSBSFContext common;
37 
38     H265RawAUD aud_nal;
39 
40     int aud;
41 
42     AVRational sample_aspect_ratio;
43 
44     int video_format;
45     int video_full_range_flag;
46     int colour_primaries;
47     int transfer_characteristics;
48     int matrix_coefficients;
49 
50     int chroma_sample_loc_type;
51 
52     AVRational tick_rate;
53     int poc_proportional_to_timing_flag;
54     int num_ticks_poc_diff_one;
55 
56     int crop_left;
57     int crop_right;
58     int crop_top;
59     int crop_bottom;
60 
61     int level;
62     int level_guess;
63     int level_warned;
64 } H265MetadataContext;
65 
66 
h265_metadata_guess_level(AVBSFContext *bsf, const CodedBitstreamFragment *au)67 static void h265_metadata_guess_level(AVBSFContext *bsf,
68                                       const CodedBitstreamFragment *au)
69 {
70     H265MetadataContext *ctx = bsf->priv_data;
71     const H265LevelDescriptor *desc;
72     const H265RawProfileTierLevel *ptl = NULL;
73     const H265RawHRDParameters    *hrd = NULL;
74     int64_t bit_rate = 0;
75     int width = 0, height = 0;
76     int tile_cols = 0, tile_rows = 0;
77     int max_dec_pic_buffering = 0;
78     int i;
79 
80     for (i = 0; i < au->nb_units; i++) {
81         const CodedBitstreamUnit *unit = &au->units[i];
82 
83         if (unit->type == HEVC_NAL_VPS) {
84             const H265RawVPS *vps = unit->content;
85 
86             ptl = &vps->profile_tier_level;
87             max_dec_pic_buffering = vps->vps_max_dec_pic_buffering_minus1[0] + 1;
88 
89             if (vps->vps_num_hrd_parameters > 0)
90                 hrd = &vps->hrd_parameters[0];
91 
92         } else if (unit->type == HEVC_NAL_SPS) {
93             const H265RawSPS *sps = unit->content;
94 
95             ptl = &sps->profile_tier_level;
96             max_dec_pic_buffering = sps->sps_max_dec_pic_buffering_minus1[0] + 1;
97 
98             width  = sps->pic_width_in_luma_samples;
99             height = sps->pic_height_in_luma_samples;
100 
101             if (sps->vui.vui_hrd_parameters_present_flag)
102                 hrd = &sps->vui.hrd_parameters;
103 
104         } else if (unit->type == HEVC_NAL_PPS) {
105             const H265RawPPS *pps = unit->content;
106 
107             if (pps->tiles_enabled_flag) {
108                 tile_cols = pps->num_tile_columns_minus1 + 1;
109                 tile_rows = pps->num_tile_rows_minus1 + 1;
110             }
111         }
112     }
113 
114     if (hrd) {
115         if (hrd->nal_hrd_parameters_present_flag) {
116             bit_rate = (hrd->nal_sub_layer_hrd_parameters[0].bit_rate_value_minus1[0] + 1) *
117                        (INT64_C(1) << hrd->bit_rate_scale + 6);
118         } else if (hrd->vcl_hrd_parameters_present_flag) {
119             bit_rate = (hrd->vcl_sub_layer_hrd_parameters[0].bit_rate_value_minus1[0] + 1) *
120                        (INT64_C(1) << hrd->bit_rate_scale + 6);
121             // Adjust for VCL vs. NAL limits.
122             bit_rate = bit_rate * 11 / 10;
123         }
124     }
125 
126     desc = ff_h265_guess_level(ptl, bit_rate, width, height,
127                                0, tile_rows, tile_cols,
128                                max_dec_pic_buffering);
129     if (desc) {
130         av_log(bsf, AV_LOG_DEBUG, "Stream appears to conform to "
131                "level %s.\n", desc->name);
132         ctx->level_guess = desc->level_idc;
133     }
134 }
135 
h265_metadata_update_level(AVBSFContext *bsf, uint8_t *level_idc)136 static void h265_metadata_update_level(AVBSFContext *bsf,
137                                        uint8_t *level_idc)
138 {
139     H265MetadataContext *ctx = bsf->priv_data;
140 
141     if (ctx->level != LEVEL_UNSET) {
142         if (ctx->level == LEVEL_AUTO) {
143             if (ctx->level_guess) {
144                 *level_idc = ctx->level_guess;
145             } else {
146                 if (!ctx->level_warned) {
147                     av_log(bsf, AV_LOG_WARNING, "Unable to determine level "
148                            "of stream: using level 8.5.\n");
149                     ctx->level_warned = 1;
150                 }
151                 *level_idc = 255;
152             }
153         } else {
154             *level_idc = ctx->level;
155         }
156     }
157 }
158 
h265_metadata_update_vps(AVBSFContext *bsf, H265RawVPS *vps)159 static int h265_metadata_update_vps(AVBSFContext *bsf,
160                                     H265RawVPS *vps)
161 {
162     H265MetadataContext *ctx = bsf->priv_data;
163 
164     if (ctx->tick_rate.num && ctx->tick_rate.den) {
165         int num, den;
166 
167         av_reduce(&num, &den, ctx->tick_rate.num, ctx->tick_rate.den,
168                   UINT32_MAX > INT_MAX ? UINT32_MAX : INT_MAX);
169 
170         vps->vps_time_scale        = num;
171         vps->vps_num_units_in_tick = den;
172 
173         vps->vps_timing_info_present_flag = 1;
174 
175         if (ctx->num_ticks_poc_diff_one > 0) {
176             vps->vps_num_ticks_poc_diff_one_minus1 =
177                 ctx->num_ticks_poc_diff_one - 1;
178             vps->vps_poc_proportional_to_timing_flag = 1;
179         } else if (ctx->num_ticks_poc_diff_one == 0) {
180             vps->vps_poc_proportional_to_timing_flag = 0;
181         }
182     }
183 
184     h265_metadata_update_level(bsf, &vps->profile_tier_level.general_level_idc);
185 
186     return 0;
187 }
188 
h265_metadata_update_sps(AVBSFContext *bsf, H265RawSPS *sps)189 static int h265_metadata_update_sps(AVBSFContext *bsf,
190                                     H265RawSPS *sps)
191 {
192     H265MetadataContext *ctx = bsf->priv_data;
193     int need_vui = 0;
194     int crop_unit_x, crop_unit_y;
195 
196     if (ctx->sample_aspect_ratio.num && ctx->sample_aspect_ratio.den) {
197         // Table E-1.
198         static const AVRational sar_idc[] = {
199             {   0,  0 }, // Unspecified (never written here).
200             {   1,  1 }, {  12, 11 }, {  10, 11 }, {  16, 11 },
201             {  40, 33 }, {  24, 11 }, {  20, 11 }, {  32, 11 },
202             {  80, 33 }, {  18, 11 }, {  15, 11 }, {  64, 33 },
203             { 160, 99 }, {   4,  3 }, {   3,  2 }, {   2,  1 },
204         };
205         int num, den, i;
206 
207         av_reduce(&num, &den, ctx->sample_aspect_ratio.num,
208                   ctx->sample_aspect_ratio.den, 65535);
209 
210         for (i = 1; i < FF_ARRAY_ELEMS(sar_idc); i++) {
211             if (num == sar_idc[i].num &&
212                 den == sar_idc[i].den)
213                 break;
214         }
215         if (i == FF_ARRAY_ELEMS(sar_idc)) {
216             sps->vui.aspect_ratio_idc = 255;
217             sps->vui.sar_width  = num;
218             sps->vui.sar_height = den;
219         } else {
220             sps->vui.aspect_ratio_idc = i;
221         }
222         sps->vui.aspect_ratio_info_present_flag = 1;
223         need_vui = 1;
224     }
225 
226 #define SET_OR_INFER(field, value, present_flag, infer) do { \
227         if (value >= 0) { \
228             field = value; \
229             need_vui = 1; \
230         } else if (!present_flag) \
231             field = infer; \
232     } while (0)
233 
234     if (ctx->video_format             >= 0 ||
235         ctx->video_full_range_flag    >= 0 ||
236         ctx->colour_primaries         >= 0 ||
237         ctx->transfer_characteristics >= 0 ||
238         ctx->matrix_coefficients      >= 0) {
239 
240         SET_OR_INFER(sps->vui.video_format, ctx->video_format,
241                      sps->vui.video_signal_type_present_flag, 5);
242 
243         SET_OR_INFER(sps->vui.video_full_range_flag,
244                      ctx->video_full_range_flag,
245                      sps->vui.video_signal_type_present_flag, 0);
246 
247         if (ctx->colour_primaries         >= 0 ||
248             ctx->transfer_characteristics >= 0 ||
249             ctx->matrix_coefficients      >= 0) {
250 
251             SET_OR_INFER(sps->vui.colour_primaries,
252                          ctx->colour_primaries,
253                          sps->vui.colour_description_present_flag, 2);
254 
255             SET_OR_INFER(sps->vui.transfer_characteristics,
256                          ctx->transfer_characteristics,
257                          sps->vui.colour_description_present_flag, 2);
258 
259             SET_OR_INFER(sps->vui.matrix_coefficients,
260                          ctx->matrix_coefficients,
261                          sps->vui.colour_description_present_flag, 2);
262 
263             sps->vui.colour_description_present_flag = 1;
264         }
265         sps->vui.video_signal_type_present_flag = 1;
266         need_vui = 1;
267     }
268 
269     if (ctx->chroma_sample_loc_type >= 0) {
270         sps->vui.chroma_sample_loc_type_top_field =
271             ctx->chroma_sample_loc_type;
272         sps->vui.chroma_sample_loc_type_bottom_field =
273             ctx->chroma_sample_loc_type;
274         sps->vui.chroma_loc_info_present_flag = 1;
275         need_vui = 1;
276     }
277 
278     if (ctx->tick_rate.num && ctx->tick_rate.den) {
279         int num, den;
280 
281         av_reduce(&num, &den, ctx->tick_rate.num, ctx->tick_rate.den,
282                   UINT32_MAX > INT_MAX ? UINT32_MAX : INT_MAX);
283 
284         sps->vui.vui_time_scale        = num;
285         sps->vui.vui_num_units_in_tick = den;
286 
287         sps->vui.vui_timing_info_present_flag = 1;
288         need_vui = 1;
289 
290         if (ctx->num_ticks_poc_diff_one > 0) {
291             sps->vui.vui_num_ticks_poc_diff_one_minus1 =
292                 ctx->num_ticks_poc_diff_one - 1;
293             sps->vui.vui_poc_proportional_to_timing_flag = 1;
294         } else if (ctx->num_ticks_poc_diff_one == 0) {
295             sps->vui.vui_poc_proportional_to_timing_flag = 0;
296         }
297     }
298 
299     if (sps->separate_colour_plane_flag || sps->chroma_format_idc == 0) {
300         crop_unit_x = 1;
301         crop_unit_y = 1;
302     } else {
303         crop_unit_x = 1 + (sps->chroma_format_idc < 3);
304         crop_unit_y = 1 + (sps->chroma_format_idc < 2);
305     }
306 #define CROP(border, unit) do { \
307         if (ctx->crop_ ## border >= 0) { \
308             if (ctx->crop_ ## border % unit != 0) { \
309                 av_log(bsf, AV_LOG_ERROR, "Invalid value for crop_%s: " \
310                        "must be a multiple of %d.\n", #border, unit); \
311                 return AVERROR(EINVAL); \
312             } \
313             sps->conf_win_ ## border ## _offset = \
314                 ctx->crop_ ## border / unit; \
315             sps->conformance_window_flag = 1; \
316         } \
317     } while (0)
318     CROP(left,   crop_unit_x);
319     CROP(right,  crop_unit_x);
320     CROP(top,    crop_unit_y);
321     CROP(bottom, crop_unit_y);
322 #undef CROP
323 
324     if (need_vui)
325         sps->vui_parameters_present_flag = 1;
326 
327     h265_metadata_update_level(bsf, &sps->profile_tier_level.general_level_idc);
328 
329     return 0;
330 }
331 
h265_metadata_update_fragment(AVBSFContext *bsf, AVPacket *pkt, CodedBitstreamFragment *au)332 static int h265_metadata_update_fragment(AVBSFContext *bsf, AVPacket *pkt,
333                                          CodedBitstreamFragment *au)
334 {
335     H265MetadataContext *ctx = bsf->priv_data;
336     int err, i;
337 
338     // If an AUD is present, it must be the first NAL unit.
339     if (au->nb_units && au->units[0].type == HEVC_NAL_AUD) {
340         if (ctx->aud == BSF_ELEMENT_REMOVE)
341             ff_cbs_delete_unit(au, 0);
342     } else {
343         if (pkt && ctx->aud == BSF_ELEMENT_INSERT) {
344             H265RawAUD *aud = &ctx->aud_nal;
345             int pic_type = 0, temporal_id = 8, layer_id = 0;
346 
347             for (i = 0; i < au->nb_units; i++) {
348                 const H265RawNALUnitHeader *nal = au->units[i].content;
349                 if (!nal)
350                     continue;
351                 if (nal->nuh_temporal_id_plus1 < temporal_id + 1)
352                     temporal_id = nal->nuh_temporal_id_plus1 - 1;
353 
354                 if (au->units[i].type <= HEVC_NAL_RSV_VCL31) {
355                     const H265RawSlice *slice = au->units[i].content;
356                     layer_id = nal->nuh_layer_id;
357                     if (slice->header.slice_type == HEVC_SLICE_B &&
358                         pic_type < 2)
359                         pic_type = 2;
360                     if (slice->header.slice_type == HEVC_SLICE_P &&
361                         pic_type < 1)
362                         pic_type = 1;
363                 }
364             }
365 
366             aud->nal_unit_header = (H265RawNALUnitHeader) {
367                 .nal_unit_type         = HEVC_NAL_AUD,
368                 .nuh_layer_id          = layer_id,
369                 .nuh_temporal_id_plus1 = temporal_id + 1,
370             };
371             aud->pic_type = pic_type;
372 
373             err = ff_cbs_insert_unit_content(au, 0, HEVC_NAL_AUD, aud, NULL);
374             if (err < 0) {
375                 av_log(bsf, AV_LOG_ERROR, "Failed to insert AUD.\n");
376                 return err;
377             }
378         }
379     }
380 
381     if (ctx->level == LEVEL_AUTO && !ctx->level_guess)
382         h265_metadata_guess_level(bsf, au);
383 
384     for (i = 0; i < au->nb_units; i++) {
385         if (au->units[i].type == HEVC_NAL_VPS) {
386             err = h265_metadata_update_vps(bsf, au->units[i].content);
387             if (err < 0)
388                 return err;
389         }
390         if (au->units[i].type == HEVC_NAL_SPS) {
391             err = h265_metadata_update_sps(bsf, au->units[i].content);
392             if (err < 0)
393                 return err;
394         }
395     }
396 
397     return 0;
398 }
399 
400 static const CBSBSFType h265_metadata_type = {
401     .codec_id        = AV_CODEC_ID_HEVC,
402     .fragment_name   = "access unit",
403     .unit_name       = "NAL unit",
404     .update_fragment = &h265_metadata_update_fragment,
405 };
406 
h265_metadata_init(AVBSFContext *bsf)407 static int h265_metadata_init(AVBSFContext *bsf)
408 {
409     return ff_cbs_bsf_generic_init(bsf, &h265_metadata_type);
410 }
411 
412 #define OFFSET(x) offsetof(H265MetadataContext, x)
413 #define FLAGS (AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_BSF_PARAM)
414 static const AVOption h265_metadata_options[] = {
415     BSF_ELEMENT_OPTIONS_PIR("aud", "Access Unit Delimiter NAL units",
416                             aud, FLAGS),
417 
418     { "sample_aspect_ratio", "Set sample aspect ratio (table E-1)",
419         OFFSET(sample_aspect_ratio), AV_OPT_TYPE_RATIONAL,
420         { .dbl = 0.0 }, 0, 65535, FLAGS },
421 
422     { "video_format", "Set video format (table E-2)",
423         OFFSET(video_format), AV_OPT_TYPE_INT,
424         { .i64 = -1 }, -1, 7, FLAGS },
425     { "video_full_range_flag", "Set video full range flag",
426         OFFSET(video_full_range_flag), AV_OPT_TYPE_INT,
427         { .i64 = -1 }, -1, 1, FLAGS },
428     { "colour_primaries", "Set colour primaries (table E-3)",
429         OFFSET(colour_primaries), AV_OPT_TYPE_INT,
430         { .i64 = -1 }, -1, 255, FLAGS },
431     { "transfer_characteristics", "Set transfer characteristics (table E-4)",
432         OFFSET(transfer_characteristics), AV_OPT_TYPE_INT,
433         { .i64 = -1 }, -1, 255, FLAGS },
434     { "matrix_coefficients", "Set matrix coefficients (table E-5)",
435         OFFSET(matrix_coefficients), AV_OPT_TYPE_INT,
436         { .i64 = -1 }, -1, 255, FLAGS },
437 
438     { "chroma_sample_loc_type", "Set chroma sample location type (figure E-1)",
439         OFFSET(chroma_sample_loc_type), AV_OPT_TYPE_INT,
440         { .i64 = -1 }, -1, 5, FLAGS },
441 
442     { "tick_rate",
443         "Set VPS and VUI tick rate (time_scale / num_units_in_tick)",
444         OFFSET(tick_rate), AV_OPT_TYPE_RATIONAL,
445         { .dbl = 0.0 }, 0, UINT_MAX, FLAGS },
446     { "num_ticks_poc_diff_one",
447         "Set VPS and VUI number of ticks per POC increment",
448         OFFSET(num_ticks_poc_diff_one), AV_OPT_TYPE_INT,
449         { .i64 = -1 }, -1, INT_MAX, FLAGS },
450 
451     { "crop_left", "Set left border crop offset",
452         OFFSET(crop_left), AV_OPT_TYPE_INT,
453         { .i64 = -1 }, -1, HEVC_MAX_WIDTH, FLAGS },
454     { "crop_right", "Set right border crop offset",
455         OFFSET(crop_right), AV_OPT_TYPE_INT,
456         { .i64 = -1 }, -1, HEVC_MAX_WIDTH, FLAGS },
457     { "crop_top", "Set top border crop offset",
458         OFFSET(crop_top), AV_OPT_TYPE_INT,
459         { .i64 = -1 }, -1, HEVC_MAX_HEIGHT, FLAGS },
460     { "crop_bottom", "Set bottom border crop offset",
461         OFFSET(crop_bottom), AV_OPT_TYPE_INT,
462         { .i64 = -1 }, -1, HEVC_MAX_HEIGHT, FLAGS },
463 
464     { "level", "Set level (tables A.6 and A.7)",
465         OFFSET(level), AV_OPT_TYPE_INT,
466         { .i64 = LEVEL_UNSET }, LEVEL_UNSET, 0xff, FLAGS, "level" },
467     { "auto", "Attempt to guess level from stream properties",
468         0, AV_OPT_TYPE_CONST,
469         { .i64 = LEVEL_AUTO }, .flags = FLAGS, .unit = "level" },
470 #define LEVEL(name, value) name, NULL, 0, AV_OPT_TYPE_CONST, \
471         { .i64 = value },      .flags = FLAGS, .unit = "level"
472     { LEVEL("1",    30) },
473     { LEVEL("2",    60) },
474     { LEVEL("2.1",  63) },
475     { LEVEL("3",    90) },
476     { LEVEL("3.1",  93) },
477     { LEVEL("4",   120) },
478     { LEVEL("4.1", 123) },
479     { LEVEL("5",   150) },
480     { LEVEL("5.1", 153) },
481     { LEVEL("5.2", 156) },
482     { LEVEL("6",   180) },
483     { LEVEL("6.1", 183) },
484     { LEVEL("6.2", 186) },
485     { LEVEL("8.5", 255) },
486 #undef LEVEL
487 
488     { NULL }
489 };
490 
491 static const AVClass h265_metadata_class = {
492     .class_name = "h265_metadata_bsf",
493     .item_name  = av_default_item_name,
494     .option     = h265_metadata_options,
495     .version    = LIBAVUTIL_VERSION_INT,
496 };
497 
498 static const enum AVCodecID h265_metadata_codec_ids[] = {
499     AV_CODEC_ID_HEVC, AV_CODEC_ID_NONE,
500 };
501 
502 const FFBitStreamFilter ff_hevc_metadata_bsf = {
503     .p.name         = "hevc_metadata",
504     .p.codec_ids    = h265_metadata_codec_ids,
505     .p.priv_class   = &h265_metadata_class,
506     .priv_data_size = sizeof(H265MetadataContext),
507     .init           = &h265_metadata_init,
508     .close          = &ff_cbs_bsf_generic_close,
509     .filter         = &ff_cbs_bsf_generic_filter,
510 };
511