1 /*
2 * "NUT" Container Format demuxer
3 * Copyright (c) 2004-2006 Michael Niedermayer
4 * Copyright (c) 2003 Alex Beregszaszi
5 *
6 * This file is part of FFmpeg.
7 *
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.
12 *
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.
17 *
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
21 */
22
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"
32 #include "isom.h"
33 #include "nut.h"
34 #include "riff.h"
35
36 #define NUT_MAX_STREAMS 256 /* arbitrary sanity check value */
37
38 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
39 int64_t *pos_arg, int64_t pos_limit);
40
get_str(AVIOContext * bc,char * string,unsigned int maxlen)41 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
42 {
43 unsigned int len = ffio_read_varlen(bc);
44
45 if (len && maxlen)
46 avio_read(bc, string, FFMIN(len, maxlen));
47 while (len > maxlen) {
48 avio_r8(bc);
49 len--;
50 if (bc->eof_reached)
51 len = maxlen;
52 }
53
54 if (maxlen)
55 string[FFMIN(len, maxlen - 1)] = 0;
56
57 if (bc->eof_reached)
58 return AVERROR_EOF;
59 if (maxlen == len)
60 return -1;
61 else
62 return 0;
63 }
64
get_s(AVIOContext * bc)65 static int64_t get_s(AVIOContext *bc)
66 {
67 int64_t v = ffio_read_varlen(bc) + 1;
68
69 if (v & 1)
70 return -(v >> 1);
71 else
72 return (v >> 1);
73 }
74
get_fourcc(AVIOContext * bc)75 static uint64_t get_fourcc(AVIOContext *bc)
76 {
77 unsigned int len = ffio_read_varlen(bc);
78
79 if (len == 2)
80 return avio_rl16(bc);
81 else if (len == 4)
82 return avio_rl32(bc);
83 else {
84 av_log(NULL, AV_LOG_ERROR, "Unsupported fourcc length %d\n", len);
85 return -1;
86 }
87 }
88
get_packetheader(NUTContext * nut,AVIOContext * bc,int calculate_checksum,uint64_t startcode)89 static int get_packetheader(NUTContext *nut, AVIOContext *bc,
90 int calculate_checksum, uint64_t startcode)
91 {
92 int64_t size;
93
94 startcode = av_be2ne64(startcode);
95 startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
96
97 ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
98 size = ffio_read_varlen(bc);
99 if (size > 4096)
100 avio_rb32(bc);
101 if (ffio_get_checksum(bc) && size > 4096)
102 return -1;
103
104 ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
105
106 return size;
107 }
108
find_any_startcode(AVIOContext * bc,int64_t pos)109 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
110 {
111 uint64_t state = 0;
112
113 if (pos >= 0)
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')
120 continue;
121 switch (state) {
122 case MAIN_STARTCODE:
123 case STREAM_STARTCODE:
124 case SYNCPOINT_STARTCODE:
125 case INFO_STARTCODE:
126 case INDEX_STARTCODE:
127 return state;
128 }
129 }
130
131 return 0;
132 }
133
134 /**
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
139 */
find_startcode(AVIOContext * bc,uint64_t code,int64_t pos)140 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
141 {
142 for (;;) {
143 uint64_t startcode = find_any_startcode(bc, pos);
144 if (startcode == code)
145 return avio_tell(bc) - 8;
146 else if (startcode == 0)
147 return -1;
148 pos = -1;
149 }
150 }
151
nut_probe(const AVProbeData * p)152 static int nut_probe(const AVProbeData *p)
153 {
154 int i;
155
156 for (i = 0; i < p->buf_size-8; i++) {
157 if (AV_RB32(p->buf+i) != MAIN_STARTCODE>>32)
158 continue;
159 if (AV_RB32(p->buf+i+4) == (MAIN_STARTCODE & 0xFFFFFFFF))
160 return AVPROBE_SCORE_MAX;
161 }
162 return 0;
163 }
164
165 #define GET_V(dst, check) \
166 do { \
167 tmp = ffio_read_varlen(bc); \
168 if (!(check)) { \
169 av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp); \
170 ret = AVERROR_INVALIDDATA; \
171 goto fail; \
172 } \
173 dst = tmp; \
174 } while (0)
175
skip_reserved(AVIOContext * bc,int64_t pos)176 static int skip_reserved(AVIOContext *bc, int64_t pos)
177 {
178 pos -= avio_tell(bc);
179 if (pos < 0) {
180 avio_seek(bc, pos, SEEK_CUR);
181 return AVERROR_INVALIDDATA;
182 } else {
183 while (pos--) {
184 if (bc->eof_reached)
185 return AVERROR_INVALIDDATA;
186 avio_r8(bc);
187 }
188 return 0;
189 }
190 }
191
decode_main_header(NUTContext * nut)192 static int decode_main_header(NUTContext *nut)
193 {
194 AVFormatContext *s = nut->avf;
195 AVIOContext *bc = s->pb;
196 uint64_t tmp, end, length;
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;
200
201 length = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
202 end = length + avio_tell(bc);
203
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",
208 nut->version);
209 return AVERROR(ENOSYS);
210 }
211 if (nut->version > 3)
212 nut->minor_version = ffio_read_varlen(bc);
213
214 GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
215
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;
220 }
221
222 GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational) && tmp < length/2);
223 nut->time_base = av_malloc_array(nut->time_base_count, sizeof(AVRational));
224 if (!nut->time_base)
225 return AVERROR(ENOMEM);
226
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;
235 goto fail;
236 }
237 }
238 tmp_pts = 0;
239 tmp_mul = 1;
240 tmp_stream = 0;
241 tmp_head_idx = 0;
242 for (i = 0; i < 256;) {
243 int tmp_flags = ffio_read_varlen(bc);
244 int tmp_fields = ffio_read_varlen(bc);
245
246 if (tmp_fields > 0)
247 tmp_pts = get_s(bc);
248 if (tmp_fields > 1)
249 tmp_mul = ffio_read_varlen(bc);
250 if (tmp_fields > 2)
251 tmp_stream = ffio_read_varlen(bc);
252 if (tmp_fields > 3)
253 tmp_size = ffio_read_varlen(bc);
254 else
255 tmp_size = 0;
256 if (tmp_fields > 4)
257 tmp_res = ffio_read_varlen(bc);
258 else
259 tmp_res = 0;
260 if (tmp_fields > 5)
261 count = ffio_read_varlen(bc);
262 else
263 count = tmp_mul - (unsigned)tmp_size;
264 if (tmp_fields > 6)
265 get_s(bc);
266 if (tmp_fields > 7)
267 tmp_head_idx = ffio_read_varlen(bc);
268
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;
273 goto fail;
274 }
275 ffio_read_varlen(bc);
276 }
277
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;
281 goto fail;
282 }
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;
287 goto fail;
288 }
289 if (tmp_size < 0 || tmp_size > INT_MAX - count) {
290 av_log(s, AV_LOG_ERROR, "illegal size\n");
291 ret = AVERROR_INVALIDDATA;
292 goto fail;
293 }
294
295 for (j = 0; j < count; j++, i++) {
296 if (i == 'N') {
297 nut->frame_code[i].flags = FLAG_INVALID;
298 j--;
299 continue;
300 }
301 nut->frame_code[i].flags = tmp_flags;
302 nut->frame_code[i].pts_delta = tmp_pts;
303 nut->frame_code[i].stream_id = tmp_stream;
304 nut->frame_code[i].size_mul = tmp_mul;
305 nut->frame_code[i].size_lsb = tmp_size + j;
306 nut->frame_code[i].reserved_count = tmp_res;
307 nut->frame_code[i].header_idx = tmp_head_idx;
308 }
309 }
310 av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
311
312 if (end > avio_tell(bc) + 4) {
313 int rem = 1024;
314 GET_V(nut->header_count, tmp < 128U);
315 nut->header_count++;
316 for (i = 1; i < nut->header_count; i++) {
317 uint8_t *hdr;
318 GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
319 if (rem < nut->header_len[i]) {
320 av_log(s, AV_LOG_ERROR,
321 "invalid elision header %d : %d > %d\n",
322 i, nut->header_len[i], rem);
323 ret = AVERROR_INVALIDDATA;
324 goto fail;
325 }
326 rem -= nut->header_len[i];
327 hdr = av_malloc(nut->header_len[i]);
328 if (!hdr) {
329 ret = AVERROR(ENOMEM);
330 goto fail;
331 }
332 avio_read(bc, hdr, nut->header_len[i]);
333 nut->header[i] = hdr;
334 }
335 av_assert0(nut->header_len[0] == 0);
336 }
337
338 // flags had been effectively introduced in version 4
339 if (nut->version > 3 && end > avio_tell(bc) + 4) {
340 nut->flags = ffio_read_varlen(bc);
341 }
342
343 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
344 av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
345 ret = AVERROR_INVALIDDATA;
346 goto fail;
347 }
348
349 nut->stream = av_calloc(stream_count, sizeof(StreamContext));
350 if (!nut->stream) {
351 ret = AVERROR(ENOMEM);
352 goto fail;
353 }
354 for (i = 0; i < stream_count; i++) {
355 if (!avformat_new_stream(s, NULL)) {
356 ret = AVERROR(ENOMEM);
357 goto fail;
358 }
359 }
360
361 return 0;
362 fail:
363 av_freep(&nut->time_base);
364 for (i = 1; i < nut->header_count; i++) {
365 av_freep(&nut->header[i]);
366 }
367 nut->header_count = 0;
368 return ret;
369 }
370
decode_stream_header(NUTContext * nut)371 static int decode_stream_header(NUTContext *nut)
372 {
373 AVFormatContext *s = nut->avf;
374 AVIOContext *bc = s->pb;
375 StreamContext *stc;
376 int class, stream_id, ret;
377 uint64_t tmp, end;
378 AVStream *st = NULL;
379
380 end = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
381 end += avio_tell(bc);
382
383 GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
384 stc = &nut->stream[stream_id];
385 st = s->streams[stream_id];
386 if (!st)
387 return AVERROR(ENOMEM);
388
389 class = ffio_read_varlen(bc);
390 tmp = get_fourcc(bc);
391 st->codecpar->codec_tag = tmp;
392 switch (class) {
393 case 0:
394 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
395 st->codecpar->codec_id = av_codec_get_id((const AVCodecTag * const []) {
396 ff_nut_video_tags,
397 ff_codec_bmp_tags,
398 ff_codec_movvideo_tags,
399 0
400 },
401 tmp);
402 break;
403 case 1:
404 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
405 st->codecpar->codec_id = av_codec_get_id((const AVCodecTag * const []) {
406 ff_nut_audio_tags,
407 ff_codec_wav_tags,
408 ff_nut_audio_extra_tags,
409 0
410 },
411 tmp);
412 break;
413 case 2:
414 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
415 st->codecpar->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
416 break;
417 case 3:
418 st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
419 st->codecpar->codec_id = ff_codec_get_id(ff_nut_data_tags, tmp);
420 break;
421 default:
422 av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
423 return AVERROR(ENOSYS);
424 }
425 if (class < 3 && st->codecpar->codec_id == AV_CODEC_ID_NONE)
426 av_log(s, AV_LOG_ERROR,
427 "Unknown codec tag '0x%04x' for stream number %d\n",
428 (unsigned int) tmp, stream_id);
429
430 GET_V(stc->time_base_id, tmp < nut->time_base_count);
431 GET_V(stc->msb_pts_shift, tmp < 16);
432 stc->max_pts_distance = ffio_read_varlen(bc);
433 GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
434 st->codecpar->video_delay = stc->decode_delay;
435 ffio_read_varlen(bc); // stream flags
436
437 GET_V(st->codecpar->extradata_size, tmp < (1 << 30));
438 if (st->codecpar->extradata_size) {
439 ret = ff_get_extradata(s, st->codecpar, bc,
440 st->codecpar->extradata_size);
441 if (ret < 0)
442 return ret;
443 }
444
445 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
446 GET_V(st->codecpar->width, tmp > 0);
447 GET_V(st->codecpar->height, tmp > 0);
448 st->sample_aspect_ratio.num = ffio_read_varlen(bc);
449 st->sample_aspect_ratio.den = ffio_read_varlen(bc);
450 if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
451 av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
452 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
453 ret = AVERROR_INVALIDDATA;
454 goto fail;
455 }
456 ffio_read_varlen(bc); /* csp type */
457 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
458 GET_V(st->codecpar->sample_rate, tmp > 0);
459 ffio_read_varlen(bc); // samplerate_den
460 GET_V(st->codecpar->channels, tmp > 0);
461 }
462 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
463 av_log(s, AV_LOG_ERROR,
464 "stream header %d checksum mismatch\n", stream_id);
465 ret = AVERROR_INVALIDDATA;
466 goto fail;
467 }
468 stc->time_base = &nut->time_base[stc->time_base_id];
469 avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
470 stc->time_base->den);
471 return 0;
472 fail:
473 if (st && st->codecpar) {
474 av_freep(&st->codecpar->extradata);
475 st->codecpar->extradata_size = 0;
476 }
477 return ret;
478 }
479
set_disposition_bits(AVFormatContext * avf,char * value,int stream_id)480 static void set_disposition_bits(AVFormatContext *avf, char *value,
481 int stream_id)
482 {
483 int flag = 0, i;
484
485 for (i = 0; ff_nut_dispositions[i].flag; ++i)
486 if (!strcmp(ff_nut_dispositions[i].str, value))
487 flag = ff_nut_dispositions[i].flag;
488 if (!flag)
489 av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
490 for (i = 0; i < avf->nb_streams; ++i)
491 if (stream_id == i || stream_id == -1)
492 avf->streams[i]->disposition |= flag;
493 }
494
decode_info_header(NUTContext * nut)495 static int decode_info_header(NUTContext *nut)
496 {
497 AVFormatContext *s = nut->avf;
498 AVIOContext *bc = s->pb;
499 uint64_t tmp, chapter_start, chapter_len;
500 unsigned int stream_id_plus1, count;
501 int i, ret = 0;
502 int64_t chapter_id, value, end;
503 char name[256], str_value[1024], type_str[256];
504 const char *type;
505 int *event_flags = NULL;
506 AVChapter *chapter = NULL;
507 AVStream *st = NULL;
508 AVDictionary **metadata = NULL;
509 int metadata_flag = 0;
510
511 end = get_packetheader(nut, bc, 1, INFO_STARTCODE);
512 end += avio_tell(bc);
513
514 GET_V(stream_id_plus1, tmp <= s->nb_streams);
515 chapter_id = get_s(bc);
516 chapter_start = ffio_read_varlen(bc);
517 chapter_len = ffio_read_varlen(bc);
518 count = ffio_read_varlen(bc);
519
520 if (chapter_id && !stream_id_plus1) {
521 int64_t start = chapter_start / nut->time_base_count;
522 chapter = avpriv_new_chapter(s, chapter_id,
523 nut->time_base[chapter_start %
524 nut->time_base_count],
525 start, start + chapter_len, NULL);
526 if (!chapter) {
527 av_log(s, AV_LOG_ERROR, "Could not create chapter.\n");
528 return AVERROR(ENOMEM);
529 }
530 metadata = &chapter->metadata;
531 } else if (stream_id_plus1) {
532 st = s->streams[stream_id_plus1 - 1];
533 metadata = &st->metadata;
534 event_flags = &st->event_flags;
535 metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
536 } else {
537 metadata = &s->metadata;
538 event_flags = &s->event_flags;
539 metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;
540 }
541
542 for (i = 0; i < count; i++) {
543 ret = get_str(bc, name, sizeof(name));
544 if (ret < 0) {
545 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
546 return ret;
547 }
548 value = get_s(bc);
549 str_value[0] = 0;
550
551 if (value == -1) {
552 type = "UTF-8";
553 ret = get_str(bc, str_value, sizeof(str_value));
554 } else if (value == -2) {
555 ret = get_str(bc, type_str, sizeof(type_str));
556 if (ret < 0) {
557 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
558 return ret;
559 }
560 type = type_str;
561 ret = get_str(bc, str_value, sizeof(str_value));
562 } else if (value == -3) {
563 type = "s";
564 value = get_s(bc);
565 } else if (value == -4) {
566 type = "t";
567 value = ffio_read_varlen(bc);
568 } else if (value < -4) {
569 type = "r";
570 get_s(bc);
571 } else {
572 type = "v";
573 }
574
575 if (ret < 0) {
576 av_log(s, AV_LOG_ERROR, "get_str failed while decoding info header\n");
577 return ret;
578 }
579
580 if (stream_id_plus1 > s->nb_streams) {
581 av_log(s, AV_LOG_WARNING,
582 "invalid stream id %d for info packet\n",
583 stream_id_plus1);
584 continue;
585 }
586
587 if (!strcmp(type, "UTF-8")) {
588 if (chapter_id == 0 && !strcmp(name, "Disposition")) {
589 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
590 continue;
591 }
592
593 if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
594 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
595 if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den ||
596 st->r_frame_rate.num < 0 || st->r_frame_rate.den < 0)
597 st->r_frame_rate.num = st->r_frame_rate.den = 0;
598 continue;
599 }
600
601 if (metadata && av_strcasecmp(name, "Uses") &&
602 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {
603 if (event_flags)
604 *event_flags |= metadata_flag;
605 av_dict_set(metadata, name, str_value, 0);
606 }
607 }
608 }
609
610 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
611 av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
612 return AVERROR_INVALIDDATA;
613 }
614 fail:
615 return FFMIN(ret, 0);
616 }
617
decode_syncpoint(NUTContext * nut,int64_t * ts,int64_t * back_ptr)618 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
619 {
620 AVFormatContext *s = nut->avf;
621 AVIOContext *bc = s->pb;
622 int64_t end;
623 uint64_t tmp;
624 int ret;
625
626 nut->last_syncpoint_pos = avio_tell(bc) - 8;
627
628 end = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
629 end += avio_tell(bc);
630
631 tmp = ffio_read_varlen(bc);
632 *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
633 if (*back_ptr < 0)
634 return AVERROR_INVALIDDATA;
635
636 ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
637 tmp / nut->time_base_count);
638
639 if (nut->flags & NUT_BROADCAST) {
640 tmp = ffio_read_varlen(bc);
641 av_log(s, AV_LOG_VERBOSE, "Syncpoint wallclock %"PRId64"\n",
642 av_rescale_q(tmp / nut->time_base_count,
643 nut->time_base[tmp % nut->time_base_count],
644 AV_TIME_BASE_Q));
645 }
646
647 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
648 av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
649 return AVERROR_INVALIDDATA;
650 }
651
652 *ts = tmp / nut->time_base_count *
653 av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
654
655 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts)) < 0)
656 return ret;
657
658 return 0;
659 }
660
661 //FIXME calculate exactly, this is just a good approximation.
find_duration(NUTContext * nut,int64_t filesize)662 static int64_t find_duration(NUTContext *nut, int64_t filesize)
663 {
664 AVFormatContext *s = nut->avf;
665 int64_t duration = 0;
666
667 ff_find_last_ts(s, -1, &duration, NULL, nut_read_timestamp);
668
669 if(duration > 0)
670 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
671 return duration;
672 }
673
find_and_decode_index(NUTContext * nut)674 static int find_and_decode_index(NUTContext *nut)
675 {
676 AVFormatContext *s = nut->avf;
677 AVIOContext *bc = s->pb;
678 uint64_t tmp, end;
679 int i, j, syncpoint_count;
680 int64_t filesize = avio_size(bc);
681 int64_t *syncpoints = NULL;
682 uint64_t max_pts;
683 int8_t *has_keyframe = NULL;
684 int ret = AVERROR_INVALIDDATA;
685
686 if(filesize <= 0)
687 return -1;
688
689 avio_seek(bc, filesize - 12, SEEK_SET);
690 avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
691 if (avio_rb64(bc) != INDEX_STARTCODE) {
692 av_log(s, AV_LOG_WARNING, "no index at the end\n");
693
694 if(s->duration<=0)
695 s->duration = find_duration(nut, filesize);
696 return ret;
697 }
698
699 end = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
700 end += avio_tell(bc);
701
702 max_pts = ffio_read_varlen(bc);
703 s->duration = av_rescale_q(max_pts / nut->time_base_count,
704 nut->time_base[max_pts % nut->time_base_count],
705 AV_TIME_BASE_Q);
706 s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
707
708 GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
709 syncpoints = av_malloc_array(syncpoint_count, sizeof(int64_t));
710 has_keyframe = av_malloc_array(syncpoint_count + 1, sizeof(int8_t));
711 if (!syncpoints || !has_keyframe) {
712 ret = AVERROR(ENOMEM);
713 goto fail;
714 }
715 for (i = 0; i < syncpoint_count; i++) {
716 syncpoints[i] = ffio_read_varlen(bc);
717 if (syncpoints[i] <= 0)
718 goto fail;
719 if (i)
720 syncpoints[i] += syncpoints[i - 1];
721 }
722
723 for (i = 0; i < s->nb_streams; i++) {
724 int64_t last_pts = -1;
725 for (j = 0; j < syncpoint_count;) {
726 uint64_t x = ffio_read_varlen(bc);
727 int type = x & 1;
728 int n = j;
729 x >>= 1;
730 if (type) {
731 int flag = x & 1;
732 x >>= 1;
733 if (n + x >= syncpoint_count + 1) {
734 av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
735 goto fail;
736 }
737 while (x--)
738 has_keyframe[n++] = flag;
739 has_keyframe[n++] = !flag;
740 } else {
741 if (x <= 1) {
742 av_log(s, AV_LOG_ERROR, "index: x %"PRIu64" is invalid\n", x);
743 goto fail;
744 }
745 while (x != 1) {
746 if (n >= syncpoint_count + 1) {
747 av_log(s, AV_LOG_ERROR, "index overflow B\n");
748 goto fail;
749 }
750 has_keyframe[n++] = x & 1;
751 x >>= 1;
752 }
753 }
754 if (has_keyframe[0]) {
755 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
756 goto fail;
757 }
758 av_assert0(n <= syncpoint_count + 1);
759 for (; j < n && j < syncpoint_count; j++) {
760 if (has_keyframe[j]) {
761 uint64_t B, A = ffio_read_varlen(bc);
762 if (!A) {
763 A = ffio_read_varlen(bc);
764 B = ffio_read_varlen(bc);
765 // eor_pts[j][i] = last_pts + A + B
766 } else
767 B = 0;
768 av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
769 last_pts + A, 0, 0, AVINDEX_KEYFRAME);
770 last_pts += A + B;
771 }
772 }
773 }
774 }
775
776 if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
777 av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
778 goto fail;
779 }
780 ret = 0;
781
782 fail:
783 av_free(syncpoints);
784 av_free(has_keyframe);
785 return ret;
786 }
787
nut_read_close(AVFormatContext * s)788 static int nut_read_close(AVFormatContext *s)
789 {
790 NUTContext *nut = s->priv_data;
791 int i;
792
793 av_freep(&nut->time_base);
794 av_freep(&nut->stream);
795 ff_nut_free_sp(nut);
796 for (i = 1; i < nut->header_count; i++)
797 av_freep(&nut->header[i]);
798
799 return 0;
800 }
801
nut_read_header(AVFormatContext * s)802 static int nut_read_header(AVFormatContext *s)
803 {
804 NUTContext *nut = s->priv_data;
805 AVIOContext *bc = s->pb;
806 int64_t pos;
807 int initialized_stream_count, ret;
808
809 nut->avf = s;
810
811 /* main header */
812 pos = 0;
813 ret = 0;
814 do {
815 if (ret == AVERROR(ENOMEM))
816 return ret;
817
818 pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
819 if (pos < 0 + 1) {
820 av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
821 goto fail;
822 }
823 } while ((ret = decode_main_header(nut)) < 0);
824
825 /* stream headers */
826 pos = 0;
827 for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
828 pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
829 if (pos < 0 + 1) {
830 av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
831 goto fail;
832 }
833 if (decode_stream_header(nut) >= 0)
834 initialized_stream_count++;
835 }
836
837 /* info headers */
838 pos = 0;
839 for (;;) {
840 uint64_t startcode = find_any_startcode(bc, pos);
841 pos = avio_tell(bc);
842
843 if (startcode == 0) {
844 av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
845 goto fail;
846 } else if (startcode == SYNCPOINT_STARTCODE) {
847 nut->next_startcode = startcode;
848 break;
849 } else if (startcode != INFO_STARTCODE) {
850 continue;
851 }
852
853 decode_info_header(nut);
854 }
855
856 s->internal->data_offset = pos - 8;
857
858 if (bc->seekable & AVIO_SEEKABLE_NORMAL) {
859 int64_t orig_pos = avio_tell(bc);
860 find_and_decode_index(nut);
861 avio_seek(bc, orig_pos, SEEK_SET);
862 }
863 av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
864
865 ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
866
867 return 0;
868
869 fail:
870 nut_read_close(s);
871
872 return AVERROR_INVALIDDATA;
873 }
874
read_sm_data(AVFormatContext * s,AVIOContext * bc,AVPacket * pkt,int is_meta,int64_t maxpos)875 static int read_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta, int64_t maxpos)
876 {
877 int count = ffio_read_varlen(bc);
878 int skip_start = 0;
879 int skip_end = 0;
880 int channels = 0;
881 int64_t channel_layout = 0;
882 int sample_rate = 0;
883 int width = 0;
884 int height = 0;
885 int i, ret;
886
887 for (i=0; i<count; i++) {
888 uint8_t name[256], str_value[256], type_str[256];
889 int value;
890 if (avio_tell(bc) >= maxpos)
891 return AVERROR_INVALIDDATA;
892 ret = get_str(bc, name, sizeof(name));
893 if (ret < 0) {
894 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
895 return ret;
896 }
897 value = get_s(bc);
898
899 if (value == -1) {
900 ret = get_str(bc, str_value, sizeof(str_value));
901 if (ret < 0) {
902 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
903 return ret;
904 }
905 av_log(s, AV_LOG_WARNING, "Unknown string %s / %s\n", name, str_value);
906 } else if (value == -2) {
907 uint8_t *dst = NULL;
908 int64_t v64, value_len;
909
910 ret = get_str(bc, type_str, sizeof(type_str));
911 if (ret < 0) {
912 av_log(s, AV_LOG_ERROR, "get_str failed while reading sm data\n");
913 return ret;
914 }
915 value_len = ffio_read_varlen(bc);
916 if (value_len < 0 || value_len >= maxpos - avio_tell(bc))
917 return AVERROR_INVALIDDATA;
918 if (!strcmp(name, "Palette")) {
919 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, value_len);
920 } else if (!strcmp(name, "Extradata")) {
921 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, value_len);
922 } else if (sscanf(name, "CodecSpecificSide%"SCNd64"", &v64) == 1) {
923 dst = av_packet_new_side_data(pkt, AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, value_len + 8);
924 if(!dst)
925 return AVERROR(ENOMEM);
926 AV_WB64(dst, v64);
927 dst += 8;
928 } else if (!strcmp(name, "ChannelLayout") && value_len == 8) {
929 channel_layout = avio_rl64(bc);
930 continue;
931 } else {
932 av_log(s, AV_LOG_WARNING, "Unknown data %s / %s\n", name, type_str);
933 avio_skip(bc, value_len);
934 continue;
935 }
936 if(!dst)
937 return AVERROR(ENOMEM);
938 avio_read(bc, dst, value_len);
939 } else if (value == -3) {
940 value = get_s(bc);
941 } else if (value == -4) {
942 value = ffio_read_varlen(bc);
943 } else if (value < -4) {
944 get_s(bc);
945 } else {
946 if (!strcmp(name, "SkipStart")) {
947 skip_start = value;
948 } else if (!strcmp(name, "SkipEnd")) {
949 skip_end = value;
950 } else if (!strcmp(name, "Channels")) {
951 channels = value;
952 } else if (!strcmp(name, "SampleRate")) {
953 sample_rate = value;
954 } else if (!strcmp(name, "Width")) {
955 width = value;
956 } else if (!strcmp(name, "Height")) {
957 height = value;
958 } else {
959 av_log(s, AV_LOG_WARNING, "Unknown integer %s\n", name);
960 }
961 }
962 }
963
964 if (channels || channel_layout || sample_rate || width || height) {
965 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_PARAM_CHANGE, 28);
966 if (!dst)
967 return AVERROR(ENOMEM);
968 bytestream_put_le32(&dst,
969 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT*(!!channels) +
970 AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT*(!!channel_layout) +
971 AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE*(!!sample_rate) +
972 AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS*(!!(width|height))
973 );
974 if (channels)
975 bytestream_put_le32(&dst, channels);
976 if (channel_layout)
977 bytestream_put_le64(&dst, channel_layout);
978 if (sample_rate)
979 bytestream_put_le32(&dst, sample_rate);
980 if (width || height){
981 bytestream_put_le32(&dst, width);
982 bytestream_put_le32(&dst, height);
983 }
984 }
985
986 if (skip_start || skip_end) {
987 uint8_t *dst = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
988 if (!dst)
989 return AVERROR(ENOMEM);
990 AV_WL32(dst, skip_start);
991 AV_WL32(dst+4, skip_end);
992 }
993
994 if (avio_tell(bc) >= maxpos)
995 return AVERROR_INVALIDDATA;
996
997 return 0;
998 }
999
decode_frame_header(NUTContext * nut,int64_t * pts,int * stream_id,uint8_t * header_idx,int frame_code)1000 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
1001 uint8_t *header_idx, int frame_code)
1002 {
1003 AVFormatContext *s = nut->avf;
1004 AVIOContext *bc = s->pb;
1005 StreamContext *stc;
1006 int size, flags, size_mul, pts_delta, i, reserved_count, ret;
1007 uint64_t tmp;
1008
1009 if (!(nut->flags & NUT_PIPE) &&
1010 avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
1011 av_log(s, AV_LOG_ERROR,
1012 "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
1013 avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
1014 return AVERROR_INVALIDDATA;
1015 }
1016
1017 flags = nut->frame_code[frame_code].flags;
1018 size_mul = nut->frame_code[frame_code].size_mul;
1019 size = nut->frame_code[frame_code].size_lsb;
1020 *stream_id = nut->frame_code[frame_code].stream_id;
1021 pts_delta = nut->frame_code[frame_code].pts_delta;
1022 reserved_count = nut->frame_code[frame_code].reserved_count;
1023 *header_idx = nut->frame_code[frame_code].header_idx;
1024
1025 if (flags & FLAG_INVALID)
1026 return AVERROR_INVALIDDATA;
1027 if (flags & FLAG_CODED)
1028 flags ^= ffio_read_varlen(bc);
1029 if (flags & FLAG_STREAM_ID) {
1030 GET_V(*stream_id, tmp < s->nb_streams);
1031 }
1032 stc = &nut->stream[*stream_id];
1033 if (flags & FLAG_CODED_PTS) {
1034 int64_t coded_pts = ffio_read_varlen(bc);
1035 // FIXME check last_pts validity?
1036 if (coded_pts < (1LL << stc->msb_pts_shift)) {
1037 *pts = ff_lsb2full(stc, coded_pts);
1038 } else
1039 *pts = coded_pts - (1LL << stc->msb_pts_shift);
1040 } else
1041 *pts = stc->last_pts + pts_delta;
1042 if (flags & FLAG_SIZE_MSB)
1043 size += size_mul * ffio_read_varlen(bc);
1044 if (flags & FLAG_MATCH_TIME)
1045 get_s(bc);
1046 if (flags & FLAG_HEADER_IDX)
1047 *header_idx = ffio_read_varlen(bc);
1048 if (flags & FLAG_RESERVED)
1049 reserved_count = ffio_read_varlen(bc);
1050 for (i = 0; i < reserved_count; i++) {
1051 if (bc->eof_reached) {
1052 av_log(s, AV_LOG_ERROR, "reached EOF while decoding frame header\n");
1053 return AVERROR_INVALIDDATA;
1054 }
1055 ffio_read_varlen(bc);
1056 }
1057
1058 if (*header_idx >= (unsigned)nut->header_count) {
1059 av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
1060 return AVERROR_INVALIDDATA;
1061 }
1062 if (size > 4096)
1063 *header_idx = 0;
1064 size -= nut->header_len[*header_idx];
1065
1066 if (flags & FLAG_CHECKSUM) {
1067 avio_rb32(bc); // FIXME check this
1068 } else if (!(nut->flags & NUT_PIPE) &&
1069 size > 2 * nut->max_distance ||
1070 FFABS(stc->last_pts - *pts) > stc->max_pts_distance) {
1071 av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
1072 return AVERROR_INVALIDDATA;
1073 }
1074
1075 stc->last_pts = *pts;
1076 stc->last_flags = flags;
1077
1078 return size;
1079 fail:
1080 return ret;
1081 }
1082
decode_frame(NUTContext * nut,AVPacket * pkt,int frame_code)1083 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
1084 {
1085 AVFormatContext *s = nut->avf;
1086 AVIOContext *bc = s->pb;
1087 int size, stream_id, discard, ret;
1088 int64_t pts, last_IP_pts;
1089 StreamContext *stc;
1090 uint8_t header_idx;
1091
1092 size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
1093 if (size < 0)
1094 return size;
1095
1096 stc = &nut->stream[stream_id];
1097
1098 if (stc->last_flags & FLAG_KEY)
1099 stc->skip_until_key_frame = 0;
1100
1101 discard = s->streams[stream_id]->discard;
1102 last_IP_pts = s->streams[stream_id]->last_IP_pts;
1103 if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
1104 (discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE &&
1105 last_IP_pts > pts) ||
1106 discard >= AVDISCARD_ALL ||
1107 stc->skip_until_key_frame) {
1108 avio_skip(bc, size);
1109 return 1;
1110 }
1111
1112 ret = av_new_packet(pkt, size + nut->header_len[header_idx]);
1113 if (ret < 0)
1114 return ret;
1115 if (nut->header[header_idx])
1116 memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
1117 pkt->pos = avio_tell(bc); // FIXME
1118 if (stc->last_flags & FLAG_SM_DATA) {
1119 int sm_size;
1120 if (read_sm_data(s, bc, pkt, 0, pkt->pos + size) < 0) {
1121 ret = AVERROR_INVALIDDATA;
1122 goto fail;
1123 }
1124 if (read_sm_data(s, bc, pkt, 1, pkt->pos + size) < 0) {
1125 ret = AVERROR_INVALIDDATA;
1126 goto fail;
1127 }
1128 sm_size = avio_tell(bc) - pkt->pos;
1129 size -= sm_size;
1130 pkt->size -= sm_size;
1131 }
1132
1133 ret = avio_read(bc, pkt->data + nut->header_len[header_idx], size);
1134 if (ret != size) {
1135 if (ret < 0)
1136 goto fail;
1137 }
1138 av_shrink_packet(pkt, nut->header_len[header_idx] + ret);
1139
1140 pkt->stream_index = stream_id;
1141 if (stc->last_flags & FLAG_KEY)
1142 pkt->flags |= AV_PKT_FLAG_KEY;
1143 pkt->pts = pts;
1144
1145 return 0;
1146 fail:
1147 av_packet_unref(pkt);
1148 return ret;
1149 }
1150
nut_read_packet(AVFormatContext * s,AVPacket * pkt)1151 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1152 {
1153 NUTContext *nut = s->priv_data;
1154 AVIOContext *bc = s->pb;
1155 int i, frame_code = 0, ret, skip;
1156 int64_t ts, back_ptr;
1157
1158 for (;;) {
1159 int64_t pos = avio_tell(bc);
1160 uint64_t tmp = nut->next_startcode;
1161 nut->next_startcode = 0;
1162
1163 if (tmp) {
1164 pos -= 8;
1165 } else {
1166 frame_code = avio_r8(bc);
1167 if (avio_feof(bc))
1168 return AVERROR_EOF;
1169 if (frame_code == 'N') {
1170 tmp = frame_code;
1171 for (i = 1; i < 8; i++)
1172 tmp = (tmp << 8) + avio_r8(bc);
1173 }
1174 }
1175 switch (tmp) {
1176 case MAIN_STARTCODE:
1177 case STREAM_STARTCODE:
1178 case INDEX_STARTCODE:
1179 skip = get_packetheader(nut, bc, 0, tmp);
1180 avio_skip(bc, skip);
1181 break;
1182 case INFO_STARTCODE:
1183 if (decode_info_header(nut) < 0)
1184 goto resync;
1185 break;
1186 case SYNCPOINT_STARTCODE:
1187 if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
1188 goto resync;
1189 frame_code = avio_r8(bc);
1190 case 0:
1191 ret = decode_frame(nut, pkt, frame_code);
1192 if (ret == 0)
1193 return 0;
1194 else if (ret == 1) // OK but discard packet
1195 break;
1196 default:
1197 resync:
1198 av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
1199 tmp = find_any_startcode(bc, FFMAX(nut->last_syncpoint_pos, nut->last_resync_pos) + 1);
1200 nut->last_resync_pos = avio_tell(bc);
1201 if (tmp == 0)
1202 return AVERROR_INVALIDDATA;
1203 av_log(s, AV_LOG_DEBUG, "sync\n");
1204 nut->next_startcode = tmp;
1205 }
1206 }
1207 }
1208
nut_read_timestamp(AVFormatContext * s,int stream_index,int64_t * pos_arg,int64_t pos_limit)1209 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
1210 int64_t *pos_arg, int64_t pos_limit)
1211 {
1212 NUTContext *nut = s->priv_data;
1213 AVIOContext *bc = s->pb;
1214 int64_t pos, pts, back_ptr;
1215 av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
1216 stream_index, *pos_arg, pos_limit);
1217
1218 pos = *pos_arg;
1219 do {
1220 pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
1221 if (pos < 1) {
1222 av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
1223 return AV_NOPTS_VALUE;
1224 }
1225 } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
1226 *pos_arg = pos - 1;
1227 av_assert0(nut->last_syncpoint_pos == *pos_arg);
1228
1229 av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
1230 if (stream_index == -2)
1231 return back_ptr;
1232 av_assert0(stream_index == -1);
1233 return pts;
1234 }
1235
read_seek(AVFormatContext * s,int stream_index,int64_t pts,int flags)1236 static int read_seek(AVFormatContext *s, int stream_index,
1237 int64_t pts, int flags)
1238 {
1239 NUTContext *nut = s->priv_data;
1240 AVStream *st = s->streams[stream_index];
1241 Syncpoint dummy = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
1242 Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
1243 Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
1244 int64_t pos, pos2, ts;
1245 int i;
1246
1247 if (nut->flags & NUT_PIPE) {
1248 return AVERROR(ENOSYS);
1249 }
1250
1251 if (st->index_entries) {
1252 int index = av_index_search_timestamp(st, pts, flags);
1253 if (index < 0)
1254 index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
1255 if (index < 0)
1256 return -1;
1257
1258 pos2 = st->index_entries[index].pos;
1259 ts = st->index_entries[index].timestamp;
1260 } else {
1261 av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pts_cmp,
1262 (void **) next_node);
1263 av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
1264 next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
1265 next_node[1]->ts);
1266 pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
1267 next_node[1]->pos, next_node[1]->pos,
1268 next_node[0]->ts, next_node[1]->ts,
1269 AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
1270 if (pos < 0)
1271 return pos;
1272
1273 if (!(flags & AVSEEK_FLAG_BACKWARD)) {
1274 dummy.pos = pos + 16;
1275 next_node[1] = &nopts_sp;
1276 av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
1277 (void **) next_node);
1278 pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
1279 next_node[1]->pos, next_node[1]->pos,
1280 next_node[0]->back_ptr, next_node[1]->back_ptr,
1281 flags, &ts, nut_read_timestamp);
1282 if (pos2 >= 0)
1283 pos = pos2;
1284 // FIXME dir but I think it does not matter
1285 }
1286 dummy.pos = pos;
1287 sp = av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp,
1288 NULL);
1289
1290 av_assert0(sp);
1291 pos2 = sp->back_ptr - 15;
1292 }
1293 av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1294 pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1295 avio_seek(s->pb, pos, SEEK_SET);
1296 nut->last_syncpoint_pos = pos;
1297 av_log(s, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1298 if (pos2 > pos || pos2 + 15 < pos)
1299 av_log(s, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1300 for (i = 0; i < s->nb_streams; i++)
1301 nut->stream[i].skip_until_key_frame = 1;
1302
1303 nut->last_resync_pos = 0;
1304
1305 return 0;
1306 }
1307
1308 AVInputFormat ff_nut_demuxer = {
1309 .name = "nut",
1310 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1311 .flags = AVFMT_SEEK_TO_PTS,
1312 .priv_data_size = sizeof(NUTContext),
1313 .read_probe = nut_probe,
1314 .read_header = nut_read_header,
1315 .read_packet = nut_read_packet,
1316 .read_close = nut_read_close,
1317 .read_seek = read_seek,
1318 .extensions = "nut",
1319 .codec_tag = ff_nut_codec_tags,
1320 };
1321