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