2 * "NUT" Container Format demuxer
3 * Copyright (c) 2004-2006 Michael Niedermayer
4 * Copyright (c) 2003 Alex Beregszaszi
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "libavutil/avstring.h"
24 #include "libavutil/avassert.h"
25 #include "libavutil/bswap.h"
26 #include "libavutil/dict.h"
27 #include "libavutil/intreadwrite.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/tree.h"
30 #include "libavcodec/bytestream.h"
31 #include "avio_internal.h"
36 #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
38 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
39 int64_t *pos_arg, int64_t pos_limit);
41 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
43 unsigned int len = ffio_read_varlen(bc);
46 avio_read(bc, string, FFMIN(len, maxlen));
47 while (len > maxlen) {
55 string[FFMIN(len, maxlen - 1)] = 0;
65 static int64_t get_s(AVIOContext *bc)
67 int64_t v = ffio_read_varlen(bc) + 1;
75 static uint64_t get_fourcc(AVIOContext *bc)
77 unsigned int len = ffio_read_varlen(bc);
84 av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
90 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
91 const char *func, int line)
93 uint64_t v = ffio_read_varlen(bc);
95 av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
96 v, v, file, func, line);
100 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
101 const char *func, int line)
103 int64_t v = get_s(bc);
105 av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
106 v, v, file, func, line);
110 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
111 char *func, int line)
113 uint64_t v = get_fourcc(bc);
115 av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
116 v, v, file, func, line);
119 #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
120 #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
121 #define get_fourcc(bc) get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
124 static int get_packetheader(NUTContext *nut, AVIOContext *bc,
125 int calculate_checksum, uint64_t startcode)
128 // start = avio_tell(bc) - 8;
130 startcode = av_be2ne64(startcode);
131 startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
133 ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
134 size = ffio_read_varlen(bc);
137 if (ffio_get_checksum(bc) && size > 4096)
140 ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
145 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
150 /* Note, this may fail if the stream is not seekable, but that should
151 * not matter, as in this case we simply start where we currently are */
152 avio_seek(bc, pos, SEEK_SET);
153 while (!avio_feof(bc)) {
154 state = (state << 8) | avio_r8(bc);
155 if ((state >> 56) != 'N')
159 case STREAM_STARTCODE:
160 case SYNCPOINT_STARTCODE:
162 case INDEX_STARTCODE:
171 * Find the given startcode.
172 * @param code the startcode
173 * @param pos the start position of the search, or -1 if the current position
174 * @return the position of the startcode or -1 if not found
176 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
179 uint64_t startcode = find_any_startcode(bc, pos);
180 if (startcode == code)
181 return avio_tell(bc) - 8;
182 else if (startcode == 0)
188 static int nut_probe(AVProbeData *p)
192 for (i = 0; i < p->buf_size-8; i++) {
193 if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
195 if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
196 return AVPROBE_SCORE_MAX;
201 #define GET_V(dst, check) \
203 tmp = ffio_read_varlen(bc); \
205 av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
206 ret = AVERROR_INVALIDDATA; \
212 static int skip_reserved(AVIOContext *bc, int64_t pos)
214 pos -= avio_tell(bc);
216 avio_seek(bc, pos, SEEK_CUR);
217 return AVERROR_INVALIDDATA;
221 return AVERROR_INVALIDDATA;
228 static int decode_main_header(NUTContext *nut)
230 AVFormatContext *s = nut->avf;
231 AVIOContext *bc = s->pb;
233 unsigned int stream_count;
234 int i, j, count, ret;
235 int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
237 end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
238 end += avio_tell(bc);
240 nut->version = ffio_read_varlen(bc);
241 if (nut->version < NUT_MIN_VERSION &&
242 nut->version > NUT_MAX_VERSION) {
243 av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
245 return AVERROR(ENOSYS);
247 if (nut->version > 3)
248 nut->minor_version = ffio_read_varlen(bc);
250 GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
252 nut->max_distance = ffio_read_varlen(bc);
253 if (nut->max_distance > 65536) {
254 av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
255 nut->max_distance = 65536;
258 GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
259 nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
261 return AVERROR(ENOMEM);
263 for (i = 0; i < nut->time_base_count; i++) {
264 GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
265 GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
266 if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
267 av_log(s, AV_LOG_ERROR, "time base invalid\n");
268 ret = AVERROR_INVALIDDATA;
276 for (i = 0; i < 256;) {
277 int tmp_flags = ffio_read_varlen(bc);
278 int tmp_fields = ffio_read_varlen(bc);
283 tmp_mul = ffio_read_varlen(bc);
285 tmp_stream = ffio_read_varlen(bc);
287 tmp_size = ffio_read_varlen(bc);
291 tmp_res = ffio_read_varlen(bc);
295 count = ffio_read_varlen(bc);
297 count = tmp_mul - tmp_size;
301 tmp_head_idx = ffio_read_varlen(bc);
303 while (tmp_fields-- > 8) {
304 if (bc->eof_reached) {
305 av_log(s, AV_LOG_ERROR, "reached EOF while decoding main header\n");
306 ret = AVERROR_INVALIDDATA;
309 ffio_read_varlen(bc);
312 if (count <= 0 || count > 256 - (i <= 'N') - i) {
313 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
314 ret = AVERROR_INVALIDDATA;
317 if (tmp_stream >= stream_count) {
318 av_log(s, AV_LOG_ERROR, "illegal stream number\n");
319 ret = AVERROR_INVALIDDATA;
323 for (j = 0; j < count; j++, i++) {
325 nut->frame_code[i].flags = FLAG_INVALID;
329 nut->frame_code[i].flags = tmp_flags;
330 nut->frame_code[i].pts_delta = tmp_pts;
331 nut->frame_code[i].stream_id = tmp_stream;
332 nut->frame_code[i].size_mul = tmp_mul;
333 nut->frame_code[i].size_lsb = tmp_size + j;
334 nut->frame_code[i].reserved_count = tmp_res;
335 nut->frame_code[i].header_idx = tmp_head_idx;
338 av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
340 if (end > avio_tell(bc) + 4) {
342 GET_V(nut->header_count, tmp < 128U);
344 for (i = 1; i < nut->header_count; i++) {
346 GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
347 rem -= nut->header_len[i];
349 av_log(s, AV_LOG_ERROR, "invalid elision header\n");
350 ret = AVERROR_INVALIDDATA;
353 hdr = av_malloc(nut->header_len[i]);
355 ret = AVERROR(ENOMEM);
358 avio_read(bc, hdr, nut->header_len[i]);
359 nut->header[i] = hdr;
361 av_assert0(nut->header_len[0] == 0);
364 // flags had been effectively introduced in version 4
365 if (nut->version > 3 && end > avio_tell(bc) + 4) {
366 nut->flags = ffio_read_varlen(bc);
369 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
370 av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
371 ret = AVERROR_INVALIDDATA;
375 nut->stream = av_calloc(stream_count, sizeof(StreamContext));
377 ret = AVERROR(ENOMEM);
380 for (i = 0; i < stream_count; i++)
381 avformat_new_stream(s, NULL);
385 av_freep(&nut->time_base);
386 for (i = 1; i < nut->header_count; i++) {
387 av_freep(&nut->header[i]);
389 nut->header_count = 0;
393 static int decode_stream_header(NUTContext *nut)
395 AVFormatContext *s = nut->avf;
396 AVIOContext *bc = s->pb;
398 int class, stream_id, ret;
402 end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
403 end += avio_tell(bc);
405 GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
406 stc = &nut->stream[stream_id];
407 st = s->streams[stream_id];
409 return AVERROR(ENOMEM);
411 class = ffio_read_varlen(bc);
412 tmp = get_fourcc(bc);
413 st->codec->codec_tag = tmp;
416 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
417 st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
420 ff_codec_movvideo_tags,
426 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
427 st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
430 ff_nut_audio_extra_tags,
436 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
437 st->codec->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
440 st->codec->codec_type = AVMEDIA_TYPE_DATA;
441 st->codec->codec_id = ff_codec_get_id(ff_nut_data_tags, tmp);
444 av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
445 return AVERROR(ENOSYS);
447 if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
448 av_log(s, AV_LOG_ERROR,
449 "Unknown codec tag '0x%04x' for stream number %d\n",
450 (unsigned int) tmp, stream_id);
452 GET_V(stc->time_base_id, tmp < nut->time_base_count);
453 GET_V(stc->msb_pts_shift, tmp < 16);
454 stc->max_pts_distance = ffio_read_varlen(bc);
455 GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
456 st->codec->has_b_frames = stc->decode_delay;
457 ffio_read_varlen(bc); // stream flags
459 GET_V(st->codec->extradata_size, tmp < (1 << 30));
460 if (st->codec->extradata_size) {
461 if (ff_get_extradata(st->codec, bc, st->codec->extradata_size) < 0)
462 return AVERROR(ENOMEM);
465 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
466 GET_V(st->codec->width, tmp > 0);
467 GET_V(st->codec->height, tmp > 0);
468 st->sample_aspect_ratio.num = ffio_read_varlen(bc);
469 st->sample_aspect_ratio.den = ffio_read_varlen(bc);
470 if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
471 av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
472 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
473 ret = AVERROR_INVALIDDATA;
476 ffio_read_varlen(bc); /* csp type */
477 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
478 GET_V(st->codec->sample_rate, tmp > 0);
479 ffio_read_varlen(bc); // samplerate_den
480 GET_V(st->codec->channels, tmp > 0);
482 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
483 av_log(s, AV_LOG_ERROR,
484 "stream header %d checksum mismatch\n", stream_id);
485 ret = AVERROR_INVALIDDATA;
488 stc->time_base = &nut->time_base[stc->time_base_id];
489 avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
490 stc->time_base->den);
493 if (st && st->codec) {
494 av_freep(&st->codec->extradata);
495 st->codec->extradata_size = 0;
500 static void set_disposition_bits(AVFormatContext *avf, char *value,
505 for (i = 0; ff_nut_dispositions[i].flag; ++i)
506 if (!strcmp(ff_nut_dispositions[i].str, value))
507 flag = ff_nut_dispositions[i].flag;
509 av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
510 for (i = 0; i < avf->nb_streams; ++i)
511 if (stream_id == i || stream_id == -1)
512 avf->streams[i]->disposition |= flag;
515 static int decode_info_header(NUTContext *nut)
517 AVFormatContext *s = nut->avf;
518 AVIOContext *bc = s->pb;
519 uint64_t tmp, chapter_start, chapter_len;
520 unsigned int stream_id_plus1, count;
521 int chapter_id, i, ret = 0;
523 char name[256], str_value[1024], type_str[256];
525 int *event_flags = NULL;
526 AVChapter *chapter = NULL;
528 AVDictionary **metadata = NULL;
529 int metadata_flag = 0;
531 end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
532 end += avio_tell(bc);
534 GET_V(stream_id_plus1, tmp <= s->nb_streams);
535 chapter_id = get_s(bc);
536 chapter_start = ffio_read_varlen(bc);
537 chapter_len = ffio_read_varlen(bc);
538 count = ffio_read_varlen(bc);
540 if (chapter_id && !stream_id_plus1) {
541 int64_t start = chapter_start / nut->time_base_count;
542 chapter = avpriv_new_chapter(s, chapter_id,
543 nut->time_base[chapter_start %
544 nut->time_base_count],
545 start, start + chapter_len, NULL);
547 av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
548 return AVERROR(ENOMEM);
550 metadata = &chapter->metadata;
551 } else if (stream_id_plus1) {
552 st = s->streams[stream_id_plus1 - 1];
553 metadata = &st->metadata;
554 event_flags = &st->event_flags;
555 metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
557 metadata = &s->metadata;
558 event_flags = &s->event_flags;
559 metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
562 for (i = 0; i < count; i++) {
563 ret = get_str(bc, name, sizeof(name));
565 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
573 ret = get_str(bc, str_value, sizeof(str_value));
574 } else if (value == -2) {
575 ret = get_str(bc, type_str, sizeof(type_str));
577 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
581 ret = get_str(bc, str_value, sizeof(str_value));
582 } else if (value == -3) {
585 } else if (value == -4) {
587 value = ffio_read_varlen(bc);
588 } else if (value < -4) {
596 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
600 if (stream_id_plus1 > s->nb_streams) {
601 av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
605 if (!strcmp(type, "UTF-8")) {
606 if (chapter_id == 0 && !strcmp(name, "Disposition")) {
607 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
611 if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
612 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
613 if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
614 st->r_frame_rate.num < 0 || st->r_frame_rate.num < 0)
615 st->r_frame_rate.num = st->r_frame_rate.den = 0;
619 if (metadata && av_strcasecmp(name, "Uses") &&
620 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
622 *event_flags |= metadata_flag;
623 av_dict_set(metadata, name, str_value, 0);
628 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
629 av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
630 return AVERROR_INVALIDDATA;
633 return FFMIN(ret, 0);
636 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
638 AVFormatContext *s = nut->avf;
639 AVIOContext *bc = s->pb;
644 nut->last_syncpoint_pos = avio_tell(bc) - 8;
646 end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
647 end += avio_tell(bc);
649 tmp = ffio_read_varlen(bc);
650 *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
652 return AVERROR_INVALIDDATA;
654 ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
655 tmp / nut->time_base_count);
657 if (nut->flags & NUT_BROADCAST) {
658 tmp = ffio_read_varlen(bc);
659 av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
660 av_rescale_q(tmp / nut->time_base_count,
661 nut->time_base[tmp % nut->time_base_count],
665 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
666 av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
667 return AVERROR_INVALIDDATA;
670 *ts = tmp / nut->time_base_count *
671 av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
673 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
679 //FIXME calculate exactly, this is just a good approximation.
680 static int64_t find_duration(NUTContext *nut, int64_t filesize)
682 AVFormatContext *s = nut->avf;
683 int64_t duration = 0;
685 ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
688 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
692 static int find_and_decode_index(NUTContext *nut)
694 AVFormatContext *s = nut->avf;
695 AVIOContext *bc = s->pb;
697 int i, j, syncpoint_count;
698 int64_t filesize = avio_size(bc);
699 int64_t *syncpoints = NULL;
701 int8_t *has_keyframe = NULL;
702 int ret = AVERROR_INVALIDDATA;
707 avio_seek(bc, filesize - 12, SEEK_SET);
708 avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
709 if (avio_rb64(bc) != INDEX_STARTCODE) {
710 av_log(s, AV_LOG_ERROR, "no index at the end\n");
713 s->duration = find_duration(nut, filesize);
717 end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
718 end += avio_tell(bc);
720 max_pts = ffio_read_varlen(bc);
721 s->duration = av_rescale_q(max_pts / nut->time_base_count,
722 nut->time_base[max_pts % nut->time_base_count],
724 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
726 GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
727 syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
728 has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
729 if (!syncpoints || !has_keyframe) {
730 ret = AVERROR(ENOMEM);
733 for (i = 0; i < syncpoint_count; i++) {
734 syncpoints[i] = ffio_read_varlen(bc);
735 if (syncpoints[i] <= 0)
738 syncpoints[i] += syncpoints[i - 1];
741 for (i = 0; i < s->nb_streams; i++) {
742 int64_t last_pts = -1;
743 for (j = 0; j < syncpoint_count;) {
744 uint64_t x = ffio_read_varlen(bc);
751 if (n + x >= syncpoint_count + 1) {
752 av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
756 has_keyframe[n++] = flag;
757 has_keyframe[n++] = !flag;
760 av_log(s, AV_LOG_ERROR, "index: x %"PRIu64" is invalid\n", x);
764 if (n >= syncpoint_count + 1) {
765 av_log(s, AV_LOG_ERROR, "index overflow B\n");
768 has_keyframe[n++] = x & 1;
772 if (has_keyframe[0]) {
773 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
776 av_assert0(n <= syncpoint_count + 1);
777 for (; j < n && j < syncpoint_count; j++) {
778 if (has_keyframe[j]) {
779 uint64_t B, A = ffio_read_varlen(bc);
781 A = ffio_read_varlen(bc);
782 B = ffio_read_varlen(bc);
783 // eor_pts[j][i] = last_pts + A + B
786 av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
787 last_pts + A, 0, 0, AVINDEX_KEYFRAME);
794 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
795 av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
802 av_free(has_keyframe);
806 static int nut_read_close(AVFormatContext *s)
808 NUTContext *nut = s->priv_data;
811 av_freep(&nut->time_base);
812 av_freep(&nut->stream);
814 for (i = 1; i < nut->header_count; i++)
815 av_freep(&nut->header[i]);
820 static int nut_read_header(AVFormatContext *s)
822 NUTContext *nut = s->priv_data;
823 AVIOContext *bc = s->pb;
825 int initialized_stream_count;
832 pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
834 av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
837 } while (decode_main_header(nut) < 0);
841 for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
842 pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
844 av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
847 if (decode_stream_header(nut) >= 0)
848 initialized_stream_count++;
854 uint64_t startcode = find_any_startcode(bc, pos);
857 if (startcode == 0) {
858 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
860 } else if (startcode == SYNCPOINT_STARTCODE) {
861 nut->next_startcode = startcode;
863 } else if (startcode != INFO_STARTCODE) {
867 decode_info_header(nut);
870 s->internal->data_offset = pos - 8;
873 int64_t orig_pos = avio_tell(bc);
874 find_and_decode_index(nut);
875 avio_seek(bc, orig_pos, SEEK_SET);
877 av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
879 ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
886 return AVERROR_INVALIDDATA;
889 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
891 int count = ffio_read_varlen(bc);
895 int64_t channel_layout = 0;
901 for (i=0; i<count; i++) {
902 uint8_t name[256], str_value[256], type_str[256];
904 if (avio_tell(bc) >= maxpos)
905 return AVERROR_INVALIDDATA;
906 ret = get_str(bc, name, sizeof(name));
908 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
914 ret = get_str(bc, str_value, sizeof(str_value));
916 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
919 av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
920 } else if (value == -2) {
922 int64_t v64, value_len;
924 ret = get_str(bc, type_str, sizeof(type_str));
926 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
929 value_len = ffio_read_varlen(bc);
930 if (avio_tell(bc) + value_len >= maxpos)
931 return AVERROR_INVALIDDATA;
932 if (!strcmp(name, "Palette")) {
933 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
934 } else if (!strcmp(name, "Extradata")) {
935 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
936 } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
937 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, value_len + 8);
939 return AVERROR(ENOMEM);
942 } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
943 channel_layout = avio_rl64(bc);
946 av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
947 avio_skip(bc, value_len);
951 return AVERROR(ENOMEM);
952 avio_read(bc, dst, value_len);
953 } else if (value == -3) {
955 } else if (value == -4) {
956 value = ffio_read_varlen(bc);
957 } else if (value < -4) {
960 if (!strcmp(name, "SkipStart")) {
962 } else if (!strcmp(name, "SkipEnd")) {
964 } else if (!strcmp(name, "Channels")) {
966 } else if (!strcmp(name, "SampleRate")) {
968 } else if (!strcmp(name, "Width")) {
970 } else if (!strcmp(name, "Height")) {
973 av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
978 if (channels || channel_layout || sample_rate || width || height) {
979 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, 28);
981 return AVERROR(ENOMEM);
982 bytestream_put_le32(&dst,
983 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT*(!!channels) +
984 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
985 AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
986 AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
989 bytestream_put_le32(&dst, channels);
991 bytestream_put_le64(&dst, channel_layout);
993 bytestream_put_le32(&dst, sample_rate);
994 if (width || height){
995 bytestream_put_le32(&dst, width);
996 bytestream_put_le32(&dst, height);
1000 if (skip_start || skip_end) {
1001 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
1003 return AVERROR(ENOMEM);
1004 AV_WL32(dst, skip_start);
1005 AV_WL32(dst+4, skip_end);
1011 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
1012 uint8_t *header_idx, int frame_code)
1014 AVFormatContext *s = nut->avf;
1015 AVIOContext *bc = s->pb;
1017 int size, flags, size_mul, pts_delta, i, reserved_count, ret;
1020 if (!(nut->flags & NUT_PIPE) &&
1021 avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
1022 av_log(s, AV_LOG_ERROR,
1023 "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
1024 avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
1025 return AVERROR_INVALIDDATA;
1028 flags = nut->frame_code[frame_code].flags;
1029 size_mul = nut->frame_code[frame_code].size_mul;
1030 size = nut->frame_code[frame_code].size_lsb;
1031 *stream_id = nut->frame_code[frame_code].stream_id;
1032 pts_delta = nut->frame_code[frame_code].pts_delta;
1033 reserved_count = nut->frame_code[frame_code].reserved_count;
1034 *header_idx = nut->frame_code[frame_code].header_idx;
1036 if (flags & FLAG_INVALID)
1037 return AVERROR_INVALIDDATA;
1038 if (flags & FLAG_CODED)
1039 flags ^= ffio_read_varlen(bc);
1040 if (flags & FLAG_STREAM_ID) {
1041 GET_V(*stream_id, tmp < s->nb_streams);
1043 stc = &nut->stream[*stream_id];
1044 if (flags & FLAG_CODED_PTS) {
1045 int coded_pts = ffio_read_varlen(bc);
1046 // FIXME check last_pts validity?
1047 if (coded_pts < (1 << stc->msb_pts_shift)) {
1048 *pts = ff_lsb2full(stc, coded_pts);
1050 *pts = coded_pts - (1LL << stc->msb_pts_shift);
1052 *pts = stc->last_pts + pts_delta;
1053 if (flags & FLAG_SIZE_MSB)
1054 size += size_mul * ffio_read_varlen(bc);
1055 if (flags & FLAG_MATCH_TIME)
1057 if (flags & FLAG_HEADER_IDX)
1058 *header_idx = ffio_read_varlen(bc);
1059 if (flags & FLAG_RESERVED)
1060 reserved_count = ffio_read_varlen(bc);
1061 for (i = 0; i < reserved_count; i++) {
1062 if (bc->eof_reached) {
1063 av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
1064 return AVERROR_INVALIDDATA;
1066 ffio_read_varlen(bc);
1069 if (*header_idx >= (unsigned)nut->header_count) {
1070 av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
1071 return AVERROR_INVALIDDATA;
1075 size -= nut->header_len[*header_idx];
1077 if (flags & FLAG_CHECKSUM) {
1078 avio_rb32(bc); // FIXME check this
1079 } else if (!(nut->flags & NUT_PIPE) &&
1080 size > 2 * nut->max_distance ||
1081 FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
1082 av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
1083 return AVERROR_INVALIDDATA;
1086 stc->last_pts = *pts;
1087 stc->last_flags = flags;
1094 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
1096 AVFormatContext *s = nut->avf;
1097 AVIOContext *bc = s->pb;
1098 int size, stream_id, discard, ret;
1099 int64_t pts, last_IP_pts;
1103 size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
1107 stc = &nut->stream[stream_id];
1109 if (stc->last_flags & FLAG_KEY)
1110 stc->skip_until_key_frame = 0;
1112 discard = s->streams[stream_id]->discard;
1113 last_IP_pts = s->streams[stream_id]->last_IP_pts;
1114 if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1115 (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1116 last_IP_pts > pts) ||
1117 discard >= AVDISCARD_ALL ||
1118 stc->skip_until_key_frame) {
1119 avio_skip(bc, size);
1123 ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
1126 memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1127 pkt->pos = avio_tell(bc); // FIXME
1128 if (stc->last_flags & FLAG_SM_DATA) {
1130 if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0) {
1131 ret = AVERROR_INVALIDDATA;
1134 if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0) {
1135 ret = AVERROR_INVALIDDATA;
1138 sm_size = avio_tell(bc) - pkt->pos;
1140 pkt->size -= sm_size;
1143 ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1148 av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1150 pkt->stream_index = stream_id;
1151 if (stc->last_flags & FLAG_KEY)
1152 pkt->flags |= AV_PKT_FLAG_KEY;
1157 av_free_packet(pkt);
1161 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1163 NUTContext *nut = s->priv_data;
1164 AVIOContext *bc = s->pb;
1165 int i, frame_code = 0, ret, skip;
1166 int64_t ts, back_ptr;
1169 int64_t pos = avio_tell(bc);
1170 uint64_t tmp = nut->next_startcode;
1171 nut->next_startcode = 0;
1176 frame_code = avio_r8(bc);
1179 if (frame_code == 'N') {
1181 for (i = 1; i < 8; i++)
1182 tmp = (tmp << 8) + avio_r8(bc);
1186 case MAIN_STARTCODE:
1187 case STREAM_STARTCODE:
1188 case INDEX_STARTCODE:
1189 skip = get_packetheader(nut, bc, 0, tmp);
1190 avio_skip(bc, skip);
1192 case INFO_STARTCODE:
1193 if (decode_info_header(nut) < 0)
1196 case SYNCPOINT_STARTCODE:
1197 if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1199 frame_code = avio_r8(bc);
1201 ret = decode_frame(nut, pkt, frame_code);
1204 else if (ret == 1) // OK but discard packet
1208 av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1209 tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
1210 nut->last_resync_pos = avio_tell(bc);
1212 return AVERROR_INVALIDDATA;
1213 av_log(s, AV_LOG_DEBUG, "sync\n");
1214 nut->next_startcode = tmp;
1219 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1220 int64_t *pos_arg, int64_t pos_limit)
1222 NUTContext *nut = s->priv_data;
1223 AVIOContext *bc = s->pb;
1224 int64_t pos, pts, back_ptr;
1225 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1226 stream_index, *pos_arg, pos_limit);
1230 pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1232 av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1233 return AV_NOPTS_VALUE;
1235 } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1237 av_assert0(nut->last_syncpoint_pos == *pos_arg);
1239 av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1240 if (stream_index == -2)
1242 av_assert0(stream_index == -1);
1246 static int read_seek(AVFormatContext *s, int stream_index,
1247 int64_t pts, int flags)
1249 NUTContext *nut = s->priv_data;
1250 AVStream *st = s->streams[stream_index];
1251 Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1252 Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1253 Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1254 int64_t pos, pos2, ts;
1257 if (nut->flags & NUT_PIPE) {
1258 return AVERROR(ENOSYS);
1261 if (st->index_entries) {
1262 int index = av_index_search_timestamp(st, pts, flags);
1264 index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1268 pos2 = st->index_entries[index].pos;
1269 ts = st->index_entries[index].timestamp;
1271 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
1272 (void **) next_node);
1273 av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1274 next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1276 pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1277 next_node[1]->pos, next_node[1]->pos,
1278 next_node[0]->ts, next_node[1]->ts,
1279 AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
1281 if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1282 dummy.pos = pos + 16;
1283 next_node[1] = &nopts_sp;
1284 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1285 (void **) next_node);
1286 pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1287 next_node[1]->pos, next_node[1]->pos,
1288 next_node[0]->back_ptr, next_node[1]->back_ptr,
1289 flags, &ts, nut_read_timestamp);
1292 // FIXME dir but I think it does not matter
1295 sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1299 pos2 = sp->back_ptr - 15;
1301 av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1302 pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1303 avio_seek(s->pb, pos, SEEK_SET);
1304 nut->last_syncpoint_pos = pos;
1305 av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1306 if (pos2 > pos || pos2 + 15 < pos)
1307 av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1308 for (i = 0; i < s->nb_streams; i++)
1309 nut->stream[i].skip_until_key_frame = 1;
1311 nut->last_resync_pos = 0;
1316 AVInputFormat ff_nut_demuxer = {
1318 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1319 .flags = AVFMT_SEEK_TO_PTS,
1320 .priv_data_size = sizeof(NUTContext),
1321 .read_probe = nut_probe,
1322 .read_header = nut_read_header,
1323 .read_packet = nut_read_packet,
1324 .read_close = nut_read_close,
1325 .read_seek = read_seek,
1326 .extensions = "nut",
1327 .codec_tag = ff_nut_codec_tags,