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);
89 static int get_packetheader(NUTContext *nut, AVIOContext *bc,
90 int calculate_checksum, uint64_t startcode)
94 startcode = av_be2ne64(startcode);
95 startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
97 ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
98 size = ffio_read_varlen(bc);
101 if (ffio_get_checksum(bc) && size > 4096)
104 ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
109 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
114 /* Note, this may fail if the stream is not seekable, but that should
115 * not matter, as in this case we simply start where we currently are */
116 avio_seek(bc, pos, SEEK_SET);
117 while (!avio_feof(bc)) {
118 state = (state << 8) | avio_r8(bc);
119 if ((state >> 56) != 'N')
123 case STREAM_STARTCODE:
124 case SYNCPOINT_STARTCODE:
126 case INDEX_STARTCODE:
135 * Find the given startcode.
136 * @param code the startcode
137 * @param pos the start position of the search, or -1 if the current position
138 * @return the position of the startcode or -1 if not found
140 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
143 uint64_t startcode = find_any_startcode(bc, pos);
144 if (startcode == code)
145 return avio_tell(bc) - 8;
146 else if (startcode == 0)
152 static int nut_probe(AVProbeData *p)
156 for (i = 0; i < p->buf_size-8; i++) {
157 if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
159 if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
160 return AVPROBE_SCORE_MAX;
165 #define GET_V(dst, check) \
167 tmp = ffio_read_varlen(bc); \
169 av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
170 ret = AVERROR_INVALIDDATA; \
176 static int skip_reserved(AVIOContext *bc, int64_t pos)
178 pos -= avio_tell(bc);
180 avio_seek(bc, pos, SEEK_CUR);
181 return AVERROR_INVALIDDATA;
185 return AVERROR_INVALIDDATA;
192 static int decode_main_header(NUTContext *nut)
194 AVFormatContext *s = nut->avf;
195 AVIOContext *bc = s->pb;
197 unsigned int stream_count;
198 int i, j, count, ret;
199 int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
201 end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
202 end += avio_tell(bc);
204 nut->version = ffio_read_varlen(bc);
205 if (nut->version < NUT_MIN_VERSION ||
206 nut->version > NUT_MAX_VERSION) {
207 av_log(s, AV_LOG_ERROR, "Version %d not supported.\n",
209 return AVERROR(ENOSYS);
211 if (nut->version > 3)
212 nut->minor_version = ffio_read_varlen(bc);
214 GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
216 nut->max_distance = ffio_read_varlen(bc);
217 if (nut->max_distance > 65536) {
218 av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
219 nut->max_distance = 65536;
222 GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
223 nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
225 return AVERROR(ENOMEM);
227 for (i = 0; i < nut->time_base_count; i++) {
228 GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
229 GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
230 if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
231 av_log(s, AV_LOG_ERROR, "invalid time base %d/%d\n",
232 nut->time_base[i].num,
233 nut->time_base[i].den);
234 ret = AVERROR_INVALIDDATA;
242 for (i = 0; i < 256;) {
243 int tmp_flags = ffio_read_varlen(bc);
244 int tmp_fields = ffio_read_varlen(bc);
249 tmp_mul = ffio_read_varlen(bc);
251 tmp_stream = ffio_read_varlen(bc);
253 tmp_size = ffio_read_varlen(bc);
257 tmp_res = ffio_read_varlen(bc);
261 count = ffio_read_varlen(bc);
263 count = tmp_mul - tmp_size;
267 tmp_head_idx = ffio_read_varlen(bc);
269 while (tmp_fields-- > 8) {
270 if (bc->eof_reached) {
271 av_log(s, AV_LOG_ERROR, "reached EOF while decoding main header\n");
272 ret = AVERROR_INVALIDDATA;
275 ffio_read_varlen(bc);
278 if (count <= 0 || count > 256 - (i <= 'N') - i) {
279 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
280 ret = AVERROR_INVALIDDATA;
283 if (tmp_stream >= stream_count) {
284 av_log(s, AV_LOG_ERROR, "illegal stream number %d >= %d\n",
285 tmp_stream, stream_count);
286 ret = AVERROR_INVALIDDATA;
290 for (j = 0; j < count; j++, i++) {
292 nut->frame_code[i].flags = FLAG_INVALID;
296 nut->frame_code[i].flags = tmp_flags;
297 nut->frame_code[i].pts_delta = tmp_pts;
298 nut->frame_code[i].stream_id = tmp_stream;
299 nut->frame_code[i].size_mul = tmp_mul;
300 nut->frame_code[i].size_lsb = tmp_size + j;
301 nut->frame_code[i].reserved_count = tmp_res;
302 nut->frame_code[i].header_idx = tmp_head_idx;
305 av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
307 if (end > avio_tell(bc) + 4) {
309 GET_V(nut->header_count, tmp < 128U);
311 for (i = 1; i < nut->header_count; i++) {
313 GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
314 if (rem < nut->header_len[i]) {
315 av_log(s, AV_LOG_ERROR,
316 "invalid elision header %d : %d > %d\n",
317 i, nut->header_len[i], rem);
318 ret = AVERROR_INVALIDDATA;
321 rem -= nut->header_len[i];
322 hdr = av_malloc(nut->header_len[i]);
324 ret = AVERROR(ENOMEM);
327 avio_read(bc, hdr, nut->header_len[i]);
328 nut->header[i] = hdr;
330 av_assert0(nut->header_len[0] == 0);
333 // flags had been effectively introduced in version 4
334 if (nut->version > 3 && end > avio_tell(bc) + 4) {
335 nut->flags = ffio_read_varlen(bc);
338 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
339 av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
340 ret = AVERROR_INVALIDDATA;
344 nut->stream = av_calloc(stream_count, sizeof(StreamContext));
346 ret = AVERROR(ENOMEM);
349 for (i = 0; i < stream_count; i++)
350 avformat_new_stream(s, NULL);
354 av_freep(&nut->time_base);
355 for (i = 1; i < nut->header_count; i++) {
356 av_freep(&nut->header[i]);
358 nut->header_count = 0;
362 static int decode_stream_header(NUTContext *nut)
364 AVFormatContext *s = nut->avf;
365 AVIOContext *bc = s->pb;
367 int class, stream_id, ret;
371 end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
372 end += avio_tell(bc);
374 GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
375 stc = &nut->stream[stream_id];
376 st = s->streams[stream_id];
378 return AVERROR(ENOMEM);
380 class = ffio_read_varlen(bc);
381 tmp = get_fourcc(bc);
382 st->codecpar->codec_tag = tmp;
385 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
386 st->codecpar->codec_id = av_codec_get_id((const AVCodecTag * const []) {
389 ff_codec_movvideo_tags,
395 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
396 st->codecpar->codec_id = av_codec_get_id((const AVCodecTag * const []) {
399 ff_nut_audio_extra_tags,
405 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
406 st->codecpar->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
409 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
410 st->codecpar->codec_id = ff_codec_get_id(ff_nut_data_tags, tmp);
413 av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
414 return AVERROR(ENOSYS);
416 if (class < 3 && st->codecpar->codec_id == AV_CODEC_ID_NONE)
417 av_log(s, AV_LOG_ERROR,
418 "Unknown codec tag '0x%04x' for stream number %d\n",
419 (unsigned int) tmp, stream_id);
421 GET_V(stc->time_base_id, tmp < nut->time_base_count);
422 GET_V(stc->msb_pts_shift, tmp < 16);
423 stc->max_pts_distance = ffio_read_varlen(bc);
424 GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
425 st->codecpar->video_delay = stc->decode_delay;
426 ffio_read_varlen(bc); // stream flags
428 GET_V(st->codecpar->extradata_size, tmp < (1 << 30));
429 if (st->codecpar->extradata_size) {
430 if (ff_get_extradata(s, st->codecpar, bc, st->codecpar->extradata_size) < 0)
431 return AVERROR(ENOMEM);
434 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
435 GET_V(st->codecpar->width, tmp > 0);
436 GET_V(st->codecpar->height, tmp > 0);
437 st->sample_aspect_ratio.num = ffio_read_varlen(bc);
438 st->sample_aspect_ratio.den = ffio_read_varlen(bc);
439 if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
440 av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
441 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
442 ret = AVERROR_INVALIDDATA;
445 ffio_read_varlen(bc); /* csp type */
446 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
447 GET_V(st->codecpar->sample_rate, tmp > 0);
448 ffio_read_varlen(bc); // samplerate_den
449 GET_V(st->codecpar->channels, tmp > 0);
451 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
452 av_log(s, AV_LOG_ERROR,
453 "stream header %d checksum mismatch\n", stream_id);
454 ret = AVERROR_INVALIDDATA;
457 stc->time_base = &nut->time_base[stc->time_base_id];
458 avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
459 stc->time_base->den);
462 if (st && st->codecpar) {
463 av_freep(&st->codecpar->extradata);
464 st->codecpar->extradata_size = 0;
469 static void set_disposition_bits(AVFormatContext *avf, char *value,
474 for (i = 0; ff_nut_dispositions[i].flag; ++i)
475 if (!strcmp(ff_nut_dispositions[i].str, value))
476 flag = ff_nut_dispositions[i].flag;
478 av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
479 for (i = 0; i < avf->nb_streams; ++i)
480 if (stream_id == i || stream_id == -1)
481 avf->streams[i]->disposition |= flag;
484 static int decode_info_header(NUTContext *nut)
486 AVFormatContext *s = nut->avf;
487 AVIOContext *bc = s->pb;
488 uint64_t tmp, chapter_start, chapter_len;
489 unsigned int stream_id_plus1, count;
490 int chapter_id, i, ret = 0;
492 char name[256], str_value[1024], type_str[256];
494 int *event_flags = NULL;
495 AVChapter *chapter = NULL;
497 AVDictionary **metadata = NULL;
498 int metadata_flag = 0;
500 end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
501 end += avio_tell(bc);
503 GET_V(stream_id_plus1, tmp <= s->nb_streams);
504 chapter_id = get_s(bc);
505 chapter_start = ffio_read_varlen(bc);
506 chapter_len = ffio_read_varlen(bc);
507 count = ffio_read_varlen(bc);
509 if (chapter_id && !stream_id_plus1) {
510 int64_t start = chapter_start / nut->time_base_count;
511 chapter = avpriv_new_chapter(s, chapter_id,
512 nut->time_base[chapter_start %
513 nut->time_base_count],
514 start, start + chapter_len, NULL);
516 av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
517 return AVERROR(ENOMEM);
519 metadata = &chapter->metadata;
520 } else if (stream_id_plus1) {
521 st = s->streams[stream_id_plus1 - 1];
522 metadata = &st->metadata;
523 event_flags = &st->event_flags;
524 metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
526 metadata = &s->metadata;
527 event_flags = &s->event_flags;
528 metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
531 for (i = 0; i < count; i++) {
532 ret = get_str(bc, name, sizeof(name));
534 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
542 ret = get_str(bc, str_value, sizeof(str_value));
543 } else if (value == -2) {
544 ret = get_str(bc, type_str, sizeof(type_str));
546 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
550 ret = get_str(bc, str_value, sizeof(str_value));
551 } else if (value == -3) {
554 } else if (value == -4) {
556 value = ffio_read_varlen(bc);
557 } else if (value < -4) {
565 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
569 if (stream_id_plus1 > s->nb_streams) {
570 av_log(s, AV_LOG_WARNING,
571 "invalid stream id %d for info packet\n",
576 if (!strcmp(type, "UTF-8")) {
577 if (chapter_id == 0 && !strcmp(name, "Disposition")) {
578 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
582 if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
583 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
584 if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
585 st->r_frame_rate.num < 0 || st->r_frame_rate.num < 0)
586 st->r_frame_rate.num = st->r_frame_rate.den = 0;
590 if (metadata && av_strcasecmp(name, "Uses") &&
591 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
593 *event_flags |= metadata_flag;
594 av_dict_set(metadata, name, str_value, 0);
599 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
600 av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
601 return AVERROR_INVALIDDATA;
604 return FFMIN(ret, 0);
607 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
609 AVFormatContext *s = nut->avf;
610 AVIOContext *bc = s->pb;
615 nut->last_syncpoint_pos = avio_tell(bc) - 8;
617 end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
618 end += avio_tell(bc);
620 tmp = ffio_read_varlen(bc);
621 *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
623 return AVERROR_INVALIDDATA;
625 ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
626 tmp / nut->time_base_count);
628 if (nut->flags & NUT_BROADCAST) {
629 tmp = ffio_read_varlen(bc);
630 av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
631 av_rescale_q(tmp / nut->time_base_count,
632 nut->time_base[tmp % nut->time_base_count],
636 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
637 av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
638 return AVERROR_INVALIDDATA;
641 *ts = tmp / nut->time_base_count *
642 av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
644 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
650 //FIXME calculate exactly, this is just a good approximation.
651 static int64_t find_duration(NUTContext *nut, int64_t filesize)
653 AVFormatContext *s = nut->avf;
654 int64_t duration = 0;
656 ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
659 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
663 static int find_and_decode_index(NUTContext *nut)
665 AVFormatContext *s = nut->avf;
666 AVIOContext *bc = s->pb;
668 int i, j, syncpoint_count;
669 int64_t filesize = avio_size(bc);
670 int64_t *syncpoints = NULL;
672 int8_t *has_keyframe = NULL;
673 int ret = AVERROR_INVALIDDATA;
678 avio_seek(bc, filesize - 12, SEEK_SET);
679 avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
680 if (avio_rb64(bc) != INDEX_STARTCODE) {
681 av_log(s, AV_LOG_WARNING, "no index at the end\n");
684 s->duration = find_duration(nut, filesize);
688 end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
689 end += avio_tell(bc);
691 max_pts = ffio_read_varlen(bc);
692 s->duration = av_rescale_q(max_pts / nut->time_base_count,
693 nut->time_base[max_pts % nut->time_base_count],
695 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
697 GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
698 syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
699 has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
700 if (!syncpoints || !has_keyframe) {
701 ret = AVERROR(ENOMEM);
704 for (i = 0; i < syncpoint_count; i++) {
705 syncpoints[i] = ffio_read_varlen(bc);
706 if (syncpoints[i] <= 0)
709 syncpoints[i] += syncpoints[i - 1];
712 for (i = 0; i < s->nb_streams; i++) {
713 int64_t last_pts = -1;
714 for (j = 0; j < syncpoint_count;) {
715 uint64_t x = ffio_read_varlen(bc);
722 if (n + x >= syncpoint_count + 1) {
723 av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
727 has_keyframe[n++] = flag;
728 has_keyframe[n++] = !flag;
731 av_log(s, AV_LOG_ERROR, "index: x %"PRIu64" is invalid\n", x);
735 if (n >= syncpoint_count + 1) {
736 av_log(s, AV_LOG_ERROR, "index overflow B\n");
739 has_keyframe[n++] = x & 1;
743 if (has_keyframe[0]) {
744 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
747 av_assert0(n <= syncpoint_count + 1);
748 for (; j < n && j < syncpoint_count; j++) {
749 if (has_keyframe[j]) {
750 uint64_t B, A = ffio_read_varlen(bc);
752 A = ffio_read_varlen(bc);
753 B = ffio_read_varlen(bc);
754 // eor_pts[j][i] = last_pts + A + B
757 av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
758 last_pts + A, 0, 0, AVINDEX_KEYFRAME);
765 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
766 av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
773 av_free(has_keyframe);
777 static int nut_read_close(AVFormatContext *s)
779 NUTContext *nut = s->priv_data;
782 av_freep(&nut->time_base);
783 av_freep(&nut->stream);
785 for (i = 1; i < nut->header_count; i++)
786 av_freep(&nut->header[i]);
791 static int nut_read_header(AVFormatContext *s)
793 NUTContext *nut = s->priv_data;
794 AVIOContext *bc = s->pb;
796 int initialized_stream_count;
803 pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
805 av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
808 } while (decode_main_header(nut) < 0);
812 for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
813 pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
815 av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
818 if (decode_stream_header(nut) >= 0)
819 initialized_stream_count++;
825 uint64_t startcode = find_any_startcode(bc, pos);
828 if (startcode == 0) {
829 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
831 } else if (startcode == SYNCPOINT_STARTCODE) {
832 nut->next_startcode = startcode;
834 } else if (startcode != INFO_STARTCODE) {
838 decode_info_header(nut);
841 s->internal->data_offset = pos - 8;
843 if (bc->seekable & AVIO_SEEKABLE_NORMAL) {
844 int64_t orig_pos = avio_tell(bc);
845 find_and_decode_index(nut);
846 avio_seek(bc, orig_pos, SEEK_SET);
848 av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
850 ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
857 return AVERROR_INVALIDDATA;
860 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
862 int count = ffio_read_varlen(bc);
866 int64_t channel_layout = 0;
872 for (i=0; i<count; i++) {
873 uint8_t name[256], str_value[256], type_str[256];
875 if (avio_tell(bc) >= maxpos)
876 return AVERROR_INVALIDDATA;
877 ret = get_str(bc, name, sizeof(name));
879 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
885 ret = get_str(bc, str_value, sizeof(str_value));
887 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
890 av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
891 } else if (value == -2) {
893 int64_t v64, value_len;
895 ret = get_str(bc, type_str, sizeof(type_str));
897 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
900 value_len = ffio_read_varlen(bc);
901 if (value_len < 0 || value_len >= maxpos - avio_tell(bc))
902 return AVERROR_INVALIDDATA;
903 if (!strcmp(name, "Palette")) {
904 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
905 } else if (!strcmp(name, "Extradata")) {
906 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
907 } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
908 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, value_len + 8);
910 return AVERROR(ENOMEM);
913 } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
914 channel_layout = avio_rl64(bc);
917 av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
918 avio_skip(bc, value_len);
922 return AVERROR(ENOMEM);
923 avio_read(bc, dst, value_len);
924 } else if (value == -3) {
926 } else if (value == -4) {
927 value = ffio_read_varlen(bc);
928 } else if (value < -4) {
931 if (!strcmp(name, "SkipStart")) {
933 } else if (!strcmp(name, "SkipEnd")) {
935 } else if (!strcmp(name, "Channels")) {
937 } else if (!strcmp(name, "SampleRate")) {
939 } else if (!strcmp(name, "Width")) {
941 } else if (!strcmp(name, "Height")) {
944 av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
949 if (channels || channel_layout || sample_rate || width || height) {
950 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, 28);
952 return AVERROR(ENOMEM);
953 bytestream_put_le32(&dst,
954 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT*(!!channels) +
955 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
956 AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
957 AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
960 bytestream_put_le32(&dst, channels);
962 bytestream_put_le64(&dst, channel_layout);
964 bytestream_put_le32(&dst, sample_rate);
965 if (width || height){
966 bytestream_put_le32(&dst, width);
967 bytestream_put_le32(&dst, height);
971 if (skip_start || skip_end) {
972 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
974 return AVERROR(ENOMEM);
975 AV_WL32(dst, skip_start);
976 AV_WL32(dst+4, skip_end);
979 if (avio_tell(bc) >= maxpos)
980 return AVERROR_INVALIDDATA;
985 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
986 uint8_t *header_idx, int frame_code)
988 AVFormatContext *s = nut->avf;
989 AVIOContext *bc = s->pb;
991 int size, flags, size_mul, pts_delta, i, reserved_count, ret;
994 if (!(nut->flags & NUT_PIPE) &&
995 avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
996 av_log(s, AV_LOG_ERROR,
997 "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
998 avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
999 return AVERROR_INVALIDDATA;
1002 flags = nut->frame_code[frame_code].flags;
1003 size_mul = nut->frame_code[frame_code].size_mul;
1004 size = nut->frame_code[frame_code].size_lsb;
1005 *stream_id = nut->frame_code[frame_code].stream_id;
1006 pts_delta = nut->frame_code[frame_code].pts_delta;
1007 reserved_count = nut->frame_code[frame_code].reserved_count;
1008 *header_idx = nut->frame_code[frame_code].header_idx;
1010 if (flags & FLAG_INVALID)
1011 return AVERROR_INVALIDDATA;
1012 if (flags & FLAG_CODED)
1013 flags ^= ffio_read_varlen(bc);
1014 if (flags & FLAG_STREAM_ID) {
1015 GET_V(*stream_id, tmp < s->nb_streams);
1017 stc = &nut->stream[*stream_id];
1018 if (flags & FLAG_CODED_PTS) {
1019 int coded_pts = ffio_read_varlen(bc);
1020 // FIXME check last_pts validity?
1021 if (coded_pts < (1 << stc->msb_pts_shift)) {
1022 *pts = ff_lsb2full(stc, coded_pts);
1024 *pts = coded_pts - (1LL << stc->msb_pts_shift);
1026 *pts = stc->last_pts + pts_delta;
1027 if (flags & FLAG_SIZE_MSB)
1028 size += size_mul * ffio_read_varlen(bc);
1029 if (flags & FLAG_MATCH_TIME)
1031 if (flags & FLAG_HEADER_IDX)
1032 *header_idx = ffio_read_varlen(bc);
1033 if (flags & FLAG_RESERVED)
1034 reserved_count = ffio_read_varlen(bc);
1035 for (i = 0; i < reserved_count; i++) {
1036 if (bc->eof_reached) {
1037 av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
1038 return AVERROR_INVALIDDATA;
1040 ffio_read_varlen(bc);
1043 if (*header_idx >= (unsigned)nut->header_count) {
1044 av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
1045 return AVERROR_INVALIDDATA;
1049 size -= nut->header_len[*header_idx];
1051 if (flags & FLAG_CHECKSUM) {
1052 avio_rb32(bc); // FIXME check this
1053 } else if (!(nut->flags & NUT_PIPE) &&
1054 size > 2 * nut->max_distance ||
1055 FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
1056 av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
1057 return AVERROR_INVALIDDATA;
1060 stc->last_pts = *pts;
1061 stc->last_flags = flags;
1068 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
1070 AVFormatContext *s = nut->avf;
1071 AVIOContext *bc = s->pb;
1072 int size, stream_id, discard, ret;
1073 int64_t pts, last_IP_pts;
1077 size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
1081 stc = &nut->stream[stream_id];
1083 if (stc->last_flags & FLAG_KEY)
1084 stc->skip_until_key_frame = 0;
1086 discard = s->streams[stream_id]->discard;
1087 last_IP_pts = s->streams[stream_id]->last_IP_pts;
1088 if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1089 (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1090 last_IP_pts > pts) ||
1091 discard >= AVDISCARD_ALL ||
1092 stc->skip_until_key_frame) {
1093 avio_skip(bc, size);
1097 ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
1100 if (nut->header[header_idx])
1101 memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1102 pkt->pos = avio_tell(bc); // FIXME
1103 if (stc->last_flags & FLAG_SM_DATA) {
1105 if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0) {
1106 ret = AVERROR_INVALIDDATA;
1109 if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0) {
1110 ret = AVERROR_INVALIDDATA;
1113 sm_size = avio_tell(bc) - pkt->pos;
1115 pkt->size -= sm_size;
1118 ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1123 av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1125 pkt->stream_index = stream_id;
1126 if (stc->last_flags & FLAG_KEY)
1127 pkt->flags |= AV_PKT_FLAG_KEY;
1132 av_packet_unref(pkt);
1136 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1138 NUTContext *nut = s->priv_data;
1139 AVIOContext *bc = s->pb;
1140 int i, frame_code = 0, ret, skip;
1141 int64_t ts, back_ptr;
1144 int64_t pos = avio_tell(bc);
1145 uint64_t tmp = nut->next_startcode;
1146 nut->next_startcode = 0;
1151 frame_code = avio_r8(bc);
1154 if (frame_code == 'N') {
1156 for (i = 1; i < 8; i++)
1157 tmp = (tmp << 8) + avio_r8(bc);
1161 case MAIN_STARTCODE:
1162 case STREAM_STARTCODE:
1163 case INDEX_STARTCODE:
1164 skip = get_packetheader(nut, bc, 0, tmp);
1165 avio_skip(bc, skip);
1167 case INFO_STARTCODE:
1168 if (decode_info_header(nut) < 0)
1171 case SYNCPOINT_STARTCODE:
1172 if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1174 frame_code = avio_r8(bc);
1176 ret = decode_frame(nut, pkt, frame_code);
1179 else if (ret == 1) // OK but discard packet
1183 av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1184 tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
1185 nut->last_resync_pos = avio_tell(bc);
1187 return AVERROR_INVALIDDATA;
1188 av_log(s, AV_LOG_DEBUG, "sync\n");
1189 nut->next_startcode = tmp;
1194 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1195 int64_t *pos_arg, int64_t pos_limit)
1197 NUTContext *nut = s->priv_data;
1198 AVIOContext *bc = s->pb;
1199 int64_t pos, pts, back_ptr;
1200 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1201 stream_index, *pos_arg, pos_limit);
1205 pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1207 av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1208 return AV_NOPTS_VALUE;
1210 } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1212 av_assert0(nut->last_syncpoint_pos == *pos_arg);
1214 av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1215 if (stream_index == -2)
1217 av_assert0(stream_index == -1);
1221 static int read_seek(AVFormatContext *s, int stream_index,
1222 int64_t pts, int flags)
1224 NUTContext *nut = s->priv_data;
1225 AVStream *st = s->streams[stream_index];
1226 Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1227 Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1228 Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1229 int64_t pos, pos2, ts;
1232 if (nut->flags & NUT_PIPE) {
1233 return AVERROR(ENOSYS);
1236 if (st->index_entries) {
1237 int index = av_index_search_timestamp(st, pts, flags);
1239 index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1243 pos2 = st->index_entries[index].pos;
1244 ts = st->index_entries[index].timestamp;
1246 av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pts_cmp,
1247 (void **) next_node);
1248 av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1249 next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1251 pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1252 next_node[1]->pos, next_node[1]->pos,
1253 next_node[0]->ts, next_node[1]->ts,
1254 AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
1258 if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1259 dummy.pos = pos + 16;
1260 next_node[1] = &nopts_sp;
1261 av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
1262 (void **) next_node);
1263 pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1264 next_node[1]->pos, next_node[1]->pos,
1265 next_node[0]->back_ptr, next_node[1]->back_ptr,
1266 flags, &ts, nut_read_timestamp);
1269 // FIXME dir but I think it does not matter
1272 sp = av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
1276 pos2 = sp->back_ptr - 15;
1278 av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1279 pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1280 avio_seek(s->pb, pos, SEEK_SET);
1281 nut->last_syncpoint_pos = pos;
1282 av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1283 if (pos2 > pos || pos2 + 15 < pos)
1284 av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1285 for (i = 0; i < s->nb_streams; i++)
1286 nut->stream[i].skip_until_key_frame = 1;
1288 nut->last_resync_pos = 0;
1293 AVInputFormat ff_nut_demuxer = {
1295 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1296 .flags = AVFMT_SEEK_TO_PTS,
1297 .priv_data_size = sizeof(NUTContext),
1298 .read_probe = nut_probe,
1299 .read_header = nut_read_header,
1300 .read_packet = nut_read_packet,
1301 .read_close = nut_read_close,
1302 .read_seek = read_seek,
1303 .extensions = "nut",
1304 .codec_tag = ff_nut_codec_tags,