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_NAME2(rw, codec, name) cbs_ ## codec ## _ ## rw ## _ ## name
257 #define FUNC_NAME1(rw, codec, name) FUNC_NAME2(rw, codec, name)
258 #define FUNC_H264(name) FUNC_NAME1(READWRITE, h264, name)
259 #define FUNC_H265(name) FUNC_NAME1(READWRITE, h265, name)
260 #define FUNC_SEI(name) FUNC_NAME1(READWRITE, sei, name)
262 #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL)
264 #define u(width, name, range_min, range_max) \
265 xu(width, name, current->name, range_min, range_max, 0, )
266 #define ub(width, name) \
267 xu(width, name, current->name, 0, MAX_UINT_BITS(width), 0, )
268 #define flag(name) ub(1, name)
269 #define ue(name, range_min, range_max) \
270 xue(name, current->name, range_min, range_max, 0, )
271 #define i(width, name, range_min, range_max) \
272 xi(width, name, current->name, range_min, range_max, 0, )
273 #define ib(width, name) \
274 xi(width, name, current->name, MIN_INT_BITS(width), MAX_INT_BITS(width), 0, )
275 #define se(name, range_min, range_max) \
276 xse(name, current->name, range_min, range_max, 0, )
278 #define us(width, name, range_min, range_max, subs, ...) \
279 xu(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
280 #define ubs(width, name, subs, ...) \
281 xu(width, name, current->name, 0, MAX_UINT_BITS(width), subs, __VA_ARGS__)
282 #define flags(name, subs, ...) \
283 xu(1, name, current->name, 0, 1, subs, __VA_ARGS__)
284 #define ues(name, range_min, range_max, subs, ...) \
285 xue(name, current->name, range_min, range_max, subs, __VA_ARGS__)
286 #define is(width, name, range_min, range_max, subs, ...) \
287 xi(width, name, current->name, range_min, range_max, subs, __VA_ARGS__)
288 #define ibs(width, name, subs, ...) \
289 xi(width, name, current->name, MIN_INT_BITS(width), MAX_INT_BITS(width), subs, __VA_ARGS__)
290 #define ses(name, range_min, range_max, subs, ...) \
291 xse(name, current->name, range_min, range_max, subs, __VA_ARGS__)
293 #define fixed(width, name, value) do { \
294 av_unused uint32_t fixed_value = value; \
295 xu(width, name, fixed_value, value, value, 0, ); \
300 #define READWRITE read
301 #define RWContext GetBitContext
303 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
305 CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \
306 SUBSCRIPTS(subs, __VA_ARGS__), \
307 &value, range_min, range_max)); \
310 #define xue(name, var, range_min, range_max, subs, ...) do { \
312 CHECK(cbs_read_ue_golomb(ctx, rw, #name, \
313 SUBSCRIPTS(subs, __VA_ARGS__), \
314 &value, range_min, range_max)); \
317 #define xi(width, name, var, range_min, range_max, subs, ...) do { \
319 CHECK(ff_cbs_read_signed(ctx, rw, width, #name, \
320 SUBSCRIPTS(subs, __VA_ARGS__), \
321 &value, range_min, range_max)); \
324 #define xse(name, var, range_min, range_max, subs, ...) do { \
326 CHECK(cbs_read_se_golomb(ctx, rw, #name, \
327 SUBSCRIPTS(subs, __VA_ARGS__), \
328 &value, range_min, range_max)); \
333 #define infer(name, value) do { \
334 current->name = value; \
337 static int cbs_h2645_read_more_rbsp_data(GetBitContext *gbc)
339 int bits_left = get_bits_left(gbc);
344 if (show_bits(gbc, bits_left) & MAX_UINT_BITS(bits_left - 1))
349 #define more_rbsp_data(var) ((var) = cbs_h2645_read_more_rbsp_data(rw))
351 #define bit_position(rw) (get_bits_count(rw))
352 #define byte_alignment(rw) (get_bits_count(rw) % 8)
354 #define allocate(name, size) do { \
355 name ## _ref = av_buffer_allocz(size + \
356 AV_INPUT_BUFFER_PADDING_SIZE); \
358 return AVERROR(ENOMEM); \
359 name = name ## _ref->data; \
362 #define FUNC(name) FUNC_SEI(name)
363 #include "cbs_sei_syntax_template.c"
366 #define FUNC(name) FUNC_H264(name)
367 #include "cbs_h264_syntax_template.c"
370 #define FUNC(name) FUNC_H265(name)
371 #include "cbs_h265_syntax_template.c"
382 #undef more_rbsp_data
384 #undef byte_alignment
389 #define READWRITE write
390 #define RWContext PutBitContext
392 #define xu(width, name, var, range_min, range_max, subs, ...) do { \
393 uint32_t value = var; \
394 CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \
395 SUBSCRIPTS(subs, __VA_ARGS__), \
396 value, range_min, range_max)); \
398 #define xue(name, var, range_min, range_max, subs, ...) do { \
399 uint32_t value = var; \
400 CHECK(cbs_write_ue_golomb(ctx, rw, #name, \
401 SUBSCRIPTS(subs, __VA_ARGS__), \
402 value, range_min, range_max)); \
404 #define xi(width, name, var, range_min, range_max, subs, ...) do { \
405 int32_t value = var; \
406 CHECK(ff_cbs_write_signed(ctx, rw, width, #name, \
407 SUBSCRIPTS(subs, __VA_ARGS__), \
408 value, range_min, range_max)); \
410 #define xse(name, var, range_min, range_max, subs, ...) do { \
411 int32_t value = var; \
412 CHECK(cbs_write_se_golomb(ctx, rw, #name, \
413 SUBSCRIPTS(subs, __VA_ARGS__), \
414 value, range_min, range_max)); \
417 #define infer(name, value) do { \
418 if (current->name != (value)) { \
419 av_log(ctx->log_ctx, AV_LOG_ERROR, \
420 "%s does not match inferred value: " \
421 "%"PRId64", but should be %"PRId64".\n", \
422 #name, (int64_t)current->name, (int64_t)(value)); \
423 return AVERROR_INVALIDDATA; \
427 #define more_rbsp_data(var) (var)
429 #define bit_position(rw) (put_bits_count(rw))
430 #define byte_alignment(rw) (put_bits_count(rw) % 8)
432 #define allocate(name, size) do { \
434 av_log(ctx->log_ctx, AV_LOG_ERROR, "%s must be set " \
435 "for writing.\n", #name); \
436 return AVERROR_INVALIDDATA; \
440 #define FUNC(name) FUNC_SEI(name)
441 #include "cbs_sei_syntax_template.c"
444 #define FUNC(name) FUNC_H264(name)
445 #include "cbs_h264_syntax_template.c"
448 #define FUNC(name) FUNC_H265(name)
449 #include "cbs_h265_syntax_template.c"
465 #undef more_rbsp_data
467 #undef byte_alignment
471 static int cbs_h2645_fragment_add_nals(CodedBitstreamContext *ctx,
472 CodedBitstreamFragment *frag,
473 const H2645Packet *packet)
477 for (i = 0; i < packet->nb_nals; i++) {
478 const H2645NAL *nal = &packet->nals[i];
480 size_t size = nal->size;
482 if (nal->nuh_layer_id > 0)
485 // Remove trailing zeroes.
486 while (size > 0 && nal->data[size - 1] == 0)
489 av_log(ctx->log_ctx, AV_LOG_VERBOSE, "Discarding empty 0 NAL unit\n");
493 ref = (nal->data == nal->raw_data) ? frag->data_ref
494 : packet->rbsp.rbsp_buffer_ref;
496 err = ff_cbs_insert_unit_data(frag, -1, nal->type,
497 (uint8_t*)nal->data, size, ref);
505 static int cbs_h2645_split_fragment(CodedBitstreamContext *ctx,
506 CodedBitstreamFragment *frag,
509 enum AVCodecID codec_id = ctx->codec->codec_id;
510 CodedBitstreamH2645Context *priv = ctx->priv_data;
514 av_assert0(frag->data && frag->nb_units == 0);
515 if (frag->data_size == 0)
518 if (header && frag->data[0] && codec_id == AV_CODEC_ID_H264) {
520 size_t size, start, end;
521 int i, count, version;
525 bytestream2_init(&gbc, frag->data, frag->data_size);
527 if (bytestream2_get_bytes_left(&gbc) < 6)
528 return AVERROR_INVALIDDATA;
530 version = bytestream2_get_byte(&gbc);
532 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid AVCC header: "
533 "first byte %u.\n", version);
534 return AVERROR_INVALIDDATA;
537 bytestream2_skip(&gbc, 3);
538 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
541 count = bytestream2_get_byte(&gbc) & 0x1f;
542 start = bytestream2_tell(&gbc);
543 for (i = 0; i < count; i++) {
544 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
545 return AVERROR_INVALIDDATA;
546 size = bytestream2_get_be16(&gbc);
547 if (bytestream2_get_bytes_left(&gbc) < size)
548 return AVERROR_INVALIDDATA;
549 bytestream2_skip(&gbc, size);
551 end = bytestream2_tell(&gbc);
553 err = ff_h2645_packet_split(&priv->read_packet,
554 frag->data + start, end - start,
555 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1, 1);
557 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC SPS array.\n");
560 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
565 count = bytestream2_get_byte(&gbc);
566 start = bytestream2_tell(&gbc);
567 for (i = 0; i < count; i++) {
568 if (bytestream2_get_bytes_left(&gbc) < 2 * (count - i))
569 return AVERROR_INVALIDDATA;
570 size = bytestream2_get_be16(&gbc);
571 if (bytestream2_get_bytes_left(&gbc) < size)
572 return AVERROR_INVALIDDATA;
573 bytestream2_skip(&gbc, size);
575 end = bytestream2_tell(&gbc);
577 err = ff_h2645_packet_split(&priv->read_packet,
578 frag->data + start, end - start,
579 ctx->log_ctx, 1, 2, AV_CODEC_ID_H264, 1, 1);
581 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split AVCC PPS array.\n");
584 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
588 if (bytestream2_get_bytes_left(&gbc) > 0) {
589 av_log(ctx->log_ctx, AV_LOG_WARNING, "%u bytes left at end of AVCC "
590 "header.\n", bytestream2_get_bytes_left(&gbc));
593 } else if (header && frag->data[0] && codec_id == AV_CODEC_ID_HEVC) {
595 size_t size, start, end;
596 int i, j, nb_arrays, nal_unit_type, nb_nals, version;
600 bytestream2_init(&gbc, frag->data, frag->data_size);
602 if (bytestream2_get_bytes_left(&gbc) < 23)
603 return AVERROR_INVALIDDATA;
605 version = bytestream2_get_byte(&gbc);
607 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid HVCC header: "
608 "first byte %u.\n", version);
609 return AVERROR_INVALIDDATA;
612 bytestream2_skip(&gbc, 20);
613 priv->nal_length_size = (bytestream2_get_byte(&gbc) & 3) + 1;
615 nb_arrays = bytestream2_get_byte(&gbc);
616 for (i = 0; i < nb_arrays; i++) {
617 nal_unit_type = bytestream2_get_byte(&gbc) & 0x3f;
618 nb_nals = bytestream2_get_be16(&gbc);
620 start = bytestream2_tell(&gbc);
621 for (j = 0; j < nb_nals; j++) {
622 if (bytestream2_get_bytes_left(&gbc) < 2)
623 return AVERROR_INVALIDDATA;
624 size = bytestream2_get_be16(&gbc);
625 if (bytestream2_get_bytes_left(&gbc) < size)
626 return AVERROR_INVALIDDATA;
627 bytestream2_skip(&gbc, size);
629 end = bytestream2_tell(&gbc);
631 err = ff_h2645_packet_split(&priv->read_packet,
632 frag->data + start, end - start,
633 ctx->log_ctx, 1, 2, AV_CODEC_ID_HEVC, 1, 1);
635 av_log(ctx->log_ctx, AV_LOG_ERROR, "Failed to split "
636 "HVCC array %d (%d NAL units of type %d).\n",
637 i, nb_nals, nal_unit_type);
640 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
646 // Annex B, or later MP4 with already-known parameters.
648 err = ff_h2645_packet_split(&priv->read_packet,
649 frag->data, frag->data_size,
651 priv->mp4, priv->nal_length_size,
656 err = cbs_h2645_fragment_add_nals(ctx, frag, &priv->read_packet);
664 #define cbs_h2645_replace_ps(h26n, ps_name, ps_var, id_element) \
665 static int cbs_h26 ## h26n ## _replace_ ## ps_var(CodedBitstreamContext *ctx, \
666 CodedBitstreamUnit *unit) \
668 CodedBitstreamH26 ## h26n ## Context *priv = ctx->priv_data; \
669 H26 ## h26n ## Raw ## ps_name *ps_var = unit->content; \
670 unsigned int id = ps_var->id_element; \
672 if (id >= FF_ARRAY_ELEMS(priv->ps_var)) { \
673 av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid " #ps_name \
674 " id : %d.\n", id); \
675 return AVERROR_INVALIDDATA; \
677 err = ff_cbs_make_unit_refcounted(ctx, unit); \
680 if (priv->ps_var[id] == priv->active_ ## ps_var) \
681 priv->active_ ## ps_var = NULL ; \
682 av_buffer_unref(&priv->ps_var ## _ref[id]); \
683 av_assert0(unit->content_ref); \
684 priv->ps_var ## _ref[id] = av_buffer_ref(unit->content_ref); \
685 if (!priv->ps_var ## _ref[id]) \
686 return AVERROR(ENOMEM); \
687 priv->ps_var[id] = (H26 ## h26n ## Raw ## ps_name *)priv->ps_var ## _ref[id]->data; \
691 cbs_h2645_replace_ps(4, SPS, sps, seq_parameter_set_id)
692 cbs_h2645_replace_ps(4, PPS, pps, pic_parameter_set_id)
693 cbs_h2645_replace_ps(5, VPS, vps, vps_video_parameter_set_id)
694 cbs_h2645_replace_ps(5, SPS, sps, sps_seq_parameter_set_id)
695 cbs_h2645_replace_ps(5, PPS, pps, pps_pic_parameter_set_id)
697 static int cbs_h264_read_nal_unit(CodedBitstreamContext *ctx,
698 CodedBitstreamUnit *unit)
703 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
707 err = ff_cbs_alloc_unit_content2(ctx, unit);
711 switch (unit->type) {
714 H264RawSPS *sps = unit->content;
716 err = cbs_h264_read_sps(ctx, &gbc, sps);
720 err = cbs_h264_replace_sps(ctx, unit);
726 case H264_NAL_SPS_EXT:
728 err = cbs_h264_read_sps_extension(ctx, &gbc, unit->content);
736 H264RawPPS *pps = unit->content;
738 err = cbs_h264_read_pps(ctx, &gbc, pps);
742 err = cbs_h264_replace_pps(ctx, unit);
749 case H264_NAL_IDR_SLICE:
750 case H264_NAL_AUXILIARY_SLICE:
752 H264RawSlice *slice = unit->content;
755 err = cbs_h264_read_slice_header(ctx, &gbc, &slice->header);
759 if (!cbs_h2645_read_more_rbsp_data(&gbc))
760 return AVERROR_INVALIDDATA;
762 pos = get_bits_count(&gbc);
763 len = unit->data_size;
765 slice->data_size = len - pos / 8;
766 slice->data_ref = av_buffer_ref(unit->data_ref);
767 if (!slice->data_ref)
768 return AVERROR(ENOMEM);
769 slice->data = unit->data + pos / 8;
770 slice->data_bit_start = pos % 8;
776 err = cbs_h264_read_aud(ctx, &gbc, unit->content);
784 err = cbs_h264_read_sei(ctx, &gbc, unit->content);
790 case H264_NAL_FILLER_DATA:
792 err = cbs_h264_read_filler(ctx, &gbc, unit->content);
798 case H264_NAL_END_SEQUENCE:
799 case H264_NAL_END_STREAM:
801 err = (unit->type == H264_NAL_END_SEQUENCE ?
802 cbs_h264_read_end_of_sequence :
803 cbs_h264_read_end_of_stream)(ctx, &gbc, unit->content);
810 return AVERROR(ENOSYS);
816 static int cbs_h265_read_nal_unit(CodedBitstreamContext *ctx,
817 CodedBitstreamUnit *unit)
822 err = init_get_bits(&gbc, unit->data, 8 * unit->data_size);
826 err = ff_cbs_alloc_unit_content2(ctx, unit);
830 switch (unit->type) {
833 H265RawVPS *vps = unit->content;
835 err = cbs_h265_read_vps(ctx, &gbc, vps);
839 err = cbs_h265_replace_vps(ctx, unit);
846 H265RawSPS *sps = unit->content;
848 err = cbs_h265_read_sps(ctx, &gbc, sps);
852 err = cbs_h265_replace_sps(ctx, unit);
860 H265RawPPS *pps = unit->content;
862 err = cbs_h265_read_pps(ctx, &gbc, pps);
866 err = cbs_h265_replace_pps(ctx, unit);
872 case HEVC_NAL_TRAIL_N:
873 case HEVC_NAL_TRAIL_R:
876 case HEVC_NAL_STSA_N:
877 case HEVC_NAL_STSA_R:
878 case HEVC_NAL_RADL_N:
879 case HEVC_NAL_RADL_R:
880 case HEVC_NAL_RASL_N:
881 case HEVC_NAL_RASL_R:
882 case HEVC_NAL_BLA_W_LP:
883 case HEVC_NAL_BLA_W_RADL:
884 case HEVC_NAL_BLA_N_LP:
885 case HEVC_NAL_IDR_W_RADL:
886 case HEVC_NAL_IDR_N_LP:
887 case HEVC_NAL_CRA_NUT:
889 H265RawSlice *slice = unit->content;
892 err = cbs_h265_read_slice_segment_header(ctx, &gbc, &slice->header);
896 if (!cbs_h2645_read_more_rbsp_data(&gbc))
897 return AVERROR_INVALIDDATA;
899 pos = get_bits_count(&gbc);
900 len = unit->data_size;
902 slice->data_size = len - pos / 8;
903 slice->data_ref = av_buffer_ref(unit->data_ref);
904 if (!slice->data_ref)
905 return AVERROR(ENOMEM);
906 slice->data = unit->data + pos / 8;
907 slice->data_bit_start = pos % 8;
913 err = cbs_h265_read_aud(ctx, &gbc, unit->content);
919 case HEVC_NAL_SEI_PREFIX:
920 case HEVC_NAL_SEI_SUFFIX:
922 err = cbs_h265_read_sei(ctx, &gbc, unit->content,
923 unit->type == HEVC_NAL_SEI_PREFIX);
931 return AVERROR(ENOSYS);
937 static int cbs_h2645_write_slice_data(CodedBitstreamContext *ctx,
938 PutBitContext *pbc, const uint8_t *data,
939 size_t data_size, int data_bit_start)
941 size_t rest = data_size - (data_bit_start + 7) / 8;
942 const uint8_t *pos = data + data_bit_start / 8;
944 av_assert0(data_bit_start >= 0 &&
945 data_size > data_bit_start / 8);
947 if (data_size * 8 + 8 > put_bits_left(pbc))
948 return AVERROR(ENOSPC);
951 goto rbsp_stop_one_bit;
953 // First copy the remaining bits of the first byte
954 // The above check ensures that we do not accidentally
955 // copy beyond the rbsp_stop_one_bit.
956 if (data_bit_start % 8)
957 put_bits(pbc, 8 - data_bit_start % 8,
958 *pos++ & MAX_UINT_BITS(8 - data_bit_start % 8));
960 if (put_bits_count(pbc) % 8 == 0) {
961 // If the writer is aligned at this point,
962 // memcpy can be used to improve performance.
963 // This happens normally for CABAC.
965 memcpy(put_bits_ptr(pbc), pos, rest);
966 skip_put_bytes(pbc, rest);
968 // If not, we have to copy manually.
969 // rbsp_stop_one_bit forces us to special-case
974 for (; rest > 4; rest -= 4, pos += 4)
975 put_bits32(pbc, AV_RB32(pos));
977 for (; rest > 1; rest--, pos++)
978 put_bits(pbc, 8, *pos);
981 temp = rest ? *pos : *pos & MAX_UINT_BITS(8 - data_bit_start % 8);
986 i = rest ? (8 - i) : (8 - i - data_bit_start % 8);
987 put_bits(pbc, i, temp);
988 if (put_bits_count(pbc) % 8)
989 put_bits(pbc, 8 - put_bits_count(pbc) % 8, 0);
995 static int cbs_h264_write_nal_unit(CodedBitstreamContext *ctx,
996 CodedBitstreamUnit *unit,
1001 switch (unit->type) {
1004 H264RawSPS *sps = unit->content;
1006 err = cbs_h264_write_sps(ctx, pbc, sps);
1010 err = cbs_h264_replace_sps(ctx, unit);
1016 case H264_NAL_SPS_EXT:
1018 H264RawSPSExtension *sps_ext = unit->content;
1020 err = cbs_h264_write_sps_extension(ctx, pbc, sps_ext);
1028 H264RawPPS *pps = unit->content;
1030 err = cbs_h264_write_pps(ctx, pbc, pps);
1034 err = cbs_h264_replace_pps(ctx, unit);
1040 case H264_NAL_SLICE:
1041 case H264_NAL_IDR_SLICE:
1042 case H264_NAL_AUXILIARY_SLICE:
1044 H264RawSlice *slice = unit->content;
1046 err = cbs_h264_write_slice_header(ctx, pbc, &slice->header);
1051 err = cbs_h2645_write_slice_data(ctx, pbc, slice->data,
1053 slice->data_bit_start);
1057 // No slice data - that was just the header.
1058 // (Bitstream may be unaligned!)
1065 err = cbs_h264_write_aud(ctx, pbc, unit->content);
1073 err = cbs_h264_write_sei(ctx, pbc, unit->content);
1079 case H264_NAL_FILLER_DATA:
1081 err = cbs_h264_write_filler(ctx, pbc, unit->content);
1087 case H264_NAL_END_SEQUENCE:
1089 err = cbs_h264_write_end_of_sequence(ctx, pbc, unit->content);
1095 case H264_NAL_END_STREAM:
1097 err = cbs_h264_write_end_of_stream(ctx, pbc, unit->content);
1104 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1105 "NAL unit type %"PRIu32".\n", unit->type);
1106 return AVERROR_PATCHWELCOME;
1112 static int cbs_h265_write_nal_unit(CodedBitstreamContext *ctx,
1113 CodedBitstreamUnit *unit,
1118 switch (unit->type) {
1121 H265RawVPS *vps = unit->content;
1123 err = cbs_h265_write_vps(ctx, pbc, vps);
1127 err = cbs_h265_replace_vps(ctx, unit);
1135 H265RawSPS *sps = unit->content;
1137 err = cbs_h265_write_sps(ctx, pbc, sps);
1141 err = cbs_h265_replace_sps(ctx, unit);
1149 H265RawPPS *pps = unit->content;
1151 err = cbs_h265_write_pps(ctx, pbc, pps);
1155 err = cbs_h265_replace_pps(ctx, unit);
1161 case HEVC_NAL_TRAIL_N:
1162 case HEVC_NAL_TRAIL_R:
1163 case HEVC_NAL_TSA_N:
1164 case HEVC_NAL_TSA_R:
1165 case HEVC_NAL_STSA_N:
1166 case HEVC_NAL_STSA_R:
1167 case HEVC_NAL_RADL_N:
1168 case HEVC_NAL_RADL_R:
1169 case HEVC_NAL_RASL_N:
1170 case HEVC_NAL_RASL_R:
1171 case HEVC_NAL_BLA_W_LP:
1172 case HEVC_NAL_BLA_W_RADL:
1173 case HEVC_NAL_BLA_N_LP:
1174 case HEVC_NAL_IDR_W_RADL:
1175 case HEVC_NAL_IDR_N_LP:
1176 case HEVC_NAL_CRA_NUT:
1178 H265RawSlice *slice = unit->content;
1180 err = cbs_h265_write_slice_segment_header(ctx, pbc, &slice->header);
1185 err = cbs_h2645_write_slice_data(ctx, pbc, slice->data,
1187 slice->data_bit_start);
1191 // No slice data - that was just the header.
1198 err = cbs_h265_write_aud(ctx, pbc, unit->content);
1204 case HEVC_NAL_SEI_PREFIX:
1205 case HEVC_NAL_SEI_SUFFIX:
1207 err = cbs_h265_write_sei(ctx, pbc, unit->content,
1208 unit->type == HEVC_NAL_SEI_PREFIX);
1216 av_log(ctx->log_ctx, AV_LOG_ERROR, "Write unimplemented for "
1217 "NAL unit type %"PRIu32".\n", unit->type);
1218 return AVERROR_PATCHWELCOME;
1224 static int cbs_h2645_unit_requires_zero_byte(enum AVCodecID codec_id,
1225 CodedBitstreamUnitType type,
1228 // Section B.1.2 in H.264, section B.2.2 in H.265.
1229 if (nal_unit_index == 0) {
1230 // Assume that this is the first NAL unit in an access unit.
1233 if (codec_id == AV_CODEC_ID_H264)
1234 return type == H264_NAL_SPS || type == H264_NAL_PPS;
1235 if (codec_id == AV_CODEC_ID_HEVC)
1236 return type == HEVC_NAL_VPS || type == HEVC_NAL_SPS || type == HEVC_NAL_PPS;
1240 static int cbs_h2645_assemble_fragment(CodedBitstreamContext *ctx,
1241 CodedBitstreamFragment *frag)
1244 size_t max_size, dp, sp;
1245 int err, i, zero_run;
1247 for (i = 0; i < frag->nb_units; i++) {
1248 // Data should already all have been written when we get here.
1249 av_assert0(frag->units[i].data);
1253 for (i = 0; i < frag->nb_units; i++) {
1254 // Start code + content with worst-case emulation prevention.
1255 max_size += 4 + frag->units[i].data_size * 3 / 2;
1258 data = av_realloc(NULL, max_size + AV_INPUT_BUFFER_PADDING_SIZE);
1260 return AVERROR(ENOMEM);
1263 for (i = 0; i < frag->nb_units; i++) {
1264 CodedBitstreamUnit *unit = &frag->units[i];
1266 if (unit->data_bit_padding > 0) {
1267 if (i < frag->nb_units - 1)
1268 av_log(ctx->log_ctx, AV_LOG_WARNING, "Probably invalid "
1269 "unaligned padding on non-final NAL unit.\n");
1271 frag->data_bit_padding = unit->data_bit_padding;
1274 if (cbs_h2645_unit_requires_zero_byte(ctx->codec->codec_id, unit->type, i)) {
1278 // start_code_prefix_one_3bytes
1284 for (sp = 0; sp < unit->data_size; sp++) {
1286 if (unit->data[sp] == 0)
1291 if ((unit->data[sp] & ~3) == 0) {
1292 // emulation_prevention_three_byte
1295 zero_run = unit->data[sp] == 0;
1297 data[dp++] = unit->data[sp];
1301 av_assert0(dp <= max_size);
1302 err = av_reallocp(&data, dp + AV_INPUT_BUFFER_PADDING_SIZE);
1305 memset(data + dp, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1307 frag->data_ref = av_buffer_create(data, dp + AV_INPUT_BUFFER_PADDING_SIZE,
1309 if (!frag->data_ref) {
1311 return AVERROR(ENOMEM);
1315 frag->data_size = dp;
1320 static void cbs_h264_flush(CodedBitstreamContext *ctx)
1322 CodedBitstreamH264Context *h264 = ctx->priv_data;
1324 for (int i = 0; i < FF_ARRAY_ELEMS(h264->sps); i++) {
1325 av_buffer_unref(&h264->sps_ref[i]);
1326 h264->sps[i] = NULL;
1328 for (int i = 0; i < FF_ARRAY_ELEMS(h264->pps); i++) {
1329 av_buffer_unref(&h264->pps_ref[i]);
1330 h264->pps[i] = NULL;
1333 h264->active_sps = NULL;
1334 h264->active_pps = NULL;
1335 h264->last_slice_nal_unit_type = 0;
1338 static void cbs_h264_close(CodedBitstreamContext *ctx)
1340 CodedBitstreamH264Context *h264 = ctx->priv_data;
1343 ff_h2645_packet_uninit(&h264->common.read_packet);
1345 for (i = 0; i < FF_ARRAY_ELEMS(h264->sps); i++)
1346 av_buffer_unref(&h264->sps_ref[i]);
1347 for (i = 0; i < FF_ARRAY_ELEMS(h264->pps); i++)
1348 av_buffer_unref(&h264->pps_ref[i]);
1351 static void cbs_h265_flush(CodedBitstreamContext *ctx)
1353 CodedBitstreamH265Context *h265 = ctx->priv_data;
1355 for (int i = 0; i < FF_ARRAY_ELEMS(h265->vps); i++) {
1356 av_buffer_unref(&h265->vps_ref[i]);
1357 h265->vps[i] = NULL;
1359 for (int i = 0; i < FF_ARRAY_ELEMS(h265->sps); i++) {
1360 av_buffer_unref(&h265->sps_ref[i]);
1361 h265->sps[i] = NULL;
1363 for (int i = 0; i < FF_ARRAY_ELEMS(h265->pps); i++) {
1364 av_buffer_unref(&h265->pps_ref[i]);
1365 h265->pps[i] = NULL;
1368 h265->active_vps = NULL;
1369 h265->active_sps = NULL;
1370 h265->active_pps = NULL;
1373 static void cbs_h265_close(CodedBitstreamContext *ctx)
1375 CodedBitstreamH265Context *h265 = ctx->priv_data;
1378 ff_h2645_packet_uninit(&h265->common.read_packet);
1380 for (i = 0; i < FF_ARRAY_ELEMS(h265->vps); i++)
1381 av_buffer_unref(&h265->vps_ref[i]);
1382 for (i = 0; i < FF_ARRAY_ELEMS(h265->sps); i++)
1383 av_buffer_unref(&h265->sps_ref[i]);
1384 for (i = 0; i < FF_ARRAY_ELEMS(h265->pps); i++)
1385 av_buffer_unref(&h265->pps_ref[i]);
1388 static void cbs_h264_free_sei(void *opaque, uint8_t *content)
1390 H264RawSEI *sei = (H264RawSEI*)content;
1391 ff_cbs_sei_free_message_list(&sei->message_list);
1395 static const CodedBitstreamUnitTypeDescriptor cbs_h264_unit_types[] = {
1396 CBS_UNIT_TYPE_POD(H264_NAL_SPS, H264RawSPS),
1397 CBS_UNIT_TYPE_POD(H264_NAL_SPS_EXT, H264RawSPSExtension),
1399 CBS_UNIT_TYPE_INTERNAL_REF(H264_NAL_PPS, H264RawPPS, slice_group_id),
1406 H264_NAL_AUXILIARY_SLICE,
1408 .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS,
1409 .content_size = sizeof(H264RawSlice),
1410 .nb_ref_offsets = 1,
1411 .ref_offsets = { offsetof(H264RawSlice, data) },
1414 CBS_UNIT_TYPE_POD(H264_NAL_AUD, H264RawAUD),
1415 CBS_UNIT_TYPE_POD(H264_NAL_FILLER_DATA, H264RawFiller),
1416 CBS_UNIT_TYPE_POD(H264_NAL_END_SEQUENCE, H264RawNALUnitHeader),
1417 CBS_UNIT_TYPE_POD(H264_NAL_END_STREAM, H264RawNALUnitHeader),
1419 CBS_UNIT_TYPE_COMPLEX(H264_NAL_SEI, H264RawSEI, &cbs_h264_free_sei),
1421 CBS_UNIT_TYPE_END_OF_LIST
1424 static void cbs_h265_free_sei(void *opaque, uint8_t *content)
1426 H265RawSEI *sei = (H265RawSEI*)content;
1427 ff_cbs_sei_free_message_list(&sei->message_list);
1431 static const CodedBitstreamUnitTypeDescriptor cbs_h265_unit_types[] = {
1432 CBS_UNIT_TYPE_INTERNAL_REF(HEVC_NAL_VPS, H265RawVPS, extension_data.data),
1433 CBS_UNIT_TYPE_INTERNAL_REF(HEVC_NAL_SPS, H265RawSPS, extension_data.data),
1434 CBS_UNIT_TYPE_INTERNAL_REF(HEVC_NAL_PPS, H265RawPPS, extension_data.data),
1436 CBS_UNIT_TYPE_POD(HEVC_NAL_AUD, H265RawAUD),
1439 // Slices of non-IRAP pictures.
1440 .nb_unit_types = CBS_UNIT_TYPE_RANGE,
1441 .unit_type_range_start = HEVC_NAL_TRAIL_N,
1442 .unit_type_range_end = HEVC_NAL_RASL_R,
1444 .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS,
1445 .content_size = sizeof(H265RawSlice),
1446 .nb_ref_offsets = 1,
1447 .ref_offsets = { offsetof(H265RawSlice, data) },
1451 // Slices of IRAP pictures.
1452 .nb_unit_types = CBS_UNIT_TYPE_RANGE,
1453 .unit_type_range_start = HEVC_NAL_BLA_W_LP,
1454 .unit_type_range_end = HEVC_NAL_CRA_NUT,
1456 .content_type = CBS_CONTENT_TYPE_INTERNAL_REFS,
1457 .content_size = sizeof(H265RawSlice),
1458 .nb_ref_offsets = 1,
1459 .ref_offsets = { offsetof(H265RawSlice, data) },
1465 HEVC_NAL_SEI_PREFIX,
1468 .content_type = CBS_CONTENT_TYPE_COMPLEX,
1469 .content_size = sizeof(H265RawSEI),
1470 .content_free = &cbs_h265_free_sei,
1473 CBS_UNIT_TYPE_END_OF_LIST
1476 const CodedBitstreamType ff_cbs_type_h264 = {
1477 .codec_id = AV_CODEC_ID_H264,
1479 .priv_data_size = sizeof(CodedBitstreamH264Context),
1481 .unit_types = cbs_h264_unit_types,
1483 .split_fragment = &cbs_h2645_split_fragment,
1484 .read_unit = &cbs_h264_read_nal_unit,
1485 .write_unit = &cbs_h264_write_nal_unit,
1486 .assemble_fragment = &cbs_h2645_assemble_fragment,
1488 .flush = &cbs_h264_flush,
1489 .close = &cbs_h264_close,
1492 const CodedBitstreamType ff_cbs_type_h265 = {
1493 .codec_id = AV_CODEC_ID_HEVC,
1495 .priv_data_size = sizeof(CodedBitstreamH265Context),
1497 .unit_types = cbs_h265_unit_types,
1499 .split_fragment = &cbs_h2645_split_fragment,
1500 .read_unit = &cbs_h265_read_nal_unit,
1501 .write_unit = &cbs_h265_write_nal_unit,
1502 .assemble_fragment = &cbs_h2645_assemble_fragment,
1504 .flush = &cbs_h265_flush,
1505 .close = &cbs_h265_close,
1508 static const SEIMessageTypeDescriptor cbs_sei_common_types[] = {
1510 SEI_TYPE_FILLER_PAYLOAD,
1512 sizeof(SEIRawFillerPayload),
1513 SEI_MESSAGE_RW(sei, filler_payload),
1516 SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35,
1518 sizeof(SEIRawUserDataRegistered),
1519 SEI_MESSAGE_RW(sei, user_data_registered),
1522 SEI_TYPE_USER_DATA_UNREGISTERED,
1524 sizeof(SEIRawUserDataUnregistered),
1525 SEI_MESSAGE_RW(sei, user_data_unregistered),
1528 SEI_TYPE_MASTERING_DISPLAY_COLOUR_VOLUME,
1530 sizeof(SEIRawMasteringDisplayColourVolume),
1531 SEI_MESSAGE_RW(sei, mastering_display_colour_volume),
1534 SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO,
1536 sizeof(SEIRawContentLightLevelInfo),
1537 SEI_MESSAGE_RW(sei, content_light_level_info),
1540 SEI_TYPE_ALTERNATIVE_TRANSFER_CHARACTERISTICS,
1542 sizeof(SEIRawAlternativeTransferCharacteristics),
1543 SEI_MESSAGE_RW(sei, alternative_transfer_characteristics),
1545 SEI_MESSAGE_TYPE_END,
1548 static const SEIMessageTypeDescriptor cbs_sei_h264_types[] = {
1550 SEI_TYPE_BUFFERING_PERIOD,
1552 sizeof(H264RawSEIBufferingPeriod),
1553 SEI_MESSAGE_RW(h264, sei_buffering_period),
1556 SEI_TYPE_PIC_TIMING,
1558 sizeof(H264RawSEIPicTiming),
1559 SEI_MESSAGE_RW(h264, sei_pic_timing),
1562 SEI_TYPE_PAN_SCAN_RECT,
1564 sizeof(H264RawSEIPanScanRect),
1565 SEI_MESSAGE_RW(h264, sei_pan_scan_rect),
1568 SEI_TYPE_RECOVERY_POINT,
1570 sizeof(H264RawSEIRecoveryPoint),
1571 SEI_MESSAGE_RW(h264, sei_recovery_point),
1574 SEI_TYPE_DISPLAY_ORIENTATION,
1576 sizeof(H264RawSEIDisplayOrientation),
1577 SEI_MESSAGE_RW(h264, sei_display_orientation),
1579 SEI_MESSAGE_TYPE_END
1582 static const SEIMessageTypeDescriptor cbs_sei_h265_types[] = {
1584 SEI_TYPE_BUFFERING_PERIOD,
1586 sizeof(H265RawSEIBufferingPeriod),
1587 SEI_MESSAGE_RW(h265, sei_buffering_period),
1590 SEI_TYPE_PIC_TIMING,
1592 sizeof(H265RawSEIPicTiming),
1593 SEI_MESSAGE_RW(h265, sei_pic_timing),
1596 SEI_TYPE_PAN_SCAN_RECT,
1598 sizeof(H265RawSEIPanScanRect),
1599 SEI_MESSAGE_RW(h265, sei_pan_scan_rect),
1602 SEI_TYPE_RECOVERY_POINT,
1604 sizeof(H265RawSEIRecoveryPoint),
1605 SEI_MESSAGE_RW(h265, sei_recovery_point),
1608 SEI_TYPE_DISPLAY_ORIENTATION,
1610 sizeof(H265RawSEIDisplayOrientation),
1611 SEI_MESSAGE_RW(h265, sei_display_orientation),
1614 SEI_TYPE_ACTIVE_PARAMETER_SETS,
1616 sizeof(H265RawSEIActiveParameterSets),
1617 SEI_MESSAGE_RW(h265, sei_active_parameter_sets),
1620 SEI_TYPE_DECODED_PICTURE_HASH,
1622 sizeof(H265RawSEIDecodedPictureHash),
1623 SEI_MESSAGE_RW(h265, sei_decoded_picture_hash),
1628 sizeof(H265RawSEITimeCode),
1629 SEI_MESSAGE_RW(h265, sei_time_code),
1632 SEI_TYPE_ALPHA_CHANNEL_INFO,
1634 sizeof(H265RawSEIAlphaChannelInfo),
1635 SEI_MESSAGE_RW(h265, sei_alpha_channel_info),
1637 SEI_MESSAGE_TYPE_END
1640 const SEIMessageTypeDescriptor *ff_cbs_sei_find_type(CodedBitstreamContext *ctx,
1643 const SEIMessageTypeDescriptor *codec_list;
1646 for (i = 0; cbs_sei_common_types[i].type >= 0; i++) {
1647 if (cbs_sei_common_types[i].type == payload_type)
1648 return &cbs_sei_common_types[i];
1651 switch (ctx->codec->codec_id) {
1652 case AV_CODEC_ID_H264:
1653 codec_list = cbs_sei_h264_types;
1655 case AV_CODEC_ID_H265:
1656 codec_list = cbs_sei_h265_types;
1662 for (i = 0; codec_list[i].type >= 0; i++) {
1663 if (codec_list[i].type == payload_type)
1664 return &codec_list[i];