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 i(width, name, range_min, range_max) \
259 xi(width, name, current->name, range_min, range_max, 0)
260 #define se(name, range_min, range_max) \
261 xse(name, current->name, range_min, range_max, 0)
263 #define us(width, name, range_min, range_max, subs, ...) \
264 xu(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
265 #define flags(name, subs, ...) \
266 xu(1, name, current->name, 0, 1, subs, __VA_ARGS__)
267 #define ues(name, range_min, range_max, subs, ...) \
268 xue(name, current->name, range_min, range_max, subs, __VA_ARGS__)
269 #define is(width, name, range_min, range_max, subs, ...) \
270 xi(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
271 #define ses(name, range_min, range_max, subs, ...) \
272 xse(name, current->name, range_min, range_max, subs, __VA_ARGS__)
274 #define fixed(width, name, value) do { \
275 av_unused uint32_t fixed_value = value; \
276 xu(width, name, fixed_value, value, value, 0); \
281 #define READWRITE read
282 #define RWContext GetBitContext
284 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
285 uint32_t value = range_min; \
286 CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \
287 SUBSCRIPTS(subs, __VA_ARGS__), \
288 &value, range_min, range_max)); \
291 #define xue(name, var, range_min, range_max, subs, ...) do { \
292 uint32_t value = range_min; \
293 CHECK(cbs_read_ue_golomb(ctx, rw, #name, \
294 SUBSCRIPTS(subs, __VA_ARGS__), \
295 &value, range_min, range_max)); \
298 #define xi(width, name, var, range_min, range_max, subs, ...) do { \
299 int32_t value = range_min; \
300 CHECK(ff_cbs_read_signed(ctx, rw, width, #name, \
301 SUBSCRIPTS(subs, __VA_ARGS__), \
302 &value, range_min, range_max)); \
305 #define xse(name, var, range_min, range_max, subs, ...) do { \
306 int32_t value = range_min; \
307 CHECK(cbs_read_se_golomb(ctx, rw, #name, \
308 SUBSCRIPTS(subs, __VA_ARGS__), \
309 &value, range_min, range_max)); \
314 #define infer(name, value) do { \
315 current->name = value; \
318 static int cbs_h2645_read_more_rbsp_data(GetBitContext *gbc)
320 int bits_left = get_bits_left(gbc);
323 if (show_bits(gbc, bits_left) == 1 << (bits_left - 1))
328 #define more_rbsp_data(var) ((var) = cbs_h2645_read_more_rbsp_data(rw))
330 #define byte_alignment(rw) (get_bits_count(rw) % 8)
332 #define allocate(name, size) do { \
333 name ## _ref = av_buffer_allocz(size + \
334 AV_INPUT_BUFFER_PADDING_SIZE); \
336 return AVERROR(ENOMEM); \
337 name = name ## _ref->data; \
340 #define FUNC(name) FUNC_H264(READWRITE, name)
341 #include "cbs_h264_syntax_template.c"
344 #define FUNC(name) FUNC_H265(READWRITE, name)
345 #include "cbs_h265_syntax_template.c"
356 #undef more_rbsp_data
357 #undef byte_alignment
362 #define READWRITE write
363 #define RWContext PutBitContext
365 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
366 uint32_t value = var; \
367 CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \
368 SUBSCRIPTS(subs, __VA_ARGS__), \
369 value, range_min, range_max)); \
371 #define xue(name, var, range_min, range_max, subs, ...) do { \
372 uint32_t value = var; \
373 CHECK(cbs_write_ue_golomb(ctx, rw, #name, \
374 SUBSCRIPTS(subs, __VA_ARGS__), \
375 value, range_min, range_max)); \
377 #define xi(width, name, var, range_min, range_max, subs, ...) do { \
378 int32_t value = var; \
379 CHECK(ff_cbs_write_signed(ctx, rw, width, #name, \
380 SUBSCRIPTS(subs, __VA_ARGS__), \
381 value, range_min, range_max)); \
383 #define xse(name, var, range_min, range_max, subs, ...) do { \
384 int32_t value = var; \
385 CHECK(cbs_write_se_golomb(ctx, rw, #name, \
386 SUBSCRIPTS(subs, __VA_ARGS__), \
387 value, range_min, range_max)); \
390 #define infer(name, value) do { \
391 if (current->name != (value)) { \
392 av_log(ctx->log_ctx, AV_LOG_WARNING, "Warning: " \
393 "%s does not match inferred value: " \
394 "%"PRId64", but should be %"PRId64".\n", \
395 #name, (int64_t)current->name, (int64_t)(value)); \
399 #define more_rbsp_data(var) (var)
401 #define byte_alignment(rw) (put_bits_count(rw) % 8)
403 #define allocate(name, size) do { \
405 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s must be set " \
406 "for writing.\n", #name); \
407 return AVERROR_INVALIDDATA; \
411 #define FUNC(name) FUNC_H264(READWRITE, name)
412 #include "cbs_h264_syntax_template.c"
415 #define FUNC(name) FUNC_H265(READWRITE, name)
416 #include "cbs_h265_syntax_template.c"
432 #undef more_rbsp_data
433 #undef byte_alignment
437 static void cbs_h264_free_pps(void *unit, uint8_t *content)
439 H264RawPPS *pps = (H264RawPPS*)content;
440 av_buffer_unref(&pps->slice_group_id_ref);
444 static void cbs_h264_free_sei_payload(H264RawSEIPayload *payload)
446 switch (payload->payload_type) {
447 case H264_SEI_TYPE_BUFFERING_PERIOD:
448 case H264_SEI_TYPE_PIC_TIMING:
449 case H264_SEI_TYPE_PAN_SCAN_RECT:
450 case H264_SEI_TYPE_RECOVERY_POINT:
451 case H264_SEI_TYPE_DISPLAY_ORIENTATION:
452 case H264_SEI_TYPE_MASTERING_DISPLAY_COLOUR_VOLUME:
454 case H264_SEI_TYPE_USER_DATA_REGISTERED:
455 av_buffer_unref(&payload->payload.user_data_registered.data_ref);
457 case H264_SEI_TYPE_USER_DATA_UNREGISTERED:
458 av_buffer_unref(&payload->payload.user_data_unregistered.data_ref);
461 av_buffer_unref(&payload->payload.other.data_ref);
466 static void cbs_h264_free_sei(void *unit, uint8_t *content)
468 H264RawSEI *sei = (H264RawSEI*)content;
470 for (i = 0; i < sei->payload_count; i++)
471 cbs_h264_free_sei_payload(&sei->payload[i]);
475 static void cbs_h264_free_slice(void *unit, uint8_t *content)
477 H264RawSlice *slice = (H264RawSlice*)content;
478 av_buffer_unref(&slice->data_ref);
482 static void cbs_h265_free_vps(void *unit, uint8_t *content)
484 H265RawVPS *vps = (H265RawVPS*)content;
485 av_buffer_unref(&vps->extension_data.data_ref);
489 static void cbs_h265_free_sps(void *unit, uint8_t *content)
491 H265RawSPS *sps = (H265RawSPS*)content;
492 av_buffer_unref(&sps->extension_data.data_ref);
496 static void cbs_h265_free_pps(void *unit, uint8_t *content)
498 H265RawPPS *pps = (H265RawPPS*)content;
499 av_buffer_unref(&pps->extension_data.data_ref);
503 static void cbs_h265_free_slice(void *unit, uint8_t *content)
505 H265RawSlice *slice = (H265RawSlice*)content;
506 av_buffer_unref(&slice->data_ref);
510 static void cbs_h265_free_sei_payload(H265RawSEIPayload *payload)
512 switch (payload->payload_type) {
513 case HEVC_SEI_TYPE_BUFFERING_PERIOD:
514 case HEVC_SEI_TYPE_PICTURE_TIMING:
515 case HEVC_SEI_TYPE_PAN_SCAN_RECT:
516 case HEVC_SEI_TYPE_RECOVERY_POINT:
517 case HEVC_SEI_TYPE_DISPLAY_ORIENTATION:
518 case HEVC_SEI_TYPE_ACTIVE_PARAMETER_SETS:
519 case HEVC_SEI_TYPE_DECODED_PICTURE_HASH:
520 case HEVC_SEI_TYPE_TIME_CODE:
521 case HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO:
522 case HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO:
523 case HEVC_SEI_TYPE_ALTERNATIVE_TRANSFER_CHARACTERISTICS:
525 case HEVC_SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35:
526 av_buffer_unref(&payload->payload.user_data_registered.data_ref);
528 case HEVC_SEI_TYPE_USER_DATA_UNREGISTERED:
529 av_buffer_unref(&payload->payload.user_data_unregistered.data_ref);
532 av_buffer_unref(&payload->payload.other.data_ref);
537 static void cbs_h265_free_sei(void *unit, uint8_t *content)
539 H265RawSEI *sei = (H265RawSEI*)content;
541 for (i = 0; i < sei->payload_count; i++)
542 cbs_h265_free_sei_payload(&sei->payload[i]);
546 static int cbs_h2645_fragment_add_nals(CodedBitstreamContext *ctx,
547 CodedBitstreamFragment *frag,
548 const H2645Packet *packet)
552 for (i = 0; i < packet->nb_nals; i++) {
553 const H2645NAL *nal = &packet->nals[i];
555 size_t size = nal->size;
557 // Remove trailing zeroes.
558 while (size > 0 && nal->data[size - 1] == 0)
560 av_assert0(size > 0);
562 ref = (nal->data == nal->raw_data) ? frag->data_ref
563 : packet->rbsp.rbsp_buffer_ref;
565 err = ff_cbs_insert_unit_data(ctx, frag, -1, nal->type,
566 (uint8_t*)nal->data, size, ref);
574 static int cbs_h2645_split_fragment(CodedBitstreamContext *ctx,
575 CodedBitstreamFragment *frag,
578 enum AVCodecID codec_id = ctx->codec->codec_id;
579 CodedBitstreamH2645Context *priv = ctx->priv_data;
583 av_assert0(frag->data && frag->nb_units == 0);
584 if (frag->data_size == 0)
587 if (header && frag->data[0] && codec_id == AV_CODEC_ID_H264) {
589 size_t size, start, end;
590 int i, count, version;
594 bytestream2_init(&gbc, frag->data, frag->data_size);
596 if (bytestream2_get_bytes_left(&gbc) < 6)
597 return AVERROR_INVALIDDATA;
599 version = bytestream2_get_byte(&gbc);
601 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid AVCC header: "
602 "first byte %u.", version);
603 return AVERROR_INVALIDDATA;
606 bytestream2_skip(&gbc, 3);
607 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
610 count = bytestream2_get_byte(&gbc) & 0x1f;
611 start = bytestream2_tell(&gbc);
612 for (i = 0; i < count; i++) {
613 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
614 return AVERROR_INVALIDDATA;
615 size = bytestream2_get_be16(&gbc);
616 if (bytestream2_get_bytes_left(&gbc) < size)
617 return AVERROR_INVALIDDATA;
618 bytestream2_skip(&gbc, size);
620 end = bytestream2_tell(&gbc);
622 err = ff_h2645_packet_split(&priv->read_packet,
623 frag->data + start, end - start,
624 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1, 1);
626 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC SPS array.\n");
629 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
634 count = bytestream2_get_byte(&gbc);
635 start = bytestream2_tell(&gbc);
636 for (i = 0; i < count; i++) {
637 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
638 return AVERROR_INVALIDDATA;
639 size = bytestream2_get_be16(&gbc);
640 if (bytestream2_get_bytes_left(&gbc) < size)
641 return AVERROR_INVALIDDATA;
642 bytestream2_skip(&gbc, size);
644 end = bytestream2_tell(&gbc);
646 err = ff_h2645_packet_split(&priv->read_packet,
647 frag->data + start, end - start,
648 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1, 1);
650 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC PPS array.\n");
653 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
657 if (bytestream2_get_bytes_left(&gbc) > 0) {
658 av_log(ctx->log_ctx, AV_LOG_WARNING, "%u bytes left at end of AVCC "
659 "header.\n", bytestream2_get_bytes_left(&gbc));
662 } else if (header && frag->data[0] && codec_id == AV_CODEC_ID_HEVC) {
664 size_t size, start, end;
665 int i, j, nb_arrays, nal_unit_type, nb_nals, version;
669 bytestream2_init(&gbc, frag->data, frag->data_size);
671 if (bytestream2_get_bytes_left(&gbc) < 23)
672 return AVERROR_INVALIDDATA;
674 version = bytestream2_get_byte(&gbc);
676 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid HVCC header: "
677 "first byte %u.", version);
678 return AVERROR_INVALIDDATA;
681 bytestream2_skip(&gbc, 20);
682 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
684 nb_arrays = bytestream2_get_byte(&gbc);
685 for (i = 0; i < nb_arrays; i++) {
686 nal_unit_type = bytestream2_get_byte(&gbc) & 0x3f;
687 nb_nals = bytestream2_get_be16(&gbc);
689 start = bytestream2_tell(&gbc);
690 for (j = 0; j < nb_nals; j++) {
691 if (bytestream2_get_bytes_left(&gbc) < 2)
692 return AVERROR_INVALIDDATA;
693 size = bytestream2_get_be16(&gbc);
694 if (bytestream2_get_bytes_left(&gbc) < size)
695 return AVERROR_INVALIDDATA;
696 bytestream2_skip(&gbc, size);
698 end = bytestream2_tell(&gbc);
700 err = ff_h2645_packet_split(&priv->read_packet,
701 frag->data + start, end - start,
702 ctx->log_ctx, 1, 2, AV_CODEC_ID_HEVC, 1, 1);
704 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split "
705 "HVCC array %d (%d NAL units of type %d).\n",
706 i, nb_nals, nal_unit_type);
709 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
715 // Annex B, or later MP4 with already-known parameters.
717 err = ff_h2645_packet_split(&priv->read_packet,
718 frag->data, frag->data_size,
720 priv->mp4, priv->nal_length_size,
725 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
733 #define cbs_h2645_replace_ps(h26n, ps_name, ps_var, id_element) \
734 static int cbs_h26 ## h26n ## _replace_ ## ps_var(CodedBitstreamContext *ctx, \
735 CodedBitstreamUnit *unit) \
737 CodedBitstreamH26 ## h26n ## Context *priv = ctx->priv_data; \
738 H26 ## h26n ## Raw ## ps_name *ps_var = unit->content; \
739 unsigned int id = ps_var->id_element; \
740 if (id > FF_ARRAY_ELEMS(priv->ps_var)) { \
741 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid " #ps_name \
742 " id : %d.\n", id); \
743 return AVERROR_INVALIDDATA; \
745 if (priv->ps_var[id] == priv->active_ ## ps_var) \
746 priv->active_ ## ps_var = NULL ; \
747 av_buffer_unref(&priv->ps_var ## _ref[id]); \
748 if (unit->content_ref) \
749 priv->ps_var ## _ref[id] = av_buffer_ref(unit->content_ref); \
751 priv->ps_var ## _ref[id] = av_buffer_alloc(sizeof(*ps_var)); \
752 if (!priv->ps_var ## _ref[id]) \
753 return AVERROR(ENOMEM); \
754 priv->ps_var[id] = (H26 ## h26n ## Raw ## ps_name *)priv->ps_var ## _ref[id]->data; \
755 if (!unit->content_ref) \
756 memcpy(priv->ps_var[id], ps_var, sizeof(*ps_var)); \
760 cbs_h2645_replace_ps(4, SPS, sps, seq_parameter_set_id)
761 cbs_h2645_replace_ps(4, PPS, pps, pic_parameter_set_id)
762 cbs_h2645_replace_ps(5, VPS, vps, vps_video_parameter_set_id)
763 cbs_h2645_replace_ps(5, SPS, sps, sps_seq_parameter_set_id)
764 cbs_h2645_replace_ps(5, PPS, pps, pps_pic_parameter_set_id)
766 static int cbs_h264_read_nal_unit(CodedBitstreamContext *ctx,
767 CodedBitstreamUnit *unit)
772 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
776 switch (unit->type) {
781 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps), NULL);
786 err = cbs_h264_read_sps(ctx, &gbc, sps);
790 err = cbs_h264_replace_sps(ctx, unit);
796 case H264_NAL_SPS_EXT:
798 err = ff_cbs_alloc_unit_content(ctx, unit,
799 sizeof(H264RawSPSExtension),
804 err = cbs_h264_read_sps_extension(ctx, &gbc, unit->content);
814 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
820 err = cbs_h264_read_pps(ctx, &gbc, pps);
824 err = cbs_h264_replace_pps(ctx, unit);
831 case H264_NAL_IDR_SLICE:
832 case H264_NAL_AUXILIARY_SLICE:
837 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
838 &cbs_h264_free_slice);
841 slice = unit->content;
843 err = cbs_h264_read_slice_header(ctx, &gbc, &slice->header);
847 pos = get_bits_count(&gbc);
848 len = unit->data_size;
849 if (!unit->data[len - 1]) {
851 for (z = 0; z < len && !unit->data[len - z - 1]; z++);
852 av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "
853 "from slice data.\n", z);
857 slice->data_size = len - pos / 8;
858 slice->data_ref = av_buffer_ref(unit->data_ref);
859 if (!slice->data_ref)
860 return AVERROR(ENOMEM);
861 slice->data = unit->data + pos / 8;
862 slice->data_bit_start = pos % 8;
868 err = ff_cbs_alloc_unit_content(ctx, unit,
869 sizeof(H264RawAUD), NULL);
873 err = cbs_h264_read_aud(ctx, &gbc, unit->content);
881 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H264RawSEI),
886 err = cbs_h264_read_sei(ctx, &gbc, unit->content);
892 case H264_NAL_FILLER_DATA:
894 err = ff_cbs_alloc_unit_content(ctx, unit,
895 sizeof(H264RawFiller), NULL);
899 err = cbs_h264_read_filler(ctx, &gbc, unit->content);
905 case H264_NAL_END_SEQUENCE:
906 case H264_NAL_END_STREAM:
908 err = ff_cbs_alloc_unit_content(ctx, unit,
909 sizeof(H264RawNALUnitHeader),
914 err = (unit->type == H264_NAL_END_SEQUENCE ?
915 cbs_h264_read_end_of_sequence :
916 cbs_h264_read_end_of_stream)(ctx, &gbc, unit->content);
923 return AVERROR(ENOSYS);
929 static int cbs_h265_read_nal_unit(CodedBitstreamContext *ctx,
930 CodedBitstreamUnit *unit)
935 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
939 switch (unit->type) {
944 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*vps),
950 err = cbs_h265_read_vps(ctx, &gbc, vps);
954 err = cbs_h265_replace_vps(ctx, unit);
963 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*sps),
969 err = cbs_h265_read_sps(ctx, &gbc, sps);
973 err = cbs_h265_replace_sps(ctx, unit);
983 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*pps),
989 err = cbs_h265_read_pps(ctx, &gbc, pps);
993 err = cbs_h265_replace_pps(ctx, unit);
999 case HEVC_NAL_TRAIL_N:
1000 case HEVC_NAL_TRAIL_R:
1001 case HEVC_NAL_TSA_N:
1002 case HEVC_NAL_TSA_R:
1003 case HEVC_NAL_STSA_N:
1004 case HEVC_NAL_STSA_R:
1005 case HEVC_NAL_RADL_N:
1006 case HEVC_NAL_RADL_R:
1007 case HEVC_NAL_RASL_N:
1008 case HEVC_NAL_RASL_R:
1009 case HEVC_NAL_BLA_W_LP:
1010 case HEVC_NAL_BLA_W_RADL:
1011 case HEVC_NAL_BLA_N_LP:
1012 case HEVC_NAL_IDR_W_RADL:
1013 case HEVC_NAL_IDR_N_LP:
1014 case HEVC_NAL_CRA_NUT:
1016 H265RawSlice *slice;
1019 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(*slice),
1020 &cbs_h265_free_slice);
1023 slice = unit->content;
1025 err = cbs_h265_read_slice_segment_header(ctx, &gbc, &slice->header);
1029 pos = get_bits_count(&gbc);
1030 len = unit->data_size;
1031 if (!unit->data[len - 1]) {
1033 for (z = 0; z < len && !unit->data[len - z - 1]; z++);
1034 av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "
1035 "from slice data.\n", z);
1039 slice->data_size = len - pos / 8;
1040 slice->data_ref = av_buffer_ref(unit->data_ref);
1041 if (!slice->data_ref)
1042 return AVERROR(ENOMEM);
1043 slice->data = unit->data + pos / 8;
1044 slice->data_bit_start = pos % 8;
1050 err = ff_cbs_alloc_unit_content(ctx, unit,
1051 sizeof(H265RawAUD), NULL);
1055 err = cbs_h265_read_aud(ctx, &gbc, unit->content);
1061 case HEVC_NAL_SEI_PREFIX:
1062 case HEVC_NAL_SEI_SUFFIX:
1064 err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(H265RawSEI),
1065 &cbs_h265_free_sei);
1070 err = cbs_h265_read_sei(ctx, &gbc, unit->content,
1071 unit->type == HEVC_NAL_SEI_PREFIX);
1079 return AVERROR(ENOSYS);
1085 static int cbs_h2645_write_slice_data(CodedBitstreamContext *ctx,
1086 PutBitContext *pbc, const uint8_t *data,
1087 size_t data_size, int data_bit_start)
1089 size_t rest = data_size - (data_bit_start + 7) / 8;
1090 const uint8_t *pos = data + data_bit_start / 8;
1092 av_assert0(data_bit_start >= 0 &&
1093 8 * data_size > data_bit_start);
1095 if (data_size * 8 + 8 > put_bits_left(pbc))
1096 return AVERROR(ENOSPC);
1099 goto rbsp_stop_one_bit;
1101 // First copy the remaining bits of the first byte
1102 // The above check ensures that we do not accidentally
1103 // copy beyond the rbsp_stop_one_bit.
1104 if (data_bit_start % 8)
1105 put_bits(pbc, 8 - data_bit_start % 8,
1106 *pos++ & MAX_UINT_BITS(8 - data_bit_start % 8));
1108 if (put_bits_count(pbc) % 8 == 0) {
1109 // If the writer is aligned at this point,
1110 // memcpy can be used to improve performance.
1111 // This happens normally for CABAC.
1112 flush_put_bits(pbc);
1113 memcpy(put_bits_ptr(pbc), pos, rest);
1114 skip_put_bytes(pbc, rest);
1116 // If not, we have to copy manually.
1117 // rbsp_stop_one_bit forces us to special-case
1122 for (; rest > 4; rest -= 4, pos += 4)
1123 put_bits32(pbc, AV_RB32(pos));
1125 for (; rest > 1; rest--, pos++)
1126 put_bits(pbc, 8, *pos);
1129 temp = rest ? *pos : *pos & MAX_UINT_BITS(8 - data_bit_start % 8);
1134 i = rest ? (8 - i) : (8 - i - data_bit_start % 8);
1135 put_bits(pbc, i, temp);
1136 if (put_bits_count(pbc) % 8)
1137 put_bits(pbc, 8 - put_bits_count(pbc) % 8, 0);
1143 static int cbs_h264_write_nal_unit(CodedBitstreamContext *ctx,
1144 CodedBitstreamUnit *unit,
1149 switch (unit->type) {
1152 H264RawSPS *sps = unit->content;
1154 err = cbs_h264_write_sps(ctx, pbc, sps);
1158 err = cbs_h264_replace_sps(ctx, unit);
1164 case H264_NAL_SPS_EXT:
1166 H264RawSPSExtension *sps_ext = unit->content;
1168 err = cbs_h264_write_sps_extension(ctx, pbc, sps_ext);
1176 H264RawPPS *pps = unit->content;
1178 err = cbs_h264_write_pps(ctx, pbc, pps);
1182 err = cbs_h264_replace_pps(ctx, unit);
1188 case H264_NAL_SLICE:
1189 case H264_NAL_IDR_SLICE:
1190 case H264_NAL_AUXILIARY_SLICE:
1192 H264RawSlice *slice = unit->content;
1194 err = cbs_h264_write_slice_header(ctx, pbc, &slice->header);
1199 err = cbs_h2645_write_slice_data(ctx, pbc, slice->data,
1201 slice->data_bit_start);
1205 // No slice data - that was just the header.
1206 // (Bitstream may be unaligned!)
1213 err = cbs_h264_write_aud(ctx, pbc, unit->content);
1221 err = cbs_h264_write_sei(ctx, pbc, unit->content);
1227 case H264_NAL_FILLER_DATA:
1229 err = cbs_h264_write_filler(ctx, pbc, unit->content);
1235 case H264_NAL_END_SEQUENCE:
1237 err = cbs_h264_write_end_of_sequence(ctx, pbc, unit->content);
1243 case H264_NAL_END_STREAM:
1245 err = cbs_h264_write_end_of_stream(ctx, pbc, unit->content);
1252 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1253 "NAL unit type %"PRIu32".\n", unit->type);
1254 return AVERROR_PATCHWELCOME;
1260 static int cbs_h265_write_nal_unit(CodedBitstreamContext *ctx,
1261 CodedBitstreamUnit *unit,
1266 switch (unit->type) {
1269 H265RawVPS *vps = unit->content;
1271 err = cbs_h265_write_vps(ctx, pbc, vps);
1275 err = cbs_h265_replace_vps(ctx, unit);
1283 H265RawSPS *sps = unit->content;
1285 err = cbs_h265_write_sps(ctx, pbc, sps);
1289 err = cbs_h265_replace_sps(ctx, unit);
1297 H265RawPPS *pps = unit->content;
1299 err = cbs_h265_write_pps(ctx, pbc, pps);
1303 err = cbs_h265_replace_pps(ctx, unit);
1309 case HEVC_NAL_TRAIL_N:
1310 case HEVC_NAL_TRAIL_R:
1311 case HEVC_NAL_TSA_N:
1312 case HEVC_NAL_TSA_R:
1313 case HEVC_NAL_STSA_N:
1314 case HEVC_NAL_STSA_R:
1315 case HEVC_NAL_RADL_N:
1316 case HEVC_NAL_RADL_R:
1317 case HEVC_NAL_RASL_N:
1318 case HEVC_NAL_RASL_R:
1319 case HEVC_NAL_BLA_W_LP:
1320 case HEVC_NAL_BLA_W_RADL:
1321 case HEVC_NAL_BLA_N_LP:
1322 case HEVC_NAL_IDR_W_RADL:
1323 case HEVC_NAL_IDR_N_LP:
1324 case HEVC_NAL_CRA_NUT:
1326 H265RawSlice *slice = unit->content;
1328 err = cbs_h265_write_slice_segment_header(ctx, pbc, &slice->header);
1333 err = cbs_h2645_write_slice_data(ctx, pbc, slice->data,
1335 slice->data_bit_start);
1339 // No slice data - that was just the header.
1346 err = cbs_h265_write_aud(ctx, pbc, unit->content);
1352 case HEVC_NAL_SEI_PREFIX:
1353 case HEVC_NAL_SEI_SUFFIX:
1355 err = cbs_h265_write_sei(ctx, pbc, unit->content,
1356 unit->type == HEVC_NAL_SEI_PREFIX);
1364 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1365 "NAL unit type %"PRIu32".\n", unit->type);
1366 return AVERROR_PATCHWELCOME;
1372 static int cbs_h2645_write_nal_unit(CodedBitstreamContext *ctx,
1373 CodedBitstreamUnit *unit)
1375 CodedBitstreamH2645Context *priv = ctx->priv_data;
1376 enum AVCodecID codec_id = ctx->codec->codec_id;
1380 if (!priv->write_buffer) {
1381 // Initial write buffer size is 1MB.
1382 priv->write_buffer_size = 1024 * 1024;
1384 reallocate_and_try_again:
1385 err = av_reallocp(&priv->write_buffer, priv->write_buffer_size);
1387 av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a "
1388 "sufficiently large write buffer (last attempt "
1389 "%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size);
1394 init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size);
1396 if (codec_id == AV_CODEC_ID_H264)
1397 err = cbs_h264_write_nal_unit(ctx, unit, &pbc);
1399 err = cbs_h265_write_nal_unit(ctx, unit, &pbc);
1401 if (err == AVERROR(ENOSPC)) {
1403 priv->write_buffer_size *= 2;
1404 goto reallocate_and_try_again;
1406 // Overflow but we didn't notice.
1407 av_assert0(put_bits_count(&pbc) <= 8 * priv->write_buffer_size);
1410 // Write failed for some other reason.
1414 if (put_bits_count(&pbc) % 8)
1415 unit->data_bit_padding = 8 - put_bits_count(&pbc) % 8;
1417 unit->data_bit_padding = 0;
1419 unit->data_size = (put_bits_count(&pbc) + 7) / 8;
1420 flush_put_bits(&pbc);
1422 err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size);
1426 memcpy(unit->data, priv->write_buffer, unit->data_size);
1431 static int cbs_h2645_assemble_fragment(CodedBitstreamContext *ctx,
1432 CodedBitstreamFragment *frag)
1435 size_t max_size, dp, sp;
1436 int err, i, zero_run;
1438 for (i = 0; i < frag->nb_units; i++) {
1439 // Data should already all have been written when we get here.
1440 av_assert0(frag->units[i].data);
1444 for (i = 0; i < frag->nb_units; i++) {
1445 // Start code + content with worst-case emulation prevention.
1446 max_size += 3 + frag->units[i].data_size * 3 / 2;
1449 data = av_malloc(max_size + AV_INPUT_BUFFER_PADDING_SIZE);
1451 return AVERROR(ENOMEM);
1454 for (i = 0; i < frag->nb_units; i++) {
1455 CodedBitstreamUnit *unit = &frag->units[i];
1457 if (unit->data_bit_padding > 0) {
1458 if (i < frag->nb_units - 1)
1459 av_log(ctx->log_ctx, AV_LOG_WARNING, "Probably invalid "
1460 "unaligned padding on non-final NAL unit.\n");
1462 frag->data_bit_padding = unit->data_bit_padding;
1465 if ((ctx->codec->codec_id == AV_CODEC_ID_H264 &&
1466 (unit->type == H264_NAL_SPS ||
1467 unit->type == H264_NAL_PPS)) ||
1468 (ctx->codec->codec_id == AV_CODEC_ID_HEVC &&
1469 (unit->type == HEVC_NAL_VPS ||
1470 unit->type == HEVC_NAL_SPS ||
1471 unit->type == HEVC_NAL_PPS)) ||
1472 i == 0 /* (Assume this is the start of an access unit.) */) {
1476 // start_code_prefix_one_3bytes
1482 for (sp = 0; sp < unit->data_size; sp++) {
1484 if (unit->data[sp] == 0)
1489 if ((unit->data[sp] & ~3) == 0) {
1490 // emulation_prevention_three_byte
1493 zero_run = unit->data[sp] == 0;
1495 data[dp++] = unit->data[sp];
1499 av_assert0(dp <= max_size);
1500 err = av_reallocp(&data, dp + AV_INPUT_BUFFER_PADDING_SIZE);
1503 memset(data + dp, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1505 frag->data_ref = av_buffer_create(data, dp + AV_INPUT_BUFFER_PADDING_SIZE,
1507 if (!frag->data_ref) {
1509 return AVERROR(ENOMEM);
1513 frag->data_size = dp;
1518 static void cbs_h264_close(CodedBitstreamContext *ctx)
1520 CodedBitstreamH264Context *h264 = ctx->priv_data;
1523 ff_h2645_packet_uninit(&h264->common.read_packet);
1525 av_freep(&h264->common.write_buffer);
1527 for (i = 0; i < FF_ARRAY_ELEMS(h264->sps); i++)
1528 av_buffer_unref(&h264->sps_ref[i]);
1529 for (i = 0; i < FF_ARRAY_ELEMS(h264->pps); i++)
1530 av_buffer_unref(&h264->pps_ref[i]);
1533 static void cbs_h265_close(CodedBitstreamContext *ctx)
1535 CodedBitstreamH265Context *h265 = ctx->priv_data;
1538 ff_h2645_packet_uninit(&h265->common.read_packet);
1540 av_freep(&h265->common.write_buffer);
1542 for (i = 0; i < FF_ARRAY_ELEMS(h265->vps); i++)
1543 av_buffer_unref(&h265->vps_ref[i]);
1544 for (i = 0; i < FF_ARRAY_ELEMS(h265->sps); i++)
1545 av_buffer_unref(&h265->sps_ref[i]);
1546 for (i = 0; i < FF_ARRAY_ELEMS(h265->pps); i++)
1547 av_buffer_unref(&h265->pps_ref[i]);
1550 const CodedBitstreamType ff_cbs_type_h264 = {
1551 .codec_id = AV_CODEC_ID_H264,
1553 .priv_data_size = sizeof(CodedBitstreamH264Context),
1555 .split_fragment = &cbs_h2645_split_fragment,
1556 .read_unit = &cbs_h264_read_nal_unit,
1557 .write_unit = &cbs_h2645_write_nal_unit,
1558 .assemble_fragment = &cbs_h2645_assemble_fragment,
1560 .close = &cbs_h264_close,
1563 const CodedBitstreamType ff_cbs_type_h265 = {
1564 .codec_id = AV_CODEC_ID_HEVC,
1566 .priv_data_size = sizeof(CodedBitstreamH265Context),
1568 .split_fragment = &cbs_h2645_split_fragment,
1569 .read_unit = &cbs_h265_read_nal_unit,
1570 .write_unit = &cbs_h2645_write_nal_unit,
1571 .assemble_fragment = &cbs_h2645_assemble_fragment,
1573 .close = &cbs_h265_close,
1576 int ff_cbs_h264_add_sei_message(CodedBitstreamContext *ctx,
1577 CodedBitstreamFragment *au,
1578 const H264RawSEIPayload *payload)
1581 CodedBitstreamUnit *nal = NULL;
1584 // Find an existing SEI NAL unit to add to.
1585 for (i = 0; i < au->nb_units; i++) {
1586 if (au->units[i].type == H264_NAL_SEI) {
1587 nal = &au->units[i];
1595 // Need to make a new SEI NAL unit. Insert it before the first
1596 // slice data NAL unit; if no slice data, add at the end.
1597 AVBufferRef *sei_ref;
1599 sei = av_mallocz(sizeof(*sei));
1601 return AVERROR(ENOMEM);
1603 sei->nal_unit_header.nal_unit_type = H264_NAL_SEI;
1604 sei->nal_unit_header.nal_ref_idc = 0;
1606 sei_ref = av_buffer_create((uint8_t*)sei, sizeof(*sei),
1607 &cbs_h264_free_sei, ctx, 0);
1610 return AVERROR(ENOMEM);
1613 for (i = 0; i < au->nb_units; i++) {
1614 if (au->units[i].type == H264_NAL_SLICE ||
1615 au->units[i].type == H264_NAL_IDR_SLICE)
1619 err = ff_cbs_insert_unit_content(ctx, au, i, H264_NAL_SEI,
1621 av_buffer_unref(&sei_ref);
1626 if (sei->payload_count >= H264_MAX_SEI_PAYLOADS) {
1627 av_log(ctx->log_ctx, AV_LOG_ERROR, "Too many payloads in "
1629 return AVERROR(EINVAL);
1632 memcpy(&sei->payload[sei->payload_count], payload, sizeof(*payload));
1633 ++sei->payload_count;
1638 int ff_cbs_h264_delete_sei_message(CodedBitstreamContext *ctx,
1639 CodedBitstreamFragment *au,
1640 CodedBitstreamUnit *nal,
1643 H264RawSEI *sei = nal->content;
1645 av_assert0(nal->type == H264_NAL_SEI);
1646 av_assert0(position >= 0 && position < sei->payload_count);
1648 if (position == 0 && sei->payload_count == 1) {
1649 // Deleting NAL unit entirely.
1652 for (i = 0; i < au->nb_units; i++) {
1653 if (&au->units[i] == nal)
1656 av_assert0(i < au->nb_units && "NAL unit not in access unit.");
1658 return ff_cbs_delete_unit(ctx, au, i);
1660 cbs_h264_free_sei_payload(&sei->payload[position]);
1662 --sei->payload_count;
1663 memmove(sei->payload + position,
1664 sei->payload + position + 1,
1665 (sei->payload_count - position) * sizeof(*sei->payload));