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