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