Statistics
| Branch: | Revision:

ffmpeg / libavformat / nutdec.c @ 4839c192

History | View | Annotate | Download (29.9 KB)

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 <strings.h>
24
#include "libavutil/avstring.h"
25
#include "libavutil/bswap.h"
26
#include "libavutil/tree.h"
27
#include "avio_internal.h"
28
#include "nut.h"
29

    
30
#undef NDEBUG
31
#include <assert.h>
32

    
33
#if FF_API_MAX_STREAMS
34
#define NUT_MAX_STREAMS MAX_STREAMS
35
#else
36
#define NUT_MAX_STREAMS 256    /* arbitrary sanity check value */
37
#endif
38

    
39
static int get_str(AVIOContext *bc, char *string, unsigned int maxlen){
40
    unsigned int len= ffio_read_varlen(bc);
41

    
42
    if(len && maxlen)
43
        avio_read(bc, string, FFMIN(len, maxlen));
44
    while(len > maxlen){
45
        avio_r8(bc);
46
        len--;
47
    }
48

    
49
    if(maxlen)
50
        string[FFMIN(len, maxlen-1)]= 0;
51

    
52
    if(maxlen == len)
53
        return -1;
54
    else
55
        return 0;
56
}
57

    
58
static int64_t get_s(AVIOContext *bc){
59
    int64_t v = ffio_read_varlen(bc) + 1;
60

    
61
    if (v&1) return -(v>>1);
62
    else     return  (v>>1);
63
}
64

    
65
static uint64_t get_fourcc(AVIOContext *bc){
66
    unsigned int len= ffio_read_varlen(bc);
67

    
68
    if     (len==2) return avio_rl16(bc);
69
    else if(len==4) return avio_rl32(bc);
70
    else            return -1;
71
}
72

    
73
#ifdef TRACE
74
static inline uint64_t get_v_trace(AVIOContext *bc, char *file, char *func, int line){
75
    uint64_t v= ffio_read_varlen(bc);
76

    
77
    av_log(NULL, AV_LOG_DEBUG, "get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
78
    return v;
79
}
80

    
81
static inline int64_t get_s_trace(AVIOContext *bc, char *file, char *func, int line){
82
    int64_t v= get_s(bc);
83

    
84
    av_log(NULL, AV_LOG_DEBUG, "get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
85
    return v;
86
}
87

    
88
static inline uint64_t get_vb_trace(AVIOContext *bc, char *file, char *func, int line){
89
    uint64_t v= get_vb(bc);
90

    
91
    av_log(NULL, AV_LOG_DEBUG, "get_vb %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
92
    return v;
93
}
94
#define ffio_read_varlen(bc)  get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
95
#define get_s(bc)  get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
96
#define get_vb(bc)  get_vb_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
97
#endif
98

    
99
static int get_packetheader(NUTContext *nut, AVIOContext *bc, int calculate_checksum, uint64_t startcode)
100
{
101
    int64_t size;
102
//    start= avio_tell(bc) - 8;
103

    
104
    startcode= av_be2ne64(startcode);
105
    startcode= ff_crc04C11DB7_update(0, (uint8_t*)&startcode, 8);
106

    
107
    init_checksum(bc, ff_crc04C11DB7_update, startcode);
108
    size= ffio_read_varlen(bc);
109
    if(size > 4096)
110
        avio_rb32(bc);
111
    if(get_checksum(bc) && size > 4096)
112
        return -1;
113

    
114
    init_checksum(bc, calculate_checksum ? ff_crc04C11DB7_update : NULL, 0);
115

    
116
    return size;
117
}
118

    
119
static uint64_t find_any_startcode(AVIOContext *bc, int64_t pos){
120
    uint64_t state=0;
121

    
122
    if(pos >= 0)
123
        avio_seek(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
124

    
125
    while(!bc->eof_reached){
126
        state= (state<<8) | avio_r8(bc);
127
        if((state>>56) != 'N')
128
            continue;
129
        switch(state){
130
        case MAIN_STARTCODE:
131
        case STREAM_STARTCODE:
132
        case SYNCPOINT_STARTCODE:
133
        case INFO_STARTCODE:
134
        case INDEX_STARTCODE:
135
            return state;
136
        }
137
    }
138

    
139
    return 0;
140
}
141

    
142
/**
143
 * Find the given startcode.
144
 * @param code the startcode
145
 * @param pos the start position of the search, or -1 if the current position
146
 * @return the position of the startcode or -1 if not found
147
 */
148
static int64_t find_startcode(AVIOContext *bc, uint64_t code, int64_t pos){
149
    for(;;){
150
        uint64_t startcode= find_any_startcode(bc, pos);
151
        if(startcode == code)
152
            return avio_tell(bc) - 8;
153
        else if(startcode == 0)
154
            return -1;
155
        pos=-1;
156
    }
157
}
158

    
159
static int nut_probe(AVProbeData *p){
160
    int i;
161
    uint64_t code= 0;
162

    
163
    for (i = 0; i < p->buf_size; i++) {
164
        code = (code << 8) | p->buf[i];
165
        if (code == MAIN_STARTCODE)
166
            return AVPROBE_SCORE_MAX;
167
    }
168
    return 0;
169
}
170

    
171
#define GET_V(dst, check) \
172
    tmp= ffio_read_varlen(bc);\
173
    if(!(check)){\
174
        av_log(s, AV_LOG_ERROR, "Error " #dst " is (%"PRId64")\n", tmp);\
175
        return -1;\
176
    }\
177
    dst= tmp;
178

    
179
static int skip_reserved(AVIOContext *bc, int64_t pos){
180
    pos -= avio_tell(bc);
181
    if(pos<0){
182
        avio_seek(bc, pos, SEEK_CUR);
183
        return -1;
184
    }else{
185
        while(pos--)
186
            avio_r8(bc);
187
        return 0;
188
    }
189
}
190

    
191
static int decode_main_header(NUTContext *nut){
192
    AVFormatContext *s= nut->avf;
193
    AVIOContext *bc = s->pb;
194
    uint64_t tmp, end;
195
    unsigned int stream_count;
196
    int i, j, tmp_stream, tmp_mul, tmp_pts, tmp_size, count, tmp_res, tmp_head_idx;
197
    int64_t tmp_match;
198

    
199
    end= get_packetheader(nut, bc, 1, MAIN_STARTCODE);
200
    end += avio_tell(bc);
201

    
202
    GET_V(tmp              , tmp >=2 && tmp <= 3)
203
    GET_V(stream_count     , tmp > 0 && tmp <= NUT_MAX_STREAMS)
204

    
205
    nut->max_distance = ffio_read_varlen(bc);
206
    if(nut->max_distance > 65536){
207
        av_log(s, AV_LOG_DEBUG, "max_distance %d\n", nut->max_distance);
208
        nut->max_distance= 65536;
209
    }
210

    
211
    GET_V(nut->time_base_count, tmp>0 && tmp<INT_MAX / sizeof(AVRational))
212
    nut->time_base= av_malloc(nut->time_base_count * sizeof(AVRational));
213

    
214
    for(i=0; i<nut->time_base_count; i++){
215
        GET_V(nut->time_base[i].num, tmp>0 && tmp<(1ULL<<31))
216
        GET_V(nut->time_base[i].den, tmp>0 && tmp<(1ULL<<31))
217
        if(av_gcd(nut->time_base[i].num, nut->time_base[i].den) != 1){
218
            av_log(s, AV_LOG_ERROR, "time base invalid\n");
219
            return AVERROR_INVALIDDATA;
220
        }
221
    }
222
    tmp_pts=0;
223
    tmp_mul=1;
224
    tmp_stream=0;
225
    tmp_match= 1-(1LL<<62);
226
    tmp_head_idx= 0;
227
    for(i=0; i<256;){
228
        int tmp_flags = ffio_read_varlen(bc);
229
        int tmp_fields= ffio_read_varlen(bc);
230
        if(tmp_fields>0) tmp_pts   = get_s(bc);
231
        if(tmp_fields>1) tmp_mul   = ffio_read_varlen(bc);
232
        if(tmp_fields>2) tmp_stream= ffio_read_varlen(bc);
233
        if(tmp_fields>3) tmp_size  = ffio_read_varlen(bc);
234
        else             tmp_size  = 0;
235
        if(tmp_fields>4) tmp_res   = ffio_read_varlen(bc);
236
        else             tmp_res   = 0;
237
        if(tmp_fields>5) count     = ffio_read_varlen(bc);
238
        else             count     = tmp_mul - tmp_size;
239
        if(tmp_fields>6) tmp_match = get_s(bc);
240
        if(tmp_fields>7) tmp_head_idx= ffio_read_varlen(bc);
241

    
242
        while(tmp_fields-- > 8)
243
           ffio_read_varlen(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 AVERROR_INVALIDDATA;
248
        }
249
        if(tmp_stream >= stream_count){
250
            av_log(s, AV_LOG_ERROR, "illegal stream number\n");
251
            return AVERROR_INVALIDDATA;
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
            nut->frame_code[i].header_idx      = tmp_head_idx;
267
        }
268
    }
269
    assert(nut->frame_code['N'].flags == FLAG_INVALID);
270

    
271
    if(end > avio_tell(bc) + 4){
272
        int rem= 1024;
273
        GET_V(nut->header_count, tmp<128U)
274
        nut->header_count++;
275
        for(i=1; i<nut->header_count; i++){
276
            GET_V(nut->header_len[i], tmp>0 && tmp<256);
277
            rem -= nut->header_len[i];
278
            if(rem < 0){
279
                av_log(s, AV_LOG_ERROR, "invalid elision header\n");
280
                return AVERROR_INVALIDDATA;
281
            }
282
            nut->header[i]= av_malloc(nut->header_len[i]);
283
            avio_read(bc, nut->header[i], nut->header_len[i]);
284
        }
285
        assert(nut->header_len[0]==0);
286
    }
287

    
288
    if(skip_reserved(bc, end) || get_checksum(bc)){
289
        av_log(s, AV_LOG_ERROR, "main header checksum mismatch\n");
290
        return AVERROR_INVALIDDATA;
291
    }
292

    
293
    nut->stream = av_mallocz(sizeof(StreamContext)*stream_count);
294
    for(i=0; i<stream_count; i++){
295
        av_new_stream(s, i);
296
    }
297

    
298
    return 0;
299
}
300

    
301
static int decode_stream_header(NUTContext *nut){
302
    AVFormatContext *s= nut->avf;
303
    AVIOContext *bc = s->pb;
304
    StreamContext *stc;
305
    int class, stream_id;
306
    uint64_t tmp, end;
307
    AVStream *st;
308

    
309
    end= get_packetheader(nut, bc, 1, STREAM_STARTCODE);
310
    end += avio_tell(bc);
311

    
312
    GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);
313
    stc= &nut->stream[stream_id];
314

    
315
    st = s->streams[stream_id];
316
    if (!st)
317
        return AVERROR(ENOMEM);
318

    
319
    class = ffio_read_varlen(bc);
320
    tmp = get_fourcc(bc);
321
    st->codec->codec_tag= tmp;
322
    switch(class)
323
    {
324
        case 0:
325
            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
326
            st->codec->codec_id = av_codec_get_id(
327
                (const AVCodecTag * const []) { ff_codec_bmp_tags, ff_nut_video_tags, 0 },
328
                tmp);
329
            break;
330
        case 1:
331
            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
332
            st->codec->codec_id = ff_codec_get_id(ff_codec_wav_tags, tmp);
333
            break;
334
        case 2:
335
            st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
336
            st->codec->codec_id = ff_codec_get_id(ff_nut_subtitle_tags, tmp);
337
            break;
338
        case 3:
339
            st->codec->codec_type = AVMEDIA_TYPE_DATA;
340
            break;
341
        default:
342
            av_log(s, AV_LOG_ERROR, "unknown stream class (%d)\n", class);
343
            return -1;
344
    }
345
    if(class<3 && st->codec->codec_id == CODEC_ID_NONE)
346
        av_log(s, AV_LOG_ERROR, "Unknown codec tag '0x%04x' for stream number %d\n",
347
               (unsigned int)tmp, stream_id);
348

    
349
    GET_V(stc->time_base_id    , tmp < nut->time_base_count);
350
    GET_V(stc->msb_pts_shift   , tmp < 16);
351
    stc->max_pts_distance= ffio_read_varlen(bc);
352
    GET_V(stc->decode_delay    , tmp < 1000); //sanity limit, raise this if Moore's law is true
353
    st->codec->has_b_frames= stc->decode_delay;
354
    ffio_read_varlen(bc); //stream flags
355

    
356
    GET_V(st->codec->extradata_size, tmp < (1<<30));
357
    if(st->codec->extradata_size){
358
        st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
359
        avio_read(bc, st->codec->extradata, st->codec->extradata_size);
360
    }
361

    
362
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO){
363
        GET_V(st->codec->width , tmp > 0)
364
        GET_V(st->codec->height, tmp > 0)
365
        st->sample_aspect_ratio.num= ffio_read_varlen(bc);
366
        st->sample_aspect_ratio.den= ffio_read_varlen(bc);
367
        if((!st->sample_aspect_ratio.num) != (!st->sample_aspect_ratio.den)){
368
            av_log(s, AV_LOG_ERROR, "invalid aspect ratio %d/%d\n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
369
            return -1;
370
        }
371
        ffio_read_varlen(bc); /* csp type */
372
    }else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO){
373
        GET_V(st->codec->sample_rate , tmp > 0)
374
        ffio_read_varlen(bc); // samplerate_den
375
        GET_V(st->codec->channels, tmp > 0)
376
    }
377
    if(skip_reserved(bc, end) || get_checksum(bc)){
378
        av_log(s, AV_LOG_ERROR, "stream header %d checksum mismatch\n", stream_id);
379
        return -1;
380
    }
381
    stc->time_base= &nut->time_base[stc->time_base_id];
382
    av_set_pts_info(s->streams[stream_id], 63, stc->time_base->num, stc->time_base->den);
383
    return 0;
384
}
385

    
386
static void set_disposition_bits(AVFormatContext* avf, char* value, int stream_id){
387
    int flag = 0, i;
388
    for (i=0; ff_nut_dispositions[i].flag; ++i) {
389
        if (!strcmp(ff_nut_dispositions[i].str, value))
390
            flag = ff_nut_dispositions[i].flag;
391
    }
392
    if (!flag)
393
        av_log(avf, AV_LOG_INFO, "unknown disposition type '%s'\n", value);
394
    for (i = 0; i < avf->nb_streams; ++i)
395
        if (stream_id == i || stream_id == -1)
396
            avf->streams[i]->disposition |= flag;
397
}
398

    
399
static int decode_info_header(NUTContext *nut){
400
    AVFormatContext *s= nut->avf;
401
    AVIOContext *bc = s->pb;
402
    uint64_t tmp, chapter_start, chapter_len;
403
    unsigned int stream_id_plus1, count;
404
    int chapter_id, i;
405
    int64_t value, end;
406
    char name[256], str_value[1024], type_str[256];
407
    const char *type;
408
    AVChapter *chapter= NULL;
409
    AVStream *st= NULL;
410
    AVMetadata **metadata = NULL;
411

    
412
    end= get_packetheader(nut, bc, 1, INFO_STARTCODE);
413
    end += avio_tell(bc);
414

    
415
    GET_V(stream_id_plus1, tmp <= s->nb_streams)
416
    chapter_id   = get_s(bc);
417
    chapter_start= ffio_read_varlen(bc);
418
    chapter_len  = ffio_read_varlen(bc);
419
    count        = ffio_read_varlen(bc);
420

    
421
    if(chapter_id && !stream_id_plus1){
422
        int64_t start= chapter_start / nut->time_base_count;
423
        chapter= ff_new_chapter(s, chapter_id,
424
                                nut->time_base[chapter_start % nut->time_base_count],
425
                                start, start + chapter_len, NULL);
426
        metadata = &chapter->metadata;
427
    } else if(stream_id_plus1) {
428
        st= s->streams[stream_id_plus1 - 1];
429
        metadata = &st->metadata;
430
    } else
431
        metadata = &s->metadata;
432

    
433
    for(i=0; i<count; i++){
434
        get_str(bc, name, sizeof(name));
435
        value= get_s(bc);
436
        if(value == -1){
437
            type= "UTF-8";
438
            get_str(bc, str_value, sizeof(str_value));
439
        }else if(value == -2){
440
            get_str(bc, type_str, sizeof(type_str));
441
            type= type_str;
442
            get_str(bc, str_value, sizeof(str_value));
443
        }else if(value == -3){
444
            type= "s";
445
            value= get_s(bc);
446
        }else if(value == -4){
447
            type= "t";
448
            value= ffio_read_varlen(bc);
449
        }else if(value < -4){
450
            type= "r";
451
            get_s(bc);
452
        }else{
453
            type= "v";
454
        }
455

    
456
        if (stream_id_plus1 > s->nb_streams) {
457
            av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");
458
            continue;
459
        }
460

    
461
        if(!strcmp(type, "UTF-8")){
462
            if(chapter_id==0 && !strcmp(name, "Disposition")) {
463
                set_disposition_bits(s, str_value, stream_id_plus1 - 1);
464
                continue;
465
            }
466
            if(metadata && strcasecmp(name,"Uses")
467
               && strcasecmp(name,"Depends") && strcasecmp(name,"Replaces"))
468
                av_metadata_set2(metadata, name, str_value, 0);
469
        }
470
    }
471

    
472
    if(skip_reserved(bc, end) || get_checksum(bc)){
473
        av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");
474
        return -1;
475
    }
476
    return 0;
477
}
478

    
479
static int decode_syncpoint(NUTContext *nut, int64_t *ts, int64_t *back_ptr){
480
    AVFormatContext *s= nut->avf;
481
    AVIOContext *bc = s->pb;
482
    int64_t end, tmp;
483

    
484
    nut->last_syncpoint_pos= avio_tell(bc)-8;
485

    
486
    end= get_packetheader(nut, bc, 1, SYNCPOINT_STARTCODE);
487
    end += avio_tell(bc);
488

    
489
    tmp= ffio_read_varlen(bc);
490
    *back_ptr= nut->last_syncpoint_pos - 16*ffio_read_varlen(bc);
491
    if(*back_ptr < 0)
492
        return -1;
493

    
494
    ff_nut_reset_ts(nut, nut->time_base[tmp % nut->time_base_count], tmp / nut->time_base_count);
495

    
496
    if(skip_reserved(bc, end) || get_checksum(bc)){
497
        av_log(s, AV_LOG_ERROR, "sync point checksum mismatch\n");
498
        return -1;
499
    }
500

    
501
    *ts= tmp / s->nb_streams * av_q2d(nut->time_base[tmp % s->nb_streams])*AV_TIME_BASE;
502
    ff_nut_add_sp(nut, nut->last_syncpoint_pos, *back_ptr, *ts);
503

    
504
    return 0;
505
}
506

    
507
static int find_and_decode_index(NUTContext *nut){
508
    AVFormatContext *s= nut->avf;
509
    AVIOContext *bc = s->pb;
510
    uint64_t tmp, end;
511
    int i, j, syncpoint_count;
512
    int64_t filesize= avio_size(bc);
513
    int64_t *syncpoints;
514
    int8_t *has_keyframe;
515
    int ret= -1;
516

    
517
    avio_seek(bc, filesize-12, SEEK_SET);
518
    avio_seek(bc, filesize-avio_rb64(bc), SEEK_SET);
519
    if(avio_rb64(bc) != INDEX_STARTCODE){
520
        av_log(s, AV_LOG_ERROR, "no index at the end\n");
521
        return -1;
522
    }
523

    
524
    end= get_packetheader(nut, bc, 1, INDEX_STARTCODE);
525
    end += avio_tell(bc);
526

    
527
    ffio_read_varlen(bc); //max_pts
528
    GET_V(syncpoint_count, tmp < INT_MAX/8 && tmp > 0)
529
    syncpoints= av_malloc(sizeof(int64_t)*syncpoint_count);
530
    has_keyframe= av_malloc(sizeof(int8_t)*(syncpoint_count+1));
531
    for(i=0; i<syncpoint_count; i++){
532
        syncpoints[i] = ffio_read_varlen(bc);
533
        if(syncpoints[i] <= 0)
534
            goto fail;
535
        if(i)
536
            syncpoints[i] += syncpoints[i-1];
537
    }
538

    
539
    for(i=0; i<s->nb_streams; i++){
540
        int64_t last_pts= -1;
541
        for(j=0; j<syncpoint_count;){
542
            uint64_t x= ffio_read_varlen(bc);
543
            int type= x&1;
544
            int n= j;
545
            x>>=1;
546
            if(type){
547
                int flag= x&1;
548
                x>>=1;
549
                if(n+x >= syncpoint_count + 1){
550
                    av_log(s, AV_LOG_ERROR, "index overflow A\n");
551
                    goto fail;
552
                }
553
                while(x--)
554
                    has_keyframe[n++]= flag;
555
                has_keyframe[n++]= !flag;
556
            }else{
557
                while(x != 1){
558
                    if(n>=syncpoint_count + 1){
559
                        av_log(s, AV_LOG_ERROR, "index overflow B\n");
560
                        goto fail;
561
                    }
562
                    has_keyframe[n++]= x&1;
563
                    x>>=1;
564
                }
565
            }
566
            if(has_keyframe[0]){
567
                av_log(s, AV_LOG_ERROR, "keyframe before first syncpoint in index\n");
568
                goto fail;
569
            }
570
            assert(n<=syncpoint_count+1);
571
            for(; j<n && j<syncpoint_count; j++){
572
                if(has_keyframe[j]){
573
                    uint64_t B, A= ffio_read_varlen(bc);
574
                    if(!A){
575
                        A= ffio_read_varlen(bc);
576
                        B= ffio_read_varlen(bc);
577
                        //eor_pts[j][i] = last_pts + A + B
578
                    }else
579
                        B= 0;
580
                    av_add_index_entry(
581
                        s->streams[i],
582
                        16*syncpoints[j-1],
583
                        last_pts + A,
584
                        0,
585
                        0,
586
                        AVINDEX_KEYFRAME);
587
                    last_pts += A + B;
588
                }
589
            }
590
        }
591
    }
592

    
593
    if(skip_reserved(bc, end) || get_checksum(bc)){
594
        av_log(s, AV_LOG_ERROR, "index checksum mismatch\n");
595
        goto fail;
596
    }
597
    ret= 0;
598
fail:
599
    av_free(syncpoints);
600
    av_free(has_keyframe);
601
    return ret;
602
}
603

    
604
static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
605
{
606
    NUTContext *nut = s->priv_data;
607
    AVIOContext *bc = s->pb;
608
    int64_t pos;
609
    int initialized_stream_count;
610

    
611
    nut->avf= s;
612

    
613
    /* main header */
614
    pos=0;
615
    do{
616
        pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
617
        if (pos<0+1){
618
            av_log(s, AV_LOG_ERROR, "No main startcode found.\n");
619
            return AVERROR_INVALIDDATA;
620
        }
621
    }while(decode_main_header(nut) < 0);
622

    
623
    /* stream headers */
624
    pos=0;
625
    for(initialized_stream_count=0; initialized_stream_count < s->nb_streams;){
626
        pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
627
        if (pos<0+1){
628
            av_log(s, AV_LOG_ERROR, "Not all stream headers found.\n");
629
            return AVERROR_INVALIDDATA;
630
        }
631
        if(decode_stream_header(nut) >= 0)
632
            initialized_stream_count++;
633
    }
634

    
635
    /* info headers */
636
    pos=0;
637
    for(;;){
638
        uint64_t startcode= find_any_startcode(bc, pos);
639
        pos= avio_tell(bc);
640

    
641
        if(startcode==0){
642
            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
643
            return AVERROR_INVALIDDATA;
644
        }else if(startcode == SYNCPOINT_STARTCODE){
645
            nut->next_startcode= startcode;
646
            break;
647
        }else if(startcode != INFO_STARTCODE){
648
            continue;
649
        }
650

    
651
        decode_info_header(nut);
652
    }
653

    
654
    s->data_offset= pos-8;
655

    
656
    if(!url_is_streamed(bc)){
657
        int64_t orig_pos= avio_tell(bc);
658
        find_and_decode_index(nut);
659
        avio_seek(bc, orig_pos, SEEK_SET);
660
    }
661
    assert(nut->next_startcode == SYNCPOINT_STARTCODE);
662

    
663
    ff_metadata_conv_ctx(s, NULL, ff_nut_metadata_conv);
664

    
665
    return 0;
666
}
667

    
668
static int decode_frame_header(NUTContext *nut, int64_t *pts, int *stream_id, uint8_t *header_idx, int frame_code){
669
    AVFormatContext *s= nut->avf;
670
    AVIOContext *bc = s->pb;
671
    StreamContext *stc;
672
    int size, flags, size_mul, pts_delta, i, reserved_count;
673
    uint64_t tmp;
674

    
675
    if(avio_tell(bc) > nut->last_syncpoint_pos + nut->max_distance){
676
        av_log(s, AV_LOG_ERROR, "Last frame must have been damaged %"PRId64" > %"PRId64" + %d\n", avio_tell(bc), nut->last_syncpoint_pos, nut->max_distance);
677
        return AVERROR_INVALIDDATA;
678
    }
679

    
680
    flags          = nut->frame_code[frame_code].flags;
681
    size_mul       = nut->frame_code[frame_code].size_mul;
682
    size           = nut->frame_code[frame_code].size_lsb;
683
    *stream_id     = nut->frame_code[frame_code].stream_id;
684
    pts_delta      = nut->frame_code[frame_code].pts_delta;
685
    reserved_count = nut->frame_code[frame_code].reserved_count;
686
    *header_idx    = nut->frame_code[frame_code].header_idx;
687

    
688
    if(flags & FLAG_INVALID)
689
        return AVERROR_INVALIDDATA;
690
    if(flags & FLAG_CODED)
691
        flags ^= ffio_read_varlen(bc);
692
    if(flags & FLAG_STREAM_ID){
693
        GET_V(*stream_id, tmp < s->nb_streams)
694
    }
695
    stc= &nut->stream[*stream_id];
696
    if(flags&FLAG_CODED_PTS){
697
        int coded_pts= ffio_read_varlen(bc);
698
//FIXME check last_pts validity?
699
        if(coded_pts < (1<<stc->msb_pts_shift)){
700
            *pts=ff_lsb2full(stc, coded_pts);
701
        }else
702
            *pts=coded_pts - (1<<stc->msb_pts_shift);
703
    }else
704
        *pts= stc->last_pts + pts_delta;
705
    if(flags&FLAG_SIZE_MSB){
706
        size += size_mul*ffio_read_varlen(bc);
707
    }
708
    if(flags&FLAG_MATCH_TIME)
709
        get_s(bc);
710
    if(flags&FLAG_HEADER_IDX)
711
        *header_idx= ffio_read_varlen(bc);
712
    if(flags&FLAG_RESERVED)
713
        reserved_count= ffio_read_varlen(bc);
714
    for(i=0; i<reserved_count; i++)
715
        ffio_read_varlen(bc);
716

    
717
    if(*header_idx >= (unsigned)nut->header_count){
718
        av_log(s, AV_LOG_ERROR, "header_idx invalid\n");
719
        return AVERROR_INVALIDDATA;
720
    }
721
    if(size > 4096)
722
        *header_idx=0;
723
    size -= nut->header_len[*header_idx];
724

    
725
    if(flags&FLAG_CHECKSUM){
726
        avio_rb32(bc); //FIXME check this
727
    }else if(size > 2*nut->max_distance || FFABS(stc->last_pts - *pts) > stc->max_pts_distance){
728
        av_log(s, AV_LOG_ERROR, "frame size > 2max_distance and no checksum\n");
729
        return AVERROR_INVALIDDATA;
730
    }
731

    
732
    stc->last_pts= *pts;
733
    stc->last_flags= flags;
734

    
735
    return size;
736
}
737

    
738
static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code){
739
    AVFormatContext *s= nut->avf;
740
    AVIOContext *bc = s->pb;
741
    int size, stream_id, discard;
742
    int64_t pts, last_IP_pts;
743
    StreamContext *stc;
744
    uint8_t header_idx;
745

    
746
    size= decode_frame_header(nut, &pts, &stream_id, &header_idx, frame_code);
747
    if(size < 0)
748
        return size;
749

    
750
    stc= &nut->stream[stream_id];
751

    
752
    if (stc->last_flags & FLAG_KEY)
753
        stc->skip_until_key_frame=0;
754

    
755
    discard= s->streams[ stream_id ]->discard;
756
    last_IP_pts= s->streams[ stream_id ]->last_IP_pts;
757
    if(  (discard >= AVDISCARD_NONKEY && !(stc->last_flags & FLAG_KEY))
758
       ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)
759
       || discard >= AVDISCARD_ALL
760
       || stc->skip_until_key_frame){
761
        avio_skip(bc, size);
762
        return 1;
763
    }
764

    
765
    av_new_packet(pkt, size + nut->header_len[header_idx]);
766
    memcpy(pkt->data, nut->header[header_idx], nut->header_len[header_idx]);
767
    pkt->pos= avio_tell(bc); //FIXME
768
    avio_read(bc, pkt->data + nut->header_len[header_idx], size);
769

    
770
    pkt->stream_index = stream_id;
771
    if (stc->last_flags & FLAG_KEY)
772
        pkt->flags |= AV_PKT_FLAG_KEY;
773
    pkt->pts = pts;
774

    
775
    return 0;
776
}
777

    
778
static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
779
{
780
    NUTContext *nut = s->priv_data;
781
    AVIOContext *bc = s->pb;
782
    int i, frame_code=0, ret, skip;
783
    int64_t ts, back_ptr;
784

    
785
    for(;;){
786
        int64_t pos= avio_tell(bc);
787
        uint64_t tmp= nut->next_startcode;
788
        nut->next_startcode=0;
789

    
790
        if(tmp){
791
            pos-=8;
792
        }else{
793
            frame_code = avio_r8(bc);
794
            if(bc->eof_reached)
795
                return -1;
796
            if(frame_code == 'N'){
797
                tmp= frame_code;
798
                for(i=1; i<8; i++)
799
                    tmp = (tmp<<8) + avio_r8(bc);
800
            }
801
        }
802
        switch(tmp){
803
        case MAIN_STARTCODE:
804
        case STREAM_STARTCODE:
805
        case INDEX_STARTCODE:
806
            skip= get_packetheader(nut, bc, 0, tmp);
807
            avio_skip(bc, skip);
808
            break;
809
        case INFO_STARTCODE:
810
            if(decode_info_header(nut)<0)
811
                goto resync;
812
            break;
813
        case SYNCPOINT_STARTCODE:
814
            if(decode_syncpoint(nut, &ts, &back_ptr)<0)
815
                goto resync;
816
            frame_code = avio_r8(bc);
817
        case 0:
818
            ret= decode_frame(nut, pkt, frame_code);
819
            if(ret==0)
820
                return 0;
821
            else if(ret==1) //ok but discard packet
822
                break;
823
        default:
824
resync:
825
av_log(s, AV_LOG_DEBUG, "syncing from %"PRId64"\n", pos);
826
            tmp= find_any_startcode(bc, nut->last_syncpoint_pos+1);
827
            if(tmp==0)
828
                return AVERROR_INVALIDDATA;
829
av_log(s, AV_LOG_DEBUG, "sync\n");
830
            nut->next_startcode= tmp;
831
        }
832
    }
833
}
834

    
835
static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
836
    NUTContext *nut = s->priv_data;
837
    AVIOContext *bc = s->pb;
838
    int64_t pos, pts, back_ptr;
839
av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%"PRId64",%"PRId64")\n", stream_index, *pos_arg, pos_limit);
840

    
841
    pos= *pos_arg;
842
    do{
843
        pos= find_startcode(bc, SYNCPOINT_STARTCODE, pos)+1;
844
        if(pos < 1){
845
            assert(nut->next_startcode == 0);
846
            av_log(s, AV_LOG_ERROR, "read_timestamp failed.\n");
847
            return AV_NOPTS_VALUE;
848
        }
849
    }while(decode_syncpoint(nut, &pts, &back_ptr) < 0);
850
    *pos_arg = pos-1;
851
    assert(nut->last_syncpoint_pos == *pos_arg);
852

    
853
    av_log(s, AV_LOG_DEBUG, "return %"PRId64" %"PRId64"\n", pts,back_ptr );
854
    if     (stream_index == -1) return pts;
855
    else if(stream_index == -2) return back_ptr;
856

    
857
assert(0);
858
}
859

    
860
static int read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags){
861
    NUTContext *nut = s->priv_data;
862
    AVStream *st= s->streams[stream_index];
863
    Syncpoint dummy={.ts= pts*av_q2d(st->time_base)*AV_TIME_BASE};
864
    Syncpoint nopts_sp= {.ts= AV_NOPTS_VALUE, .back_ptr= AV_NOPTS_VALUE};
865
    Syncpoint *sp, *next_node[2]= {&nopts_sp, &nopts_sp};
866
    int64_t pos, pos2, ts;
867
    int i;
868

    
869
    if(st->index_entries){
870
        int index= av_index_search_timestamp(st, pts, flags);
871
        if(index<0)
872
            return -1;
873

    
874
        pos2= st->index_entries[index].pos;
875
        ts  = st->index_entries[index].timestamp;
876
    }else{
877
        av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pts_cmp,
878
                     (void **) next_node);
879
        av_log(s, AV_LOG_DEBUG, "%"PRIu64"-%"PRIu64" %"PRId64"-%"PRId64"\n", next_node[0]->pos, next_node[1]->pos,
880
                                                    next_node[0]->ts , next_node[1]->ts);
881
        pos= av_gen_search(s, -1, dummy.ts, next_node[0]->pos, next_node[1]->pos, next_node[1]->pos,
882
                                            next_node[0]->ts , next_node[1]->ts, AVSEEK_FLAG_BACKWARD, &ts, nut_read_timestamp);
883

    
884
        if(!(flags & AVSEEK_FLAG_BACKWARD)){
885
            dummy.pos= pos+16;
886
            next_node[1]= &nopts_sp;
887
            av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
888
                         (void **) next_node);
889
            pos2= av_gen_search(s, -2, dummy.pos, next_node[0]->pos     , next_node[1]->pos, next_node[1]->pos,
890
                                                next_node[0]->back_ptr, next_node[1]->back_ptr, flags, &ts, nut_read_timestamp);
891
            if(pos2>=0)
892
                pos= pos2;
893
            //FIXME dir but I think it does not matter
894
        }
895
        dummy.pos= pos;
896
        sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
897
                         NULL);
898

    
899
        assert(sp);
900
        pos2= sp->back_ptr  - 15;
901
    }
902
    av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos2);
903
    pos= find_startcode(s->pb, SYNCPOINT_STARTCODE, pos2);
904
    avio_seek(s->pb, pos, SEEK_SET);
905
    av_log(NULL, AV_LOG_DEBUG, "SP: %"PRId64"\n", pos);
906
    if(pos2 > pos || pos2 + 15 < pos){
907
        av_log(NULL, AV_LOG_ERROR, "no syncpoint at backptr pos\n");
908
    }
909
    for(i=0; i<s->nb_streams; i++)
910
        nut->stream[i].skip_until_key_frame=1;
911

    
912
    return 0;
913
}
914

    
915
static int nut_read_close(AVFormatContext *s)
916
{
917
    NUTContext *nut = s->priv_data;
918
    int i;
919

    
920
    av_freep(&nut->time_base);
921
    av_freep(&nut->stream);
922
    ff_nut_free_sp(nut);
923
    for(i = 1; i < nut->header_count; i++)
924
        av_freep(&nut->header[i]);
925

    
926
    return 0;
927
}
928

    
929
#if CONFIG_NUT_DEMUXER
930
AVInputFormat ff_nut_demuxer = {
931
    "nut",
932
    NULL_IF_CONFIG_SMALL("NUT format"),
933
    sizeof(NUTContext),
934
    nut_probe,
935
    nut_read_header,
936
    nut_read_packet,
937
    nut_read_close,
938
    read_seek,
939
    .extensions = "nut",
940
    .codec_tag = (const AVCodecTag * const []) { ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
941
};
942
#endif