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