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"
35 #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
37 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
38 int64_t *pos_arg, int64_t pos_limit);
40 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
42 unsigned int len = ffio_read_varlen(bc);
45 avio_read(bc, string, FFMIN(len, maxlen));
46 while (len > maxlen) {
52 string[FFMIN(len, maxlen - 1)] = 0;
60 static int64_t get_s(AVIOContext *bc)
62 int64_t v = ffio_read_varlen(bc) + 1;
70 static uint64_t get_fourcc(AVIOContext *bc)
72 unsigned int len = ffio_read_varlen(bc);
79 av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
85 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
86 const char *func, int line)
88 uint64_t v = ffio_read_varlen(bc);
90 av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
91 v, v, file, func, line);
95 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
96 const char *func, int line)
98 int64_t v = get_s(bc);
100 av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
101 v, v, file, func, line);
105 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
106 char *func, int line)
108 uint64_t v = get_fourcc(bc);
110 av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
111 v, v, file, func, line);
114 #define ffio_read_varlen(bc) get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
115 #define get_s(bc) get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
116 #define get_fourcc(bc) get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
119 static int get_packetheader(NUTContext *nut, AVIOContext *bc,
120 int calculate_checksum, uint64_t startcode)
123 // start = avio_tell(bc) - 8;
125 startcode = av_be2ne64(startcode);
126 startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
128 ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
129 size = ffio_read_varlen(bc);
132 if (ffio_get_checksum(bc) && size > 4096)
135 ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
140 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
145 /* Note, this may fail if the stream is not seekable, but that should
146 * not matter, as in this case we simply start where we currently are */
147 avio_seek(bc, pos, SEEK_SET);
148 while (!url_feof(bc)) {
149 state = (state << 8) | avio_r8(bc);
150 if ((state >> 56) != 'N')
154 case STREAM_STARTCODE:
155 case SYNCPOINT_STARTCODE:
157 case INDEX_STARTCODE:
166 * Find the given startcode.
167 * @param code the startcode
168 * @param pos the start position of the search, or -1 if the current position
169 * @return the position of the startcode or -1 if not found
171 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
174 uint64_t startcode = find_any_startcode(bc, pos);
175 if (startcode == code)
176 return avio_tell(bc) - 8;
177 else if (startcode == 0)
183 static int nut_probe(AVProbeData *p)
188 for (i = 0; i < p->buf_size; i++) {
189 code = (code << 8) | p->buf[i];
190 if (code == MAIN_STARTCODE)
191 return AVPROBE_SCORE_MAX;
196 #define GET_V(dst, check) \
198 tmp = ffio_read_varlen(bc); \
200 av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
201 return AVERROR_INVALIDDATA; \
206 static int skip_reserved(AVIOContext *bc, int64_t pos)
208 pos -= avio_tell(bc);
210 avio_seek(bc, pos, SEEK_CUR);
211 return AVERROR_INVALIDDATA;
219 static int decode_main_header(NUTContext *nut)
221 AVFormatContext *s = nut->avf;
222 AVIOContext *bc = s->pb;
224 unsigned int stream_count;
226 int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
228 end = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
229 end += avio_tell(bc);
231 tmp = ffio_read_varlen(bc);
232 if (tmp < NUT_MIN_VERSION && tmp > NUT_MAX_VERSION) {
233 av_log(s, AV_LOG_ERROR, "Version %"PRId64" not supported.\n",
235 return AVERROR(ENOSYS);
238 if (nut->version > 3)
239 nut->minor_version = ffio_read_varlen(bc);
241 GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
243 nut->max_distance = ffio_read_varlen(bc);
244 if (nut->max_distance > 65536) {
245 av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
246 nut->max_distance = 65536;
249 GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
250 nut->time_base = av_malloc(nut->time_base_count * sizeof(AVRational));
252 return AVERROR(ENOMEM);
254 for (i = 0; i < nut->time_base_count; i++) {
255 GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
256 GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
257 if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
258 av_log(s, AV_LOG_ERROR, "time base invalid\n");
259 return AVERROR_INVALIDDATA;
266 for (i = 0; i < 256;) {
267 int tmp_flags = ffio_read_varlen(bc);
268 int tmp_fields = ffio_read_varlen(bc);
273 tmp_mul = ffio_read_varlen(bc);
275 tmp_stream = ffio_read_varlen(bc);
277 tmp_size = ffio_read_varlen(bc);
281 tmp_res = ffio_read_varlen(bc);
285 count = ffio_read_varlen(bc);
287 count = tmp_mul - tmp_size;
291 tmp_head_idx = ffio_read_varlen(bc);
293 while (tmp_fields-- > 8)
294 ffio_read_varlen(bc);
296 if (count == 0 || i + count > 256) {
297 av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
298 return AVERROR_INVALIDDATA;
300 if (tmp_stream >= stream_count) {
301 av_log(s, AV_LOG_ERROR, "illegal stream number\n");
302 return AVERROR_INVALIDDATA;
305 for (j = 0; j < count; j++, i++) {
307 nut->frame_code[i].flags = FLAG_INVALID;
311 nut->frame_code[i].flags = tmp_flags;
312 nut->frame_code[i].pts_delta = tmp_pts;
313 nut->frame_code[i].stream_id = tmp_stream;
314 nut->frame_code[i].size_mul = tmp_mul;
315 nut->frame_code[i].size_lsb = tmp_size + j;
316 nut->frame_code[i].reserved_count = tmp_res;
317 nut->frame_code[i].header_idx = tmp_head_idx;
320 av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
322 if (end > avio_tell(bc) + 4) {
324 GET_V(nut->header_count, tmp < 128U);
326 for (i = 1; i < nut->header_count; i++) {
328 GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
329 rem -= nut->header_len[i];
331 av_log(s, AV_LOG_ERROR, "invalid elision header\n");
332 return AVERROR_INVALIDDATA;
334 hdr = av_malloc(nut->header_len[i]);
336 return AVERROR(ENOMEM);
337 avio_read(bc, hdr, nut->header_len[i]);
338 nut->header[i] = hdr;
340 av_assert0(nut->header_len[0] == 0);
343 // flags had been effectively introduced in version 4
344 if (nut->version > 3 && end > avio_tell(bc) + 4) {
345 nut->flags = ffio_read_varlen(bc);
348 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
349 av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
350 return AVERROR_INVALIDDATA;
353 nut->stream = av_calloc(stream_count, sizeof(StreamContext));
355 return AVERROR(ENOMEM);
356 for (i = 0; i < stream_count; i++)
357 avformat_new_stream(s, NULL);
362 static int decode_stream_header(NUTContext *nut)
364 AVFormatContext *s = nut->avf;
365 AVIOContext *bc = s->pb;
367 int class, stream_id;
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->codec->codec_tag = tmp;
385 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
386 st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
394 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
395 st->codec->codec_id = av_codec_get_id((const AVCodecTag * const []) {
398 ff_nut_audio_extra_tags,
404 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
405 st->codec->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
408 st->codec->codec_type = AVMEDIA_TYPE_DATA;
409 st->codec->codec_id = ff_codec_get_id(ff_nut_data_tags, tmp);
412 av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
413 return AVERROR(ENOSYS);
415 if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
416 av_log(s, AV_LOG_ERROR,
417 "Unknown codec tag '0x%04x' for stream number %d\n",
418 (unsigned int) tmp, stream_id);
420 GET_V(stc->time_base_id, tmp < nut->time_base_count);
421 GET_V(stc->msb_pts_shift, tmp < 16);
422 stc->max_pts_distance = ffio_read_varlen(bc);
423 GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
424 st->codec->has_b_frames = stc->decode_delay;
425 ffio_read_varlen(bc); // stream flags
427 GET_V(st->codec->extradata_size, tmp < (1 << 30));
428 if (st->codec->extradata_size) {
429 if (ff_get_extradata(st->codec, bc, st->codec->extradata_size) < 0)
430 return AVERROR(ENOMEM);
433 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
434 GET_V(st->codec->width, tmp > 0);
435 GET_V(st->codec->height, tmp > 0);
436 st->sample_aspect_ratio.num = ffio_read_varlen(bc);
437 st->sample_aspect_ratio.den = ffio_read_varlen(bc);
438 if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
439 av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
440 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
441 return AVERROR_INVALIDDATA;
443 ffio_read_varlen(bc); /* csp type */
444 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
445 GET_V(st->codec->sample_rate, tmp > 0);
446 ffio_read_varlen(bc); // samplerate_den
447 GET_V(st->codec->channels, tmp > 0);
449 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
450 av_log(s, AV_LOG_ERROR,
451 "stream header %d checksum mismatch\n", stream_id);
452 return AVERROR_INVALIDDATA;
454 stc->time_base = &nut->time_base[stc->time_base_id];
455 avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
456 stc->time_base->den);
460 static void set_disposition_bits(AVFormatContext *avf, char *value,
465 for (i = 0; ff_nut_dispositions[i].flag; ++i)
466 if (!strcmp(ff_nut_dispositions[i].str, value))
467 flag = ff_nut_dispositions[i].flag;
469 av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
470 for (i = 0; i < avf->nb_streams; ++i)
471 if (stream_id == i || stream_id == -1)
472 avf->streams[i]->disposition |= flag;
475 static int decode_info_header(NUTContext *nut)
477 AVFormatContext *s = nut->avf;
478 AVIOContext *bc = s->pb;
479 uint64_t tmp, chapter_start, chapter_len;
480 unsigned int stream_id_plus1, count;
483 char name[256], str_value[1024], type_str[256];
485 AVChapter *chapter = NULL;
487 AVDictionary **metadata = NULL;
489 end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
490 end += avio_tell(bc);
492 GET_V(stream_id_plus1, tmp <= s->nb_streams);
493 chapter_id = get_s(bc);
494 chapter_start = ffio_read_varlen(bc);
495 chapter_len = ffio_read_varlen(bc);
496 count = ffio_read_varlen(bc);
498 if (chapter_id && !stream_id_plus1) {
499 int64_t start = chapter_start / nut->time_base_count;
500 chapter = avpriv_new_chapter(s, chapter_id,
501 nut->time_base[chapter_start %
502 nut->time_base_count],
503 start, start + chapter_len, NULL);
504 metadata = &chapter->metadata;
505 } else if (stream_id_plus1) {
506 st = s->streams[stream_id_plus1 - 1];
507 metadata = &st->metadata;
509 metadata = &s->metadata;
511 for (i = 0; i < count; i++) {
512 get_str(bc, name, sizeof(name));
516 get_str(bc, str_value, sizeof(str_value));
517 } else if (value == -2) {
518 get_str(bc, type_str, sizeof(type_str));
520 get_str(bc, str_value, sizeof(str_value));
521 } else if (value == -3) {
524 } else if (value == -4) {
526 value = ffio_read_varlen(bc);
527 } else if (value < -4) {
534 if (stream_id_plus1 > s->nb_streams) {
535 av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
539 if (!strcmp(type, "UTF-8")) {
540 if (chapter_id == 0 && !strcmp(name, "Disposition")) {
541 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
545 if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
546 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
547 if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den)
548 st->r_frame_rate.num = st->r_frame_rate.den = 0;
552 if (metadata && av_strcasecmp(name, "Uses") &&
553 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces"))
554 av_dict_set(metadata, name, str_value, 0);
558 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
559 av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
560 return AVERROR_INVALIDDATA;
565 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
567 AVFormatContext *s = nut->avf;
568 AVIOContext *bc = s->pb;
573 nut->last_syncpoint_pos = avio_tell(bc) - 8;
575 end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
576 end += avio_tell(bc);
578 tmp = ffio_read_varlen(bc);
579 *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
581 return AVERROR_INVALIDDATA;
583 ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
584 tmp / nut->time_base_count);
586 if (nut->flags & NUT_BROADCAST) {
587 tmp = ffio_read_varlen(bc);
588 av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
589 av_rescale_q(tmp / nut->time_base_count,
590 nut->time_base[tmp % nut->time_base_count],
594 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
595 av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
596 return AVERROR_INVALIDDATA;
599 *ts = tmp / nut->time_base_count *
600 av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
602 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
608 //FIXME calculate exactly, this is just a good approximation.
609 static int64_t find_duration(NUTContext *nut, int64_t filesize)
611 AVFormatContext *s = nut->avf;
612 int64_t duration = 0;
614 ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
617 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
621 static int find_and_decode_index(NUTContext *nut)
623 AVFormatContext *s = nut->avf;
624 AVIOContext *bc = s->pb;
626 int i, j, syncpoint_count;
627 int64_t filesize = avio_size(bc);
630 int8_t *has_keyframe;
631 int ret = AVERROR_INVALIDDATA;
636 avio_seek(bc, filesize - 12, SEEK_SET);
637 avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
638 if (avio_rb64(bc) != INDEX_STARTCODE) {
639 av_log(s, AV_LOG_ERROR, "no index at the end\n");
642 s->duration = find_duration(nut, filesize);
646 end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
647 end += avio_tell(bc);
649 max_pts = ffio_read_varlen(bc);
650 s->duration = av_rescale_q(max_pts / nut->time_base_count,
651 nut->time_base[max_pts % nut->time_base_count],
653 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
655 GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
656 syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
657 has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
658 if (!syncpoints || !has_keyframe) {
659 ret = AVERROR(ENOMEM);
662 for (i = 0; i < syncpoint_count; i++) {
663 syncpoints[i] = ffio_read_varlen(bc);
664 if (syncpoints[i] <= 0)
667 syncpoints[i] += syncpoints[i - 1];
670 for (i = 0; i < s->nb_streams; i++) {
671 int64_t last_pts = -1;
672 for (j = 0; j < syncpoint_count;) {
673 uint64_t x = ffio_read_varlen(bc);
680 if (n + x >= syncpoint_count + 1) {
681 av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
685 has_keyframe[n++] = flag;
686 has_keyframe[n++] = !flag;
689 if (n >= syncpoint_count + 1) {
690 av_log(s, AV_LOG_ERROR, "index overflow B\n");
693 has_keyframe[n++] = x & 1;
697 if (has_keyframe[0]) {
698 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
701 av_assert0(n <= syncpoint_count + 1);
702 for (; j < n && j < syncpoint_count; j++) {
703 if (has_keyframe[j]) {
704 uint64_t B, A = ffio_read_varlen(bc);
706 A = ffio_read_varlen(bc);
707 B = ffio_read_varlen(bc);
708 // eor_pts[j][i] = last_pts + A + B
711 av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
712 last_pts + A, 0, 0, AVINDEX_KEYFRAME);
719 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
720 av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
727 av_free(has_keyframe);
731 static int nut_read_header(AVFormatContext *s)
733 NUTContext *nut = s->priv_data;
734 AVIOContext *bc = s->pb;
736 int initialized_stream_count;
743 pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
745 av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
746 return AVERROR_INVALIDDATA;
748 } while (decode_main_header(nut) < 0);
752 for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
753 pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
755 av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
756 return AVERROR_INVALIDDATA;
758 if (decode_stream_header(nut) >= 0)
759 initialized_stream_count++;
765 uint64_t startcode = find_any_startcode(bc, pos);
768 if (startcode == 0) {
769 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
770 return AVERROR_INVALIDDATA;
771 } else if (startcode == SYNCPOINT_STARTCODE) {
772 nut->next_startcode = startcode;
774 } else if (startcode != INFO_STARTCODE) {
778 decode_info_header(nut);
781 s->data_offset = pos - 8;
784 int64_t orig_pos = avio_tell(bc);
785 find_and_decode_index(nut);
786 avio_seek(bc, orig_pos, SEEK_SET);
788 av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
790 ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
795 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
797 int count = ffio_read_varlen(bc);
801 int64_t channel_layout = 0;
807 for (i=0; i<count; i++) {
808 uint8_t name[256], str_value[256], type_str[256];
810 if (avio_tell(bc) >= maxpos)
811 return AVERROR_INVALIDDATA;
812 get_str(bc, name, sizeof(name));
816 get_str(bc, str_value, sizeof(str_value));
817 av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
818 } else if (value == -2) {
820 int64_t v64, value_len;
822 get_str(bc, type_str, sizeof(type_str));
823 value_len = ffio_read_varlen(bc);
824 if (avio_tell(bc) + value_len >= maxpos)
825 return AVERROR_INVALIDDATA;
826 if (!strcmp(name, "Palette")) {
827 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
828 } else if (!strcmp(name, "Extradata")) {
829 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
830 } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
831 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, value_len + 8);
833 return AVERROR(ENOMEM);
836 } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
837 channel_layout = avio_rl64(bc);
840 av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
841 avio_skip(bc, value_len);
845 return AVERROR(ENOMEM);
846 avio_read(bc, dst, value_len);
847 } else if (value == -3) {
849 } else if (value == -4) {
850 value = ffio_read_varlen(bc);
851 } else if (value < -4) {
854 if (!strcmp(name, "SkipStart")) {
856 } else if (!strcmp(name, "SkipEnd")) {
858 } else if (!strcmp(name, "Channels")) {
860 } else if (!strcmp(name, "SampleRate")) {
862 } else if (!strcmp(name, "Width")) {
864 } else if (!strcmp(name, "Height")) {
867 av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
872 if (channels || channel_layout || sample_rate || width || height) {
873 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, 28);
875 return AVERROR(ENOMEM);
876 bytestream_put_le32(&dst,
877 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT*(!!channels) +
878 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
879 AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
880 AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
883 bytestream_put_le32(&dst, channels);
885 bytestream_put_le64(&dst, channel_layout);
887 bytestream_put_le32(&dst, sample_rate);
888 if (width || height){
889 bytestream_put_le32(&dst, width);
890 bytestream_put_le32(&dst, height);
894 if (skip_start || skip_end) {
895 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
897 return AVERROR(ENOMEM);
898 AV_WL32(dst, skip_start);
899 AV_WL32(dst+4, skip_end);
905 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
906 uint8_t *header_idx, int frame_code)
908 AVFormatContext *s = nut->avf;
909 AVIOContext *bc = s->pb;
911 int size, flags, size_mul, pts_delta, i, reserved_count;
914 if (!(nut->flags & NUT_PIPE) &&
915 avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
916 av_log(s, AV_LOG_ERROR,
917 "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
918 avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
919 return AVERROR_INVALIDDATA;
922 flags = nut->frame_code[frame_code].flags;
923 size_mul = nut->frame_code[frame_code].size_mul;
924 size = nut->frame_code[frame_code].size_lsb;
925 *stream_id = nut->frame_code[frame_code].stream_id;
926 pts_delta = nut->frame_code[frame_code].pts_delta;
927 reserved_count = nut->frame_code[frame_code].reserved_count;
928 *header_idx = nut->frame_code[frame_code].header_idx;
930 if (flags & FLAG_INVALID)
931 return AVERROR_INVALIDDATA;
932 if (flags & FLAG_CODED)
933 flags ^= ffio_read_varlen(bc);
934 if (flags & FLAG_STREAM_ID) {
935 GET_V(*stream_id, tmp < s->nb_streams);
937 stc = &nut->stream[*stream_id];
938 if (flags & FLAG_CODED_PTS) {
939 int coded_pts = ffio_read_varlen(bc);
940 // FIXME check last_pts validity?
941 if (coded_pts < (1 << stc->msb_pts_shift)) {
942 *pts = ff_lsb2full(stc, coded_pts);
944 *pts = coded_pts - (1LL << stc->msb_pts_shift);
946 *pts = stc->last_pts + pts_delta;
947 if (flags & FLAG_SIZE_MSB)
948 size += size_mul * ffio_read_varlen(bc);
949 if (flags & FLAG_MATCH_TIME)
951 if (flags & FLAG_HEADER_IDX)
952 *header_idx = ffio_read_varlen(bc);
953 if (flags & FLAG_RESERVED)
954 reserved_count = ffio_read_varlen(bc);
955 for (i = 0; i < reserved_count; i++)
956 ffio_read_varlen(bc);
958 if (*header_idx >= (unsigned)nut->header_count) {
959 av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
960 return AVERROR_INVALIDDATA;
964 size -= nut->header_len[*header_idx];
966 if (flags & FLAG_CHECKSUM) {
967 avio_rb32(bc); // FIXME check this
968 } else if (!(nut->flags & NUT_PIPE) &&
969 size > 2 * nut->max_distance ||
970 FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
971 av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
972 return AVERROR_INVALIDDATA;
975 stc->last_pts = *pts;
976 stc->last_flags = flags;
981 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
983 AVFormatContext *s = nut->avf;
984 AVIOContext *bc = s->pb;
985 int size, stream_id, discard;
986 int64_t pts, last_IP_pts;
991 size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
995 stc = &nut->stream[stream_id];
997 if (stc->last_flags & FLAG_KEY)
998 stc->skip_until_key_frame = 0;
1000 discard = s->streams[stream_id]->discard;
1001 last_IP_pts = s->streams[stream_id]->last_IP_pts;
1002 if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1003 (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1004 last_IP_pts > pts) ||
1005 discard >= AVDISCARD_ALL ||
1006 stc->skip_until_key_frame) {
1007 avio_skip(bc, size);
1011 if (av_new_packet(pkt, size + nut->header_len[header_idx]) < 0)
1012 return AVERROR(ENOMEM);
1013 memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1014 pkt->pos = avio_tell(bc); // FIXME
1015 if (stc->last_flags & FLAG_SM_DATA) {
1017 if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0)
1018 return AVERROR_INVALIDDATA;
1019 if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0)
1020 return AVERROR_INVALIDDATA;
1021 sm_size = avio_tell(bc) - pkt->pos;
1023 pkt->size -= sm_size;
1026 ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1031 av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1033 pkt->stream_index = stream_id;
1034 if (stc->last_flags & FLAG_KEY)
1035 pkt->flags |= AV_PKT_FLAG_KEY;
1041 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1043 NUTContext *nut = s->priv_data;
1044 AVIOContext *bc = s->pb;
1045 int i, frame_code = 0, ret, skip;
1046 int64_t ts, back_ptr;
1049 int64_t pos = avio_tell(bc);
1050 uint64_t tmp = nut->next_startcode;
1051 nut->next_startcode = 0;
1056 frame_code = avio_r8(bc);
1059 if (frame_code == 'N') {
1061 for (i = 1; i < 8; i++)
1062 tmp = (tmp << 8) + avio_r8(bc);
1066 case MAIN_STARTCODE:
1067 case STREAM_STARTCODE:
1068 case INDEX_STARTCODE:
1069 skip = get_packetheader(nut, bc, 0, tmp);
1070 avio_skip(bc, skip);
1072 case INFO_STARTCODE:
1073 if (decode_info_header(nut) < 0)
1076 case SYNCPOINT_STARTCODE:
1077 if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1079 frame_code = avio_r8(bc);
1081 ret = decode_frame(nut, pkt, frame_code);
1084 else if (ret == 1) // OK but discard packet
1088 av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1089 tmp = find_any_startcode(bc, nut->last_syncpoint_pos + 1);
1091 return AVERROR_INVALIDDATA;
1092 av_log(s, AV_LOG_DEBUG, "sync\n");
1093 nut->next_startcode = tmp;
1098 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1099 int64_t *pos_arg, int64_t pos_limit)
1101 NUTContext *nut = s->priv_data;
1102 AVIOContext *bc = s->pb;
1103 int64_t pos, pts, back_ptr;
1104 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1105 stream_index, *pos_arg, pos_limit);
1109 pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1111 av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1112 return AV_NOPTS_VALUE;
1114 } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1116 av_assert0(nut->last_syncpoint_pos == *pos_arg);
1118 av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1119 if (stream_index == -2)
1121 av_assert0(stream_index == -1);
1125 static int read_seek(AVFormatContext *s, int stream_index,
1126 int64_t pts, int flags)
1128 NUTContext *nut = s->priv_data;
1129 AVStream *st = s->streams[stream_index];
1130 Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1131 Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1132 Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1133 int64_t pos, pos2, ts;
1136 if (nut->flags & NUT_PIPE) {
1137 return AVERROR(ENOSYS);
1140 if (st->index_entries) {
1141 int index = av_index_search_timestamp(st, pts, flags);
1143 index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1147 pos2 = st->index_entries[index].pos;
1148 ts = st->index_entries[index].timestamp;
1150 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
1151 (void **) next_node);
1152 av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1153 next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1155 pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1156 next_node[1]->pos, next_node[1]->pos,
1157 next_node[0]->ts, next_node[1]->ts,
1158 AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
1160 if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1161 dummy.pos = pos + 16;
1162 next_node[1] = &nopts_sp;
1163 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1164 (void **) next_node);
1165 pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1166 next_node[1]->pos, next_node[1]->pos,
1167 next_node[0]->back_ptr, next_node[1]->back_ptr,
1168 flags, &ts, nut_read_timestamp);
1171 // FIXME dir but I think it does not matter
1174 sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1178 pos2 = sp->back_ptr - 15;
1180 av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1181 pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1182 avio_seek(s->pb, pos, SEEK_SET);
1183 av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1184 if (pos2 > pos || pos2 + 15 < pos)
1185 av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1186 for (i = 0; i < s->nb_streams; i++)
1187 nut->stream[i].skip_until_key_frame = 1;
1192 static int nut_read_close(AVFormatContext *s)
1194 NUTContext *nut = s->priv_data;
1197 av_freep(&nut->time_base);
1198 av_freep(&nut->stream);
1199 ff_nut_free_sp(nut);
1200 for (i = 1; i < nut->header_count; i++)
1201 av_freep(&nut->header[i]);
1206 AVInputFormat ff_nut_demuxer = {
1208 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1209 .flags = AVFMT_SEEK_TO_PTS,
1210 .priv_data_size = sizeof(NUTContext),
1211 .read_probe = nut_probe,
1212 .read_header = nut_read_header,
1213 .read_packet = nut_read_packet,
1214 .read_close = nut_read_close,
1215 .read_seek = read_seek,
1216 .extensions = "nut",
1217 .codec_tag = ff_nut_codec_tags,