]> git.sesse.net Git - ffmpeg/blob - libavformat/nutdec.c
Merge commit '1f3f896564501c23b44fcf605567c78ce066b539'
[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/mathematics.h"
28 #include "libavutil/tree.h"
29 #include "avio_internal.h"
30 #include "nut.h"
31
32 #define NUT_MAX_STREAMS 256    /* arbitrary sanity check value */
33
34 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
35                                   int64_t *pos_arg, int64_t pos_limit);
36
37 static int get_str(AVIOContext *bc, char *string, unsigned int maxlen)
38 {
39     unsigned int len = ffio_read_varlen(bc);
40
41     if (len && maxlen)
42         avio_read(bc, string, FFMIN(len, maxlen));
43     while (len > maxlen) {
44         avio_r8(bc);
45         len--;
46     }
47
48     if (maxlen)
49         string[FFMIN(len, maxlen - 1)] = 0;
50
51     if (maxlen == len)
52         return -1;
53     else
54         return 0;
55 }
56
57 static int64_t get_s(AVIOContext *bc)
58 {
59     int64_t v = ffio_read_varlen(bc) + 1;
60
61     if (v & 1)
62         return -(v >> 1);
63     else
64         return  (v >> 1);
65 }
66
67 static uint64_t get_fourcc(AVIOContext *bc)
68 {
69     unsigned int len = ffio_read_varlen(bc);
70
71     if (len == 2)
72         return avio_rl16(bc);
73     else if (len == 4)
74         return avio_rl32(bc);
75     else
76         return -1;
77 }
78
79 #ifdef TRACE
80 static inline uint64_t get_v_trace(AVIOContext *bc, const char *file,
81                                    const char *func, int line)
82 {
83     uint64_t v = ffio_read_varlen(bc);
84
85     av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n",
86            v, v, file, func, line);
87     return v;
88 }
89
90 static inline int64_t get_s_trace(AVIOContext *bc, const char *file,
91                                   const char *func, int line)
92 {
93     int64_t v = get_s(bc);
94
95     av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n",
96            v, v, file, func, line);
97     return v;
98 }
99
100 static inline uint64_t get_4cc_trace(AVIOContext *bc, char *file,
101                                     char *func, int line)
102 {
103     uint64_t v = get_fourcc(bc);
104
105     av_log(NULL, AV_LOG_DEBUG, "get_fourcc %5"PRId64" / %"PRIX64" in %s %s:%d\n",
106            v, v, file, func, line);
107     return v;
108 }
109 #define ffio_read_varlen(bc) get_v_trace(bc,  __FILE__, __PRETTY_FUNCTION__, __LINE__)
110 #define get_s(bc)            get_s_trace(bc,  __FILE__, __PRETTY_FUNCTION__, __LINE__)
111 #define get_fourcc(bc)       get_4cc_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
112 #endif
113
114 static int get_packetheader(NUTContext *nut, AVIOContext *bc,
115                             int calculate_checksum, uint64_t startcode)
116 {
117     int64_t size;
118 //    start = avio_tell(bc) - 8;
119
120     startcode = av_be2ne64(startcode);
121     startcode = ff_crc04C11DB7_update(0, (uint8_t*) &startcode, 8);
122
123     ffio_init_checksum(bc, ff_crc04C11DB7_update, startcode);
124     size = ffio_read_varlen(bc);
125     if (size > 4096)
126         avio_rb32(bc);
127     if (ffio_get_checksum(bc) && size > 4096)
128         return -1;
129
130     ffio_init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
131
132     return size;
133 }
134
135 static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos)
136 {
137     uint64_t state = 0;
138
139     if (pos >= 0)
140         /* Note, this may fail if the stream is not seekable, but that should
141          * not matter, as in this case we simply start where we currently are */
142         avio_seek(bc, pos, SEEK_SET);
143     while (!url_feof(bc)) {
144         state = (state << 8) | avio_r8(bc);
145         if ((state >> 56) != 'N')
146             continue;
147         switch (state) {
148         case MAIN_STARTCODE:
149         case STREAM_STARTCODE:
150         case SYNCPOINT_STARTCODE:
151         case INFO_STARTCODE:
152         case INDEX_STARTCODE:
153             return state;
154         }
155     }
156
157     return 0;
158 }
159
160 /**
161  * Find the given startcode.
162  * @param code the startcode
163  * @param pos the start position of the search, or -1 if the current position
164  * @return the position of the startcode or -1 if not found
165  */
166 static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos)
167 {
168     for (;;) {
169         uint64_t startcode = find_any_startcode(bc, pos);
170         if (startcode == code)
171             return avio_tell(bc) - 8;
172         else if (startcode == 0)
173             return -1;
174         pos = -1;
175     }
176 }
177
178 static int nut_probe(AVProbeData *p)
179 {
180     int i;
181     uint64_t code = 0;
182
183     for (i = 0; i < p->buf_size; i++) {
184         code = (code << 8) | p->buf[i];
185         if (code == MAIN_STARTCODE)
186             return AVPROBE_SCORE_MAX;
187     }
188     return 0;
189 }
190
191 #define GET_V(dst, check)                                                     \
192     do {                                                                      \
193         tmp = ffio_read_varlen(bc);                                           \
194         if (!(check)) {                                                       \
195             av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);  \
196             return -1;                                                        \
197         }                                                                     \
198         dst = tmp;                                                            \
199     } while (0)
200
201 static int skip_reserved(AVIOContext *bc, int64_t pos)
202 {
203     pos -= avio_tell(bc);
204     if (pos < 0) {
205         avio_seek(bc, pos, SEEK_CUR);
206         return -1;
207     } else {
208         while (pos--)
209             avio_r8(bc);
210         return 0;
211     }
212 }
213
214 static int decode_main_header(NUTContext *nut)
215 {
216     AVFormatContext *s = nut->avf;
217     AVIOContext *bc    = s->pb;
218     uint64_t tmp, end;
219     unsigned int stream_count;
220     int i, j, count;
221     int tmp_stream, tmp_mul, tmp_pts, tmp_size, tmp_res, tmp_head_idx;
222
223     end  = get_packetheader(nut, bc, 1, MAIN_STARTCODE);
224     end += avio_tell(bc);
225
226     GET_V(tmp, tmp >= 2 && tmp <= 3);
227     GET_V(stream_count, tmp > 0 && tmp <= NUT_MAX_STREAMS);
228
229     nut->max_distance = ffio_read_varlen(bc);
230     if (nut->max_distance > 65536) {
231         av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
232         nut->max_distance = 65536;
233     }
234
235     GET_V(nut->time_base_count, tmp > 0 && tmp < INT_MAX / sizeof(AVRational));
236     nut->time_base = av_malloc(nut->time_base_count * sizeof(AVRational));
237
238     for (i = 0; i < nut->time_base_count; i++) {
239         GET_V(nut->time_base[i].num, tmp > 0 && tmp < (1ULL << 31));
240         GET_V(nut->time_base[i].den, tmp > 0 && tmp < (1ULL << 31));
241         if (av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1) {
242             av_log(s, AV_LOG_ERROR, "time base invalid\n");
243             return AVERROR_INVALIDDATA;
244         }
245     }
246     tmp_pts      = 0;
247     tmp_mul      = 1;
248     tmp_stream   = 0;
249     tmp_head_idx = 0;
250     for (i = 0; i < 256;) {
251         int tmp_flags  = ffio_read_varlen(bc);
252         int tmp_fields = ffio_read_varlen(bc);
253
254         if (tmp_fields > 0)
255             tmp_pts = get_s(bc);
256         if (tmp_fields > 1)
257             tmp_mul = ffio_read_varlen(bc);
258         if (tmp_fields > 2)
259             tmp_stream = ffio_read_varlen(bc);
260         if (tmp_fields > 3)
261             tmp_size = ffio_read_varlen(bc);
262         else
263             tmp_size = 0;
264         if (tmp_fields > 4)
265             tmp_res = ffio_read_varlen(bc);
266         else
267             tmp_res = 0;
268         if (tmp_fields > 5)
269             count = ffio_read_varlen(bc);
270         else
271             count = tmp_mul - tmp_size;
272         if (tmp_fields > 6)
273             get_s(bc);
274         if (tmp_fields > 7)
275             tmp_head_idx = ffio_read_varlen(bc);
276
277         while (tmp_fields-- > 8)
278             ffio_read_varlen(bc);
279
280         if (count == 0 || i + count > 256) {
281             av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
282             return AVERROR_INVALIDDATA;
283         }
284         if (tmp_stream >= stream_count) {
285             av_log(s, AV_LOG_ERROR, "illegal stream number\n");
286             return AVERROR_INVALIDDATA;
287         }
288
289         for (j = 0; j < count; j++, i++) {
290             if (i == 'N') {
291                 nut->frame_code[i].flags = FLAG_INVALID;
292                 j--;
293                 continue;
294             }
295             nut->frame_code[i].flags          = tmp_flags;
296             nut->frame_code[i].pts_delta      = tmp_pts;
297             nut->frame_code[i].stream_id      = tmp_stream;
298             nut->frame_code[i].size_mul       = tmp_mul;
299             nut->frame_code[i].size_lsb       = tmp_size + j;
300             nut->frame_code[i].reserved_count = tmp_res;
301             nut->frame_code[i].header_idx     = tmp_head_idx;
302         }
303     }
304     av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
305
306     if (end > avio_tell(bc) + 4) {
307         int rem = 1024;
308         GET_V(nut->header_count, tmp < 128U);
309         nut->header_count++;
310         for (i = 1; i < nut->header_count; i++) {
311             uint8_t *hdr;
312             GET_V(nut->header_len[i], tmp > 0 && tmp < 256);
313             rem -= nut->header_len[i];
314             if (rem < 0) {
315                 av_log(s, AV_LOG_ERROR, "invalid elision header\n");
316                 return AVERROR_INVALIDDATA;
317             }
318             hdr = av_malloc(nut->header_len[i]);
319             if (!hdr)
320                 return AVERROR(ENOMEM);
321             avio_read(bc, hdr, nut->header_len[i]);
322             nut->header[i] = hdr;
323         }
324         av_assert0(nut->header_len[0] == 0);
325     }
326
327     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
328         av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
329         return AVERROR_INVALIDDATA;
330     }
331
332     nut->stream = av_mallocz(sizeof(StreamContext) * stream_count);
333     for (i = 0; i < stream_count; i++)
334         avformat_new_stream(s, NULL);
335
336     return 0;
337 }
338
339 static int decode_stream_header(NUTContext *nut)
340 {
341     AVFormatContext *s = nut->avf;
342     AVIOContext *bc    = s->pb;
343     StreamContext *stc;
344     int class, stream_id;
345     uint64_t tmp, end;
346     AVStream *st;
347
348     end  = get_packetheader(nut, bc, 1, STREAM_STARTCODE);
349     end += avio_tell(bc);
350
351     GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
352     stc = &nut->stream[stream_id];
353     st  = s->streams[stream_id];
354     if (!st)
355         return AVERROR(ENOMEM);
356
357     class                = ffio_read_varlen(bc);
358     tmp                  = get_fourcc(bc);
359     st->codec->codec_tag = tmp;
360     switch (class) {
361     case 0:
362         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
363         st->codec->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
364                                                     ff_nut_video_tags,
365                                                     ff_codec_bmp_tags,
366                                                     0
367                                                 },
368                                                 tmp);
369         break;
370     case 1:
371         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
372         st->codec->codec_id   = av_codec_get_id((const AVCodecTag * const []) {
373                                                     ff_nut_audio_tags,
374                                                     ff_codec_wav_tags,
375                                                     0
376                                                 },
377                                                 tmp);
378         break;
379     case 2:
380         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
381         st->codec->codec_id   = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
382         break;
383     case 3:
384         st->codec->codec_type = AVMEDIA_TYPE_DATA;
385         st->codec->codec_id   = ff_codec_get_id(ff_nut_data_tags, tmp);
386         break;
387     default:
388         av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
389         return -1;
390     }
391     if (class < 3 && st->codec->codec_id == AV_CODEC_ID_NONE)
392         av_log(s, AV_LOG_ERROR,
393                "Unknown codec tag '0x%04x' for stream number %d\n",
394                (unsigned int) tmp, stream_id);
395
396     GET_V(stc->time_base_id, tmp < nut->time_base_count);
397     GET_V(stc->msb_pts_shift, tmp < 16);
398     stc->max_pts_distance = ffio_read_varlen(bc);
399     GET_V(stc->decode_delay, tmp < 1000); // sanity limit, raise this if Moore's law is true
400     st->codec->has_b_frames = stc->decode_delay;
401     ffio_read_varlen(bc); // stream flags
402
403     GET_V(st->codec->extradata_size, tmp < (1 << 30));
404     if (st->codec->extradata_size) {
405         st->codec->extradata = av_mallocz(st->codec->extradata_size +
406                                           FF_INPUT_BUFFER_PADDING_SIZE);
407         avio_read(bc, st->codec->extradata, st->codec->extradata_size);
408     }
409
410     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
411         GET_V(st->codec->width,  tmp > 0);
412         GET_V(st->codec->height, tmp > 0);
413         st->sample_aspect_ratio.num = ffio_read_varlen(bc);
414         st->sample_aspect_ratio.den = ffio_read_varlen(bc);
415         if ((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)) {
416             av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n",
417                    st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
418             return -1;
419         }
420         ffio_read_varlen(bc); /* csp type */
421     } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
422         GET_V(st->codec->sample_rate, tmp > 0);
423         ffio_read_varlen(bc); // samplerate_den
424         GET_V(st->codec->channels, tmp > 0);
425     }
426     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
427         av_log(s, AV_LOG_ERROR,
428                "stream header %d checksum mismatch\n", stream_id);
429         return -1;
430     }
431     stc->time_base = &nut->time_base[stc->time_base_id];
432     avpriv_set_pts_info(s->streams[stream_id], 63, stc->time_base->num,
433                         stc->time_base->den);
434     return 0;
435 }
436
437 static void set_disposition_bits(AVFormatContext *avf, char *value,
438                                  int stream_id)
439 {
440     int flag = 0, i;
441
442     for (i = 0; ff_nut_dispositions[i].flag; ++i)
443         if (!strcmp(ff_nut_dispositions[i].str, value))
444             flag = ff_nut_dispositions[i].flag;
445     if (!flag)
446         av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
447     for (i = 0; i < avf->nb_streams; ++i)
448         if (stream_id == i || stream_id == -1)
449             avf->streams[i]->disposition |= flag;
450 }
451
452 static int decode_info_header(NUTContext *nut)
453 {
454     AVFormatContext *s = nut->avf;
455     AVIOContext *bc    = s->pb;
456     uint64_t tmp, chapter_start, chapter_len;
457     unsigned int stream_id_plus1, count;
458     int chapter_id, i;
459     int64_t value, end;
460     char name[256], str_value[1024], type_str[256];
461     const char *type;
462     AVChapter *chapter      = NULL;
463     AVStream *st            = NULL;
464     AVDictionary **metadata = NULL;
465
466     end  = get_packetheader(nut, bc, 1, INFO_STARTCODE);
467     end += avio_tell(bc);
468
469     GET_V(stream_id_plus1, tmp <= s->nb_streams);
470     chapter_id    = get_s(bc);
471     chapter_start = ffio_read_varlen(bc);
472     chapter_len   = ffio_read_varlen(bc);
473     count         = ffio_read_varlen(bc);
474
475     if (chapter_id && !stream_id_plus1) {
476         int64_t start = chapter_start / nut->time_base_count;
477         chapter = avpriv_new_chapter(s, chapter_id,
478                                      nut->time_base[chapter_start %
479                                                     nut->time_base_count],
480                                      start, start + chapter_len, NULL);
481         metadata = &chapter->metadata;
482     } else if (stream_id_plus1) {
483         st       = s->streams[stream_id_plus1 - 1];
484         metadata = &st->metadata;
485     } else
486         metadata = &s->metadata;
487
488     for (i = 0; i < count; i++) {
489         get_str(bc, name, sizeof(name));
490         value = get_s(bc);
491         if (value == -1) {
492             type = "UTF-8";
493             get_str(bc, str_value, sizeof(str_value));
494         } else if (value == -2) {
495             get_str(bc, type_str, sizeof(type_str));
496             type = type_str;
497             get_str(bc, str_value, sizeof(str_value));
498         } else if (value == -3) {
499             type  = "s";
500             value = get_s(bc);
501         } else if (value == -4) {
502             type  = "t";
503             value = ffio_read_varlen(bc);
504         } else if (value < -4) {
505             type = "r";
506             get_s(bc);
507         } else {
508             type = "v";
509         }
510
511         if (stream_id_plus1 > s->nb_streams) {
512             av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
513             continue;
514         }
515
516         if (!strcmp(type, "UTF-8")) {
517             if (chapter_id == 0 && !strcmp(name, "Disposition")) {
518                 set_disposition_bits(s, str_value, stream_id_plus1 - 1);
519                 continue;
520             }
521
522             if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {
523                 sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);
524                 continue;
525             }
526
527             if (metadata && av_strcasecmp(name, "Uses") &&
528                 av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces"))
529                 av_dict_set(metadata, name, str_value, 0);
530         }
531     }
532
533     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
534         av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
535         return -1;
536     }
537     return 0;
538 }
539
540 static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr)
541 {
542     AVFormatContext *s = nut->avf;
543     AVIOContext *bc    = s->pb;
544     int64_t end;
545     uint64_t tmp;
546
547     nut->last_syncpoint_pos = avio_tell(bc) - 8;
548
549     end  = get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
550     end += avio_tell(bc);
551
552     tmp       = ffio_read_varlen(bc);
553     *back_ptr = nut->last_syncpoint_pos - 16 * ffio_read_varlen(bc);
554     if (*back_ptr < 0)
555         return -1;
556
557     ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count],
558                     tmp / nut->time_base_count);
559
560     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
561         av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
562         return -1;
563     }
564
565     *ts = tmp / nut->time_base_count *
566           av_q2d(nut->time_base[tmp % nut->time_base_count]) * AV_TIME_BASE;
567     ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts);
568
569     return 0;
570 }
571
572 //FIXME calculate exactly, this is just a good approximation.
573 static int64_t find_duration(NUTContext *nut, int64_t filesize)
574 {
575     AVFormatContext *s = nut->avf;
576     int64_t duration = 0;
577
578     int64_t pos = FFMAX(0, filesize - 2*nut->max_distance);
579     for(;;){
580         int64_t ts = nut_read_timestamp(s, -1, &pos, INT64_MAX);
581         if(ts < 0)
582             break;
583         duration = FFMAX(duration, ts);
584         pos++;
585     }
586     if(duration > 0)
587         s->duration_estimation_method = AVFMT_DURATION_FROM_PTS;
588     return duration;
589 }
590
591 static int find_and_decode_index(NUTContext *nut)
592 {
593     AVFormatContext *s = nut->avf;
594     AVIOContext *bc    = s->pb;
595     uint64_t tmp, end;
596     int i, j, syncpoint_count;
597     int64_t filesize = avio_size(bc);
598     int64_t *syncpoints;
599     int8_t *has_keyframe;
600     int ret = -1;
601
602     if(filesize <= 0)
603         return -1;
604
605     avio_seek(bc, filesize - 12, SEEK_SET);
606     avio_seek(bc, filesize - avio_rb64(bc), SEEK_SET);
607     if (avio_rb64(bc) != INDEX_STARTCODE) {
608         av_log(s, AV_LOG_ERROR, "no index at the end\n");
609
610         if(s->duration<=0)
611             s->duration = find_duration(nut, filesize);
612         return -1;
613     }
614
615     end  = get_packetheader(nut, bc, 1, INDEX_STARTCODE);
616     end += avio_tell(bc);
617
618     ffio_read_varlen(bc); // max_pts
619     GET_V(syncpoint_count, tmp < INT_MAX / 8 && tmp > 0);
620     syncpoints   = av_malloc(sizeof(int64_t) *  syncpoint_count);
621     has_keyframe = av_malloc(sizeof(int8_t)  * (syncpoint_count + 1));
622     for (i = 0; i < syncpoint_count; i++) {
623         syncpoints[i] = ffio_read_varlen(bc);
624         if (syncpoints[i] <= 0)
625             goto fail;
626         if (i)
627             syncpoints[i] += syncpoints[i - 1];
628     }
629
630     for (i = 0; i < s->nb_streams; i++) {
631         int64_t last_pts = -1;
632         for (j = 0; j < syncpoint_count;) {
633             uint64_t x = ffio_read_varlen(bc);
634             int type   = x & 1;
635             int n      = j;
636             x >>= 1;
637             if (type) {
638                 int flag = x & 1;
639                 x >>= 1;
640                 if (n + x >= syncpoint_count + 1) {
641                     av_log(s, AV_LOG_ERROR, "index overflow A %d + %"PRIu64" >= %d\n", n, x, syncpoint_count + 1);
642                     goto fail;
643                 }
644                 while (x--)
645                     has_keyframe[n++] = flag;
646                 has_keyframe[n++] = !flag;
647             } else {
648                 while (x != 1) {
649                     if (n >= syncpoint_count + 1) {
650                         av_log(s, AV_LOG_ERROR, "index overflow B\n");
651                         goto fail;
652                     }
653                     has_keyframe[n++] = x & 1;
654                     x >>= 1;
655                 }
656             }
657             if (has_keyframe[0]) {
658                 av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
659                 goto fail;
660             }
661             av_assert0(n <= syncpoint_count + 1);
662             for (; j < n && j < syncpoint_count; j++) {
663                 if (has_keyframe[j]) {
664                     uint64_t B, A = ffio_read_varlen(bc);
665                     if (!A) {
666                         A = ffio_read_varlen(bc);
667                         B = ffio_read_varlen(bc);
668                         // eor_pts[j][i] = last_pts + A + B
669                     } else
670                         B = 0;
671                     av_add_index_entry(s->streams[i], 16 * syncpoints[j - 1],
672                                        last_pts + A, 0, 0, AVINDEX_KEYFRAME);
673                     last_pts += A + B;
674                 }
675             }
676         }
677     }
678
679     if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {
680         av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
681         goto fail;
682     }
683     ret = 0;
684
685 fail:
686     av_free(syncpoints);
687     av_free(has_keyframe);
688     return ret;
689 }
690
691 static int nut_read_header(AVFormatContext *s)
692 {
693     NUTContext *nut = s->priv_data;
694     AVIOContext *bc = s->pb;
695     int64_t pos;
696     int initialized_stream_count;
697
698     nut->avf = s;
699
700     /* main header */
701     pos = 0;
702     do {
703         pos = find_startcode(bc, MAIN_STARTCODE, pos) + 1;
704         if (pos < 0 + 1) {
705             av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
706             return AVERROR_INVALIDDATA;
707         }
708     } while (decode_main_header(nut) < 0);
709
710     /* stream headers */
711     pos = 0;
712     for (initialized_stream_count = 0; initialized_stream_count < s->nb_streams;) {
713         pos = find_startcode(bc, STREAM_STARTCODE, pos) + 1;
714         if (pos < 0 + 1) {
715             av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
716             return AVERROR_INVALIDDATA;
717         }
718         if (decode_stream_header(nut) >= 0)
719             initialized_stream_count++;
720     }
721
722     /* info headers */
723     pos = 0;
724     for (;;) {
725         uint64_t startcode = find_any_startcode(bc, pos);
726         pos = avio_tell(bc);
727
728         if (startcode == 0) {
729             av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
730             return AVERROR_INVALIDDATA;
731         } else if (startcode == SYNCPOINT_STARTCODE) {
732             nut->next_startcode = startcode;
733             break;
734         } else if (startcode != INFO_STARTCODE) {
735             continue;
736         }
737
738         decode_info_header(nut);
739     }
740
741     s->data_offset = pos - 8;
742
743     if (bc->seekable) {
744         int64_t orig_pos = avio_tell(bc);
745         find_and_decode_index(nut);
746         avio_seek(bc, orig_pos, SEEK_SET);
747     }
748     av_assert0(nut->next_startcode == SYNCPOINT_STARTCODE);
749
750     ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
751
752     return 0;
753 }
754
755 static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id,
756                                uint8_t *header_idx, int frame_code)
757 {
758     AVFormatContext *s = nut->avf;
759     AVIOContext *bc    = s->pb;
760     StreamContext *stc;
761     int size, flags, size_mul, pts_delta, i, reserved_count;
762     uint64_t tmp;
763
764     if (avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance) {
765         av_log(s, AV_LOG_ERROR,
766                "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n",
767                avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
768         return AVERROR_INVALIDDATA;
769     }
770
771     flags          = nut->frame_code[frame_code].flags;
772     size_mul       = nut->frame_code[frame_code].size_mul;
773     size           = nut->frame_code[frame_code].size_lsb;
774     *stream_id     = nut->frame_code[frame_code].stream_id;
775     pts_delta      = nut->frame_code[frame_code].pts_delta;
776     reserved_count = nut->frame_code[frame_code].reserved_count;
777     *header_idx    = nut->frame_code[frame_code].header_idx;
778
779     if (flags & FLAG_INVALID)
780         return AVERROR_INVALIDDATA;
781     if (flags & FLAG_CODED)
782         flags ^= ffio_read_varlen(bc);
783     if (flags & FLAG_STREAM_ID) {
784         GET_V(*stream_id, tmp < s->nb_streams);
785     }
786     stc = &nut->stream[*stream_id];
787     if (flags & FLAG_CODED_PTS) {
788         int coded_pts = ffio_read_varlen(bc);
789         // FIXME check last_pts validity?
790         if (coded_pts < (1 << stc->msb_pts_shift)) {
791             *pts = ff_lsb2full(stc, coded_pts);
792         } else
793             *pts = coded_pts - (1LL << stc->msb_pts_shift);
794     } else
795         *pts = stc->last_pts + pts_delta;
796     if (flags & FLAG_SIZE_MSB)
797         size += size_mul * ffio_read_varlen(bc);
798     if (flags & FLAG_MATCH_TIME)
799         get_s(bc);
800     if (flags & FLAG_HEADER_IDX)
801         *header_idx = ffio_read_varlen(bc);
802     if (flags & FLAG_RESERVED)
803         reserved_count = ffio_read_varlen(bc);
804     for (i = 0; i < reserved_count; i++)
805         ffio_read_varlen(bc);
806
807     if (*header_idx >= (unsigned)nut->header_count) {
808         av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
809         return AVERROR_INVALIDDATA;
810     }
811     if (size > 4096)
812         *header_idx = 0;
813     size -= nut->header_len[*header_idx];
814
815     if (flags & FLAG_CHECKSUM) {
816         avio_rb32(bc); // FIXME check this
817     } else if (size > 2 * nut->max_distance || FFABS(stc->last_pts - *pts) >
818                stc->max_pts_distance) {
819         av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
820         return AVERROR_INVALIDDATA;
821     }
822
823     stc->last_pts   = *pts;
824     stc->last_flags = flags;
825
826     return size;
827 }
828
829 static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code)
830 {
831     AVFormatContext *s = nut->avf;
832     AVIOContext *bc    = s->pb;
833     int size, stream_id, discard;
834     int64_t pts, last_IP_pts;
835     StreamContext *stc;
836     uint8_t header_idx;
837
838     size = decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
839     if (size < 0)
840         return size;
841
842     stc = &nut->stream[stream_id];
843
844     if (stc->last_flags & FLAG_KEY)
845         stc->skip_until_key_frame = 0;
846
847     discard     = s->streams[stream_id]->discard;
848     last_IP_pts = s->streams[stream_id]->last_IP_pts;
849     if ((discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY)) ||
850         (discard >= AVDISCARD_BIDIR  && last_IP_pts != AV_NOPTS_VALUE &&
851          last_IP_pts > pts) ||
852         discard >= AVDISCARD_ALL ||
853         stc->skip_until_key_frame) {
854         avio_skip(bc, size);
855         return 1;
856     }
857
858     if (av_new_packet(pkt, size + nut->header_len[header_idx]) < 0)
859         return AVERROR(ENOMEM);
860     memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
861     pkt->pos = avio_tell(bc); // FIXME
862     avio_read(bc, pkt->data + nut->header_len[header_idx], size);
863
864     pkt->stream_index = stream_id;
865     if (stc->last_flags & FLAG_KEY)
866         pkt->flags |= AV_PKT_FLAG_KEY;
867     pkt->pts = pts;
868
869     return 0;
870 }
871
872 static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
873 {
874     NUTContext *nut = s->priv_data;
875     AVIOContext *bc = s->pb;
876     int i, frame_code = 0, ret, skip;
877     int64_t ts, back_ptr;
878
879     for (;;) {
880         int64_t pos  = avio_tell(bc);
881         uint64_t tmp = nut->next_startcode;
882         nut->next_startcode = 0;
883
884         if (tmp) {
885             pos -= 8;
886         } else {
887             frame_code = avio_r8(bc);
888             if (url_feof(bc))
889                 return -1;
890             if (frame_code == 'N') {
891                 tmp = frame_code;
892                 for (i = 1; i < 8; i++)
893                     tmp = (tmp << 8) + avio_r8(bc);
894             }
895         }
896         switch (tmp) {
897         case MAIN_STARTCODE:
898         case STREAM_STARTCODE:
899         case INDEX_STARTCODE:
900             skip = get_packetheader(nut, bc, 0, tmp);
901             avio_skip(bc, skip);
902             break;
903         case INFO_STARTCODE:
904             if (decode_info_header(nut) < 0)
905                 goto resync;
906             break;
907         case SYNCPOINT_STARTCODE:
908             if (decode_syncpoint(nut, &ts, &back_ptr) < 0)
909                 goto resync;
910             frame_code = avio_r8(bc);
911         case 0:
912             ret = decode_frame(nut, pkt, frame_code);
913             if (ret == 0)
914                 return 0;
915             else if (ret == 1) // OK but discard packet
916                 break;
917         default:
918 resync:
919             av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
920             tmp = find_any_startcode(bc, nut->last_syncpoint_pos + 1);
921             if (tmp == 0)
922                 return AVERROR_INVALIDDATA;
923             av_log(s, AV_LOG_DEBUG, "sync\n");
924             nut->next_startcode = tmp;
925         }
926     }
927 }
928
929 static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index,
930                                   int64_t *pos_arg, int64_t pos_limit)
931 {
932     NUTContext *nut = s->priv_data;
933     AVIOContext *bc = s->pb;
934     int64_t pos, pts, back_ptr;
935     av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n",
936            stream_index, *pos_arg, pos_limit);
937
938     pos = *pos_arg;
939     do {
940         pos = find_startcode(bc, SYNCPOINT_STARTCODE, pos) + 1;
941         if (pos < 1) {
942             av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
943             return AV_NOPTS_VALUE;
944         }
945     } while (decode_syncpoint(nut, &pts, &back_ptr) < 0);
946     *pos_arg = pos - 1;
947     av_assert0(nut->last_syncpoint_pos == *pos_arg);
948
949     av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts, back_ptr);
950     if (stream_index == -2)
951         return back_ptr;
952     av_assert0(stream_index == -1);
953     return pts;
954 }
955
956 static int read_seek(AVFormatContext *s, int stream_index,
957                      int64_t pts, int flags)
958 {
959     NUTContext *nut    = s->priv_data;
960     AVStream *st       = s->streams[stream_index];
961     Syncpoint dummy    = { .ts = pts * av_q2d(st->time_base) * AV_TIME_BASE };
962     Syncpoint nopts_sp = { .ts = AV_NOPTS_VALUE, .back_ptr = AV_NOPTS_VALUE };
963     Syncpoint *sp, *next_node[2] = { &nopts_sp, &nopts_sp };
964     int64_t pos, pos2, ts;
965     int i;
966
967     if (st->index_entries) {
968         int index = av_index_search_timestamp(st, pts, flags);
969         if (index < 0)
970             index = av_index_search_timestamp(st, pts, flags ^ AVSEEK_FLAG_BACKWARD);
971         if (index < 0)
972             return -1;
973
974         pos2 = st->index_entries[index].pos;
975         ts   = st->index_entries[index].timestamp;
976     } else {
977         av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
978                      (void **) next_node);
979         av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n",
980                next_node[0]->pos, next_node[1]->pos, next_node[0]->ts,
981                next_node[1]->ts);
982         pos = ff_gen_search(s, -1, dummy.ts, next_node[0]->pos,
983                             next_node[1]->pos, next_node[1]->pos,
984                             next_node[0]->ts, next_node[1]->ts,
985                             AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
986
987         if (!(flags & AVSEEK_FLAG_BACKWARD)) {
988             dummy.pos    = pos + 16;
989             next_node[1] = &nopts_sp;
990             av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
991                          (void **) next_node);
992             pos2 = ff_gen_search(s, -2, dummy.pos, next_node[0]->pos,
993                                  next_node[1]->pos, next_node[1]->pos,
994                                  next_node[0]->back_ptr, next_node[1]->back_ptr,
995                                  flags, &ts, nut_read_timestamp);
996             if (pos2 >= 0)
997                 pos = pos2;
998             // FIXME dir but I think it does not matter
999         }
1000         dummy.pos = pos;
1001         sp = av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
1002                           NULL);
1003
1004         av_assert0(sp);
1005         pos2 = sp->back_ptr - 15;
1006     }
1007     av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
1008     pos = find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
1009     avio_seek(s->pb, pos, SEEK_SET);
1010     av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
1011     if (pos2 > pos || pos2 + 15 < pos)
1012         av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
1013     for (i = 0; i < s->nb_streams; i++)
1014         nut->stream[i].skip_until_key_frame = 1;
1015
1016     return 0;
1017 }
1018
1019 static int nut_read_close(AVFormatContext *s)
1020 {
1021     NUTContext *nut = s->priv_data;
1022     int i;
1023
1024     av_freep(&nut->time_base);
1025     av_freep(&nut->stream);
1026     ff_nut_free_sp(nut);
1027     for (i = 1; i < nut->header_count; i++)
1028         av_freep(&nut->header[i]);
1029
1030     return 0;
1031 }
1032
1033 AVInputFormat ff_nut_demuxer = {
1034     .name           = "nut",
1035     .long_name      = NULL_IF_CONFIG_SMALL("NUT"),
1036     .flags          = AVFMT_SEEK_TO_PTS,
1037     .priv_data_size = sizeof(NUTContext),
1038     .read_probe     = nut_probe,
1039     .read_header    = nut_read_header,
1040     .read_packet    = nut_read_packet,
1041     .read_close     = nut_read_close,
1042     .read_seek      = read_seek,
1043     .extensions     = "nut",
1044     .codec_tag      = ff_nut_codec_tags,
1045 };