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