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/mathematics.h"
28 #include "libavutil/tree.h"
29 #include "avio_internal.h"
32 #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
34 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
35 int64_t *pos_arg, int64_t pos_limit);
37 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
39 unsigned int len = ffio_read_varlen(bc);
42 avio_read(bc, string, FFMIN(len, maxlen));
43 while (len > maxlen) {
49 string[FFMIN(len, maxlen - 1)] = 0;
57 static int64_t get_s(AVIOContext *bc)
59 int64_t v = ffio_read_varlen(bc) + 1;
67 static uint64_t get_fourcc(AVIOContext *bc)
69 unsigned int len = ffio_read_varlen(bc);
80 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
81 const char *func, int line)
83 uint64_t v = ffio_read_varlen(bc);
85 av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
86 v, v, file, func, line);
90 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
91 const char *func, int line)
93 int64_t v = get_s(bc);
95 av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
96 v, v, file, func, line);
100 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
101 char *func, int line)
103 uint64_t v = get_fourcc(bc);
105 av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
106 v, v, file, func, line);
109 #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
110 #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
111 #define get_fourcc(bc) get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
114 static int get_packetheader(NUTContext *nut, AVIOContext *bc,
115 int calculate_checksum, uint64_t startcode)
118 // start = avio_tell(bc) - 8;
120 startcode = av_be2ne64(startcode);
121 startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
123 ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
124 size = ffio_read_varlen(bc);
127 if (ffio_get_checksum(bc) && size > 4096)
130 ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
135 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
140 /* Note, this may fail if the stream is not seekable, but that should
141 * not matter, as in this case we simply start where we currently are */
142 avio_seek(bc, pos, SEEK_SET);
143 while (!url_feof(bc)) {
144 state = (state << 8) | avio_r8(bc);
145 if ((state >> 56) != 'N')
149 case STREAM_STARTCODE:
150 case SYNCPOINT_STARTCODE:
152 case INDEX_STARTCODE:
161 * Find the given startcode.
162 * @param code the startcode
163 * @param pos the start position of the search, or -1 if the current position
164 * @return the position of the startcode or -1 if not found
166 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
169 uint64_t startcode = find_any_startcode(bc, pos);
170 if (startcode == code)
171 return avio_tell(bc) - 8;
172 else if (startcode == 0)
178 static int nut_probe(AVProbeData *p)
183 for (i = 0; i < p->buf_size; i++) {
184 code = (code << 8) | p->buf[i];
185 if (code == MAIN_STARTCODE)
186 return AVPROBE_SCORE_MAX;
191 #define GET_V(dst, check) \
193 tmp = ffio_read_varlen(bc); \
195 av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
201 static int skip_reserved(AVIOContext *bc, int64_t pos)
203 pos -= avio_tell(bc);
205 avio_seek(bc, pos, SEEK_CUR);
214 static int decode_main_header(NUTContext *nut)
216 AVFormatContext *s = nut->avf;
217 AVIOContext *bc = s->pb;
219 unsigned int stream_count;
221 int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
223 end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
224 end += avio_tell(bc);
226 GET_V(tmp, tmp >= 2 && tmp <= 3);
227 GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
229 nut->max_distance = ffio_read_varlen(bc);
230 if (nut->max_distance > 65536) {
231 av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
232 nut->max_distance = 65536;
235 GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
236 nut->time_base = av_malloc(nut->time_base_count * sizeof(AVRational));
238 for (i = 0; i < nut->time_base_count; i++) {
239 GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
240 GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
241 if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
242 av_log(s, AV_LOG_ERROR, "time base invalid\n");
243 return AVERROR_INVALIDDATA;
250 for (i = 0; i < 256;) {
251 int tmp_flags = ffio_read_varlen(bc);
252 int tmp_fields = ffio_read_varlen(bc);
257 tmp_mul = ffio_read_varlen(bc);
259 tmp_stream = ffio_read_varlen(bc);
261 tmp_size = ffio_read_varlen(bc);
265 tmp_res = ffio_read_varlen(bc);
269 count = ffio_read_varlen(bc);
271 count = tmp_mul - tmp_size;
275 tmp_head_idx = ffio_read_varlen(bc);
277 while (tmp_fields-- > 8)
278 ffio_read_varlen(bc);
280 if (count == 0 || i + count > 256) {
281 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
282 return AVERROR_INVALIDDATA;
284 if (tmp_stream >= stream_count) {
285 av_log(s, AV_LOG_ERROR, "illegal stream number\n");
286 return AVERROR_INVALIDDATA;
289 for (j = 0; j < count; j++, i++) {
291 nut->frame_code[i].flags = FLAG_INVALID;
295 nut->frame_code[i].flags = tmp_flags;
296 nut->frame_code[i].pts_delta = tmp_pts;
297 nut->frame_code[i].stream_id = tmp_stream;
298 nut->frame_code[i].size_mul = tmp_mul;
299 nut->frame_code[i].size_lsb = tmp_size + j;
300 nut->frame_code[i].reserved_count = tmp_res;
301 nut->frame_code[i].header_idx = tmp_head_idx;
304 av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
306 if (end > avio_tell(bc) + 4) {
308 GET_V(nut->header_count, tmp < 128U);
310 for (i = 1; i < nut->header_count; i++) {
312 GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
313 rem -= nut->header_len[i];
315 av_log(s, AV_LOG_ERROR, "invalid elision header\n");
316 return AVERROR_INVALIDDATA;
318 hdr = av_malloc(nut->header_len[i]);
320 return AVERROR(ENOMEM);
321 avio_read(bc, hdr, nut->header_len[i]);
322 nut->header[i] = hdr;
324 av_assert0(nut->header_len[0] == 0);
327 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
328 av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
329 return AVERROR_INVALIDDATA;
332 nut->stream = av_mallocz(sizeof(StreamContext) * stream_count);
333 for (i = 0; i < stream_count; i++)
334 avformat_new_stream(s, NULL);
339 static int decode_stream_header(NUTContext *nut)
341 AVFormatContext *s = nut->avf;
342 AVIOContext *bc = s->pb;
344 int class, stream_id;
348 end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
349 end += avio_tell(bc);
351 GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
352 stc = &nut->stream[stream_id];
353 st = s->streams[stream_id];
355 return AVERROR(ENOMEM);
357 class = ffio_read_varlen(bc);
358 tmp = get_fourcc(bc);
359 st->codec->codec_tag = tmp;
362 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
363 st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
371 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
372 st->codec->codec_id = ff_codec_get_id(ff_codec_wav_tags, tmp);
375 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
376 st->codec->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
379 st->codec->codec_type = AVMEDIA_TYPE_DATA;
382 av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
385 if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
386 av_log(s, AV_LOG_ERROR,
387 "Unknown codec tag '0x%04x' for stream number %d\n",
388 (unsigned int) tmp, stream_id);
390 GET_V(stc->time_base_id, tmp < nut->time_base_count);
391 GET_V(stc->msb_pts_shift, tmp < 16);
392 stc->max_pts_distance = ffio_read_varlen(bc);
393 GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
394 st->codec->has_b_frames = stc->decode_delay;
395 ffio_read_varlen(bc); // stream flags
397 GET_V(st->codec->extradata_size, tmp < (1 << 30));
398 if (st->codec->extradata_size) {
399 st->codec->extradata = av_mallocz(st->codec->extradata_size +
400 FF_INPUT_BUFFER_PADDING_SIZE);
401 avio_read(bc, st->codec->extradata, st->codec->extradata_size);
404 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
405 GET_V(st->codec->width, tmp > 0);
406 GET_V(st->codec->height, tmp > 0);
407 st->sample_aspect_ratio.num = ffio_read_varlen(bc);
408 st->sample_aspect_ratio.den = ffio_read_varlen(bc);
409 if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
410 av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
411 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
414 ffio_read_varlen(bc); /* csp type */
415 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
416 GET_V(st->codec->sample_rate, tmp > 0);
417 ffio_read_varlen(bc); // samplerate_den
418 GET_V(st->codec->channels, tmp > 0);
420 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
421 av_log(s, AV_LOG_ERROR,
422 "stream header %d checksum mismatch\n", stream_id);
425 stc->time_base = &nut->time_base[stc->time_base_id];
426 avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
427 stc->time_base->den);
431 static void set_disposition_bits(AVFormatContext *avf, char *value,
436 for (i = 0; ff_nut_dispositions[i].flag; ++i)
437 if (!strcmp(ff_nut_dispositions[i].str, value))
438 flag = ff_nut_dispositions[i].flag;
440 av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
441 for (i = 0; i < avf->nb_streams; ++i)
442 if (stream_id == i || stream_id == -1)
443 avf->streams[i]->disposition |= flag;
446 static int decode_info_header(NUTContext *nut)
448 AVFormatContext *s = nut->avf;
449 AVIOContext *bc = s->pb;
450 uint64_t tmp, chapter_start, chapter_len;
451 unsigned int stream_id_plus1, count;
454 char name[256], str_value[1024], type_str[256];
456 AVChapter *chapter = NULL;
458 AVDictionary **metadata = NULL;
460 end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
461 end += avio_tell(bc);
463 GET_V(stream_id_plus1, tmp <= s->nb_streams);
464 chapter_id = get_s(bc);
465 chapter_start = ffio_read_varlen(bc);
466 chapter_len = ffio_read_varlen(bc);
467 count = ffio_read_varlen(bc);
469 if (chapter_id && !stream_id_plus1) {
470 int64_t start = chapter_start / nut->time_base_count;
471 chapter = avpriv_new_chapter(s, chapter_id,
472 nut->time_base[chapter_start %
473 nut->time_base_count],
474 start, start + chapter_len, NULL);
475 metadata = &chapter->metadata;
476 } else if (stream_id_plus1) {
477 st = s->streams[stream_id_plus1 - 1];
478 metadata = &st->metadata;
480 metadata = &s->metadata;
482 for (i = 0; i < count; i++) {
483 get_str(bc, name, sizeof(name));
487 get_str(bc, str_value, sizeof(str_value));
488 } else if (value == -2) {
489 get_str(bc, type_str, sizeof(type_str));
491 get_str(bc, str_value, sizeof(str_value));
492 } else if (value == -3) {
495 } else if (value == -4) {
497 value = ffio_read_varlen(bc);
498 } else if (value < -4) {
505 if (stream_id_plus1 > s->nb_streams) {
506 av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
510 if (!strcmp(type, "UTF-8")) {
511 if (chapter_id == 0 && !strcmp(name, "Disposition")) {
512 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
516 if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
517 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
521 if (metadata && av_strcasecmp(name, "Uses") &&
522 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces"))
523 av_dict_set(metadata, name, str_value, 0);
527 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
528 av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
534 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
536 AVFormatContext *s = nut->avf;
537 AVIOContext *bc = s->pb;
541 nut->last_syncpoint_pos = avio_tell(bc) - 8;
543 end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
544 end += avio_tell(bc);
546 tmp = ffio_read_varlen(bc);
547 *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
551 ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
552 tmp / nut->time_base_count);
554 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
555 av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
559 *ts = tmp / nut->time_base_count *
560 av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
561 ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts);
566 //FIXME calculate exactly, this is just a good approximation.
567 static int64_t find_duration(NUTContext *nut, int64_t filesize)
569 AVFormatContext *s = nut->avf;
570 int64_t duration = 0;
572 int64_t pos = FFMAX(0, filesize - 2*nut->max_distance);
574 int64_t ts = nut_read_timestamp(s, -1, &pos, INT64_MAX);
577 duration = FFMAX(duration, ts);
581 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
585 static int find_and_decode_index(NUTContext *nut)
587 AVFormatContext *s = nut->avf;
588 AVIOContext *bc = s->pb;
590 int i, j, syncpoint_count;
591 int64_t filesize = avio_size(bc);
593 int8_t *has_keyframe;
599 avio_seek(bc, filesize - 12, SEEK_SET);
600 avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
601 if (avio_rb64(bc) != INDEX_STARTCODE) {
602 av_log(s, AV_LOG_ERROR, "no index at the end\n");
605 s->duration = find_duration(nut, filesize);
609 end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
610 end += avio_tell(bc);
612 ffio_read_varlen(bc); // max_pts
613 GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
614 syncpoints = av_malloc(sizeof(int64_t) * syncpoint_count);
615 has_keyframe = av_malloc(sizeof(int8_t) * (syncpoint_count + 1));
616 for (i = 0; i < syncpoint_count; i++) {
617 syncpoints[i] = ffio_read_varlen(bc);
618 if (syncpoints[i] <= 0)
621 syncpoints[i] += syncpoints[i - 1];
624 for (i = 0; i < s->nb_streams; i++) {
625 int64_t last_pts = -1;
626 for (j = 0; j < syncpoint_count;) {
627 uint64_t x = ffio_read_varlen(bc);
634 if (n + x >= syncpoint_count + 1) {
635 av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
639 has_keyframe[n++] = flag;
640 has_keyframe[n++] = !flag;
643 if (n >= syncpoint_count + 1) {
644 av_log(s, AV_LOG_ERROR, "index overflow B\n");
647 has_keyframe[n++] = x & 1;
651 if (has_keyframe[0]) {
652 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
655 av_assert0(n <= syncpoint_count + 1);
656 for (; j < n && j < syncpoint_count; j++) {
657 if (has_keyframe[j]) {
658 uint64_t B, A = ffio_read_varlen(bc);
660 A = ffio_read_varlen(bc);
661 B = ffio_read_varlen(bc);
662 // eor_pts[j][i] = last_pts + A + B
665 av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
666 last_pts + A, 0, 0, AVINDEX_KEYFRAME);
673 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
674 av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
681 av_free(has_keyframe);
685 static int nut_read_header(AVFormatContext *s)
687 NUTContext *nut = s->priv_data;
688 AVIOContext *bc = s->pb;
690 int initialized_stream_count;
697 pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
699 av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
700 return AVERROR_INVALIDDATA;
702 } while (decode_main_header(nut) < 0);
706 for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
707 pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
709 av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
710 return AVERROR_INVALIDDATA;
712 if (decode_stream_header(nut) >= 0)
713 initialized_stream_count++;
719 uint64_t startcode = find_any_startcode(bc, pos);
722 if (startcode == 0) {
723 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
724 return AVERROR_INVALIDDATA;
725 } else if (startcode == SYNCPOINT_STARTCODE) {
726 nut->next_startcode = startcode;
728 } else if (startcode != INFO_STARTCODE) {
732 decode_info_header(nut);
735 s->data_offset = pos - 8;
738 int64_t orig_pos = avio_tell(bc);
739 find_and_decode_index(nut);
740 avio_seek(bc, orig_pos, SEEK_SET);
742 av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
744 ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
749 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
750 uint8_t *header_idx, int frame_code)
752 AVFormatContext *s = nut->avf;
753 AVIOContext *bc = s->pb;
755 int size, flags, size_mul, pts_delta, i, reserved_count;
758 if (avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
759 av_log(s, AV_LOG_ERROR,
760 "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
761 avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
762 return AVERROR_INVALIDDATA;
765 flags = nut->frame_code[frame_code].flags;
766 size_mul = nut->frame_code[frame_code].size_mul;
767 size = nut->frame_code[frame_code].size_lsb;
768 *stream_id = nut->frame_code[frame_code].stream_id;
769 pts_delta = nut->frame_code[frame_code].pts_delta;
770 reserved_count = nut->frame_code[frame_code].reserved_count;
771 *header_idx = nut->frame_code[frame_code].header_idx;
773 if (flags & FLAG_INVALID)
774 return AVERROR_INVALIDDATA;
775 if (flags & FLAG_CODED)
776 flags ^= ffio_read_varlen(bc);
777 if (flags & FLAG_STREAM_ID) {
778 GET_V(*stream_id, tmp < s->nb_streams);
780 stc = &nut->stream[*stream_id];
781 if (flags & FLAG_CODED_PTS) {
782 int coded_pts = ffio_read_varlen(bc);
783 // FIXME check last_pts validity?
784 if (coded_pts < (1 << stc->msb_pts_shift)) {
785 *pts = ff_lsb2full(stc, coded_pts);
787 *pts = coded_pts - (1 << stc->msb_pts_shift);
789 *pts = stc->last_pts + pts_delta;
790 if (flags & FLAG_SIZE_MSB)
791 size += size_mul * ffio_read_varlen(bc);
792 if (flags & FLAG_MATCH_TIME)
794 if (flags & FLAG_HEADER_IDX)
795 *header_idx = ffio_read_varlen(bc);
796 if (flags & FLAG_RESERVED)
797 reserved_count = ffio_read_varlen(bc);
798 for (i = 0; i < reserved_count; i++)
799 ffio_read_varlen(bc);
801 if (*header_idx >= (unsigned)nut->header_count) {
802 av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
803 return AVERROR_INVALIDDATA;
807 size -= nut->header_len[*header_idx];
809 if (flags & FLAG_CHECKSUM) {
810 avio_rb32(bc); // FIXME check this
811 } else if (size > 2 * nut->max_distance || FFABS(stc->last_pts - *pts) >
812 stc->max_pts_distance) {
813 av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
814 return AVERROR_INVALIDDATA;
817 stc->last_pts = *pts;
818 stc->last_flags = flags;
823 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
825 AVFormatContext *s = nut->avf;
826 AVIOContext *bc = s->pb;
827 int size, stream_id, discard;
828 int64_t pts, last_IP_pts;
832 size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
836 stc = &nut->stream[stream_id];
838 if (stc->last_flags & FLAG_KEY)
839 stc->skip_until_key_frame = 0;
841 discard = s->streams[stream_id]->discard;
842 last_IP_pts = s->streams[stream_id]->last_IP_pts;
843 if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
844 (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
845 last_IP_pts > pts) ||
846 discard >= AVDISCARD_ALL ||
847 stc->skip_until_key_frame) {
852 av_new_packet(pkt, size + nut->header_len[header_idx]);
853 memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
854 pkt->pos = avio_tell(bc); // FIXME
855 avio_read(bc, pkt->data + nut->header_len[header_idx], size);
857 pkt->stream_index = stream_id;
858 if (stc->last_flags & FLAG_KEY)
859 pkt->flags |= AV_PKT_FLAG_KEY;
865 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
867 NUTContext *nut = s->priv_data;
868 AVIOContext *bc = s->pb;
869 int i, frame_code = 0, ret, skip;
870 int64_t ts, back_ptr;
873 int64_t pos = avio_tell(bc);
874 uint64_t tmp = nut->next_startcode;
875 nut->next_startcode = 0;
880 frame_code = avio_r8(bc);
883 if (frame_code == 'N') {
885 for (i = 1; i < 8; i++)
886 tmp = (tmp << 8) + avio_r8(bc);
891 case STREAM_STARTCODE:
892 case INDEX_STARTCODE:
893 skip = get_packetheader(nut, bc, 0, tmp);
897 if (decode_info_header(nut) < 0)
900 case SYNCPOINT_STARTCODE:
901 if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
903 frame_code = avio_r8(bc);
905 ret = decode_frame(nut, pkt, frame_code);
908 else if (ret == 1) // OK but discard packet
912 av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
913 tmp = find_any_startcode(bc, nut->last_syncpoint_pos + 1);
915 return AVERROR_INVALIDDATA;
916 av_log(s, AV_LOG_DEBUG, "sync\n");
917 nut->next_startcode = tmp;
922 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
923 int64_t *pos_arg, int64_t pos_limit)
925 NUTContext *nut = s->priv_data;
926 AVIOContext *bc = s->pb;
927 int64_t pos, pts, back_ptr;
928 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
929 stream_index, *pos_arg, pos_limit);
933 pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
935 av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
936 return AV_NOPTS_VALUE;
938 } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
940 av_assert0(nut->last_syncpoint_pos == *pos_arg);
942 av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
943 if (stream_index == -2)
945 av_assert0(stream_index == -1);
949 static int read_seek(AVFormatContext *s, int stream_index,
950 int64_t pts, int flags)
952 NUTContext *nut = s->priv_data;
953 AVStream *st = s->streams[stream_index];
954 Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
955 Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
956 Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
957 int64_t pos, pos2, ts;
960 if (st->index_entries) {
961 int index = av_index_search_timestamp(st, pts, flags);
963 index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
967 pos2 = st->index_entries[index].pos;
968 ts = st->index_entries[index].timestamp;
970 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
971 (void **) next_node);
972 av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
973 next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
975 pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
976 next_node[1]->pos, next_node[1]->pos,
977 next_node[0]->ts, next_node[1]->ts,
978 AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
980 if (!(flags & AVSEEK_FLAG_BACKWARD)) {
981 dummy.pos = pos + 16;
982 next_node[1] = &nopts_sp;
983 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
984 (void **) next_node);
985 pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
986 next_node[1]->pos, next_node[1]->pos,
987 next_node[0]->back_ptr, next_node[1]->back_ptr,
988 flags, &ts, nut_read_timestamp);
991 // FIXME dir but I think it does not matter
994 sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
998 pos2 = sp->back_ptr - 15;
1000 av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1001 pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1002 avio_seek(s->pb, pos, SEEK_SET);
1003 av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1004 if (pos2 > pos || pos2 + 15 < pos)
1005 av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1006 for (i = 0; i < s->nb_streams; i++)
1007 nut->stream[i].skip_until_key_frame = 1;
1012 static int nut_read_close(AVFormatContext *s)
1014 NUTContext *nut = s->priv_data;
1017 av_freep(&nut->time_base);
1018 av_freep(&nut->stream);
1019 ff_nut_free_sp(nut);
1020 for (i = 1; i < nut->header_count; i++)
1021 av_freep(&nut->header[i]);
1026 AVInputFormat ff_nut_demuxer = {
1028 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1029 .flags = AVFMT_SEEK_TO_PTS,
1030 .priv_data_size = sizeof(NUTContext),
1031 .read_probe = nut_probe,
1032 .read_header = nut_read_header,
1033 .read_packet = nut_read_packet,
1034 .read_close = nut_read_close,
1035 .read_seek = read_seek,
1036 .extensions = "nut",
1037 .codec_tag = (const AVCodecTag * const []) {
1038 ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags,
1039 ff_nut_subtitle_tags, 0