OSDN Git Service

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