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_PAN_SCAN_RECT:
429 case H264_SEI_TYPE_RECOVERY_POINT:
430 case H264_SEI_TYPE_DISPLAY_ORIENTATION:
431 case H264_SEI_TYPE_MASTERING_DISPLAY_COLOUR_VOLUME:
433 case H264_SEI_TYPE_USER_DATA_REGISTERED:
434 av_buffer_unref(&payload->payload.user_data_registered.data_ref);
436 case H264_SEI_TYPE_USER_DATA_UNREGISTERED:
437 av_buffer_unref(&payload->payload.user_data_unregistered.data_ref);
440 av_buffer_unref(&payload->payload.other.data_ref);
445 static void cbs_h264_free_sei(void *unit, uint8_t *content)
447 H264RawSEI *sei = (H264RawSEI*)content;
449 for (i = 0; i < sei->payload_count; i++)
450 cbs_h264_free_sei_payload(&sei->payload[i]);
454 static void cbs_h264_free_slice(void *unit, uint8_t *content)
456 H264RawSlice *slice = (H264RawSlice*)content;
457 av_buffer_unref(&slice->data_ref);
461 static void cbs_h265_free_vps(void *unit, uint8_t *content)
463 H265RawVPS *vps = (H265RawVPS*)content;
464 av_buffer_unref(&vps->extension_data.data_ref);
468 static void cbs_h265_free_sps(void *unit, uint8_t *content)
470 H265RawSPS *sps = (H265RawSPS*)content;
471 av_buffer_unref(&sps->extension_data.data_ref);
475 static void cbs_h265_free_pps(void *unit, uint8_t *content)
477 H265RawPPS *pps = (H265RawPPS*)content;
478 av_buffer_unref(&pps->extension_data.data_ref);
482 static void cbs_h265_free_slice(void *unit, uint8_t *content)
484 H265RawSlice *slice = (H265RawSlice*)content;
485 av_buffer_unref(&slice->data_ref);
489 static void cbs_h265_free_sei_payload(H265RawSEIPayload *payload)
491 switch (payload->payload_type) {
492 case HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO:
493 case HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO:
496 av_buffer_unref(&payload->payload.other.data_ref);
501 static void cbs_h265_free_sei(void *unit, uint8_t *content)
503 H265RawSEI *sei = (H265RawSEI*)content;
505 for (i = 0; i < sei->payload_count; i++)
506 cbs_h265_free_sei_payload(&sei->payload[i]);
510 static int cbs_h2645_fragment_add_nals(CodedBitstreamContext *ctx,
511 CodedBitstreamFragment *frag,
512 const H2645Packet *packet)
516 for (i = 0; i < packet->nb_nals; i++) {
517 const H2645NAL *nal = &packet->nals[i];
518 size_t size = nal->size;
521 // Remove trailing zeroes.
522 while (size > 0 && nal->data[size - 1] == 0)
524 av_assert0(size > 0);
526 data = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
528 return AVERROR(ENOMEM);
529 memcpy(data, nal->data, size);
530 memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
532 err = ff_cbs_insert_unit_data(ctx, frag, -1, nal->type,
543 static int cbs_h2645_split_fragment(CodedBitstreamContext *ctx,
544 CodedBitstreamFragment *frag,
547 enum AVCodecID codec_id = ctx->codec->codec_id;
548 CodedBitstreamH2645Context *priv = ctx->priv_data;
552 av_assert0(frag->data && frag->nb_units == 0);
553 if (frag->data_size == 0)
556 if (header && frag->data[0] && codec_id == AV_CODEC_ID_H264) {
558 size_t size, start, end;
559 int i, count, version;
563 bytestream2_init(&gbc, frag->data, frag->data_size);
565 if (bytestream2_get_bytes_left(&gbc) < 6)
566 return AVERROR_INVALIDDATA;
568 version = bytestream2_get_byte(&gbc);
570 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid AVCC header: "
571 "first byte %u.", version);
572 return AVERROR_INVALIDDATA;
575 bytestream2_skip(&gbc, 3);
576 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
579 count = bytestream2_get_byte(&gbc) & 0x1f;
580 start = bytestream2_tell(&gbc);
581 for (i = 0; i < count; i++) {
582 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
583 return AVERROR_INVALIDDATA;
584 size = bytestream2_get_be16(&gbc);
585 if (bytestream2_get_bytes_left(&gbc) < size)
586 return AVERROR_INVALIDDATA;
587 bytestream2_skip(&gbc, size);
589 end = bytestream2_tell(&gbc);
591 err = ff_h2645_packet_split(&priv->read_packet,
592 frag->data + start, end - start,
593 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1);
595 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC SPS array.\n");
598 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
603 count = bytestream2_get_byte(&gbc);
604 start = bytestream2_tell(&gbc);
605 for (i = 0; i < count; i++) {
606 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
607 return AVERROR_INVALIDDATA;
608 size = bytestream2_get_be16(&gbc);
609 if (bytestream2_get_bytes_left(&gbc) < size)
610 return AVERROR_INVALIDDATA;
611 bytestream2_skip(&gbc, size);
613 end = bytestream2_tell(&gbc);
615 err = ff_h2645_packet_split(&priv->read_packet,
616 frag->data + start, end - start,
617 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1);
619 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC PPS array.\n");
622 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
626 if (bytestream2_get_bytes_left(&gbc) > 0) {
627 av_log(ctx->log_ctx, AV_LOG_WARNING, "%u bytes left at end of AVCC "
628 "header.\n", bytestream2_get_bytes_left(&gbc));
631 } else if (header && frag->data[0] && codec_id == AV_CODEC_ID_HEVC) {
633 size_t size, start, end;
634 int i, j, nb_arrays, nal_unit_type, nb_nals, version;
638 bytestream2_init(&gbc, frag->data, frag->data_size);
640 if (bytestream2_get_bytes_left(&gbc) < 23)
641 return AVERROR_INVALIDDATA;
643 version = bytestream2_get_byte(&gbc);
645 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid HVCC header: "
646 "first byte %u.", version);
647 return AVERROR_INVALIDDATA;
650 bytestream2_skip(&gbc, 20);
651 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
653 nb_arrays = bytestream2_get_byte(&gbc);
654 for (i = 0; i < nb_arrays; i++) {
655 nal_unit_type = bytestream2_get_byte(&gbc) & 0x3f;
656 nb_nals = bytestream2_get_be16(&gbc);
658 start = bytestream2_tell(&gbc);
659 for (j = 0; j < nb_nals; j++) {
660 if (bytestream2_get_bytes_left(&gbc) < 2)
661 return AVERROR_INVALIDDATA;
662 size = bytestream2_get_be16(&gbc);
663 if (bytestream2_get_bytes_left(&gbc) < size)
664 return AVERROR_INVALIDDATA;
665 bytestream2_skip(&gbc, size);
667 end = bytestream2_tell(&gbc);
669 err = ff_h2645_packet_split(&priv->read_packet,
670 frag->data + start, end - start,
671 ctx->log_ctx, 1, 2, AV_CODEC_ID_HEVC, 1);
673 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split "
674 "HVCC array %d (%d NAL units of type %d).\n",
675 i, nb_nals, nal_unit_type);
678 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
684 // Annex B, or later MP4 with already-known parameters.
686 err = ff_h2645_packet_split(&priv->read_packet,
687 frag->data, frag->data_size,
689 priv->mp4, priv->nal_length_size,
694 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
702 #define cbs_h2645_replace_ps(h26n, ps_name, ps_var, id_element) \
703 static int cbs_h26 ## h26n ## _replace_ ## ps_var(CodedBitstreamContext *ctx, \
704 CodedBitstreamUnit *unit) \
706 CodedBitstreamH26 ## h26n ## Context *priv = ctx->priv_data; \
707 H26 ## h26n ## Raw ## ps_name *ps_var = unit->content; \
708 unsigned int id = ps_var->id_element; \
709 if (id > FF_ARRAY_ELEMS(priv->ps_var)) { \
710 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid " #ps_name \
711 " id : %d.\n", id); \
712 return AVERROR_INVALIDDATA; \
714 if (priv->ps_var[id] == priv->active_ ## ps_var) \
715 priv->active_ ## ps_var = NULL ; \
716 av_buffer_unref(&priv->ps_var ## _ref[id]); \
717 if (unit->content_ref) \
718 priv->ps_var ## _ref[id] = av_buffer_ref(unit->content_ref); \
720 priv->ps_var ## _ref[id] = av_buffer_alloc(sizeof(*ps_var)); \
721 if (!priv->ps_var ## _ref[id]) \
722 return AVERROR(ENOMEM); \
723 priv->ps_var[id] = (H26 ## h26n ## Raw ## ps_name *)priv->ps_var ## _ref[id]->data; \
724 if (!unit->content_ref) \
725 memcpy(priv->ps_var[id], ps_var, sizeof(*ps_var)); \
729 cbs_h2645_replace_ps(4, SPS, sps, seq_parameter_set_id)
730 cbs_h2645_replace_ps(4, PPS, pps, pic_parameter_set_id)
731 cbs_h2645_replace_ps(5, VPS, vps, vps_video_parameter_set_id)
732 cbs_h2645_replace_ps(5, SPS, sps, sps_seq_parameter_set_id)
733 cbs_h2645_replace_ps(5, PPS, pps, pps_pic_parameter_set_id)
735 static int cbs_h264_read_nal_unit(CodedBitstreamContext *ctx,
736 CodedBitstreamUnit *unit)
741 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
745 switch (unit->type) {
750 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps), NULL);
755 err = cbs_h264_read_sps(ctx, &gbc, sps);
759 err = cbs_h264_replace_sps(ctx, unit);
765 case H264_NAL_SPS_EXT:
767 err = ff_cbs_alloc_unit_content(ctx, unit,
768 sizeof(H264RawSPSExtension),
773 err = cbs_h264_read_sps_extension(ctx, &gbc, unit->content);
783 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
789 err = cbs_h264_read_pps(ctx, &gbc, pps);
793 err = cbs_h264_replace_pps(ctx, unit);
800 case H264_NAL_IDR_SLICE:
801 case H264_NAL_AUXILIARY_SLICE:
806 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
807 &cbs_h264_free_slice);
810 slice = unit->content;
812 err = cbs_h264_read_slice_header(ctx, &gbc, &slice->header);
816 pos = get_bits_count(&gbc);
817 len = unit->data_size;
818 if (!unit->data[len - 1]) {
820 for (z = 0; z < len && !unit->data[len - z - 1]; z++);
821 av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "
822 "from slice data.\n", z);
826 slice->data_size = len - pos / 8;
827 slice->data_ref = av_buffer_ref(unit->data_ref);
828 if (!slice->data_ref)
829 return AVERROR(ENOMEM);
830 slice->data = unit->data + pos / 8;
831 slice->data_bit_start = pos % 8;
837 err = ff_cbs_alloc_unit_content(ctx, unit,
838 sizeof(H264RawAUD), NULL);
842 err = cbs_h264_read_aud(ctx, &gbc, unit->content);
850 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H264RawSEI),
855 err = cbs_h264_read_sei(ctx, &gbc, unit->content);
861 case H264_NAL_FILLER_DATA:
863 err = ff_cbs_alloc_unit_content(ctx, unit,
864 sizeof(H264RawFiller), NULL);
868 err = cbs_h264_read_filler(ctx, &gbc, unit->content);
875 return AVERROR(ENOSYS);
881 static int cbs_h265_read_nal_unit(CodedBitstreamContext *ctx,
882 CodedBitstreamUnit *unit)
887 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
891 switch (unit->type) {
896 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*vps),
902 err = cbs_h265_read_vps(ctx, &gbc, vps);
906 err = cbs_h265_replace_vps(ctx, unit);
915 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps),
921 err = cbs_h265_read_sps(ctx, &gbc, sps);
925 err = cbs_h265_replace_sps(ctx, unit);
935 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
941 err = cbs_h265_read_pps(ctx, &gbc, pps);
945 err = cbs_h265_replace_pps(ctx, unit);
951 case HEVC_NAL_TRAIL_N:
952 case HEVC_NAL_TRAIL_R:
955 case HEVC_NAL_STSA_N:
956 case HEVC_NAL_STSA_R:
957 case HEVC_NAL_RADL_N:
958 case HEVC_NAL_RADL_R:
959 case HEVC_NAL_RASL_N:
960 case HEVC_NAL_RASL_R:
961 case HEVC_NAL_BLA_W_LP:
962 case HEVC_NAL_BLA_W_RADL:
963 case HEVC_NAL_BLA_N_LP:
964 case HEVC_NAL_IDR_W_RADL:
965 case HEVC_NAL_IDR_N_LP:
966 case HEVC_NAL_CRA_NUT:
971 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
972 &cbs_h265_free_slice);
975 slice = unit->content;
977 err = cbs_h265_read_slice_segment_header(ctx, &gbc, &slice->header);
981 pos = get_bits_count(&gbc);
982 len = unit->data_size;
983 if (!unit->data[len - 1]) {
985 for (z = 0; z < len && !unit->data[len - z - 1]; z++);
986 av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "
987 "from slice data.\n", z);
991 slice->data_size = len - pos / 8;
992 slice->data_ref = av_buffer_ref(unit->data_ref);
993 if (!slice->data_ref)
994 return AVERROR(ENOMEM);
995 slice->data = unit->data + pos / 8;
996 slice->data_bit_start = pos % 8;
1002 err = ff_cbs_alloc_unit_content(ctx, unit,
1003 sizeof(H265RawAUD), NULL);
1007 err = cbs_h265_read_aud(ctx, &gbc, unit->content);
1013 case HEVC_NAL_SEI_PREFIX:
1015 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H265RawSEI),
1016 &cbs_h265_free_sei);
1021 err = cbs_h265_read_sei(ctx, &gbc, unit->content);
1029 return AVERROR(ENOSYS);
1035 static int cbs_h264_write_nal_unit(CodedBitstreamContext *ctx,
1036 CodedBitstreamUnit *unit,
1041 switch (unit->type) {
1044 H264RawSPS *sps = unit->content;
1046 err = cbs_h264_write_sps(ctx, pbc, sps);
1050 err = cbs_h264_replace_sps(ctx, unit);
1056 case H264_NAL_SPS_EXT:
1058 H264RawSPSExtension *sps_ext = unit->content;
1060 err = cbs_h264_write_sps_extension(ctx, pbc, sps_ext);
1068 H264RawPPS *pps = unit->content;
1070 err = cbs_h264_write_pps(ctx, pbc, pps);
1074 err = cbs_h264_replace_pps(ctx, unit);
1080 case H264_NAL_SLICE:
1081 case H264_NAL_IDR_SLICE:
1082 case H264_NAL_AUXILIARY_SLICE:
1084 H264RawSlice *slice = unit->content;
1086 int bits_left, end, zeroes;
1088 err = cbs_h264_write_slice_header(ctx, pbc, &slice->header);
1093 if (slice->data_size * 8 + 8 > put_bits_left(pbc))
1094 return AVERROR(ENOSPC);
1096 init_get_bits(&gbc, slice->data, slice->data_size * 8);
1097 skip_bits_long(&gbc, slice->data_bit_start);
1099 // Copy in two-byte blocks, but stop before copying the
1100 // rbsp_stop_one_bit in the final byte.
1101 while (get_bits_left(&gbc) > 23)
1102 put_bits(pbc, 16, get_bits(&gbc, 16));
1104 bits_left = get_bits_left(&gbc);
1105 end = get_bits(&gbc, bits_left);
1107 // rbsp_stop_one_bit must be present here.
1109 zeroes = ff_ctz(end);
1110 if (bits_left > zeroes + 1)
1111 put_bits(pbc, bits_left - zeroes - 1,
1112 end >> (zeroes + 1));
1113 put_bits(pbc, 1, 1);
1114 while (put_bits_count(pbc) % 8 != 0)
1115 put_bits(pbc, 1, 0);
1117 // No slice data - that was just the header.
1118 // (Bitstream may be unaligned!)
1125 err = cbs_h264_write_aud(ctx, pbc, unit->content);
1133 err = cbs_h264_write_sei(ctx, pbc, unit->content);
1139 case H264_NAL_FILLER_DATA:
1141 err = cbs_h264_write_filler(ctx, pbc, unit->content);
1148 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1149 "NAL unit type %"PRIu32".\n", unit->type);
1150 return AVERROR_PATCHWELCOME;
1156 static int cbs_h265_write_nal_unit(CodedBitstreamContext *ctx,
1157 CodedBitstreamUnit *unit,
1162 switch (unit->type) {
1165 H265RawVPS *vps = unit->content;
1167 err = cbs_h265_write_vps(ctx, pbc, vps);
1171 err = cbs_h265_replace_vps(ctx, unit);
1179 H265RawSPS *sps = unit->content;
1181 err = cbs_h265_write_sps(ctx, pbc, sps);
1185 err = cbs_h265_replace_sps(ctx, unit);
1193 H265RawPPS *pps = unit->content;
1195 err = cbs_h265_write_pps(ctx, pbc, pps);
1199 err = cbs_h265_replace_pps(ctx, unit);
1205 case HEVC_NAL_TRAIL_N:
1206 case HEVC_NAL_TRAIL_R:
1207 case HEVC_NAL_TSA_N:
1208 case HEVC_NAL_TSA_R:
1209 case HEVC_NAL_STSA_N:
1210 case HEVC_NAL_STSA_R:
1211 case HEVC_NAL_RADL_N:
1212 case HEVC_NAL_RADL_R:
1213 case HEVC_NAL_RASL_N:
1214 case HEVC_NAL_RASL_R:
1215 case HEVC_NAL_BLA_W_LP:
1216 case HEVC_NAL_BLA_W_RADL:
1217 case HEVC_NAL_BLA_N_LP:
1218 case HEVC_NAL_IDR_W_RADL:
1219 case HEVC_NAL_IDR_N_LP:
1220 case HEVC_NAL_CRA_NUT:
1222 H265RawSlice *slice = unit->content;
1224 int bits_left, end, zeroes;
1226 err = cbs_h265_write_slice_segment_header(ctx, pbc, &slice->header);
1231 if (slice->data_size * 8 + 8 > put_bits_left(pbc))
1232 return AVERROR(ENOSPC);
1234 init_get_bits(&gbc, slice->data, slice->data_size * 8);
1235 skip_bits_long(&gbc, slice->data_bit_start);
1237 // Copy in two-byte blocks, but stop before copying the
1238 // rbsp_stop_one_bit in the final byte.
1239 while (get_bits_left(&gbc) > 23)
1240 put_bits(pbc, 16, get_bits(&gbc, 16));
1242 bits_left = get_bits_left(&gbc);
1243 end = get_bits(&gbc, bits_left);
1245 // rbsp_stop_one_bit must be present here.
1247 zeroes = ff_ctz(end);
1248 if (bits_left > zeroes + 1)
1249 put_bits(pbc, bits_left - zeroes - 1,
1250 end >> (zeroes + 1));
1251 put_bits(pbc, 1, 1);
1252 while (put_bits_count(pbc) % 8 != 0)
1253 put_bits(pbc, 1, 0);
1255 // No slice data - that was just the header.
1262 err = cbs_h265_write_aud(ctx, pbc, unit->content);
1268 case HEVC_NAL_SEI_PREFIX:
1270 err = cbs_h265_write_sei(ctx, pbc, unit->content);
1278 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1279 "NAL unit type %"PRIu32".\n", unit->type);
1280 return AVERROR_PATCHWELCOME;
1286 static int cbs_h2645_write_nal_unit(CodedBitstreamContext *ctx,
1287 CodedBitstreamUnit *unit)
1289 CodedBitstreamH2645Context *priv = ctx->priv_data;
1290 enum AVCodecID codec_id = ctx->codec->codec_id;
1294 if (!priv->write_buffer) {
1295 // Initial write buffer size is 1MB.
1296 priv->write_buffer_size = 1024 * 1024;
1298 reallocate_and_try_again:
1299 err = av_reallocp(&priv->write_buffer, priv->write_buffer_size);
1301 av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a "
1302 "sufficiently large write buffer (last attempt "
1303 "%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size);
1308 init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size);
1310 if (codec_id == AV_CODEC_ID_H264)
1311 err = cbs_h264_write_nal_unit(ctx, unit, &pbc);
1313 err = cbs_h265_write_nal_unit(ctx, unit, &pbc);
1315 if (err == AVERROR(ENOSPC)) {
1317 priv->write_buffer_size *= 2;
1318 goto reallocate_and_try_again;
1320 // Overflow but we didn't notice.
1321 av_assert0(put_bits_count(&pbc) <= 8 * priv->write_buffer_size);
1324 // Write failed for some other reason.
1328 if (put_bits_count(&pbc) % 8)
1329 unit->data_bit_padding = 8 - put_bits_count(&pbc) % 8;
1331 unit->data_bit_padding = 0;
1333 unit->data_size = (put_bits_count(&pbc) + 7) / 8;
1334 flush_put_bits(&pbc);
1336 err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size);
1340 memcpy(unit->data, priv->write_buffer, unit->data_size);
1345 static int cbs_h2645_assemble_fragment(CodedBitstreamContext *ctx,
1346 CodedBitstreamFragment *frag)
1349 size_t max_size, dp, sp;
1350 int err, i, zero_run;
1352 for (i = 0; i < frag->nb_units; i++) {
1353 // Data should already all have been written when we get here.
1354 av_assert0(frag->units[i].data);
1358 for (i = 0; i < frag->nb_units; i++) {
1359 // Start code + content with worst-case emulation prevention.
1360 max_size += 3 + frag->units[i].data_size * 3 / 2;
1363 data = av_malloc(max_size + AV_INPUT_BUFFER_PADDING_SIZE);
1365 return AVERROR(ENOMEM);
1368 for (i = 0; i < frag->nb_units; i++) {
1369 CodedBitstreamUnit *unit = &frag->units[i];
1371 if (unit->data_bit_padding > 0) {
1372 if (i < frag->nb_units - 1)
1373 av_log(ctx->log_ctx, AV_LOG_WARNING, "Probably invalid "
1374 "unaligned padding on non-final NAL unit.\n");
1376 frag->data_bit_padding = unit->data_bit_padding;
1379 if ((ctx->codec->codec_id == AV_CODEC_ID_H264 &&
1380 (unit->type == H264_NAL_SPS ||
1381 unit->type == H264_NAL_PPS)) ||
1382 (ctx->codec->codec_id == AV_CODEC_ID_HEVC &&
1383 (unit->type == HEVC_NAL_VPS ||
1384 unit->type == HEVC_NAL_SPS ||
1385 unit->type == HEVC_NAL_PPS)) ||
1386 i == 0 /* (Assume this is the start of an access unit.) */) {
1390 // start_code_prefix_one_3bytes
1396 for (sp = 0; sp < unit->data_size; sp++) {
1398 if (unit->data[sp] == 0)
1403 if ((unit->data[sp] & ~3) == 0) {
1404 // emulation_prevention_three_byte
1407 zero_run = unit->data[sp] == 0;
1409 data[dp++] = unit->data[sp];
1413 av_assert0(dp <= max_size);
1414 err = av_reallocp(&data, dp + AV_INPUT_BUFFER_PADDING_SIZE);
1417 memset(data + dp, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1419 frag->data_ref = av_buffer_create(data, dp + AV_INPUT_BUFFER_PADDING_SIZE,
1421 if (!frag->data_ref) {
1423 return AVERROR(ENOMEM);
1427 frag->data_size = dp;
1432 static void cbs_h264_close(CodedBitstreamContext *ctx)
1434 CodedBitstreamH264Context *h264 = ctx->priv_data;
1437 ff_h2645_packet_uninit(&h264->common.read_packet);
1439 av_freep(&h264->common.write_buffer);
1441 for (i = 0; i < FF_ARRAY_ELEMS(h264->sps); i++)
1442 av_buffer_unref(&h264->sps_ref[i]);
1443 for (i = 0; i < FF_ARRAY_ELEMS(h264->pps); i++)
1444 av_buffer_unref(&h264->pps_ref[i]);
1447 static void cbs_h265_close(CodedBitstreamContext *ctx)
1449 CodedBitstreamH265Context *h265 = ctx->priv_data;
1452 ff_h2645_packet_uninit(&h265->common.read_packet);
1454 av_freep(&h265->common.write_buffer);
1456 for (i = 0; i < FF_ARRAY_ELEMS(h265->vps); i++)
1457 av_buffer_unref(&h265->vps_ref[i]);
1458 for (i = 0; i < FF_ARRAY_ELEMS(h265->sps); i++)
1459 av_buffer_unref(&h265->sps_ref[i]);
1460 for (i = 0; i < FF_ARRAY_ELEMS(h265->pps); i++)
1461 av_buffer_unref(&h265->pps_ref[i]);
1464 const CodedBitstreamType ff_cbs_type_h264 = {
1465 .codec_id = AV_CODEC_ID_H264,
1467 .priv_data_size = sizeof(CodedBitstreamH264Context),
1469 .split_fragment = &cbs_h2645_split_fragment,
1470 .read_unit = &cbs_h264_read_nal_unit,
1471 .write_unit = &cbs_h2645_write_nal_unit,
1472 .assemble_fragment = &cbs_h2645_assemble_fragment,
1474 .close = &cbs_h264_close,
1477 const CodedBitstreamType ff_cbs_type_h265 = {
1478 .codec_id = AV_CODEC_ID_HEVC,
1480 .priv_data_size = sizeof(CodedBitstreamH265Context),
1482 .split_fragment = &cbs_h2645_split_fragment,
1483 .read_unit = &cbs_h265_read_nal_unit,
1484 .write_unit = &cbs_h2645_write_nal_unit,
1485 .assemble_fragment = &cbs_h2645_assemble_fragment,
1487 .close = &cbs_h265_close,
1490 int ff_cbs_h264_add_sei_message(CodedBitstreamContext *ctx,
1491 CodedBitstreamFragment *au,
1492 const H264RawSEIPayload *payload)
1495 CodedBitstreamUnit *nal = NULL;
1498 // Find an existing SEI NAL unit to add to.
1499 for (i = 0; i < au->nb_units; i++) {
1500 if (au->units[i].type == H264_NAL_SEI) {
1501 nal = &au->units[i];
1509 // Need to make a new SEI NAL unit. Insert it before the first
1510 // slice data NAL unit; if no slice data, add at the end.
1511 AVBufferRef *sei_ref;
1513 sei = av_mallocz(sizeof(*sei));
1515 return AVERROR(ENOMEM);
1517 sei->nal_unit_header.nal_unit_type = H264_NAL_SEI;
1518 sei->nal_unit_header.nal_ref_idc = 0;
1520 sei_ref = av_buffer_create((uint8_t*)sei, sizeof(*sei),
1521 &cbs_h264_free_sei, ctx, 0);
1524 return AVERROR(ENOMEM);
1527 for (i = 0; i < au->nb_units; i++) {
1528 if (au->units[i].type == H264_NAL_SLICE ||
1529 au->units[i].type == H264_NAL_IDR_SLICE)
1533 err = ff_cbs_insert_unit_content(ctx, au, i, H264_NAL_SEI,
1535 av_buffer_unref(&sei_ref);
1540 if (sei->payload_count >= H264_MAX_SEI_PAYLOADS) {
1541 av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many payloads in "
1543 return AVERROR(EINVAL);
1546 memcpy(&sei->payload[sei->payload_count], payload, sizeof(*payload));
1547 ++sei->payload_count;
1552 int ff_cbs_h264_delete_sei_message(CodedBitstreamContext *ctx,
1553 CodedBitstreamFragment *au,
1554 CodedBitstreamUnit *nal,
1557 H264RawSEI *sei = nal->content;
1559 av_assert0(nal->type == H264_NAL_SEI);
1560 av_assert0(position >= 0 && position < sei->payload_count);
1562 if (position == 0 && sei->payload_count == 1) {
1563 // Deleting NAL unit entirely.
1566 for (i = 0; i < au->nb_units; i++) {
1567 if (&au->units[i] == nal)
1570 av_assert0(i < au->nb_units && "NAL unit not in access unit.");
1572 return ff_cbs_delete_unit(ctx, au, i);
1574 cbs_h264_free_sei_payload(&sei->payload[position]);
1576 --sei->payload_count;
1577 memmove(sei->payload + position,
1578 sei->payload + position + 1,
1579 (sei->payload_count - position) * sizeof(*sei->payload));