]> git.sesse.net Git - ffmpeg/blob - libavcodec/h264_metadata_bsf.c
h264_metadata: Use common SEI addition function
[ffmpeg] / libavcodec / h264_metadata_bsf.c
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
29 enum {
30     PASS,
31     INSERT,
32     REMOVE,
33 };
34
35 typedef 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
68 static 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
205 static 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
212     err = ff_bsf_get_packet(bsf, &in);
213     if (err < 0)
214         goto fail;
215
216     err = ff_cbs_read_packet(ctx->cbc, au, in);
217     if (err < 0) {
218         av_log(bsf, AV_LOG_ERROR, "Failed to read packet.\n");
219         goto fail;
220     }
221
222     if (au->nb_units == 0) {
223         av_log(bsf, AV_LOG_ERROR, "No NAL units in packet.\n");
224         err = AVERROR_INVALIDDATA;
225         goto fail;
226     }
227
228     // If an AUD is present, it must be the first NAL unit.
229     if (au->units[0].type == H264_NAL_AUD) {
230         if (ctx->aud == REMOVE)
231             ff_cbs_delete_unit(ctx->cbc, au, 0);
232     } else {
233         if (ctx->aud == INSERT) {
234             static const int primary_pic_type_table[] = {
235                 0x084, // 2, 7
236                 0x0a5, // 0, 2, 5, 7
237                 0x0e7, // 0, 1, 2, 5, 6, 7
238                 0x210, // 4, 9
239                 0x318, // 3, 4, 8, 9
240                 0x294, // 2, 4, 7, 9
241                 0x3bd, // 0, 2, 3, 4, 5, 7, 8, 9
242                 0x3ff, // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
243             };
244             int primary_pic_type_mask = 0xff;
245             H264RawAUD *aud = &ctx->aud_nal;
246
247             for (i = 0; i < au->nb_units; i++) {
248                 if (au->units[i].type == H264_NAL_SLICE ||
249                     au->units[i].type == H264_NAL_IDR_SLICE) {
250                     H264RawSlice *slice = au->units[i].content;
251                     for (j = 0; j < FF_ARRAY_ELEMS(primary_pic_type_table); j++) {
252                          if (!(primary_pic_type_table[j] &
253                                (1 << slice->header.slice_type)))
254                              primary_pic_type_mask &= ~(1 << j);
255                     }
256                 }
257             }
258             for (j = 0; j < FF_ARRAY_ELEMS(primary_pic_type_table); j++)
259                 if (primary_pic_type_mask & (1 << j))
260                     break;
261             if (j >= FF_ARRAY_ELEMS(primary_pic_type_table)) {
262                 av_log(bsf, AV_LOG_ERROR, "No usable primary_pic_type: "
263                        "invalid slice types?\n");
264                 err = AVERROR_INVALIDDATA;
265                 goto fail;
266             }
267
268             aud->nal_unit_header.nal_unit_type = H264_NAL_AUD;
269             aud->primary_pic_type = j;
270
271             err = ff_cbs_insert_unit_content(ctx->cbc, au,
272                                              0, H264_NAL_AUD, aud, NULL);
273             if (err < 0) {
274                 av_log(bsf, AV_LOG_ERROR, "Failed to insert AUD.\n");
275                 goto fail;
276             }
277         }
278     }
279
280     has_sps = 0;
281     for (i = 0; i < au->nb_units; i++) {
282         if (au->units[i].type == H264_NAL_SPS) {
283             err = h264_metadata_update_sps(bsf, au->units[i].content);
284             if (err < 0)
285                 goto fail;
286             has_sps = 1;
287         }
288     }
289
290     // Only insert the SEI in access units containing SPSs.
291     if (has_sps && ctx->sei_user_data) {
292         H264RawSEIPayload payload = {
293             .payload_type = H264_SEI_TYPE_USER_DATA_UNREGISTERED,
294         };
295         H264RawSEIUserDataUnregistered *udu =
296             &payload.payload.user_data_unregistered;
297
298         for (i = j = 0; j < 32 && ctx->sei_user_data[i]; i++) {
299             int c, v;
300             c = ctx->sei_user_data[i];
301             if (c == '-') {
302                 continue;
303             } else if (av_isxdigit(c)) {
304                 c = av_tolower(c);
305                 v = (c <= '9' ? c - '0' : c - 'a' + 10);
306             } else {
307                 goto invalid_user_data;
308             }
309             if (i & 1)
310                 udu->uuid_iso_iec_11578[j / 2] |= v;
311             else
312                 udu->uuid_iso_iec_11578[j / 2] = v << 4;
313             ++j;
314         }
315         if (j == 32 && ctx->sei_user_data[i] == '+') {
316             size_t len = strlen(ctx->sei_user_data + i + 1);
317
318             udu->data_ref = av_buffer_alloc(len + 1);
319             if (!udu->data_ref) {
320                 err = AVERROR(ENOMEM);
321                 goto fail;
322             }
323
324             udu->data        = udu->data_ref->data;
325             udu->data_length = len + 1;
326             memcpy(udu->data, ctx->sei_user_data + i + 1, len + 1);
327
328             payload.payload_size = 16 + udu->data_length;
329
330             err = ff_cbs_h264_add_sei_message(ctx->cbc, au, &payload);
331             if (err < 0) {
332                 av_log(bsf, AV_LOG_ERROR, "Failed to add user data SEI "
333                        "message to access unit.\n");
334                 goto fail;
335             }
336
337         } else {
338         invalid_user_data:
339             av_log(bsf, AV_LOG_ERROR, "Invalid user data: "
340                    "must be \"UUID+string\".\n");
341             err = AVERROR(EINVAL);
342         }
343     }
344
345     err = ff_cbs_write_packet(ctx->cbc, out, au);
346     if (err < 0) {
347         av_log(bsf, AV_LOG_ERROR, "Failed to write packet.\n");
348         goto fail;
349     }
350
351     err = av_packet_copy_props(out, in);
352     if (err < 0)
353         goto fail;
354
355     err = 0;
356 fail:
357     ff_cbs_fragment_uninit(ctx->cbc, au);
358
359     av_packet_free(&in);
360
361     return err;
362 }
363
364 static int h264_metadata_init(AVBSFContext *bsf)
365 {
366     H264MetadataContext *ctx = bsf->priv_data;
367     CodedBitstreamFragment *au = &ctx->access_unit;
368     int err, i;
369
370     err = ff_cbs_init(&ctx->cbc, AV_CODEC_ID_H264, bsf);
371     if (err < 0)
372         return err;
373
374     if (bsf->par_in->extradata) {
375         err = ff_cbs_read_extradata(ctx->cbc, au, bsf->par_in);
376         if (err < 0) {
377             av_log(bsf, AV_LOG_ERROR, "Failed to read extradata.\n");
378             goto fail;
379         }
380
381         for (i = 0; i < au->nb_units; i++) {
382             if (au->units[i].type == H264_NAL_SPS) {
383                 err = h264_metadata_update_sps(bsf, au->units[i].content);
384                 if (err < 0)
385                     goto fail;
386             }
387         }
388
389         err = ff_cbs_write_extradata(ctx->cbc, bsf->par_out, au);
390         if (err < 0) {
391             av_log(bsf, AV_LOG_ERROR, "Failed to write extradata.\n");
392             goto fail;
393         }
394     }
395
396     err = 0;
397 fail:
398     ff_cbs_fragment_uninit(ctx->cbc, au);
399     return err;
400 }
401
402 static void h264_metadata_close(AVBSFContext *bsf)
403 {
404     H264MetadataContext *ctx = bsf->priv_data;
405     ff_cbs_close(&ctx->cbc);
406 }
407
408 #define OFFSET(x) offsetof(H264MetadataContext, x)
409 static const AVOption h264_metadata_options[] = {
410     { "aud", "Access Unit Delimiter NAL units",
411         OFFSET(aud), AV_OPT_TYPE_INT,
412         { .i64 = PASS }, PASS, REMOVE, 0, "aud" },
413     { "pass",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = PASS   }, .unit = "aud" },
414     { "insert", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = INSERT }, .unit = "aud" },
415     { "remove", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = REMOVE }, .unit = "aud" },
416
417     { "sample_aspect_ratio", "Set sample aspect ratio (table E-1)",
418         OFFSET(sample_aspect_ratio), AV_OPT_TYPE_RATIONAL,
419         { .i64 = 0 }, 0, 65535 },
420
421     { "video_format", "Set video format (table E-2)",
422         OFFSET(video_format), AV_OPT_TYPE_INT,
423         { .i64 = -1 }, -1, 7 },
424     { "video_full_range_flag", "Set video full range flag",
425         OFFSET(video_full_range_flag), AV_OPT_TYPE_INT,
426         { .i64 = -1 }, -1, 1 },
427     { "colour_primaries", "Set colour primaries (table E-3)",
428         OFFSET(colour_primaries), AV_OPT_TYPE_INT,
429         { .i64 = -1 }, -1, 255 },
430     { "transfer_characteristics", "Set transfer characteristics (table E-4)",
431         OFFSET(transfer_characteristics), AV_OPT_TYPE_INT,
432         { .i64 = -1 }, -1, 255 },
433     { "matrix_coefficients", "Set matrix coefficients (table E-5)",
434         OFFSET(matrix_coefficients), AV_OPT_TYPE_INT,
435         { .i64 = -1 }, -1, 255 },
436
437     { "chroma_sample_loc_type", "Set chroma sample location type (figure E-1)",
438         OFFSET(chroma_sample_loc_type), AV_OPT_TYPE_INT,
439         { .i64 = -1 }, -1, 6 },
440
441     { "tick_rate", "Set VUI tick rate (num_units_in_tick / time_scale)",
442         OFFSET(tick_rate), AV_OPT_TYPE_RATIONAL,
443         { .i64 = 0 }, 0, UINT_MAX },
444     { "fixed_frame_rate_flag", "Set VUI fixed frame rate flag",
445         OFFSET(fixed_frame_rate_flag), AV_OPT_TYPE_INT,
446         { .i64 = -1 }, -1, 1 },
447
448     { "crop_left", "Set left border crop offset",
449         OFFSET(crop_left), AV_OPT_TYPE_INT,
450         { .i64 = -1 }, -1, H264_MAX_WIDTH },
451     { "crop_right", "Set right border crop offset",
452         OFFSET(crop_right), AV_OPT_TYPE_INT,
453         { .i64 = -1 }, -1, H264_MAX_WIDTH },
454     { "crop_top", "Set top border crop offset",
455         OFFSET(crop_top), AV_OPT_TYPE_INT,
456         { .i64 = -1 }, -1, H264_MAX_HEIGHT },
457     { "crop_bottom", "Set bottom border crop offset",
458         OFFSET(crop_bottom), AV_OPT_TYPE_INT,
459         { .i64 = -1 }, -1, H264_MAX_HEIGHT },
460
461     { "sei_user_data", "Insert SEI user data (UUID+string)",
462         OFFSET(sei_user_data), AV_OPT_TYPE_STRING, { .str = NULL } },
463
464     { NULL }
465 };
466
467 static const AVClass h264_metadata_class = {
468     .class_name = "h264_metadata_bsf",
469     .item_name  = av_default_item_name,
470     .option     = h264_metadata_options,
471     .version    = LIBAVCODEC_VERSION_MAJOR,
472 };
473
474 static const enum AVCodecID h264_metadata_codec_ids[] = {
475     AV_CODEC_ID_H264, AV_CODEC_ID_NONE,
476 };
477
478 const AVBitStreamFilter ff_h264_metadata_bsf = {
479     .name           = "h264_metadata",
480     .priv_data_size = sizeof(H264MetadataContext),
481     .priv_class     = &h264_metadata_class,
482     .init           = &h264_metadata_init,
483     .close          = &h264_metadata_close,
484     .filter         = &h264_metadata_filter,
485     .codec_ids      = h264_metadata_codec_ids,
486 };