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