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