h264_metadata: Fix double-free
[libav.git] / libavcodec / h264_metadata_bsf.c
CommitLineData
9e93001b
MT
1/*
2 * This file is part of Libav.
3 *
4 * Libav 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 * Libav 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 Libav; 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/avstring.h"
20#include "libavutil/common.h"
21#include "libavutil/opt.h"
22
23#include "bsf.h"
24#include "cbs.h"
25#include "cbs_h264.h"
26#include "h264.h"
27#include "h264_sei.h"
28
29enum {
30 PASS,
31 INSERT,
32 REMOVE,
33};
34
35typedef struct H264MetadataContext {
36 const AVClass *class;
37
38 CodedBitstreamContext cbc;
39 CodedBitstreamFragment access_unit;
40
41 H264RawAUD aud_nal;
42 H264RawSEI sei_nal;
43
44 int aud;
45
46 AVRational sample_aspect_ratio;
47
48 int video_format;
49 int video_full_range_flag;
50 int colour_primaries;
51 int transfer_characteristics;
52 int matrix_coefficients;
53
54 int chroma_sample_loc_type;
55
56 AVRational tick_rate;
57 int fixed_frame_rate_flag;
58
59 int crop_left;
60 int crop_right;
61 int crop_top;
62 int crop_bottom;
63
64 const char *sei_user_data;
65} H264MetadataContext;
66
67
68static int h264_metadata_update_sps(AVBSFContext *bsf,
69 H264RawSPS *sps)
70{
71 H264MetadataContext *ctx = bsf->priv_data;
72 int need_vui = 0;
73 int crop_unit_x, crop_unit_y;
74
75 if (ctx->sample_aspect_ratio.num && ctx->sample_aspect_ratio.den) {
76 // Table E-1.
77 static const AVRational sar_idc[] = {
78 { 0, 0 }, // Unspecified (never written here).
79 { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
80 { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
81 { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
82 { 160, 99 }, { 4, 3 }, { 3, 2 }, { 2, 1 },
83 };
84 int num, den, i;
85
86 av_reduce(&num, &den, ctx->sample_aspect_ratio.num,
87 ctx->sample_aspect_ratio.den, 65535);
88
89 for (i = 1; i < FF_ARRAY_ELEMS(sar_idc); i++) {
90 if (num == sar_idc[i].num &&
91 den == sar_idc[i].den)
92 break;
93 }
94 if (i == FF_ARRAY_ELEMS(sar_idc)) {
95 sps->vui.aspect_ratio_idc = 255;
96 sps->vui.sar_width = num;
97 sps->vui.sar_height = den;
98 } else {
99 sps->vui.aspect_ratio_idc = i;
100 }
101 sps->vui.aspect_ratio_info_present_flag = 1;
102 need_vui = 1;
103 }
104
105#define SET_OR_INFER(field, value, present_flag, infer) do { \
106 if (value >= 0) { \
107 field = value; \
108 need_vui = 1; \
109 } else if (!present_flag) \
110 field = infer; \
111 } while (0)
112
113 if (ctx->video_format >= 0 ||
114 ctx->video_full_range_flag >= 0 ||
115 ctx->colour_primaries >= 0 ||
116 ctx->transfer_characteristics >= 0 ||
117 ctx->matrix_coefficients >= 0) {
118
119 SET_OR_INFER(sps->vui.video_format, ctx->video_format,
120 sps->vui.video_signal_type_present_flag, 5);
121
122 SET_OR_INFER(sps->vui.video_full_range_flag,
123 ctx->video_full_range_flag,
124 sps->vui.video_signal_type_present_flag, 0);
125
126 if (ctx->colour_primaries >= 0 ||
127 ctx->transfer_characteristics >= 0 ||
128 ctx->matrix_coefficients >= 0) {
129
130 SET_OR_INFER(sps->vui.colour_primaries,
131 ctx->colour_primaries,
132 sps->vui.colour_description_present_flag, 2);
133
134 SET_OR_INFER(sps->vui.transfer_characteristics,
135 ctx->transfer_characteristics,
136 sps->vui.colour_description_present_flag, 2);
137
138 SET_OR_INFER(sps->vui.matrix_coefficients,
139 ctx->matrix_coefficients,
140 sps->vui.colour_description_present_flag, 2);
141
142 sps->vui.colour_description_present_flag = 1;
143 }
144 sps->vui.video_signal_type_present_flag = 1;
145 need_vui = 1;
146 }
147
148 if (ctx->chroma_sample_loc_type >= 0) {
149 sps->vui.chroma_sample_loc_type_top_field =
150 ctx->chroma_sample_loc_type;
151 sps->vui.chroma_sample_loc_type_bottom_field =
152 ctx->chroma_sample_loc_type;
153 sps->vui.chroma_loc_info_present_flag = 1;
154 need_vui = 1;
155 }
156
157 if (ctx->tick_rate.num && ctx->tick_rate.den) {
158 int num, den;
159
160 av_reduce(&num, &den, ctx->tick_rate.num, ctx->tick_rate.den,
161 UINT32_MAX > INT_MAX ? UINT32_MAX : INT_MAX);
162
163 sps->vui.time_scale = num;
164 sps->vui.num_units_in_tick = den;
165
166 sps->vui.timing_info_present_flag = 1;
167 need_vui = 1;
168 }
169 SET_OR_INFER(sps->vui.fixed_frame_rate_flag,
170 ctx->fixed_frame_rate_flag,
171 sps->vui.timing_info_present_flag, 0);
172
173 if (sps->separate_colour_plane_flag || sps->chroma_format_idc == 0) {
174 crop_unit_x = 1;
175 crop_unit_y = 2 - sps->frame_mbs_only_flag;
176 } else {
177 crop_unit_x = 1 + (sps->chroma_format_idc < 3);
178 crop_unit_y = (1 + (sps->chroma_format_idc < 2)) *
179 (2 - sps->frame_mbs_only_flag);
180 }
181#define CROP(border, unit) do { \
182 if (ctx->crop_ ## border >= 0) { \
183 if (ctx->crop_ ## border % unit != 0) { \
184 av_log(bsf, AV_LOG_ERROR, "Invalid value for crop_%s: " \
185 "must be a multiple of %d.\n", #border, unit); \
186 return AVERROR(EINVAL); \
187 } \
188 sps->frame_crop_ ## border ## _offset = \
189 ctx->crop_ ## border / unit; \
190 sps->frame_cropping_flag = 1; \
191 } \
192 } while (0)
193 CROP(left, crop_unit_x);
194 CROP(right, crop_unit_x);
195 CROP(top, crop_unit_y);
196 CROP(bottom, crop_unit_y);
197#undef CROP
198
199 if (need_vui)
200 sps->vui_parameters_present_flag = 1;
201
202 return 0;
203}
204
205static int h264_metadata_filter(AVBSFContext *bsf, AVPacket *out)
206{
207 H264MetadataContext *ctx = bsf->priv_data;
208 AVPacket *in = NULL;
209 CodedBitstreamFragment *au = &ctx->access_unit;
210 int err, i, j, has_sps;
211 char *sei_udu_string = NULL;
212
213 err = ff_bsf_get_packet(bsf, &in);
214 if (err < 0)
215 goto fail;
216
217 err = ff_cbs_read_packet(&ctx->cbc, au, in);
218 if (err < 0) {
219 av_log(bsf, AV_LOG_ERROR, "Failed to read packet.\n");
220 goto fail;
221 }
222
223 if (au->nb_units == 0) {
224 av_log(bsf, AV_LOG_ERROR, "No NAL units in packet.\n");
225 err = AVERROR_INVALIDDATA;
226 goto fail;
227 }
228
229 // If an AUD is present, it must be the first NAL unit.
230 if (au->units[0].type == H264_NAL_AUD) {
231 if (ctx->aud == REMOVE)
232 ff_cbs_delete_unit(&ctx->cbc, au, 0);
233 } else {
234 if (ctx->aud == INSERT) {
235 static const int primary_pic_type_table[] = {
236 0x084, // 2, 7
237 0x0a5, // 0, 2, 5, 7
238 0x0e7, // 0, 1, 2, 5, 6, 7
239 0x210, // 4, 9
240 0x318, // 3, 4, 8, 9
241 0x294, // 2, 4, 7, 9
242 0x3bd, // 0, 2, 3, 4, 5, 7, 8, 9
243 0x3ff, // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
244 };
245 int primary_pic_type_mask = 0xff;
246 H264RawAUD *aud = &ctx->aud_nal;
247
248 for (i = 0; i < au->nb_units; i++) {
249 if (au->units[i].type == H264_NAL_SLICE ||
250 au->units[i].type == H264_NAL_IDR_SLICE) {
251 H264RawSlice *slice = au->units[i].content;
252 for (j = 0; j < FF_ARRAY_ELEMS(primary_pic_type_table); j++) {
253 if (!(primary_pic_type_table[j] &
254 (1 << slice->header.slice_type)))
255 primary_pic_type_mask &= ~(1 << j);
256 }
257 }
258 }
259 for (j = 0; j < FF_ARRAY_ELEMS(primary_pic_type_table); j++)
260 if (primary_pic_type_mask & (1 << j))
261 break;
262 if (j >= FF_ARRAY_ELEMS(primary_pic_type_table)) {
263 av_log(bsf, AV_LOG_ERROR, "No usable primary_pic_type: "
264 "invalid slice types?\n");
265 err = AVERROR_INVALIDDATA;
266 goto fail;
267 }
268
269 aud->nal_unit_header.nal_unit_type = H264_NAL_AUD;
270 aud->primary_pic_type = j;
271
272 err = ff_cbs_insert_unit_content(&ctx->cbc, au,
273 0, H264_NAL_AUD, aud);
274 if (err < 0) {
275 av_log(bsf, AV_LOG_ERROR, "Failed to insert AUD.\n");
276 goto fail;
277 }
278 }
279 }
280
281 has_sps = 0;
282 for (i = 0; i < au->nb_units; i++) {
283 if (au->units[i].type == H264_NAL_SPS) {
284 err = h264_metadata_update_sps(bsf, au->units[i].content);
285 if (err < 0)
286 goto fail;
287 has_sps = 1;
288 }
289 }
290
291 // Only insert the SEI in access units containing SPSs.
292 if (has_sps && ctx->sei_user_data) {
293 H264RawSEI *sei;
294 H264RawSEIPayload *payload;
295 H264RawSEIUserDataUnregistered *udu;
c42b62d1 296 int sei_pos, sei_new;
9e93001b
MT
297
298 for (i = 0; i < au->nb_units; i++) {
299 if (au->units[i].type == H264_NAL_SEI ||
300 au->units[i].type == H264_NAL_SLICE ||
301 au->units[i].type == H264_NAL_IDR_SLICE)
302 break;
303 }
304 sei_pos = i;
305
306 if (sei_pos < au->nb_units &&
307 au->units[sei_pos].type == H264_NAL_SEI) {
c42b62d1 308 sei_new = 0;
9e93001b
MT
309 sei = au->units[sei_pos].content;
310 } else {
c42b62d1 311 sei_new = 1;
9e93001b
MT
312 sei = &ctx->sei_nal;
313 memset(sei, 0, sizeof(*sei));
314
315 sei->nal_unit_header.nal_unit_type = H264_NAL_SEI;
316
317 err = ff_cbs_insert_unit_content(&ctx->cbc, au,
318 sei_pos, H264_NAL_SEI, sei);
319 if (err < 0) {
320 av_log(bsf, AV_LOG_ERROR, "Failed to insert SEI.\n");
321 goto fail;
322 }
323 }
324
325 payload = &sei->payload[sei->payload_count];
326
327 payload->payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED;
328 udu = &payload->payload.user_data_unregistered;
329
330 for (i = j = 0; j < 32 && ctx->sei_user_data[i]; i++) {
331 int c, v;
332 c = ctx->sei_user_data[i];
333 if (c == '-') {
334 continue;
335 } else if (av_isxdigit(c)) {
336 c = av_tolower(c);
337 v = (c <= '9' ? c - '0' : c - 'a' + 10);
338 } else {
339 goto invalid_user_data;
340 }
341 if (i & 1)
342 udu->uuid_iso_iec_11578[j / 2] |= v;
343 else
344 udu->uuid_iso_iec_11578[j / 2] = v << 4;
345 ++j;
346 }
347 if (j == 32 && ctx->sei_user_data[i] == '+') {
348 sei_udu_string = av_strdup(ctx->sei_user_data + i + 1);
349 if (!sei_udu_string) {
350 err = AVERROR(ENOMEM);
351 goto sei_fail;
352 }
353
354 udu->data = sei_udu_string;
355 udu->data_length = strlen(sei_udu_string);
356
357 payload->payload_size = 16 + udu->data_length;
358
c42b62d1
MT
359 if (!sei_new) {
360 // This will be freed by the existing internal
361 // reference in fragment_uninit().
362 sei_udu_string = NULL;
363 }
364
9e93001b
MT
365 } else {
366 invalid_user_data:
367 av_log(bsf, AV_LOG_ERROR, "Invalid user data: "
368 "must be \"UUID+string\".\n");
369 err = AVERROR(EINVAL);
370 sei_fail:
371 memset(payload, 0, sizeof(&payload));
372 goto fail;
373 }
374
375 ++sei->payload_count;
376 }
377
378 err = ff_cbs_write_packet(&ctx->cbc, out, au);
379 if (err < 0) {
380 av_log(bsf, AV_LOG_ERROR, "Failed to write packet.\n");
381 goto fail;
382 }
383
384 err = av_packet_copy_props(out, in);
385 if (err < 0)
386 goto fail;
387
388 err = 0;
389fail:
390 ff_cbs_fragment_uninit(&ctx->cbc, au);
391 av_freep(&sei_udu_string);
392
393 av_packet_free(&in);
394
395 return err;
396}
397
398static int h264_metadata_init(AVBSFContext *bsf)
399{
400 H264MetadataContext *ctx = bsf->priv_data;
401 CodedBitstreamFragment *au = &ctx->access_unit;
402 int err, i;
403
404 err = ff_cbs_init(&ctx->cbc, AV_CODEC_ID_H264, bsf);
405 if (err < 0)
406 return err;
407
408 if (bsf->par_in->extradata) {
409 err = ff_cbs_read_extradata(&ctx->cbc, au, bsf->par_in);
410 if (err < 0) {
411 av_log(bsf, AV_LOG_ERROR, "Failed to read extradata.\n");
412 goto fail;
413 }
414
415 for (i = 0; i < au->nb_units; i++) {
416 if (au->units[i].type == H264_NAL_SPS) {
417 err = h264_metadata_update_sps(bsf, au->units[i].content);
418 if (err < 0)
419 goto fail;
420 }
421 }
422
423 err = ff_cbs_write_extradata(&ctx->cbc, bsf->par_out, au);
424 if (err < 0) {
425 av_log(bsf, AV_LOG_ERROR, "Failed to write extradata.\n");
426 goto fail;
427 }
428 }
429
430 err = 0;
431fail:
432 ff_cbs_fragment_uninit(&ctx->cbc, au);
433 return err;
434}
435
436static void h264_metadata_close(AVBSFContext *bsf)
437{
438 H264MetadataContext *ctx = bsf->priv_data;
439 ff_cbs_close(&ctx->cbc);
440}
441
442#define OFFSET(x) offsetof(H264MetadataContext, x)
443static const AVOption h264_metadata_options[] = {
444 { "aud", "Access Unit Delimiter NAL units",
445 OFFSET(aud), AV_OPT_TYPE_INT,
446 { .i64 = PASS }, PASS, REMOVE, 0, "aud" },
447 { "pass", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PASS }, .unit = "aud" },
448 { "insert", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = INSERT }, .unit = "aud" },
449 { "remove", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = REMOVE }, .unit = "aud" },
450
451 { "sample_aspect_ratio", "Set sample aspect ratio (table E-1)",
452 OFFSET(sample_aspect_ratio), AV_OPT_TYPE_RATIONAL,
453 { .i64 = 0 }, 0, 65535 },
454
455 { "video_format", "Set video format (table E-2)",
456 OFFSET(video_format), AV_OPT_TYPE_INT,
457 { .i64 = -1 }, -1, 7 },
458 { "video_full_range_flag", "Set video full range flag",
459 OFFSET(video_full_range_flag), AV_OPT_TYPE_INT,
460 { .i64 = -1 }, -1, 1 },
461 { "colour_primaries", "Set colour primaries (table E-3)",
462 OFFSET(colour_primaries), AV_OPT_TYPE_INT,
463 { .i64 = -1 }, -1, 255 },
464 { "transfer_characteristics", "Set transfer characteristics (table E-4)",
465 OFFSET(transfer_characteristics), AV_OPT_TYPE_INT,
466 { .i64 = -1 }, -1, 255 },
467 { "matrix_coefficients", "Set matrix coefficients (table E-5)",
468 OFFSET(matrix_coefficients), AV_OPT_TYPE_INT,
469 { .i64 = -1 }, -1, 255 },
470
471 { "chroma_sample_loc_type", "Set chroma sample location type (figure E-1)",
472 OFFSET(chroma_sample_loc_type), AV_OPT_TYPE_INT,
473 { .i64 = -1 }, -1, 6 },
474
475 { "tick_rate", "Set VUI tick rate (num_units_in_tick / time_scale)",
476 OFFSET(tick_rate), AV_OPT_TYPE_RATIONAL,
477 { .i64 = 0 }, 0, UINT_MAX },
478 { "fixed_frame_rate_flag", "Set VUI fixed frame rate flag",
479 OFFSET(fixed_frame_rate_flag), AV_OPT_TYPE_INT,
480 { .i64 = -1 }, -1, 1 },
481
482 { "crop_left", "Set left border crop offset",
483 OFFSET(crop_left), AV_OPT_TYPE_INT,
484 { .i64 = -1 }, -1, H264_MAX_WIDTH },
485 { "crop_right", "Set right border crop offset",
486 OFFSET(crop_right), AV_OPT_TYPE_INT,
487 { .i64 = -1 }, -1, H264_MAX_WIDTH },
488 { "crop_top", "Set top border crop offset",
489 OFFSET(crop_top), AV_OPT_TYPE_INT,
490 { .i64 = -1 }, -1, H264_MAX_HEIGHT },
491 { "crop_bottom", "Set bottom border crop offset",
492 OFFSET(crop_bottom), AV_OPT_TYPE_INT,
493 { .i64 = -1 }, -1, H264_MAX_HEIGHT },
494
495 { "sei_user_data", "Insert SEI user data (UUID+string)",
496 OFFSET(sei_user_data), AV_OPT_TYPE_STRING, { .str = NULL } },
497
498 { NULL }
499};
500
501static const AVClass h264_metadata_class = {
502 .class_name = "h264_metadata_bsf",
503 .item_name = av_default_item_name,
504 .option = h264_metadata_options,
505 .version = LIBAVCODEC_VERSION_MAJOR,
506};
507
508static const enum AVCodecID h264_metadata_codec_ids[] = {
509 AV_CODEC_ID_H264, AV_CODEC_ID_NONE,
510};
511
512const AVBitStreamFilter ff_h264_metadata_bsf = {
513 .name = "h264_metadata",
514 .priv_data_size = sizeof(H264MetadataContext),
515 .priv_class = &h264_metadata_class,
516 .init = &h264_metadata_init,
517 .close = &h264_metadata_close,
518 .filter = &h264_metadata_filter,
519 .codec_ids = h264_metadata_codec_ids,
520};