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