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