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"
29 #include "h2645_parse.h"
34 static int cbs_read_ue_golomb(CodedBitstreamContext *ctx, GetBitContext *gbc,
35 const char *name, const int *subscripts,
37 uint32_t range_min, uint32_t range_max)
44 position = get_bits_count(gbc);
46 for (i = 0; i < 32; i++) {
47 if (get_bits_left(gbc) < i + 1) {
48 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid ue-golomb code at "
49 "%s: bitstream ended.\n", name);
50 return AVERROR_INVALIDDATA;
53 bits[i] = k ? '1' : '0';
58 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid ue-golomb code at "
59 "%s: more than 31 zeroes.\n", name);
60 return AVERROR_INVALIDDATA;
63 for (j = 0; j < i; j++) {
65 bits[i + j + 1] = k ? '1' : '0';
66 value = value << 1 | k;
71 if (ctx->trace_enable)
72 ff_cbs_trace_syntax_element(ctx, position, name, subscripts,
75 if (value < range_min || value > range_max) {
76 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
77 "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n",
78 name, value, range_min, range_max);
79 return AVERROR_INVALIDDATA;
86 static int cbs_read_se_golomb(CodedBitstreamContext *ctx, GetBitContext *gbc,
87 const char *name, const int *subscripts,
89 int32_t range_min, int32_t range_max)
97 position = get_bits_count(gbc);
99 for (i = 0; i < 32; i++) {
100 if (get_bits_left(gbc) < i + 1) {
101 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid se-golomb code at "
102 "%s: bitstream ended.\n", name);
103 return AVERROR_INVALIDDATA;
106 bits[i] = k ? '1' : '0';
111 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid se-golomb code at "
112 "%s: more than 31 zeroes.\n", name);
113 return AVERROR_INVALIDDATA;
116 for (j = 0; j < i; j++) {
118 bits[i + j + 1] = k ? '1' : '0';
123 value = -(int32_t)(v / 2);
127 if (ctx->trace_enable)
128 ff_cbs_trace_syntax_element(ctx, position, name, subscripts,
131 if (value < range_min || value > range_max) {
132 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
133 "%"PRId32", but must be in [%"PRId32",%"PRId32"].\n",
134 name, value, range_min, range_max);
135 return AVERROR_INVALIDDATA;
142 static int cbs_write_ue_golomb(CodedBitstreamContext *ctx, PutBitContext *pbc,
143 const char *name, const int *subscripts,
145 uint32_t range_min, uint32_t range_max)
149 if (value < range_min || value > range_max) {
150 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
151 "%"PRIu32", but must be in [%"PRIu32",%"PRIu32"].\n",
152 name, value, range_min, range_max);
153 return AVERROR_INVALIDDATA;
155 av_assert0(value != UINT32_MAX);
157 len = av_log2(value + 1);
158 if (put_bits_left(pbc) < 2 * len + 1)
159 return AVERROR(ENOSPC);
161 if (ctx->trace_enable) {
165 for (i = 0; i < len; i++)
168 for (i = 0; i < len; i++)
169 bits[len + i + 1] = (value + 1) >> (len - i - 1) & 1 ? '1' : '0';
170 bits[len + len + 1] = 0;
172 ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc),
173 name, subscripts, bits, value);
176 put_bits(pbc, len, 0);
178 put_bits(pbc, len + 1, value + 1);
180 put_bits32(pbc, value + 1);
185 static int cbs_write_se_golomb(CodedBitstreamContext *ctx, PutBitContext *pbc,
186 const char *name, const int *subscripts,
188 int32_t range_min, int32_t range_max)
193 if (value < range_min || value > range_max) {
194 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s out of range: "
195 "%"PRId32", but must be in [%"PRId32",%"PRId32"].\n",
196 name, value, range_min, range_max);
197 return AVERROR_INVALIDDATA;
199 av_assert0(value != INT32_MIN);
204 uvalue = 2 * (uint32_t)value - 1;
206 uvalue = 2 * (uint32_t)-value;
208 len = av_log2(uvalue + 1);
209 if (put_bits_left(pbc) < 2 * len + 1)
210 return AVERROR(ENOSPC);
212 if (ctx->trace_enable) {
216 for (i = 0; i < len; i++)
219 for (i = 0; i < len; i++)
220 bits[len + i + 1] = (uvalue + 1) >> (len - i - 1) & 1 ? '1' : '0';
221 bits[len + len + 1] = 0;
223 ff_cbs_trace_syntax_element(ctx, put_bits_count(pbc),
224 name, subscripts, bits, value);
227 put_bits(pbc, len, 0);
229 put_bits(pbc, len + 1, uvalue + 1);
231 put_bits32(pbc, uvalue + 1);
236 // payload_extension_present() - true if we are before the last 1-bit
237 // in the payload structure, which must be in the last byte.
238 static int cbs_h265_payload_extension_present(GetBitContext *gbc, uint32_t payload_size,
241 int bits_left = payload_size * 8 - cur_pos;
242 return (bits_left > 0 &&
243 (bits_left > 7 || show_bits(gbc, bits_left) & MAX_UINT_BITS(bits_left - 1)));
246 #define HEADER(name) do { \
247 ff_cbs_trace_header(ctx, name); \
250 #define CHECK(call) do { \
256 #define FUNC_NAME(rw, codec, name) cbs_ ## codec ## _ ## rw ## _ ## name
257 #define FUNC_H264(rw, name) FUNC_NAME(rw, h264, name)
258 #define FUNC_H265(rw, name) FUNC_NAME(rw, h265, name)
260 #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL)
262 #define u(width, name, range_min, range_max) \
263 xu(width, name, current->name, range_min, range_max, 0, )
264 #define ub(width, name) \
265 xu(width, name, current->name, 0, MAX_UINT_BITS(width), 0, )
266 #define flag(name) ub(1, name)
267 #define ue(name, range_min, range_max) \
268 xue(name, current->name, range_min, range_max, 0, )
269 #define i(width, name, range_min, range_max) \
270 xi(width, name, current->name, range_min, range_max, 0, )
271 #define ib(width, name) \
272 xi(width, name, current->name, MIN_INT_BITS(width), MAX_INT_BITS(width), 0, )
273 #define se(name, range_min, range_max) \
274 xse(name, current->name, range_min, range_max, 0, )
276 #define us(width, name, range_min, range_max, subs, ...) \
277 xu(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
278 #define ubs(width, name, subs, ...) \
279 xu(width, name, current->name, 0, MAX_UINT_BITS(width), subs, __VA_ARGS__)
280 #define flags(name, subs, ...) \
281 xu(1, name, current->name, 0, 1, subs, __VA_ARGS__)
282 #define ues(name, range_min, range_max, subs, ...) \
283 xue(name, current->name, range_min, range_max, subs, __VA_ARGS__)
284 #define is(width, name, range_min, range_max, subs, ...) \
285 xi(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
286 #define ibs(width, name, subs, ...) \
287 xi(width, name, current->name, MIN_INT_BITS(width), MAX_INT_BITS(width), subs, __VA_ARGS__)
288 #define ses(name, range_min, range_max, subs, ...) \
289 xse(name, current->name, range_min, range_max, subs, __VA_ARGS__)
291 #define fixed(width, name, value) do { \
292 av_unused uint32_t fixed_value = value; \
293 xu(width, name, fixed_value, value, value, 0, ); \
298 #define READWRITE read
299 #define RWContext GetBitContext
301 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
303 CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \
304 SUBSCRIPTS(subs, __VA_ARGS__), \
305 &value, range_min, range_max)); \
308 #define xue(name, var, range_min, range_max, subs, ...) do { \
310 CHECK(cbs_read_ue_golomb(ctx, rw, #name, \
311 SUBSCRIPTS(subs, __VA_ARGS__), \
312 &value, range_min, range_max)); \
315 #define xi(width, name, var, range_min, range_max, subs, ...) do { \
317 CHECK(ff_cbs_read_signed(ctx, rw, width, #name, \
318 SUBSCRIPTS(subs, __VA_ARGS__), \
319 &value, range_min, range_max)); \
322 #define xse(name, var, range_min, range_max, subs, ...) do { \
324 CHECK(cbs_read_se_golomb(ctx, rw, #name, \
325 SUBSCRIPTS(subs, __VA_ARGS__), \
326 &value, range_min, range_max)); \
331 #define infer(name, value) do { \
332 current->name = value; \
335 static int cbs_h2645_read_more_rbsp_data(GetBitContext *gbc)
337 int bits_left = get_bits_left(gbc);
342 if (show_bits(gbc, bits_left) & MAX_UINT_BITS(bits_left - 1))
347 #define more_rbsp_data(var) ((var) = cbs_h2645_read_more_rbsp_data(rw))
349 #define byte_alignment(rw) (get_bits_count(rw) % 8)
351 #define allocate(name, size) do { \
352 name ## _ref = av_buffer_allocz(size + \
353 AV_INPUT_BUFFER_PADDING_SIZE); \
355 return AVERROR(ENOMEM); \
356 name = name ## _ref->data; \
359 #define FUNC(name) FUNC_H264(READWRITE, name)
360 #include "cbs_h264_syntax_template.c"
363 #define FUNC(name) FUNC_H265(READWRITE, name)
364 #include "cbs_h265_syntax_template.c"
375 #undef more_rbsp_data
376 #undef byte_alignment
381 #define READWRITE write
382 #define RWContext PutBitContext
384 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
385 uint32_t value = var; \
386 CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \
387 SUBSCRIPTS(subs, __VA_ARGS__), \
388 value, range_min, range_max)); \
390 #define xue(name, var, range_min, range_max, subs, ...) do { \
391 uint32_t value = var; \
392 CHECK(cbs_write_ue_golomb(ctx, rw, #name, \
393 SUBSCRIPTS(subs, __VA_ARGS__), \
394 value, range_min, range_max)); \
396 #define xi(width, name, var, range_min, range_max, subs, ...) do { \
397 int32_t value = var; \
398 CHECK(ff_cbs_write_signed(ctx, rw, width, #name, \
399 SUBSCRIPTS(subs, __VA_ARGS__), \
400 value, range_min, range_max)); \
402 #define xse(name, var, range_min, range_max, subs, ...) do { \
403 int32_t value = var; \
404 CHECK(cbs_write_se_golomb(ctx, rw, #name, \
405 SUBSCRIPTS(subs, __VA_ARGS__), \
406 value, range_min, range_max)); \
409 #define infer(name, value) do { \
410 if (current->name != (value)) { \
411 av_log(ctx->log_ctx, AV_LOG_WARNING, "Warning: " \
412 "%s does not match inferred value: " \
413 "%"PRId64", but should be %"PRId64".\n", \
414 #name, (int64_t)current->name, (int64_t)(value)); \
418 #define more_rbsp_data(var) (var)
420 #define byte_alignment(rw) (put_bits_count(rw) % 8)
422 #define allocate(name, size) do { \
424 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s must be set " \
425 "for writing.\n", #name); \
426 return AVERROR_INVALIDDATA; \
430 #define FUNC(name) FUNC_H264(READWRITE, name)
431 #include "cbs_h264_syntax_template.c"
434 #define FUNC(name) FUNC_H265(READWRITE, name)
435 #include "cbs_h265_syntax_template.c"
451 #undef more_rbsp_data
452 #undef byte_alignment
456 static void cbs_h264_free_pps(void *opaque, uint8_t *content)
458 H264RawPPS *pps = (H264RawPPS*)content;
459 av_buffer_unref(&pps->slice_group_id_ref);
463 static void cbs_h264_free_sei_payload(H264RawSEIPayload *payload)
465 switch (payload->payload_type) {
466 case H264_SEI_TYPE_BUFFERING_PERIOD:
467 case H264_SEI_TYPE_PIC_TIMING:
468 case H264_SEI_TYPE_PAN_SCAN_RECT:
469 case H264_SEI_TYPE_RECOVERY_POINT:
470 case H264_SEI_TYPE_DISPLAY_ORIENTATION:
471 case H264_SEI_TYPE_MASTERING_DISPLAY_COLOUR_VOLUME:
472 case H264_SEI_TYPE_ALTERNATIVE_TRANSFER:
474 case H264_SEI_TYPE_USER_DATA_REGISTERED:
475 av_buffer_unref(&payload->payload.user_data_registered.data_ref);
477 case H264_SEI_TYPE_USER_DATA_UNREGISTERED:
478 av_buffer_unref(&payload->payload.user_data_unregistered.data_ref);
481 av_buffer_unref(&payload->payload.other.data_ref);
486 static void cbs_h264_free_sei(void *opaque, uint8_t *content)
488 H264RawSEI *sei = (H264RawSEI*)content;
490 for (i = 0; i < sei->payload_count; i++)
491 cbs_h264_free_sei_payload(&sei->payload[i]);
495 static void cbs_h264_free_slice(void *opaque, uint8_t *content)
497 H264RawSlice *slice = (H264RawSlice*)content;
498 av_buffer_unref(&slice->data_ref);
502 static void cbs_h265_free_vps(void *opaque, uint8_t *content)
504 H265RawVPS *vps = (H265RawVPS*)content;
505 av_buffer_unref(&vps->extension_data.data_ref);
509 static void cbs_h265_free_sps(void *opaque, uint8_t *content)
511 H265RawSPS *sps = (H265RawSPS*)content;
512 av_buffer_unref(&sps->extension_data.data_ref);
516 static void cbs_h265_free_pps(void *opaque, uint8_t *content)
518 H265RawPPS *pps = (H265RawPPS*)content;
519 av_buffer_unref(&pps->extension_data.data_ref);
523 static void cbs_h265_free_slice(void *opaque, uint8_t *content)
525 H265RawSlice *slice = (H265RawSlice*)content;
526 av_buffer_unref(&slice->data_ref);
530 static void cbs_h265_free_sei_payload(H265RawSEIPayload *payload)
532 switch (payload->payload_type) {
533 case HEVC_SEI_TYPE_BUFFERING_PERIOD:
534 case HEVC_SEI_TYPE_PICTURE_TIMING:
535 case HEVC_SEI_TYPE_PAN_SCAN_RECT:
536 case HEVC_SEI_TYPE_RECOVERY_POINT:
537 case HEVC_SEI_TYPE_DISPLAY_ORIENTATION:
538 case HEVC_SEI_TYPE_ACTIVE_PARAMETER_SETS:
539 case HEVC_SEI_TYPE_DECODED_PICTURE_HASH:
540 case HEVC_SEI_TYPE_TIME_CODE:
541 case HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO:
542 case HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO:
543 case HEVC_SEI_TYPE_ALTERNATIVE_TRANSFER_CHARACTERISTICS:
544 case HEVC_SEI_TYPE_ALPHA_CHANNEL_INFO:
546 case HEVC_SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35:
547 av_buffer_unref(&payload->payload.user_data_registered.data_ref);
549 case HEVC_SEI_TYPE_USER_DATA_UNREGISTERED:
550 av_buffer_unref(&payload->payload.user_data_unregistered.data_ref);
553 av_buffer_unref(&payload->payload.other.data_ref);
556 av_buffer_unref(&payload->extension_data.data_ref);
559 static void cbs_h265_free_sei(void *opaque, uint8_t *content)
561 H265RawSEI *sei = (H265RawSEI*)content;
563 for (i = 0; i < sei->payload_count; i++)
564 cbs_h265_free_sei_payload(&sei->payload[i]);
568 static int cbs_h2645_fragment_add_nals(CodedBitstreamContext *ctx,
569 CodedBitstreamFragment *frag,
570 const H2645Packet *packet)
574 for (i = 0; i < packet->nb_nals; i++) {
575 const H2645NAL *nal = &packet->nals[i];
577 size_t size = nal->size;
579 if (nal->nuh_layer_id > 0)
582 // Remove trailing zeroes.
583 while (size > 0 && nal->data[size - 1] == 0)
586 av_log(ctx->log_ctx, AV_LOG_VERBOSE, "Discarding empty 0 NAL unit\n");
590 ref = (nal->data == nal->raw_data) ? frag->data_ref
591 : packet->rbsp.rbsp_buffer_ref;
593 err = ff_cbs_insert_unit_data(ctx, frag, -1, nal->type,
594 (uint8_t*)nal->data, size, ref);
602 static int cbs_h2645_split_fragment(CodedBitstreamContext *ctx,
603 CodedBitstreamFragment *frag,
606 enum AVCodecID codec_id = ctx->codec->codec_id;
607 CodedBitstreamH2645Context *priv = ctx->priv_data;
611 av_assert0(frag->data && frag->nb_units == 0);
612 if (frag->data_size == 0)
615 if (header && frag->data[0] && codec_id == AV_CODEC_ID_H264) {
617 size_t size, start, end;
618 int i, count, version;
622 bytestream2_init(&gbc, frag->data, frag->data_size);
624 if (bytestream2_get_bytes_left(&gbc) < 6)
625 return AVERROR_INVALIDDATA;
627 version = bytestream2_get_byte(&gbc);
629 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid AVCC header: "
630 "first byte %u.\n", version);
631 return AVERROR_INVALIDDATA;
634 bytestream2_skip(&gbc, 3);
635 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
638 count = bytestream2_get_byte(&gbc) & 0x1f;
639 start = bytestream2_tell(&gbc);
640 for (i = 0; i < count; i++) {
641 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
642 return AVERROR_INVALIDDATA;
643 size = bytestream2_get_be16(&gbc);
644 if (bytestream2_get_bytes_left(&gbc) < size)
645 return AVERROR_INVALIDDATA;
646 bytestream2_skip(&gbc, size);
648 end = bytestream2_tell(&gbc);
650 err = ff_h2645_packet_split(&priv->read_packet,
651 frag->data + start, end - start,
652 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1, 1);
654 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC SPS array.\n");
657 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
662 count = bytestream2_get_byte(&gbc);
663 start = bytestream2_tell(&gbc);
664 for (i = 0; i < count; i++) {
665 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
666 return AVERROR_INVALIDDATA;
667 size = bytestream2_get_be16(&gbc);
668 if (bytestream2_get_bytes_left(&gbc) < size)
669 return AVERROR_INVALIDDATA;
670 bytestream2_skip(&gbc, size);
672 end = bytestream2_tell(&gbc);
674 err = ff_h2645_packet_split(&priv->read_packet,
675 frag->data + start, end - start,
676 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1, 1);
678 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC PPS array.\n");
681 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
685 if (bytestream2_get_bytes_left(&gbc) > 0) {
686 av_log(ctx->log_ctx, AV_LOG_WARNING, "%u bytes left at end of AVCC "
687 "header.\n", bytestream2_get_bytes_left(&gbc));
690 } else if (header && frag->data[0] && codec_id == AV_CODEC_ID_HEVC) {
692 size_t size, start, end;
693 int i, j, nb_arrays, nal_unit_type, nb_nals, version;
697 bytestream2_init(&gbc, frag->data, frag->data_size);
699 if (bytestream2_get_bytes_left(&gbc) < 23)
700 return AVERROR_INVALIDDATA;
702 version = bytestream2_get_byte(&gbc);
704 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid HVCC header: "
705 "first byte %u.\n", version);
706 return AVERROR_INVALIDDATA;
709 bytestream2_skip(&gbc, 20);
710 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
712 nb_arrays = bytestream2_get_byte(&gbc);
713 for (i = 0; i < nb_arrays; i++) {
714 nal_unit_type = bytestream2_get_byte(&gbc) & 0x3f;
715 nb_nals = bytestream2_get_be16(&gbc);
717 start = bytestream2_tell(&gbc);
718 for (j = 0; j < nb_nals; j++) {
719 if (bytestream2_get_bytes_left(&gbc) < 2)
720 return AVERROR_INVALIDDATA;
721 size = bytestream2_get_be16(&gbc);
722 if (bytestream2_get_bytes_left(&gbc) < size)
723 return AVERROR_INVALIDDATA;
724 bytestream2_skip(&gbc, size);
726 end = bytestream2_tell(&gbc);
728 err = ff_h2645_packet_split(&priv->read_packet,
729 frag->data + start, end - start,
730 ctx->log_ctx, 1, 2, AV_CODEC_ID_HEVC, 1, 1);
732 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split "
733 "HVCC array %d (%d NAL units of type %d).\n",
734 i, nb_nals, nal_unit_type);
737 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
743 // Annex B, or later MP4 with already-known parameters.
745 err = ff_h2645_packet_split(&priv->read_packet,
746 frag->data, frag->data_size,
748 priv->mp4, priv->nal_length_size,
753 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
761 #define cbs_h2645_replace_ps(h26n, ps_name, ps_var, id_element) \
762 static int cbs_h26 ## h26n ## _replace_ ## ps_var(CodedBitstreamContext *ctx, \
763 CodedBitstreamUnit *unit) \
765 CodedBitstreamH26 ## h26n ## Context *priv = ctx->priv_data; \
766 H26 ## h26n ## Raw ## ps_name *ps_var = unit->content; \
767 unsigned int id = ps_var->id_element; \
768 if (id >= FF_ARRAY_ELEMS(priv->ps_var)) { \
769 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid " #ps_name \
770 " id : %d.\n", id); \
771 return AVERROR_INVALIDDATA; \
773 if (priv->ps_var[id] == priv->active_ ## ps_var) \
774 priv->active_ ## ps_var = NULL ; \
775 av_buffer_unref(&priv->ps_var ## _ref[id]); \
776 if (unit->content_ref) \
777 priv->ps_var ## _ref[id] = av_buffer_ref(unit->content_ref); \
779 priv->ps_var ## _ref[id] = av_buffer_alloc(sizeof(*ps_var)); \
780 if (!priv->ps_var ## _ref[id]) \
781 return AVERROR(ENOMEM); \
782 priv->ps_var[id] = (H26 ## h26n ## Raw ## ps_name *)priv->ps_var ## _ref[id]->data; \
783 if (!unit->content_ref) \
784 memcpy(priv->ps_var[id], ps_var, sizeof(*ps_var)); \
788 cbs_h2645_replace_ps(4, SPS, sps, seq_parameter_set_id)
789 cbs_h2645_replace_ps(4, PPS, pps, pic_parameter_set_id)
790 cbs_h2645_replace_ps(5, VPS, vps, vps_video_parameter_set_id)
791 cbs_h2645_replace_ps(5, SPS, sps, sps_seq_parameter_set_id)
792 cbs_h2645_replace_ps(5, PPS, pps, pps_pic_parameter_set_id)
794 static int cbs_h264_read_nal_unit(CodedBitstreamContext *ctx,
795 CodedBitstreamUnit *unit)
800 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
804 switch (unit->type) {
809 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps), NULL);
814 err = cbs_h264_read_sps(ctx, &gbc, sps);
818 err = cbs_h264_replace_sps(ctx, unit);
824 case H264_NAL_SPS_EXT:
826 err = ff_cbs_alloc_unit_content(ctx, unit,
827 sizeof(H264RawSPSExtension),
832 err = cbs_h264_read_sps_extension(ctx, &gbc, unit->content);
842 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
848 err = cbs_h264_read_pps(ctx, &gbc, pps);
852 err = cbs_h264_replace_pps(ctx, unit);
859 case H264_NAL_IDR_SLICE:
860 case H264_NAL_AUXILIARY_SLICE:
865 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
866 &cbs_h264_free_slice);
869 slice = unit->content;
871 err = cbs_h264_read_slice_header(ctx, &gbc, &slice->header);
875 if (!cbs_h2645_read_more_rbsp_data(&gbc))
876 return AVERROR_INVALIDDATA;
878 pos = get_bits_count(&gbc);
879 len = unit->data_size;
881 slice->data_size = len - pos / 8;
882 slice->data_ref = av_buffer_ref(unit->data_ref);
883 if (!slice->data_ref)
884 return AVERROR(ENOMEM);
885 slice->data = unit->data + pos / 8;
886 slice->data_bit_start = pos % 8;
892 err = ff_cbs_alloc_unit_content(ctx, unit,
893 sizeof(H264RawAUD), NULL);
897 err = cbs_h264_read_aud(ctx, &gbc, unit->content);
905 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H264RawSEI),
910 err = cbs_h264_read_sei(ctx, &gbc, unit->content);
916 case H264_NAL_FILLER_DATA:
918 err = ff_cbs_alloc_unit_content(ctx, unit,
919 sizeof(H264RawFiller), NULL);
923 err = cbs_h264_read_filler(ctx, &gbc, unit->content);
929 case H264_NAL_END_SEQUENCE:
930 case H264_NAL_END_STREAM:
932 err = ff_cbs_alloc_unit_content(ctx, unit,
933 sizeof(H264RawNALUnitHeader),
938 err = (unit->type == H264_NAL_END_SEQUENCE ?
939 cbs_h264_read_end_of_sequence :
940 cbs_h264_read_end_of_stream)(ctx, &gbc, unit->content);
947 return AVERROR(ENOSYS);
953 static int cbs_h265_read_nal_unit(CodedBitstreamContext *ctx,
954 CodedBitstreamUnit *unit)
959 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
963 switch (unit->type) {
968 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*vps),
974 err = cbs_h265_read_vps(ctx, &gbc, vps);
978 err = cbs_h265_replace_vps(ctx, unit);
987 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps),
993 err = cbs_h265_read_sps(ctx, &gbc, sps);
997 err = cbs_h265_replace_sps(ctx, unit);
1007 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
1008 &cbs_h265_free_pps);
1011 pps = unit->content;
1013 err = cbs_h265_read_pps(ctx, &gbc, pps);
1017 err = cbs_h265_replace_pps(ctx, unit);
1023 case HEVC_NAL_TRAIL_N:
1024 case HEVC_NAL_TRAIL_R:
1025 case HEVC_NAL_TSA_N:
1026 case HEVC_NAL_TSA_R:
1027 case HEVC_NAL_STSA_N:
1028 case HEVC_NAL_STSA_R:
1029 case HEVC_NAL_RADL_N:
1030 case HEVC_NAL_RADL_R:
1031 case HEVC_NAL_RASL_N:
1032 case HEVC_NAL_RASL_R:
1033 case HEVC_NAL_BLA_W_LP:
1034 case HEVC_NAL_BLA_W_RADL:
1035 case HEVC_NAL_BLA_N_LP:
1036 case HEVC_NAL_IDR_W_RADL:
1037 case HEVC_NAL_IDR_N_LP:
1038 case HEVC_NAL_CRA_NUT:
1040 H265RawSlice *slice;
1043 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
1044 &cbs_h265_free_slice);
1047 slice = unit->content;
1049 err = cbs_h265_read_slice_segment_header(ctx, &gbc, &slice->header);
1053 if (!cbs_h2645_read_more_rbsp_data(&gbc))
1054 return AVERROR_INVALIDDATA;
1056 pos = get_bits_count(&gbc);
1057 len = unit->data_size;
1059 slice->data_size = len - pos / 8;
1060 slice->data_ref = av_buffer_ref(unit->data_ref);
1061 if (!slice->data_ref)
1062 return AVERROR(ENOMEM);
1063 slice->data = unit->data + pos / 8;
1064 slice->data_bit_start = pos % 8;
1070 err = ff_cbs_alloc_unit_content(ctx, unit,
1071 sizeof(H265RawAUD), NULL);
1075 err = cbs_h265_read_aud(ctx, &gbc, unit->content);
1081 case HEVC_NAL_SEI_PREFIX:
1082 case HEVC_NAL_SEI_SUFFIX:
1084 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H265RawSEI),
1085 &cbs_h265_free_sei);
1090 err = cbs_h265_read_sei(ctx, &gbc, unit->content,
1091 unit->type == HEVC_NAL_SEI_PREFIX);
1099 return AVERROR(ENOSYS);
1105 static int cbs_h2645_write_slice_data(CodedBitstreamContext *ctx,
1106 PutBitContext *pbc, const uint8_t *data,
1107 size_t data_size, int data_bit_start)
1109 size_t rest = data_size - (data_bit_start + 7) / 8;
1110 const uint8_t *pos = data + data_bit_start / 8;
1112 av_assert0(data_bit_start >= 0 &&
1113 data_size > data_bit_start / 8);
1115 if (data_size * 8 + 8 > put_bits_left(pbc))
1116 return AVERROR(ENOSPC);
1119 goto rbsp_stop_one_bit;
1121 // First copy the remaining bits of the first byte
1122 // The above check ensures that we do not accidentally
1123 // copy beyond the rbsp_stop_one_bit.
1124 if (data_bit_start % 8)
1125 put_bits(pbc, 8 - data_bit_start % 8,
1126 *pos++ & MAX_UINT_BITS(8 - data_bit_start % 8));
1128 if (put_bits_count(pbc) % 8 == 0) {
1129 // If the writer is aligned at this point,
1130 // memcpy can be used to improve performance.
1131 // This happens normally for CABAC.
1132 flush_put_bits(pbc);
1133 memcpy(put_bits_ptr(pbc), pos, rest);
1134 skip_put_bytes(pbc, rest);
1136 // If not, we have to copy manually.
1137 // rbsp_stop_one_bit forces us to special-case
1142 for (; rest > 4; rest -= 4, pos += 4)
1143 put_bits32(pbc, AV_RB32(pos));
1145 for (; rest > 1; rest--, pos++)
1146 put_bits(pbc, 8, *pos);
1149 temp = rest ? *pos : *pos & MAX_UINT_BITS(8 - data_bit_start % 8);
1154 i = rest ? (8 - i) : (8 - i - data_bit_start % 8);
1155 put_bits(pbc, i, temp);
1156 if (put_bits_count(pbc) % 8)
1157 put_bits(pbc, 8 - put_bits_count(pbc) % 8, 0);
1163 static int cbs_h264_write_nal_unit(CodedBitstreamContext *ctx,
1164 CodedBitstreamUnit *unit,
1169 switch (unit->type) {
1172 H264RawSPS *sps = unit->content;
1174 err = cbs_h264_write_sps(ctx, pbc, sps);
1178 err = cbs_h264_replace_sps(ctx, unit);
1184 case H264_NAL_SPS_EXT:
1186 H264RawSPSExtension *sps_ext = unit->content;
1188 err = cbs_h264_write_sps_extension(ctx, pbc, sps_ext);
1196 H264RawPPS *pps = unit->content;
1198 err = cbs_h264_write_pps(ctx, pbc, pps);
1202 err = cbs_h264_replace_pps(ctx, unit);
1208 case H264_NAL_SLICE:
1209 case H264_NAL_IDR_SLICE:
1210 case H264_NAL_AUXILIARY_SLICE:
1212 H264RawSlice *slice = unit->content;
1214 err = cbs_h264_write_slice_header(ctx, pbc, &slice->header);
1219 err = cbs_h2645_write_slice_data(ctx, pbc, slice->data,
1221 slice->data_bit_start);
1225 // No slice data - that was just the header.
1226 // (Bitstream may be unaligned!)
1233 err = cbs_h264_write_aud(ctx, pbc, unit->content);
1241 err = cbs_h264_write_sei(ctx, pbc, unit->content);
1247 case H264_NAL_FILLER_DATA:
1249 err = cbs_h264_write_filler(ctx, pbc, unit->content);
1255 case H264_NAL_END_SEQUENCE:
1257 err = cbs_h264_write_end_of_sequence(ctx, pbc, unit->content);
1263 case H264_NAL_END_STREAM:
1265 err = cbs_h264_write_end_of_stream(ctx, pbc, unit->content);
1272 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1273 "NAL unit type %"PRIu32".\n", unit->type);
1274 return AVERROR_PATCHWELCOME;
1280 static int cbs_h265_write_nal_unit(CodedBitstreamContext *ctx,
1281 CodedBitstreamUnit *unit,
1286 switch (unit->type) {
1289 H265RawVPS *vps = unit->content;
1291 err = cbs_h265_write_vps(ctx, pbc, vps);
1295 err = cbs_h265_replace_vps(ctx, unit);
1303 H265RawSPS *sps = unit->content;
1305 err = cbs_h265_write_sps(ctx, pbc, sps);
1309 err = cbs_h265_replace_sps(ctx, unit);
1317 H265RawPPS *pps = unit->content;
1319 err = cbs_h265_write_pps(ctx, pbc, pps);
1323 err = cbs_h265_replace_pps(ctx, unit);
1329 case HEVC_NAL_TRAIL_N:
1330 case HEVC_NAL_TRAIL_R:
1331 case HEVC_NAL_TSA_N:
1332 case HEVC_NAL_TSA_R:
1333 case HEVC_NAL_STSA_N:
1334 case HEVC_NAL_STSA_R:
1335 case HEVC_NAL_RADL_N:
1336 case HEVC_NAL_RADL_R:
1337 case HEVC_NAL_RASL_N:
1338 case HEVC_NAL_RASL_R:
1339 case HEVC_NAL_BLA_W_LP:
1340 case HEVC_NAL_BLA_W_RADL:
1341 case HEVC_NAL_BLA_N_LP:
1342 case HEVC_NAL_IDR_W_RADL:
1343 case HEVC_NAL_IDR_N_LP:
1344 case HEVC_NAL_CRA_NUT:
1346 H265RawSlice *slice = unit->content;
1348 err = cbs_h265_write_slice_segment_header(ctx, pbc, &slice->header);
1353 err = cbs_h2645_write_slice_data(ctx, pbc, slice->data,
1355 slice->data_bit_start);
1359 // No slice data - that was just the header.
1366 err = cbs_h265_write_aud(ctx, pbc, unit->content);
1372 case HEVC_NAL_SEI_PREFIX:
1373 case HEVC_NAL_SEI_SUFFIX:
1375 err = cbs_h265_write_sei(ctx, pbc, unit->content,
1376 unit->type == HEVC_NAL_SEI_PREFIX);
1384 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1385 "NAL unit type %"PRIu32".\n", unit->type);
1386 return AVERROR_PATCHWELCOME;
1392 static int cbs_h2645_assemble_fragment(CodedBitstreamContext *ctx,
1393 CodedBitstreamFragment *frag)
1396 size_t max_size, dp, sp;
1397 int err, i, zero_run;
1399 for (i = 0; i < frag->nb_units; i++) {
1400 // Data should already all have been written when we get here.
1401 av_assert0(frag->units[i].data);
1405 for (i = 0; i < frag->nb_units; i++) {
1406 // Start code + content with worst-case emulation prevention.
1407 max_size += 4 + frag->units[i].data_size * 3 / 2;
1410 data = av_realloc(NULL, max_size + AV_INPUT_BUFFER_PADDING_SIZE);
1412 return AVERROR(ENOMEM);
1415 for (i = 0; i < frag->nb_units; i++) {
1416 CodedBitstreamUnit *unit = &frag->units[i];
1418 if (unit->data_bit_padding > 0) {
1419 if (i < frag->nb_units - 1)
1420 av_log(ctx->log_ctx, AV_LOG_WARNING, "Probably invalid "
1421 "unaligned padding on non-final NAL unit.\n");
1423 frag->data_bit_padding = unit->data_bit_padding;
1426 if ((ctx->codec->codec_id == AV_CODEC_ID_H264 &&
1427 (unit->type == H264_NAL_SPS ||
1428 unit->type == H264_NAL_PPS)) ||
1429 (ctx->codec->codec_id == AV_CODEC_ID_HEVC &&
1430 (unit->type == HEVC_NAL_VPS ||
1431 unit->type == HEVC_NAL_SPS ||
1432 unit->type == HEVC_NAL_PPS)) ||
1433 i == 0 /* (Assume this is the start of an access unit.) */) {
1437 // start_code_prefix_one_3bytes
1443 for (sp = 0; sp < unit->data_size; sp++) {
1445 if (unit->data[sp] == 0)
1450 if ((unit->data[sp] & ~3) == 0) {
1451 // emulation_prevention_three_byte
1454 zero_run = unit->data[sp] == 0;
1456 data[dp++] = unit->data[sp];
1460 av_assert0(dp <= max_size);
1461 err = av_reallocp(&data, dp + AV_INPUT_BUFFER_PADDING_SIZE);
1464 memset(data + dp, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1466 frag->data_ref = av_buffer_create(data, dp + AV_INPUT_BUFFER_PADDING_SIZE,
1468 if (!frag->data_ref) {
1470 return AVERROR(ENOMEM);
1474 frag->data_size = dp;
1479 static void cbs_h264_close(CodedBitstreamContext *ctx)
1481 CodedBitstreamH264Context *h264 = ctx->priv_data;
1484 ff_h2645_packet_uninit(&h264->common.read_packet);
1486 for (i = 0; i < FF_ARRAY_ELEMS(h264->sps); i++)
1487 av_buffer_unref(&h264->sps_ref[i]);
1488 for (i = 0; i < FF_ARRAY_ELEMS(h264->pps); i++)
1489 av_buffer_unref(&h264->pps_ref[i]);
1492 static void cbs_h265_close(CodedBitstreamContext *ctx)
1494 CodedBitstreamH265Context *h265 = ctx->priv_data;
1497 ff_h2645_packet_uninit(&h265->common.read_packet);
1499 for (i = 0; i < FF_ARRAY_ELEMS(h265->vps); i++)
1500 av_buffer_unref(&h265->vps_ref[i]);
1501 for (i = 0; i < FF_ARRAY_ELEMS(h265->sps); i++)
1502 av_buffer_unref(&h265->sps_ref[i]);
1503 for (i = 0; i < FF_ARRAY_ELEMS(h265->pps); i++)
1504 av_buffer_unref(&h265->pps_ref[i]);
1507 const CodedBitstreamType ff_cbs_type_h264 = {
1508 .codec_id = AV_CODEC_ID_H264,
1510 .priv_data_size = sizeof(CodedBitstreamH264Context),
1512 .split_fragment = &cbs_h2645_split_fragment,
1513 .read_unit = &cbs_h264_read_nal_unit,
1514 .write_unit = &cbs_h264_write_nal_unit,
1515 .assemble_fragment = &cbs_h2645_assemble_fragment,
1517 .close = &cbs_h264_close,
1520 const CodedBitstreamType ff_cbs_type_h265 = {
1521 .codec_id = AV_CODEC_ID_HEVC,
1523 .priv_data_size = sizeof(CodedBitstreamH265Context),
1525 .split_fragment = &cbs_h2645_split_fragment,
1526 .read_unit = &cbs_h265_read_nal_unit,
1527 .write_unit = &cbs_h265_write_nal_unit,
1528 .assemble_fragment = &cbs_h2645_assemble_fragment,
1530 .close = &cbs_h265_close,
1533 int ff_cbs_h264_add_sei_message(CodedBitstreamContext *ctx,
1534 CodedBitstreamFragment *au,
1535 H264RawSEIPayload *payload)
1537 H264RawSEI *sei = NULL;
1540 // Find an existing SEI NAL unit to add to.
1541 for (i = 0; i < au->nb_units; i++) {
1542 if (au->units[i].type == H264_NAL_SEI) {
1543 sei = au->units[i].content;
1544 if (sei->payload_count < H264_MAX_SEI_PAYLOADS)
1552 // Need to make a new SEI NAL unit. Insert it before the first
1553 // slice data NAL unit; if no slice data, add at the end.
1554 AVBufferRef *sei_ref;
1556 sei = av_mallocz(sizeof(*sei));
1558 err = AVERROR(ENOMEM);
1562 sei->nal_unit_header.nal_unit_type = H264_NAL_SEI;
1563 sei->nal_unit_header.nal_ref_idc = 0;
1565 sei_ref = av_buffer_create((uint8_t*)sei, sizeof(*sei),
1566 &cbs_h264_free_sei, NULL, 0);
1569 err = AVERROR(ENOMEM);
1573 for (i = 0; i < au->nb_units; i++) {
1574 if (au->units[i].type == H264_NAL_SLICE ||
1575 au->units[i].type == H264_NAL_IDR_SLICE)
1579 err = ff_cbs_insert_unit_content(ctx, au, i, H264_NAL_SEI,
1581 av_buffer_unref(&sei_ref);
1586 memcpy(&sei->payload[sei->payload_count], payload, sizeof(*payload));
1587 ++sei->payload_count;
1591 cbs_h264_free_sei_payload(payload);
1595 void ff_cbs_h264_delete_sei_message(CodedBitstreamContext *ctx,
1596 CodedBitstreamFragment *au,
1597 CodedBitstreamUnit *nal,
1600 H264RawSEI *sei = nal->content;
1602 av_assert0(nal->type == H264_NAL_SEI);
1603 av_assert0(position >= 0 && position < sei->payload_count);
1605 if (position == 0 && sei->payload_count == 1) {
1606 // Deleting NAL unit entirely.
1609 for (i = 0; i < au->nb_units; i++) {
1610 if (&au->units[i] == nal)
1614 ff_cbs_delete_unit(ctx, au, i);
1616 cbs_h264_free_sei_payload(&sei->payload[position]);
1618 --sei->payload_count;
1619 memmove(sei->payload + position,
1620 sei->payload + position + 1,
1621 (sei->payload_count - position) * sizeof(*sei->payload));