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