2 * This file is part of FFmpeg.
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.
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.
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
19 #include "libavutil/attributes.h"
20 #include "libavutil/avassert.h"
22 #include "bytestream.h"
24 #include "cbs_internal.h"
30 #include "h2645_parse.h"
35 static int cbs_read_ue_golomb(CodedBitstreamContext *ctx, GetBitContext *gbc,
36 const char *name, const int *subscripts,
38 uint32_t range_min, uint32_t range_max)
45 position = get_bits_count(gbc);
47 for (i = 0; i < 32; i++) {
48 if (get_bits_left(gbc) < i + 1) {
49 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid ue-golomb code at "
50 "%s: bitstream ended.\n", name);
51 return AVERROR_INVALIDDATA;
54 bits[i] = k ? '1' : '0';
59 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid ue-golomb code at "
60 "%s: more than 31 zeroes.\n", name);
61 return AVERROR_INVALIDDATA;
64 for (j = 0; j < i; j++) {
66 bits[i + j + 1] = k ? '1' : '0';
67 value = value << 1 | k;
72 if (ctx->trace_enable)
73 ff_cbs_trace_syntax_element(ctx, position, name, subscripts,
76 if (value < range_min || value > range_max) {
77 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
78 "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n",
79 name, value, range_min, range_max);
80 return AVERROR_INVALIDDATA;
87 static int cbs_read_se_golomb(CodedBitstreamContext *ctx, GetBitContext *gbc,
88 const char *name, const int *subscripts,
90 int32_t range_min, int32_t range_max)
98 position = get_bits_count(gbc);
100 for (i = 0; i < 32; i++) {
101 if (get_bits_left(gbc) < i + 1) {
102 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid se-golomb code at "
103 "%s: bitstream ended.\n", name);
104 return AVERROR_INVALIDDATA;
107 bits[i] = k ? '1' : '0';
112 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid se-golomb code at "
113 "%s: more than 31 zeroes.\n", name);
114 return AVERROR_INVALIDDATA;
117 for (j = 0; j < i; j++) {
119 bits[i + j + 1] = k ? '1' : '0';
124 value = -(int32_t)(v / 2);
128 if (ctx->trace_enable)
129 ff_cbs_trace_syntax_element(ctx, position, name, subscripts,
132 if (value < range_min || value > range_max) {
133 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
134 "%"PRId32", but must be in [%"PRId32",%"PRId32"].\n",
135 name, value, range_min, range_max);
136 return AVERROR_INVALIDDATA;
143 static int cbs_write_ue_golomb(CodedBitstreamContext *ctx, PutBitContext *pbc,
144 const char *name, const int *subscripts,
146 uint32_t range_min, uint32_t range_max)
150 if (value < range_min || value > range_max) {
151 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
152 "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n",
153 name, value, range_min, range_max);
154 return AVERROR_INVALIDDATA;
156 av_assert0(value != UINT32_MAX);
158 len = av_log2(value + 1);
159 if (put_bits_left(pbc) < 2 * len + 1)
160 return AVERROR(ENOSPC);
162 if (ctx->trace_enable) {
166 for (i = 0; i < len; i++)
169 for (i = 0; i < len; i++)
170 bits[len + i + 1] = (value + 1) >> (len - i - 1) & 1 ? '1' : '0';
171 bits[len + len + 1] = 0;
173 ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc),
174 name, subscripts, bits, value);
177 put_bits(pbc, len, 0);
179 put_bits(pbc, len + 1, value + 1);
181 put_bits32(pbc, value + 1);
186 static int cbs_write_se_golomb(CodedBitstreamContext *ctx, PutBitContext *pbc,
187 const char *name, const int *subscripts,
189 int32_t range_min, int32_t range_max)
194 if (value < range_min || value > range_max) {
195 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
196 "%"PRId32", but must be in [%"PRId32",%"PRId32"].\n",
197 name, value, range_min, range_max);
198 return AVERROR_INVALIDDATA;
200 av_assert0(value != INT32_MIN);
205 uvalue = 2 * (uint32_t)value - 1;
207 uvalue = 2 * (uint32_t)-value;
209 len = av_log2(uvalue + 1);
210 if (put_bits_left(pbc) < 2 * len + 1)
211 return AVERROR(ENOSPC);
213 if (ctx->trace_enable) {
217 for (i = 0; i < len; i++)
220 for (i = 0; i < len; i++)
221 bits[len + i + 1] = (uvalue + 1) >> (len - i - 1) & 1 ? '1' : '0';
222 bits[len + len + 1] = 0;
224 ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc),
225 name, subscripts, bits, value);
228 put_bits(pbc, len, 0);
230 put_bits(pbc, len + 1, uvalue + 1);
232 put_bits32(pbc, uvalue + 1);
237 #define HEADER(name) do { \
238 ff_cbs_trace_header(ctx, name); \
241 #define CHECK(call) do { \
247 #define FUNC_NAME(rw, codec, name) cbs_ ## codec ## _ ## rw ## _ ## name
248 #define FUNC_H264(rw, name) FUNC_NAME(rw, h264, name)
249 #define FUNC_H265(rw, name) FUNC_NAME(rw, h265, name)
251 #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL)
253 #define u(width, name, range_min, range_max) \
254 xu(width, name, current->name, range_min, range_max, 0)
255 #define flag(name) u(1, name, 0, 1)
256 #define ue(name, range_min, range_max) \
257 xue(name, current->name, range_min, range_max, 0)
258 #define se(name, range_min, range_max) \
259 xse(name, current->name, range_min, range_max, 0)
261 #define us(width, name, range_min, range_max, subs, ...) \
262 xu(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
263 #define flags(name, subs, ...) \
264 xu(1, name, current->name, 0, 1, subs, __VA_ARGS__)
265 #define ues(name, range_min, range_max, subs, ...) \
266 xue(name, current->name, range_min, range_max, subs, __VA_ARGS__)
267 #define ses(name, range_min, range_max, subs, ...) \
268 xse(name, current->name, range_min, range_max, subs, __VA_ARGS__)
270 #define fixed(width, name, value) do { \
271 av_unused uint32_t fixed_value = value; \
272 xu(width, name, fixed_value, value, value, 0); \
277 #define READWRITE read
278 #define RWContext GetBitContext
280 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
281 uint32_t value = range_min; \
282 CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \
283 SUBSCRIPTS(subs, __VA_ARGS__), \
284 &value, range_min, range_max)); \
287 #define xue(name, var, range_min, range_max, subs, ...) do { \
288 uint32_t value = range_min; \
289 CHECK(cbs_read_ue_golomb(ctx, rw, #name, \
290 SUBSCRIPTS(subs, __VA_ARGS__), \
291 &value, range_min, range_max)); \
294 #define xse(name, var, range_min, range_max, subs, ...) do { \
295 int32_t value = range_min; \
296 CHECK(cbs_read_se_golomb(ctx, rw, #name, \
297 SUBSCRIPTS(subs, __VA_ARGS__), \
298 &value, range_min, range_max)); \
303 #define infer(name, value) do { \
304 current->name = value; \
307 static int cbs_h2645_read_more_rbsp_data(GetBitContext *gbc)
309 int bits_left = get_bits_left(gbc);
312 if (show_bits(gbc, bits_left) == 1 << (bits_left - 1))
317 #define more_rbsp_data(var) ((var) = cbs_h2645_read_more_rbsp_data(rw))
319 #define byte_alignment(rw) (get_bits_count(rw) % 8)
321 #define allocate(name, size) do { \
322 name ## _ref = av_buffer_allocz(size); \
324 return AVERROR(ENOMEM); \
325 name = name ## _ref->data; \
328 #define FUNC(name) FUNC_H264(READWRITE, name)
329 #include "cbs_h264_syntax_template.c"
332 #define FUNC(name) FUNC_H265(READWRITE, name)
333 #include "cbs_h265_syntax_template.c"
343 #undef more_rbsp_data
344 #undef byte_alignment
349 #define READWRITE write
350 #define RWContext PutBitContext
352 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
353 uint32_t value = var; \
354 CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \
355 SUBSCRIPTS(subs, __VA_ARGS__), \
356 value, range_min, range_max)); \
358 #define xue(name, var, range_min, range_max, subs, ...) do { \
359 uint32_t value = var; \
360 CHECK(cbs_write_ue_golomb(ctx, rw, #name, \
361 SUBSCRIPTS(subs, __VA_ARGS__), \
362 value, range_min, range_max)); \
364 #define xse(name, var, range_min, range_max, subs, ...) do { \
365 int32_t value = var; \
366 CHECK(cbs_write_se_golomb(ctx, rw, #name, \
367 SUBSCRIPTS(subs, __VA_ARGS__), \
368 value, range_min, range_max)); \
371 #define infer(name, value) do { \
372 if (current->name != (value)) { \
373 av_log(ctx->log_ctx, AV_LOG_WARNING, "Warning: " \
374 "%s does not match inferred value: " \
375 "%"PRId64", but should be %"PRId64".\n", \
376 #name, (int64_t)current->name, (int64_t)(value)); \
380 #define more_rbsp_data(var) (var)
382 #define byte_alignment(rw) (put_bits_count(rw) % 8)
384 #define allocate(name, size) do { \
386 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s must be set " \
387 "for writing.\n", #name); \
388 return AVERROR_INVALIDDATA; \
392 #define FUNC(name) FUNC_H264(READWRITE, name)
393 #include "cbs_h264_syntax_template.c"
396 #define FUNC(name) FUNC_H265(READWRITE, name)
397 #include "cbs_h265_syntax_template.c"
411 #undef more_rbsp_data
412 #undef byte_alignment
416 static void cbs_h264_free_pps(void *unit, uint8_t *content)
418 H264RawPPS *pps = (H264RawPPS*)content;
419 av_buffer_unref(&pps->slice_group_id_ref);
423 static void cbs_h264_free_sei_payload(H264RawSEIPayload *payload)
425 switch (payload->payload_type) {
426 case H264_SEI_TYPE_BUFFERING_PERIOD:
427 case H264_SEI_TYPE_PIC_TIMING:
428 case H264_SEI_TYPE_RECOVERY_POINT:
429 case H264_SEI_TYPE_DISPLAY_ORIENTATION:
431 case H264_SEI_TYPE_USER_DATA_REGISTERED:
432 av_buffer_unref(&payload->payload.user_data_registered.data_ref);
434 case H264_SEI_TYPE_USER_DATA_UNREGISTERED:
435 av_buffer_unref(&payload->payload.user_data_unregistered.data_ref);
438 av_buffer_unref(&payload->payload.other.data_ref);
443 static void cbs_h264_free_sei(void *unit, uint8_t *content)
445 H264RawSEI *sei = (H264RawSEI*)content;
447 for (i = 0; i < sei->payload_count; i++)
448 cbs_h264_free_sei_payload(&sei->payload[i]);
452 static void cbs_h264_free_slice(void *unit, uint8_t *content)
454 H264RawSlice *slice = (H264RawSlice*)content;
455 av_buffer_unref(&slice->data_ref);
459 static void cbs_h265_free_vps(void *unit, uint8_t *content)
461 H265RawVPS *vps = (H265RawVPS*)content;
462 av_buffer_unref(&vps->extension_data.data_ref);
466 static void cbs_h265_free_sps(void *unit, uint8_t *content)
468 H265RawSPS *sps = (H265RawSPS*)content;
469 av_buffer_unref(&sps->extension_data.data_ref);
473 static void cbs_h265_free_pps(void *unit, uint8_t *content)
475 H265RawPPS *pps = (H265RawPPS*)content;
476 av_buffer_unref(&pps->extension_data.data_ref);
480 static void cbs_h265_free_slice(void *unit, uint8_t *content)
482 H265RawSlice *slice = (H265RawSlice*)content;
483 av_buffer_unref(&slice->data_ref);
487 static void cbs_h265_free_sei_payload(H265RawSEIPayload *payload)
489 switch (payload->payload_type) {
490 case HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO:
491 case HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO:
494 av_buffer_unref(&payload->payload.other.data_ref);
499 static void cbs_h265_free_sei(void *unit, uint8_t *content)
501 H265RawSEI *sei = (H265RawSEI*)content;
503 for (i = 0; i < sei->payload_count; i++)
504 cbs_h265_free_sei_payload(&sei->payload[i]);
508 static int cbs_h2645_fragment_add_nals(CodedBitstreamContext *ctx,
509 CodedBitstreamFragment *frag,
510 const H2645Packet *packet)
514 for (i = 0; i < packet->nb_nals; i++) {
515 const H2645NAL *nal = &packet->nals[i];
516 size_t size = nal->size;
519 // Remove trailing zeroes.
520 while (size > 0 && nal->data[size - 1] == 0)
522 av_assert0(size > 0);
524 data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
526 return AVERROR(ENOMEM);
527 memcpy(data, nal->data, size);
528 memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
530 err = ff_cbs_insert_unit_data(ctx, frag, -1, nal->type,
541 static int cbs_h2645_split_fragment(CodedBitstreamContext *ctx,
542 CodedBitstreamFragment *frag,
545 enum AVCodecID codec_id = ctx->codec->codec_id;
546 CodedBitstreamH2645Context *priv = ctx->priv_data;
550 av_assert0(frag->data && frag->nb_units == 0);
551 if (frag->data_size == 0)
554 if (header && frag->data[0] && codec_id == AV_CODEC_ID_H264) {
556 size_t size, start, end;
557 int i, count, version;
561 bytestream2_init(&gbc, frag->data, frag->data_size);
563 if (bytestream2_get_bytes_left(&gbc) < 6)
564 return AVERROR_INVALIDDATA;
566 version = bytestream2_get_byte(&gbc);
568 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid AVCC header: "
569 "first byte %u.", version);
570 return AVERROR_INVALIDDATA;
573 bytestream2_skip(&gbc, 3);
574 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
577 count = bytestream2_get_byte(&gbc) & 0x1f;
578 start = bytestream2_tell(&gbc);
579 for (i = 0; i < count; i++) {
580 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
581 return AVERROR_INVALIDDATA;
582 size = bytestream2_get_be16(&gbc);
583 if (bytestream2_get_bytes_left(&gbc) < size)
584 return AVERROR_INVALIDDATA;
585 bytestream2_skip(&gbc, size);
587 end = bytestream2_tell(&gbc);
589 err = ff_h2645_packet_split(&priv->read_packet,
590 frag->data + start, end - start,
591 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1);
593 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC SPS array.\n");
596 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
601 count = bytestream2_get_byte(&gbc);
602 start = bytestream2_tell(&gbc);
603 for (i = 0; i < count; i++) {
604 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
605 return AVERROR_INVALIDDATA;
606 size = bytestream2_get_be16(&gbc);
607 if (bytestream2_get_bytes_left(&gbc) < size)
608 return AVERROR_INVALIDDATA;
609 bytestream2_skip(&gbc, size);
611 end = bytestream2_tell(&gbc);
613 err = ff_h2645_packet_split(&priv->read_packet,
614 frag->data + start, end - start,
615 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1);
617 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC PPS array.\n");
620 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
624 if (bytestream2_get_bytes_left(&gbc) > 0) {
625 av_log(ctx->log_ctx, AV_LOG_WARNING, "%u bytes left at end of AVCC "
626 "header.\n", bytestream2_get_bytes_left(&gbc));
629 } else if (header && frag->data[0] && codec_id == AV_CODEC_ID_HEVC) {
631 size_t size, start, end;
632 int i, j, nb_arrays, nal_unit_type, nb_nals, version;
636 bytestream2_init(&gbc, frag->data, frag->data_size);
638 if (bytestream2_get_bytes_left(&gbc) < 23)
639 return AVERROR_INVALIDDATA;
641 version = bytestream2_get_byte(&gbc);
643 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid HVCC header: "
644 "first byte %u.", version);
645 return AVERROR_INVALIDDATA;
648 bytestream2_skip(&gbc, 20);
649 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
651 nb_arrays = bytestream2_get_byte(&gbc);
652 for (i = 0; i < nb_arrays; i++) {
653 nal_unit_type = bytestream2_get_byte(&gbc) & 0x3f;
654 nb_nals = bytestream2_get_be16(&gbc);
656 start = bytestream2_tell(&gbc);
657 for (j = 0; j < nb_nals; j++) {
658 if (bytestream2_get_bytes_left(&gbc) < 2)
659 return AVERROR_INVALIDDATA;
660 size = bytestream2_get_be16(&gbc);
661 if (bytestream2_get_bytes_left(&gbc) < size)
662 return AVERROR_INVALIDDATA;
663 bytestream2_skip(&gbc, size);
665 end = bytestream2_tell(&gbc);
667 err = ff_h2645_packet_split(&priv->read_packet,
668 frag->data + start, end - start,
669 ctx->log_ctx, 1, 2, AV_CODEC_ID_HEVC, 1);
671 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split "
672 "HVCC array %d (%d NAL units of type %d).\n",
673 i, nb_nals, nal_unit_type);
676 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
682 // Annex B, or later MP4 with already-known parameters.
684 err = ff_h2645_packet_split(&priv->read_packet,
685 frag->data, frag->data_size,
687 priv->mp4, priv->nal_length_size,
692 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
700 #define cbs_h2645_replace_ps(h26n, ps_name, ps_var, id_element) \
701 static int cbs_h26 ## h26n ## _replace_ ## ps_var(CodedBitstreamContext *ctx, \
702 CodedBitstreamUnit *unit) \
704 CodedBitstreamH26 ## h26n ## Context *priv = ctx->priv_data; \
705 H26 ## h26n ## Raw ## ps_name *ps_var = unit->content; \
706 unsigned int id = ps_var->id_element; \
707 if (id > FF_ARRAY_ELEMS(priv->ps_var)) { \
708 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid " #ps_name \
709 " id : %d.\n", id); \
710 return AVERROR_INVALIDDATA; \
712 if (priv->ps_var[id] == priv->active_ ## ps_var) \
713 priv->active_ ## ps_var = NULL ; \
714 av_buffer_unref(&priv->ps_var ## _ref[id]); \
715 if (unit->content_ref) \
716 priv->ps_var ## _ref[id] = av_buffer_ref(unit->content_ref); \
718 priv->ps_var ## _ref[id] = av_buffer_alloc(sizeof(*ps_var)); \
719 if (!priv->ps_var ## _ref[id]) \
720 return AVERROR(ENOMEM); \
721 priv->ps_var[id] = (H26 ## h26n ## Raw ## ps_name *)priv->ps_var ## _ref[id]->data; \
722 if (!unit->content_ref) \
723 memcpy(priv->ps_var[id], ps_var, sizeof(*ps_var)); \
727 cbs_h2645_replace_ps(4, SPS, sps, seq_parameter_set_id)
728 cbs_h2645_replace_ps(4, PPS, pps, pic_parameter_set_id)
729 cbs_h2645_replace_ps(5, VPS, vps, vps_video_parameter_set_id)
730 cbs_h2645_replace_ps(5, SPS, sps, sps_seq_parameter_set_id)
731 cbs_h2645_replace_ps(5, PPS, pps, pps_pic_parameter_set_id)
733 static int cbs_h264_read_nal_unit(CodedBitstreamContext *ctx,
734 CodedBitstreamUnit *unit)
739 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
743 switch (unit->type) {
748 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps), NULL);
753 err = cbs_h264_read_sps(ctx, &gbc, sps);
757 err = cbs_h264_replace_sps(ctx, unit);
763 case H264_NAL_SPS_EXT:
765 err = ff_cbs_alloc_unit_content(ctx, unit,
766 sizeof(H264RawSPSExtension),
771 err = cbs_h264_read_sps_extension(ctx, &gbc, unit->content);
781 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
787 err = cbs_h264_read_pps(ctx, &gbc, pps);
791 err = cbs_h264_replace_pps(ctx, unit);
798 case H264_NAL_IDR_SLICE:
799 case H264_NAL_AUXILIARY_SLICE:
804 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
805 &cbs_h264_free_slice);
808 slice = unit->content;
810 err = cbs_h264_read_slice_header(ctx, &gbc, &slice->header);
814 pos = get_bits_count(&gbc);
815 len = unit->data_size;
816 if (!unit->data[len - 1]) {
818 for (z = 0; z < len && !unit->data[len - z - 1]; z++);
819 av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "
820 "from slice data.\n", z);
824 slice->data_size = len - pos / 8;
825 slice->data_ref = av_buffer_ref(unit->data_ref);
826 if (!slice->data_ref)
827 return AVERROR(ENOMEM);
828 slice->data = unit->data + pos / 8;
829 slice->data_bit_start = pos % 8;
835 err = ff_cbs_alloc_unit_content(ctx, unit,
836 sizeof(H264RawAUD), NULL);
840 err = cbs_h264_read_aud(ctx, &gbc, unit->content);
848 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H264RawSEI),
853 err = cbs_h264_read_sei(ctx, &gbc, unit->content);
859 case H264_NAL_FILLER_DATA:
861 err = ff_cbs_alloc_unit_content(ctx, unit,
862 sizeof(H264RawFiller), NULL);
866 err = cbs_h264_read_filler(ctx, &gbc, unit->content);
873 return AVERROR(ENOSYS);
879 static int cbs_h265_read_nal_unit(CodedBitstreamContext *ctx,
880 CodedBitstreamUnit *unit)
885 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
889 switch (unit->type) {
894 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*vps),
900 err = cbs_h265_read_vps(ctx, &gbc, vps);
904 err = cbs_h265_replace_vps(ctx, unit);
913 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps),
919 err = cbs_h265_read_sps(ctx, &gbc, sps);
923 err = cbs_h265_replace_sps(ctx, unit);
933 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
939 err = cbs_h265_read_pps(ctx, &gbc, pps);
943 err = cbs_h265_replace_pps(ctx, unit);
949 case HEVC_NAL_TRAIL_N:
950 case HEVC_NAL_TRAIL_R:
953 case HEVC_NAL_STSA_N:
954 case HEVC_NAL_STSA_R:
955 case HEVC_NAL_RADL_N:
956 case HEVC_NAL_RADL_R:
957 case HEVC_NAL_RASL_N:
958 case HEVC_NAL_RASL_R:
959 case HEVC_NAL_BLA_W_LP:
960 case HEVC_NAL_BLA_W_RADL:
961 case HEVC_NAL_BLA_N_LP:
962 case HEVC_NAL_IDR_W_RADL:
963 case HEVC_NAL_IDR_N_LP:
964 case HEVC_NAL_CRA_NUT:
969 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
970 &cbs_h265_free_slice);
973 slice = unit->content;
975 err = cbs_h265_read_slice_segment_header(ctx, &gbc, &slice->header);
979 pos = get_bits_count(&gbc);
980 len = unit->data_size;
981 if (!unit->data[len - 1]) {
983 for (z = 0; z < len && !unit->data[len - z - 1]; z++);
984 av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "
985 "from slice data.\n", z);
989 slice->data_size = len - pos / 8;
990 slice->data_ref = av_buffer_ref(unit->data_ref);
991 if (!slice->data_ref)
992 return AVERROR(ENOMEM);
993 slice->data = unit->data + pos / 8;
994 slice->data_bit_start = pos % 8;
1000 err = ff_cbs_alloc_unit_content(ctx, unit,
1001 sizeof(H265RawAUD), NULL);
1005 err = cbs_h265_read_aud(ctx, &gbc, unit->content);
1011 case HEVC_NAL_SEI_PREFIX:
1013 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H265RawSEI),
1014 &cbs_h265_free_sei);
1019 err = cbs_h265_read_sei(ctx, &gbc, unit->content);
1027 return AVERROR(ENOSYS);
1033 static int cbs_h264_write_nal_unit(CodedBitstreamContext *ctx,
1034 CodedBitstreamUnit *unit,
1039 switch (unit->type) {
1042 H264RawSPS *sps = unit->content;
1044 err = cbs_h264_write_sps(ctx, pbc, sps);
1048 err = cbs_h264_replace_sps(ctx, unit);
1054 case H264_NAL_SPS_EXT:
1056 H264RawSPSExtension *sps_ext = unit->content;
1058 err = cbs_h264_write_sps_extension(ctx, pbc, sps_ext);
1066 H264RawPPS *pps = unit->content;
1068 err = cbs_h264_write_pps(ctx, pbc, pps);
1072 err = cbs_h264_replace_pps(ctx, unit);
1078 case H264_NAL_SLICE:
1079 case H264_NAL_IDR_SLICE:
1080 case H264_NAL_AUXILIARY_SLICE:
1082 H264RawSlice *slice = unit->content;
1084 int bits_left, end, zeroes;
1086 err = cbs_h264_write_slice_header(ctx, pbc, &slice->header);
1091 if (slice->data_size * 8 + 8 > put_bits_left(pbc))
1092 return AVERROR(ENOSPC);
1094 init_get_bits(&gbc, slice->data, slice->data_size * 8);
1095 skip_bits_long(&gbc, slice->data_bit_start);
1097 // Copy in two-byte blocks, but stop before copying the
1098 // rbsp_stop_one_bit in the final byte.
1099 while (get_bits_left(&gbc) > 23)
1100 put_bits(pbc, 16, get_bits(&gbc, 16));
1102 bits_left = get_bits_left(&gbc);
1103 end = get_bits(&gbc, bits_left);
1105 // rbsp_stop_one_bit must be present here.
1107 zeroes = ff_ctz(end);
1108 if (bits_left > zeroes + 1)
1109 put_bits(pbc, bits_left - zeroes - 1,
1110 end >> (zeroes + 1));
1111 put_bits(pbc, 1, 1);
1112 while (put_bits_count(pbc) % 8 != 0)
1113 put_bits(pbc, 1, 0);
1115 // No slice data - that was just the header.
1116 // (Bitstream may be unaligned!)
1123 err = cbs_h264_write_aud(ctx, pbc, unit->content);
1131 err = cbs_h264_write_sei(ctx, pbc, unit->content);
1137 case H264_NAL_FILLER_DATA:
1139 err = cbs_h264_write_filler(ctx, pbc, unit->content);
1146 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1147 "NAL unit type %"PRIu32".\n", unit->type);
1148 return AVERROR_PATCHWELCOME;
1154 static int cbs_h265_write_nal_unit(CodedBitstreamContext *ctx,
1155 CodedBitstreamUnit *unit,
1160 switch (unit->type) {
1163 H265RawVPS *vps = unit->content;
1165 err = cbs_h265_write_vps(ctx, pbc, vps);
1169 err = cbs_h265_replace_vps(ctx, unit);
1177 H265RawSPS *sps = unit->content;
1179 err = cbs_h265_write_sps(ctx, pbc, sps);
1183 err = cbs_h265_replace_sps(ctx, unit);
1191 H265RawPPS *pps = unit->content;
1193 err = cbs_h265_write_pps(ctx, pbc, pps);
1197 err = cbs_h265_replace_pps(ctx, unit);
1203 case HEVC_NAL_TRAIL_N:
1204 case HEVC_NAL_TRAIL_R:
1205 case HEVC_NAL_TSA_N:
1206 case HEVC_NAL_TSA_R:
1207 case HEVC_NAL_STSA_N:
1208 case HEVC_NAL_STSA_R:
1209 case HEVC_NAL_RADL_N:
1210 case HEVC_NAL_RADL_R:
1211 case HEVC_NAL_RASL_N:
1212 case HEVC_NAL_RASL_R:
1213 case HEVC_NAL_BLA_W_LP:
1214 case HEVC_NAL_BLA_W_RADL:
1215 case HEVC_NAL_BLA_N_LP:
1216 case HEVC_NAL_IDR_W_RADL:
1217 case HEVC_NAL_IDR_N_LP:
1218 case HEVC_NAL_CRA_NUT:
1220 H265RawSlice *slice = unit->content;
1222 int bits_left, end, zeroes;
1224 err = cbs_h265_write_slice_segment_header(ctx, pbc, &slice->header);
1229 if (slice->data_size * 8 + 8 > put_bits_left(pbc))
1230 return AVERROR(ENOSPC);
1232 init_get_bits(&gbc, slice->data, slice->data_size * 8);
1233 skip_bits_long(&gbc, slice->data_bit_start);
1235 // Copy in two-byte blocks, but stop before copying the
1236 // rbsp_stop_one_bit in the final byte.
1237 while (get_bits_left(&gbc) > 23)
1238 put_bits(pbc, 16, get_bits(&gbc, 16));
1240 bits_left = get_bits_left(&gbc);
1241 end = get_bits(&gbc, bits_left);
1243 // rbsp_stop_one_bit must be present here.
1245 zeroes = ff_ctz(end);
1246 if (bits_left > zeroes + 1)
1247 put_bits(pbc, bits_left - zeroes - 1,
1248 end >> (zeroes + 1));
1249 put_bits(pbc, 1, 1);
1250 while (put_bits_count(pbc) % 8 != 0)
1251 put_bits(pbc, 1, 0);
1253 // No slice data - that was just the header.
1260 err = cbs_h265_write_aud(ctx, pbc, unit->content);
1266 case HEVC_NAL_SEI_PREFIX:
1268 err = cbs_h265_write_sei(ctx, pbc, unit->content);
1276 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1277 "NAL unit type %"PRIu32".\n", unit->type);
1278 return AVERROR_PATCHWELCOME;
1284 static int cbs_h2645_write_nal_unit(CodedBitstreamContext *ctx,
1285 CodedBitstreamUnit *unit)
1287 CodedBitstreamH2645Context *priv = ctx->priv_data;
1288 enum AVCodecID codec_id = ctx->codec->codec_id;
1292 if (!priv->write_buffer) {
1293 // Initial write buffer size is 1MB.
1294 priv->write_buffer_size = 1024 * 1024;
1296 reallocate_and_try_again:
1297 err = av_reallocp(&priv->write_buffer, priv->write_buffer_size);
1299 av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a "
1300 "sufficiently large write buffer (last attempt "
1301 "%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size);
1306 init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size);
1308 if (codec_id == AV_CODEC_ID_H264)
1309 err = cbs_h264_write_nal_unit(ctx, unit, &pbc);
1311 err = cbs_h265_write_nal_unit(ctx, unit, &pbc);
1313 if (err == AVERROR(ENOSPC)) {
1315 priv->write_buffer_size *= 2;
1316 goto reallocate_and_try_again;
1318 // Overflow but we didn't notice.
1319 av_assert0(put_bits_count(&pbc) <= 8 * priv->write_buffer_size);
1322 // Write failed for some other reason.
1326 if (put_bits_count(&pbc) % 8)
1327 unit->data_bit_padding = 8 - put_bits_count(&pbc) % 8;
1329 unit->data_bit_padding = 0;
1331 unit->data_size = (put_bits_count(&pbc) + 7) / 8;
1332 flush_put_bits(&pbc);
1334 err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size);
1338 memcpy(unit->data, priv->write_buffer, unit->data_size);
1343 static int cbs_h2645_assemble_fragment(CodedBitstreamContext *ctx,
1344 CodedBitstreamFragment *frag)
1347 size_t max_size, dp, sp;
1348 int err, i, zero_run;
1350 for (i = 0; i < frag->nb_units; i++) {
1351 // Data should already all have been written when we get here.
1352 av_assert0(frag->units[i].data);
1356 for (i = 0; i < frag->nb_units; i++) {
1357 // Start code + content with worst-case emulation prevention.
1358 max_size += 3 + frag->units[i].data_size * 3 / 2;
1361 data = av_malloc(max_size + AV_INPUT_BUFFER_PADDING_SIZE);
1363 return AVERROR(ENOMEM);
1366 for (i = 0; i < frag->nb_units; i++) {
1367 CodedBitstreamUnit *unit = &frag->units[i];
1369 if (unit->data_bit_padding > 0) {
1370 if (i < frag->nb_units - 1)
1371 av_log(ctx->log_ctx, AV_LOG_WARNING, "Probably invalid "
1372 "unaligned padding on non-final NAL unit.\n");
1374 frag->data_bit_padding = unit->data_bit_padding;
1377 if ((ctx->codec->codec_id == AV_CODEC_ID_H264 &&
1378 (unit->type == H264_NAL_SPS ||
1379 unit->type == H264_NAL_PPS)) ||
1380 (ctx->codec->codec_id == AV_CODEC_ID_HEVC &&
1381 (unit->type == HEVC_NAL_VPS ||
1382 unit->type == HEVC_NAL_SPS ||
1383 unit->type == HEVC_NAL_PPS)) ||
1384 i == 0 /* (Assume this is the start of an access unit.) */) {
1388 // start_code_prefix_one_3bytes
1394 for (sp = 0; sp < unit->data_size; sp++) {
1396 if (unit->data[sp] == 0)
1401 if ((unit->data[sp] & ~3) == 0) {
1402 // emulation_prevention_three_byte
1405 zero_run = unit->data[sp] == 0;
1407 data[dp++] = unit->data[sp];
1411 av_assert0(dp <= max_size);
1412 err = av_reallocp(&data, dp + AV_INPUT_BUFFER_PADDING_SIZE);
1415 memset(data + dp, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1417 frag->data_ref = av_buffer_create(data, dp + AV_INPUT_BUFFER_PADDING_SIZE,
1419 if (!frag->data_ref) {
1421 return AVERROR(ENOMEM);
1425 frag->data_size = dp;
1430 static void cbs_h264_close(CodedBitstreamContext *ctx)
1432 CodedBitstreamH264Context *h264 = ctx->priv_data;
1435 ff_h2645_packet_uninit(&h264->common.read_packet);
1437 av_freep(&h264->common.write_buffer);
1439 for (i = 0; i < FF_ARRAY_ELEMS(h264->sps); i++)
1440 av_buffer_unref(&h264->sps_ref[i]);
1441 for (i = 0; i < FF_ARRAY_ELEMS(h264->pps); i++)
1442 av_buffer_unref(&h264->pps_ref[i]);
1445 static void cbs_h265_close(CodedBitstreamContext *ctx)
1447 CodedBitstreamH265Context *h265 = ctx->priv_data;
1450 ff_h2645_packet_uninit(&h265->common.read_packet);
1452 av_freep(&h265->common.write_buffer);
1454 for (i = 0; i < FF_ARRAY_ELEMS(h265->vps); i++)
1455 av_buffer_unref(&h265->vps_ref[i]);
1456 for (i = 0; i < FF_ARRAY_ELEMS(h265->sps); i++)
1457 av_buffer_unref(&h265->sps_ref[i]);
1458 for (i = 0; i < FF_ARRAY_ELEMS(h265->pps); i++)
1459 av_buffer_unref(&h265->pps_ref[i]);
1462 const CodedBitstreamType ff_cbs_type_h264 = {
1463 .codec_id = AV_CODEC_ID_H264,
1465 .priv_data_size = sizeof(CodedBitstreamH264Context),
1467 .split_fragment = &cbs_h2645_split_fragment,
1468 .read_unit = &cbs_h264_read_nal_unit,
1469 .write_unit = &cbs_h2645_write_nal_unit,
1470 .assemble_fragment = &cbs_h2645_assemble_fragment,
1472 .close = &cbs_h264_close,
1475 const CodedBitstreamType ff_cbs_type_h265 = {
1476 .codec_id = AV_CODEC_ID_HEVC,
1478 .priv_data_size = sizeof(CodedBitstreamH265Context),
1480 .split_fragment = &cbs_h2645_split_fragment,
1481 .read_unit = &cbs_h265_read_nal_unit,
1482 .write_unit = &cbs_h2645_write_nal_unit,
1483 .assemble_fragment = &cbs_h2645_assemble_fragment,
1485 .close = &cbs_h265_close,
1488 int ff_cbs_h264_add_sei_message(CodedBitstreamContext *ctx,
1489 CodedBitstreamFragment *au,
1490 const H264RawSEIPayload *payload)
1493 CodedBitstreamUnit *nal = NULL;
1496 // Find an existing SEI NAL unit to add to.
1497 for (i = 0; i < au->nb_units; i++) {
1498 if (au->units[i].type == H264_NAL_SEI) {
1499 nal = &au->units[i];
1507 // Need to make a new SEI NAL unit. Insert it before the first
1508 // slice data NAL unit; if no slice data, add at the end.
1509 AVBufferRef *sei_ref;
1511 sei = av_mallocz(sizeof(*sei));
1513 return AVERROR(ENOMEM);
1515 sei->nal_unit_header.nal_unit_type = H264_NAL_SEI;
1516 sei->nal_unit_header.nal_ref_idc = 0;
1518 sei_ref = av_buffer_create((uint8_t*)sei, sizeof(*sei),
1519 &cbs_h264_free_sei, ctx, 0);
1522 return AVERROR(ENOMEM);
1525 for (i = 0; i < au->nb_units; i++) {
1526 if (au->units[i].type == H264_NAL_SLICE ||
1527 au->units[i].type == H264_NAL_IDR_SLICE)
1531 err = ff_cbs_insert_unit_content(ctx, au, i, H264_NAL_SEI,
1533 av_buffer_unref(&sei_ref);
1538 if (sei->payload_count >= H264_MAX_SEI_PAYLOADS) {
1539 av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many payloads in "
1541 return AVERROR(EINVAL);
1544 memcpy(&sei->payload[sei->payload_count], payload, sizeof(*payload));
1545 ++sei->payload_count;
1550 int ff_cbs_h264_delete_sei_message(CodedBitstreamContext *ctx,
1551 CodedBitstreamFragment *au,
1552 CodedBitstreamUnit *nal,
1555 H264RawSEI *sei = nal->content;
1557 av_assert0(nal->type == H264_NAL_SEI);
1558 av_assert0(position >= 0 && position < sei->payload_count);
1560 if (position == 0 && sei->payload_count == 1) {
1561 // Deleting NAL unit entirely.
1564 for (i = 0; i < au->nb_units; i++) {
1565 if (&au->units[i] == nal)
1568 av_assert0(i < au->nb_units && "NAL unit not in access unit.");
1570 return ff_cbs_delete_unit(ctx, au, i);
1572 cbs_h264_free_sei_payload(&sei->payload[position]);
1574 --sei->payload_count;
1575 memmove(sei->payload + position,
1576 sei->payload + position + 1,
1577 (sei->payload_count - position) * sizeof(*sei->payload));