Statistics
| Branch: | Revision:

ffmpeg / libavformat / nut.c @ 1c24c51d

History | View | Annotate | Download (45.3 KB)

1
/*
2
 * "NUT" Container Format muxer and demuxer (DRAFT-200403??)
3
 * Copyright (c) 2003 Alex Beregszaszi
4
 * Copyright (c) 2004 Michael Niedermayer
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public
17
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
 *
20
 * NUT DRAFT can be found in MPlayer CVS at DOCS/tech/mpcf.txt
21
 *
22
 * AND http://people.fsn.hu/~alex/nut/ (TeX, pdf, ps, dvi, ..)
23
 *
24
 */
25

    
26
/*
27
 * TODO:
28
 * - seeking
29
 * - index writing
30
 * - index packet reading support
31
*/
32

    
33
//#define DEBUG 1
34

    
35
#include <limits.h>
36
#include "avformat.h"
37
#include "mpegaudio.h"
38
#include "avi.h"
39

    
40
#undef NDEBUG
41
#include <assert.h>
42

    
43
//from /dev/random
44

    
45
#define     MAIN_STARTCODE (0x7A561F5F04ADULL + (((uint64_t)('N'<<8) + 'M')<<48)) 
46
#define   STREAM_STARTCODE (0x11405BF2F9DBULL + (((uint64_t)('N'<<8) + 'S')<<48)) 
47
#define KEYFRAME_STARTCODE (0xE4ADEECA4569ULL + (((uint64_t)('N'<<8) + 'K')<<48)) 
48
#define    INDEX_STARTCODE (0xDD672F23E64EULL + (((uint64_t)('N'<<8) + 'X')<<48)) 
49
#define     INFO_STARTCODE (0xAB68B596BA78ULL + (((uint64_t)('N'<<8) + 'I')<<48)) 
50

    
51
#define MAX_TYPE1_DISTANCE (1024*16-1)
52
#define MAX_TYPE2_DISTANCE (1024*64-1)
53

    
54
#define MAX_SIZE_LRU 2
55
#define MAX_PTS_LRU 3
56

    
57
#define FLAG_FRAME_TYPE      1
58
#define FLAG_DATA_SIZE       2
59
#define FLAG_PTS            16
60
#define FLAG_FULL_PTS        4
61
#define FLAG_KEY_FRAME      32
62
#define FLAG_PRED_KEY_FRAME 64
63

    
64
typedef struct {
65
    uint8_t flags;
66
    uint8_t stream_id_plus1;
67
    uint8_t size_mul;
68
    uint8_t size_lsb;
69
} FrameCode;
70

    
71
typedef struct {
72
    int last_key_frame;
73
    int msb_timestamp_shift;
74
    int rate_num;
75
    int rate_den;
76
    int64_t last_pts;
77
    int64_t last_full_pts;
78
    int lru_pts_delta[MAX_PTS_LRU];
79
    int lru_size[MAX_SIZE_LRU];
80
    int initial_pts_predictor[MAX_PTS_LRU];
81
    int initial_size_predictor[MAX_SIZE_LRU];
82
    int64_t last_sync_pos;                    ///<pos of last 1/2 type frame
83
} StreamContext;
84

    
85
typedef struct {
86
    AVFormatContext *avf;
87
    int64_t packet_start;
88
    int64_t last_packet_start;
89
    int written_packet_size;
90
    int64_t packet_size_pos;
91
    int64_t last_frame_start[3];
92
    FrameCode frame_code[256];
93
    int stream_count;
94
    uint64_t next_startcode;     ///< stores the next startcode if it has alraedy been parsed but the stream isnt seekable
95
    StreamContext *stream;
96
} NUTContext;
97

    
98
static char *info_table[][2]={
99
        {NULL                        ,  NULL }, // end
100
        {NULL                        ,  NULL },
101
        {NULL                        , "UTF8"},
102
        {NULL                        , "v"},
103
        {NULL                        , "s"},
104
        {"StreamId"                , "v"},
105
        {"SegmentId"                , "v"},
106
        {"StartTimestamp"        , "v"},
107
        {"EndTimestamp"                , "v"},
108
        {"Author"                , "UTF8"},
109
        {"Title"                , "UTF8"},
110
        {"Description"                , "UTF8"},
111
        {"Copyright"                , "UTF8"},
112
        {"Encoder"                , "UTF8"},
113
        {"Keyword"                , "UTF8"},
114
        {"Cover"                , "JPEG"},
115
        {"Cover"                , "PNG"},
116
};
117

    
118
static void update_lru(int *lru, int current, int count){
119
    int i;
120

    
121
    for(i=0; i<count-1; i++){
122
        if(lru[i] == current)
123
            break;
124
    }
125

    
126
    for(; i; i--){
127
        lru[i]= lru[i-1];
128
    }
129

    
130
    lru[0]= current;
131
}
132

    
133
static void update(NUTContext *nut, int stream_index, int64_t frame_start, int frame_type, int frame_code, int key_frame, int size, int64_t pts){
134
    StreamContext *stream= &nut->stream[stream_index];
135
    const int flags=nut->frame_code[frame_code].flags; 
136
    
137
    stream->last_key_frame= key_frame;
138
    nut->last_frame_start[ frame_type ]= frame_start;
139
    if(frame_type == 0)
140
        update_lru(stream->lru_pts_delta, pts - stream->last_pts, 3);
141
    update_lru(stream->lru_size, size, 2);
142
    stream->last_pts= pts;
143
    if((flags & FLAG_PTS) && (flags & FLAG_FULL_PTS))
144
        stream->last_full_pts= pts;
145
}
146

    
147
static void reset(AVFormatContext *s/*, int frame_type*/){
148
    NUTContext *nut = s->priv_data;
149
    int i;
150
    
151
    for(i=0; i<s->nb_streams; i++){
152
        StreamContext *stream= &nut->stream[i];
153
    
154
        stream->last_key_frame= 1;
155
        memcpy(stream->lru_pts_delta, stream->initial_pts_predictor, sizeof(int)*MAX_PTS_LRU);
156
        memcpy(stream->lru_size, stream->initial_size_predictor, sizeof(int)*MAX_SIZE_LRU);
157
    }
158
}
159

    
160
static void build_frame_code(AVFormatContext *s){
161
    NUTContext *nut = s->priv_data;
162
    int key_frame, frame_type, full_pts, index, pred, stream_id;
163
    int start=0;
164
    int end= 255;
165
    int keyframe_0_esc= s->nb_streams > 2;
166

    
167
    if(keyframe_0_esc){
168
        /* keyframe = 0 escapes, 3 codes */
169
        for(frame_type=0; frame_type<2; frame_type++){
170
            for(full_pts=frame_type; full_pts<2; full_pts++){
171
                FrameCode *ft= &nut->frame_code[start];
172
                ft->flags= FLAG_FRAME_TYPE*frame_type + FLAG_FULL_PTS*full_pts;
173
                ft->flags|= FLAG_DATA_SIZE | FLAG_PTS; 
174
                ft->stream_id_plus1= 0;
175
                ft->size_mul=1;
176
                start++;
177
            }
178
        }
179
    }
180

    
181
    for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
182
        int start2= start + (end-start)*stream_id / s->nb_streams;
183
        int end2  = start + (end-start)*(stream_id+1) / s->nb_streams;
184
        AVCodecContext *codec = &s->streams[stream_id]->codec;
185
        int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
186
        int intra_only= /*codec->intra_only || */is_audio;
187
        int pred_count;
188

    
189
        for(key_frame=0; key_frame<2; key_frame++){
190
            if(intra_only && keyframe_0_esc && key_frame==0)
191
                continue;
192
            
193
            for(frame_type=0; frame_type<2; frame_type++){
194
                for(full_pts=frame_type; full_pts<2; full_pts++){
195
                    FrameCode *ft= &nut->frame_code[start2];
196
                    ft->flags= FLAG_FRAME_TYPE*frame_type + FLAG_FULL_PTS*full_pts + FLAG_KEY_FRAME*key_frame;
197
                    ft->flags|= FLAG_DATA_SIZE | FLAG_PTS;
198
                    ft->stream_id_plus1= stream_id + 1;
199
                    ft->size_mul=1;
200
                    start2++;
201
                }
202
            }
203
        }
204

    
205
        key_frame= intra_only;
206
#if 1
207
        if(is_audio){
208
            int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
209
            for(pred=0; pred<MAX_SIZE_LRU; pred++){
210
                for(frame_type=0; frame_type<1; frame_type++){
211
                    FrameCode *ft= &nut->frame_code[start2];
212
                    ft->flags= FLAG_KEY_FRAME*key_frame + (FLAG_FULL_PTS+FLAG_PTS+FLAG_FRAME_TYPE)*frame_type;
213
                    ft->stream_id_plus1= stream_id + 1;
214
                    ft->size_mul=1;
215
                    ft->size_lsb=1 + pred;
216
                    start2++;
217
                }
218
                nut->stream[stream_id].initial_size_predictor[pred]= frame_bytes + pred;
219
            }
220
        }else{
221
            FrameCode *ft= &nut->frame_code[start2];
222
            ft->flags= FLAG_KEY_FRAME | FLAG_DATA_SIZE;
223
            ft->stream_id_plus1= stream_id + 1;
224
            ft->size_mul=1;
225
            start2++;
226
        }
227
#endif
228
        pred_count= 2 + codec->has_b_frames + (codec->codec_id == CODEC_ID_VORBIS);
229
        for(pred=0; pred<pred_count; pred++){
230
            int start3= start2 + (end2-start2)*pred / pred_count;
231
            int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
232

    
233
            for(index=start3; index<end3; index++){
234
                FrameCode *ft= &nut->frame_code[index];
235
                ft->flags= FLAG_KEY_FRAME*key_frame + pred*4;
236
                ft->flags|= FLAG_DATA_SIZE;
237
                ft->stream_id_plus1= stream_id + 1;
238
//FIXME use single byte size and pred from last
239
                ft->size_mul= end3-start3;
240
                ft->size_lsb= index - start3;
241
            }
242
            nut->stream[stream_id].initial_pts_predictor[pred]= pred+1;
243
        }
244
    }
245
    memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
246
    nut->frame_code['N'].flags= 1;
247
}
248

    
249
static uint64_t get_v(ByteIOContext *bc)
250
{
251
    uint64_t val = 0;
252

    
253
    for(;;)
254
    {
255
        int tmp = get_byte(bc);
256

    
257
        if (tmp&0x80)
258
            val= (val<<7) + tmp - 0x80;
259
        else
260
            return (val<<7) + tmp;
261
    }
262
    return -1;
263
}
264

    
265
static int get_str(ByteIOContext *bc, char *string, int maxlen){
266
    int len= get_v(bc);
267
    
268
    if(len && maxlen)
269
        get_buffer(bc, string, FFMIN(len, maxlen));
270
    while(len > maxlen){
271
        get_byte(bc);
272
        len--;
273
    }
274

    
275
    if(maxlen)
276
        string[FFMIN(len, maxlen-1)]= 0;
277
    
278
    if(maxlen == len)
279
        return -1;
280
    else
281
        return 0;
282
}
283

    
284
static uint64_t get_vb(ByteIOContext *bc){
285
    uint64_t val=0;
286
    int i= get_v(bc);
287
    
288
    if(i>8)
289
        return UINT64_MAX;
290
    
291
    while(i--)
292
        val = (val<<8) + get_byte(bc);
293
    
294
    return val;
295
}
296

    
297
static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int prefix_length, int calculate_checksum)
298
{
299
    int64_t start, size, last_size;
300
    start= url_ftell(bc) - prefix_length;
301

    
302
    if(nut->written_packet_size >= 0 && start != nut->packet_start + nut->written_packet_size){
303
        av_log(nut->avf, AV_LOG_ERROR, "get_packetheader called at weird position\n");
304
        if(prefix_length<8)
305
            return -1;
306
    }
307
    
308
    init_checksum(bc, calculate_checksum ? update_adler32 : NULL, 0);
309

    
310
    size= get_v(bc);
311
    last_size= get_v(bc);
312
    if(nut->written_packet_size >= 0 && nut->written_packet_size != last_size){
313
        av_log(nut->avf, AV_LOG_ERROR, "packet size missmatch %d != %lld at %lld\n", nut->written_packet_size, last_size, start);
314
        if(prefix_length<8)
315
            return -1;
316
    }
317

    
318
    nut->last_packet_start = nut->packet_start;
319
    nut->packet_start = start;
320
    nut->written_packet_size= size;
321

    
322
    return size;
323
}
324

    
325
static int check_checksum(ByteIOContext *bc){
326
    unsigned long checksum= get_checksum(bc);
327
    return checksum != get_be32(bc);
328
}
329

    
330
/**
331
 * 
332
 */
333
static int get_length(uint64_t val){
334
    int i;
335

    
336
    for (i=7; val>>i; i+=7);
337

    
338
    return i;
339
}
340

    
341
static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
342
    uint64_t state=0;
343
    
344
    if(pos >= 0)
345
        url_fseek(bc, pos, SEEK_SET); //note, this may fail if the stream isnt seekable, but that shouldnt matter, as in this case we simply start where we are currently
346

    
347
    while(!url_feof(bc)){
348
        state= (state<<8) | get_byte(bc);
349
        if((state>>56) != 'N')
350
            continue;
351
        switch(state){
352
        case MAIN_STARTCODE:
353
        case STREAM_STARTCODE:
354
        case KEYFRAME_STARTCODE:
355
        case INFO_STARTCODE:
356
        case INDEX_STARTCODE:
357
            return state;
358
        }
359
    }
360

    
361
    return 0;
362
}
363

    
364
/**
365
 * find the given startcode.
366
 * @param code the startcode
367
 * @param pos the start position of the search, or -1 if the current position
368
 * @returns the position of the startcode or -1 if not found
369
 */
370
static int64_t find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
371
    for(;;){
372
        uint64_t startcode= find_any_startcode(bc, pos);
373
        if(startcode == code)
374
            return url_ftell(bc) - 8;
375
        else if(startcode == 0)
376
            return -1;
377
        pos=-1;
378
    }
379
}
380

    
381
#ifdef CONFIG_ENCODERS
382
static void put_v(ByteIOContext *bc, uint64_t val)
383
{
384
    int i;
385

    
386
    val &= 0x7FFFFFFFFFFFFFFFULL; // FIXME can only encode upto 63 bits currently
387
    i= get_length(val);
388

    
389
    for (i-=7; i>0; i-=7){
390
        put_byte(bc, 0x80 | (val>>i));
391
    }
392

    
393
    put_byte(bc, val&0x7f);
394
}
395

    
396
/**
397
 * stores a string as vb.
398
 */
399
static void put_str(ByteIOContext *bc, const char *string){
400
    int len= strlen(string);
401
    
402
    put_v(bc, len);
403
    put_buffer(bc, string, len);
404
}
405

    
406
static void put_vb(ByteIOContext *bc, uint64_t val){
407
    int i;
408
    
409
    for (i=8; val>>i; i+=8);
410

    
411
    put_v(bc, i>>3);
412
    for(i-=8; i>=0; i-=8)
413
        put_byte(bc, (val>>i)&0xFF);
414
}
415

    
416
static int put_packetheader(NUTContext *nut, ByteIOContext *bc, int max_size, int calculate_checksum)
417
{
418
    put_flush_packet(bc);
419
    nut->last_packet_start= nut->packet_start;
420
    nut->packet_start+= nut->written_packet_size;
421
    nut->packet_size_pos = url_ftell(bc);
422
    nut->written_packet_size = max_size;
423
    
424
    if(calculate_checksum)
425
        init_checksum(bc, update_adler32, 0);
426

    
427
    /* packet header */
428
    put_v(bc, nut->written_packet_size); /* forward ptr */
429
    put_v(bc, nut->packet_start - nut->last_packet_start); /* backward ptr */
430

    
431
    return 0;
432
}
433

    
434
static int update_packetheader(NUTContext *nut, ByteIOContext *bc, int additional_size, int calculate_checksum){
435
    int64_t start= nut->packet_start;
436
    int64_t cur= url_ftell(bc);
437
    int size= cur - start + additional_size;
438
    
439
    if(calculate_checksum)
440
        size += 4;
441
    
442
    if(size != nut->written_packet_size){
443
        int i;
444

    
445
        assert( size <= nut->written_packet_size );
446
    
447
        url_fseek(bc, nut->packet_size_pos, SEEK_SET);
448
        for(i=get_length(size); i < get_length(nut->written_packet_size); i+=7)
449
            put_byte(bc, 0x80);
450
        put_v(bc, size);
451

    
452
        url_fseek(bc, cur, SEEK_SET);
453
        nut->written_packet_size= size; //FIXME may fail if multiple updates with differing sizes, as get_length may differ
454
        
455
        if(calculate_checksum)
456
            put_be32(bc, get_checksum(bc));
457
    }
458
    
459
    return 0;
460
}
461

    
462
static int nut_write_header(AVFormatContext *s)
463
{
464
    NUTContext *nut = s->priv_data;
465
    ByteIOContext *bc = &s->pb;
466
    AVCodecContext *codec;
467
    int i, j;
468

    
469
    nut->avf= s;
470
    
471
    nut->stream =        
472
        av_mallocz(sizeof(StreamContext)*s->nb_streams);
473
    
474
    av_set_pts_info(s, 60, 1, AV_TIME_BASE);
475
    
476
    /* main header */
477
    put_be64(bc, MAIN_STARTCODE);
478
    put_packetheader(nut, bc, 120+5*256, 1);
479
    put_v(bc, 1); /* version */
480
    put_v(bc, s->nb_streams);
481
    put_v(bc, 3);
482
    
483
    build_frame_code(s);
484
    assert(nut->frame_code['N'].flags == 1);
485
    for(i=0; i<256;){
486
        int tmp_flags = nut->frame_code[i].flags;
487
        int tmp_stream= nut->frame_code[i].stream_id_plus1;
488
        int tmp_mul   = nut->frame_code[i].size_mul;
489
        int tmp_size  = nut->frame_code[i].size_lsb;
490
        put_v(bc, tmp_flags);
491
        put_v(bc, tmp_stream);
492
        put_v(bc, tmp_mul);
493
        put_v(bc, tmp_size);
494

    
495
        for(j=0; i<256; j++,i++){
496
            if(nut->frame_code[i].flags           != tmp_flags ) break;
497
            if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;
498
            if(nut->frame_code[i].size_mul        != tmp_mul   ) break;
499
            if(nut->frame_code[i].size_lsb        != tmp_size  ) break;
500
            if(++tmp_size >= tmp_mul){
501
                tmp_size=0;
502
                tmp_stream++;
503
            }
504
        }
505
        put_v(bc, j);
506
    }
507

    
508
    update_packetheader(nut, bc, 0, 1);
509
    
510
    /* stream headers */
511
    for (i = 0; i < s->nb_streams; i++)
512
    {
513
        int nom, denom, gcd;
514

    
515
        codec = &s->streams[i]->codec;
516
        
517
        put_be64(bc, STREAM_STARTCODE);
518
        put_packetheader(nut, bc, 120 + codec->extradata_size, 1);
519
        put_v(bc, i /*s->streams[i]->index*/);
520
        put_v(bc, (codec->codec_type == CODEC_TYPE_AUDIO) ? 32 : 0);
521
        if (codec->codec_tag)
522
            put_vb(bc, codec->codec_tag);
523
        else if (codec->codec_type == CODEC_TYPE_VIDEO)
524
        {
525
            put_vb(bc, codec_get_bmp_tag(codec->codec_id));
526
        }
527
        else if (codec->codec_type == CODEC_TYPE_AUDIO)
528
        {
529
            put_vb(bc, codec_get_wav_tag(codec->codec_id));
530
        }
531
        else
532
            put_vb(bc, 0);
533

    
534
        if (codec->codec_type == CODEC_TYPE_VIDEO)
535
        {
536
            nom = codec->frame_rate;
537
            denom = codec->frame_rate_base;
538
        }
539
        else
540
        {
541
            nom = codec->sample_rate;
542
            if(codec->frame_size>0)
543
                denom= codec->frame_size;
544
            else
545
                denom= 1; //unlucky
546
        }
547
        gcd= ff_gcd(nom, denom);
548
        nom   /= gcd;
549
        denom /= gcd;
550
        nut->stream[i].rate_num= nom;
551
        nut->stream[i].rate_den= denom;
552

    
553
        put_v(bc, codec->bit_rate);
554
        put_vb(bc, 0); /* no language code */
555
        put_v(bc, nom);
556
        put_v(bc, denom);
557
        if(nom / denom < 1000)
558
            nut->stream[i].msb_timestamp_shift = 7;
559
        else
560
            nut->stream[i].msb_timestamp_shift = 14;
561
        put_v(bc, nut->stream[i].msb_timestamp_shift);
562
        for(j=0; j<3; j++)
563
                put_v(bc, nut->stream[i].initial_pts_predictor[j]);
564
        for(j=0; j<2; j++)
565
                put_v(bc, nut->stream[i].initial_size_predictor[j]);
566
        put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
567
        
568
        if(codec->extradata_size){
569
            put_v(bc, 1);
570
            put_v(bc, codec->extradata_size);
571
            put_buffer(bc, codec->extradata, codec->extradata_size);            
572
        }
573
        put_v(bc, 0); /* end of codec specific headers */
574
        
575
        switch(codec->codec_type)
576
        {
577
            case CODEC_TYPE_AUDIO:
578
                put_v(bc, (codec->sample_rate * denom) / nom);
579
                put_v(bc, codec->channels);
580
                break;
581
            case CODEC_TYPE_VIDEO:
582
                put_v(bc, codec->width);
583
                put_v(bc, codec->height);
584
                put_v(bc, codec->sample_aspect_ratio.num);
585
                put_v(bc, codec->sample_aspect_ratio.den);
586
                put_v(bc, 0); /* csp type -- unknown */
587
                break;
588
            default:
589
                break;
590
        }
591
        update_packetheader(nut, bc, 0, 1);
592
    }
593

    
594
    /* info header */
595
    put_be64(bc, INFO_STARTCODE);
596
    put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+
597
        strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1); 
598
    if (s->author[0])
599
    {
600
        put_v(bc, 9); /* type */
601
        put_str(bc, s->author);
602
    }
603
    if (s->title[0])
604
    {
605
        put_v(bc, 10); /* type */
606
        put_str(bc, s->title);
607
    }
608
    if (s->comment[0])
609
    {
610
        put_v(bc, 11); /* type */
611
        put_str(bc, s->comment);
612
    }
613
    if (s->copyright[0])
614
    {
615
        put_v(bc, 12); /* type */
616
        put_str(bc, s->copyright);
617
    }
618
    /* encoder */
619
    put_v(bc, 13); /* type */
620
    put_str(bc, LIBAVFORMAT_IDENT);
621
    
622
    put_v(bc, 0); /* eof info */
623
    update_packetheader(nut, bc, 0, 1);
624
        
625
    put_flush_packet(bc);
626
    
627
    return 0;
628
}
629

    
630
static int nut_write_packet(AVFormatContext *s, int stream_index, 
631
                            const uint8_t *buf, int size, int64_t pts)
632
{
633
    NUTContext *nut = s->priv_data;
634
    StreamContext *stream= &nut->stream[stream_index];
635
    ByteIOContext *bc = &s->pb;
636
    int key_frame = 0, full_pts=0;
637
    AVCodecContext *enc;
638
    int64_t lsb_pts, delta_pts;
639
    int frame_type, best_length, frame_code, flags, i, size_mul, size_lsb;
640
    const int64_t frame_start= url_ftell(bc);
641

    
642
    if (stream_index > s->nb_streams)
643
        return 1;
644
        
645
    pts= (av_rescale(pts, stream->rate_num, stream->rate_den) + AV_TIME_BASE/2) / AV_TIME_BASE;
646

    
647
    enc = &s->streams[stream_index]->codec;
648
    key_frame = enc->coded_frame->key_frame;
649
    delta_pts= pts - stream->last_pts;
650
    
651
    frame_type=0;
652
    if(frame_start + size + 20 - FFMAX(nut->last_frame_start[1], nut->last_frame_start[2]) > MAX_TYPE1_DISTANCE)
653
        frame_type=1;
654
    if(key_frame){
655
        if(frame_type==1 && frame_start + size - nut->last_frame_start[2] > MAX_TYPE2_DISTANCE)
656
            frame_type=2;
657
        if(!stream->last_key_frame)
658
            frame_type=2;
659
    }
660

    
661
    if(frame_type>0){
662
        update_packetheader(nut, bc, 0, 0);
663
        reset(s);
664
        full_pts=1;
665
    }
666
    //FIXME ensure that the timestamp can be represented by either delta or lsb or full_pts=1
667

    
668
    lsb_pts = pts & ((1 << stream->msb_timestamp_shift)-1);
669

    
670
    best_length=INT_MAX;
671
    frame_code= -1;
672
    for(i=0; i<256; i++){
673
        int stream_id_plus1= nut->frame_code[i].stream_id_plus1;
674
        int fc_key_frame= stream->last_key_frame;
675
        int length=0;
676
        size_mul= nut->frame_code[i].size_mul;
677
        size_lsb= nut->frame_code[i].size_lsb;
678
        flags= nut->frame_code[i].flags;
679

    
680
        if(stream_id_plus1 == 0) length+= get_length(stream_index);
681
        else if(stream_id_plus1 - 1 != stream_index)
682
            continue;
683
        if(flags & FLAG_PRED_KEY_FRAME){
684
            if(flags & FLAG_KEY_FRAME)
685
                fc_key_frame= !fc_key_frame;
686
        }else{
687
            fc_key_frame= !!(flags & FLAG_KEY_FRAME);
688
        }
689
        assert(key_frame==0 || key_frame==1);
690
        if(fc_key_frame != key_frame)
691
            continue;
692

    
693
        if((!!(flags & FLAG_FRAME_TYPE)) != (frame_type > 0))
694
            continue;
695
        
696
        if(size_mul <= size_lsb){
697
            int p= stream->lru_size[size_lsb - size_mul];
698
            if(p != size)
699
                continue;
700
        }else{
701
            if(size % size_mul != size_lsb)
702
                continue;
703
            if(flags & FLAG_DATA_SIZE)
704
                length += get_length(size / size_mul);
705
            else if(size/size_mul)
706
                continue;
707
        }
708

    
709
        if(full_pts != ((flags & FLAG_PTS) && (flags & FLAG_FULL_PTS)))
710
            continue;
711
            
712
        if(flags&FLAG_PTS){
713
            if(flags&FLAG_FULL_PTS){
714
                length += get_length(pts);
715
            }else{
716
                length += get_length(lsb_pts);
717
            }
718
        }else{
719
            int delta= stream->lru_pts_delta[(flags & 12)>>2];
720
            if(delta != pts - stream->last_pts)
721
                continue;
722
            assert(frame_type == 0);
723
        }
724

    
725
        if(length < best_length){
726
            best_length= length;
727
            frame_code=i;
728
        }
729
//    av_log(s, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d %d %d\n", key_frame, frame_type, full_pts, size, stream_index, flags, size_mul, size_lsb, stream_id_plus1, length);
730
    }
731

    
732
    assert(frame_code != -1);
733
    flags= nut->frame_code[frame_code].flags;
734
    size_mul= nut->frame_code[frame_code].size_mul;
735
    size_lsb= nut->frame_code[frame_code].size_lsb;
736
#if 0
737
    best_length /= 7;
738
    best_length ++; //frame_code
739
    if(frame_type>0){
740
        best_length += 4; //packet header
741
        if(frame_type>1)
742
            best_length += 8; // startcode
743
    }
744
    av_log(s, AV_LOG_DEBUG, "kf:%d ft:%d pt:%d fc:%2X len:%2d size:%d stream:%d flag:%d mul:%d lsb:%d s+1:%d pts_delta:%d\n", key_frame, frame_type, full_pts ? 2 : ((flags & FLAG_PTS) ? 1 : 0), frame_code, best_length, size, stream_index, flags, size_mul, size_lsb, nut->frame_code[frame_code].stream_id_plus1,(int)(pts - stream->last_pts));
745
#endif
746

    
747
    if (frame_type==2)
748
        put_be64(bc, KEYFRAME_STARTCODE);
749
    put_byte(bc, frame_code);
750

    
751
    if(frame_type>0)
752
        put_packetheader(nut, bc, FFMAX(size+20, MAX_TYPE1_DISTANCE), 0);
753
    if(nut->frame_code[frame_code].stream_id_plus1 == 0)
754
        put_v(bc, stream_index);
755
    if (flags & FLAG_PTS){
756
        if (flags & FLAG_FULL_PTS)
757
            put_v(bc, pts);
758
        else
759
            put_v(bc, lsb_pts);
760
    }
761
    if(flags & FLAG_DATA_SIZE)
762
        put_v(bc, size / size_mul);
763
    if(size > MAX_TYPE1_DISTANCE){
764
        assert(frame_type > 0);
765
        update_packetheader(nut, bc, size, 0);
766
    }
767
    
768
    put_buffer(bc, buf, size);
769

    
770
    update(nut, stream_index, frame_start, frame_type, frame_code, key_frame, size, pts);
771
    
772
    return 0;
773
}
774

    
775
static int nut_write_trailer(AVFormatContext *s)
776
{
777
    NUTContext *nut = s->priv_data;
778
    ByteIOContext *bc = &s->pb;
779

    
780
    update_packetheader(nut, bc, 0, 0);
781

    
782
#if 0
783
    int i;
784

785
    /* WRITE INDEX */
786

787
    for (i = 0; s->nb_streams; i++)
788
    {
789
        put_be64(bc, INDEX_STARTCODE);
790
        put_packetheader(nut, bc, 64, 1);
791
        put_v(bc, s->streams[i]->id);
792
        put_v(bc, ...);
793
        update_packetheader(nut, bc, 0, 1);
794
    }
795
#endif
796

    
797
    put_flush_packet(bc);
798
    
799
    av_freep(&nut->stream);
800

    
801
    return 0;
802
}
803
#endif //CONFIG_ENCODERS
804

    
805
static int nut_probe(AVProbeData *p)
806
{
807
    int i;
808
    uint64_t code;
809

    
810
    code = 0xff;
811
    for (i = 0; i < p->buf_size; i++) {
812
        int c = p->buf[i];
813
        code = (code << 8) | c;
814
        if (code == MAIN_STARTCODE)
815
            return AVPROBE_SCORE_MAX;
816
    }
817
    return 0;
818
}
819

    
820
static int decode_main_header(NUTContext *nut){
821
    AVFormatContext *s= nut->avf;
822
    ByteIOContext *bc = &s->pb;
823
    uint64_t tmp;
824
    int i, j;
825
    
826
    get_packetheader(nut, bc, 8, 1);
827

    
828
    tmp = get_v(bc);
829
    if (tmp != 1){
830
        av_log(s, AV_LOG_ERROR, "bad version (%Ld)\n", tmp);
831
        return -1;
832
    }
833
    
834
    nut->stream_count = get_v(bc);
835
    get_v(bc); //checksum threshold
836

    
837
    for(i=0; i<256;){
838
        int tmp_flags = get_v(bc);
839
        int tmp_stream= get_v(bc);
840
        int tmp_mul   = get_v(bc);
841
        int tmp_size  = get_v(bc);
842
        int count     = get_v(bc);
843

    
844
        if(count == 0 || i+count > 256){
845
            av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
846
            return -1;
847
        }
848

    
849
        if((tmp_flags & FLAG_FRAME_TYPE) && tmp_flags != 1){
850
            if(tmp_flags & FLAG_PRED_KEY_FRAME){
851
                av_log(s, AV_LOG_ERROR, "keyframe prediction in non 0 frame type\n");
852
                return -1;
853
            }
854
            if(!(tmp_flags & FLAG_PTS) || !(tmp_flags & FLAG_FULL_PTS) ){
855
                av_log(s, AV_LOG_ERROR, "no full pts in non 0 frame type\n");
856
                return -1;
857
            }
858
        }
859

    
860
        for(j=0; j<count; j++,i++){
861
            if(tmp_stream > nut->stream_count + 1){
862
                av_log(s, AV_LOG_ERROR, "illegal stream number\n");
863
                return -1;
864
            }
865

    
866
            nut->frame_code[i].flags           = tmp_flags ;
867
            nut->frame_code[i].stream_id_plus1 = tmp_stream;
868
            nut->frame_code[i].size_mul        = tmp_mul   ;
869
            nut->frame_code[i].size_lsb        = tmp_size  ;
870
            if(++tmp_size >= tmp_mul){
871
                tmp_size=0;
872
                tmp_stream++;
873
            }
874
        }
875
    }
876
    if(nut->frame_code['N'].flags != 1){
877
        av_log(s, AV_LOG_ERROR, "illegal frame_code table\n");
878
        return -1;
879
    }
880

    
881
    if(check_checksum(bc)){
882
        av_log(s, AV_LOG_ERROR, "Main header checksum missmatch\n");
883
        return -1;
884
    }
885

    
886
    return 0;
887
}
888

    
889
static int decode_stream_header(NUTContext *nut){
890
    AVFormatContext *s= nut->avf;
891
    ByteIOContext *bc = &s->pb;
892
    int class, nom, denom, stream_id, i;
893
    uint64_t tmp;
894
    AVStream *st;
895
    
896
    get_packetheader(nut, bc, 8, 1);
897
    stream_id= get_v(bc);
898
    if(stream_id >= nut->stream_count || s->streams[stream_id])
899
        return -1;
900
    
901
    st = av_new_stream(s, stream_id);
902
    if (!st)
903
        return AVERROR_NOMEM;
904
    class = get_v(bc);
905
    tmp = get_vb(bc);
906
    switch(class)
907
    {
908
        case 0:
909
            st->codec.codec_type = CODEC_TYPE_VIDEO;
910
            st->codec.codec_id = codec_get_bmp_id(tmp);
911
            if (st->codec.codec_id == CODEC_ID_NONE)
912
                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
913
            break;
914
        case 32:
915
            st->codec.codec_type = CODEC_TYPE_AUDIO;
916
            st->codec.codec_id = codec_get_wav_id(tmp);
917
            if (st->codec.codec_id == CODEC_ID_NONE)
918
                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
919
            break;
920
        default:
921
            av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);
922
            return -1;
923
    }
924
    s->bit_rate += get_v(bc);
925
    get_vb(bc); /* language code */
926
    nom = get_v(bc);
927
    denom = get_v(bc);
928
    nut->stream[stream_id].msb_timestamp_shift = get_v(bc);
929
    for(i=0; i<3; i++)
930
            nut->stream[stream_id].initial_pts_predictor[i]= get_v(bc);
931
    for(i=0; i<2; i++)
932
            nut->stream[stream_id].initial_size_predictor[i]= get_v(bc);
933
    get_byte(bc); /* flags */
934

    
935
    /* codec specific data headers */
936
    while(get_v(bc) != 0){
937
        st->codec.extradata_size= get_v(bc);
938
        st->codec.extradata= av_mallocz(st->codec.extradata_size);
939
        get_buffer(bc, st->codec.extradata, st->codec.extradata_size);            
940
//            url_fskip(bc, get_v(bc));
941
    }
942
    
943
    if (class == 0) /* VIDEO */
944
    {
945
        st->codec.width = get_v(bc);
946
        st->codec.height = get_v(bc);
947
        st->codec.sample_aspect_ratio.num= get_v(bc);
948
        st->codec.sample_aspect_ratio.den= get_v(bc);
949
        get_v(bc); /* csp type */
950

    
951
        st->codec.frame_rate = nom;
952
        st->codec.frame_rate_base = denom;
953
    }
954
    if (class == 32) /* AUDIO */
955
    {
956
        st->codec.sample_rate = (get_v(bc) * nom) / denom;
957
        st->codec.channels = get_v(bc);
958
    }
959
    if(check_checksum(bc)){
960
        av_log(s, AV_LOG_ERROR, "Stream header %d checksum missmatch\n", stream_id);
961
        return -1;
962
    }
963
    nut->stream[stream_id].rate_num= nom;
964
    nut->stream[stream_id].rate_den= denom;
965
    return 0;
966
}
967

    
968
static int decode_info_header(NUTContext *nut){
969
    AVFormatContext *s= nut->avf;
970
    ByteIOContext *bc = &s->pb;
971
    
972
    get_packetheader(nut, bc, 8, 1);
973

    
974
    for(;;){
975
        int id= get_v(bc);
976
        char *name, *type, custom_name[256], custom_type[256];
977

    
978
        if(!id)
979
            break;
980
        else if(id >= sizeof(info_table)/sizeof(info_table[0])){
981
            av_log(s, AV_LOG_ERROR, "info id is too large %d %d\n", id, sizeof(info_table)/sizeof(info_table[0]));
982
            return -1;
983
        }
984

    
985
        type= info_table[id][1];
986
        name= info_table[id][0];
987
//av_log(s, AV_LOG_DEBUG, "%d %s %s\n", id, type, name);
988

    
989
        if(!type){
990
            get_str(bc, custom_type, sizeof(custom_type));
991
            type= custom_type;
992
        }
993
        if(!name){
994
            get_str(bc, custom_name, sizeof(custom_name));
995
            name= custom_name;
996
        }
997
        
998
        if(!strcmp(type, "v")){
999
            int value= get_v(bc);
1000
        }else{
1001
            if(!strcmp(name, "Author"))
1002
                get_str(bc, s->author, sizeof(s->author));
1003
            else if(!strcmp(name, "Title"))
1004
                get_str(bc, s->title, sizeof(s->title));
1005
            else if(!strcmp(name, "Copyright"))
1006
                get_str(bc, s->copyright, sizeof(s->copyright));
1007
            else if(!strcmp(name, "Description"))
1008
                get_str(bc, s->comment, sizeof(s->comment));
1009
            else
1010
                get_str(bc, NULL, 0);
1011
        }
1012
    }
1013
    if(check_checksum(bc)){
1014
        av_log(s, AV_LOG_ERROR, "Info header checksum missmatch\n");
1015
        return -1;
1016
    }
1017
    return 0;
1018
}
1019

    
1020
static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
1021
{
1022
    NUTContext *nut = s->priv_data;
1023
    ByteIOContext *bc = &s->pb;
1024
    int64_t pos;
1025
    int inited_stream_count;
1026

    
1027
    nut->avf= s;
1028
    
1029
    av_set_pts_info(s, 60, 1, AV_TIME_BASE);
1030

    
1031
    /* main header */
1032
    pos=0;
1033
    for(;;){
1034
        pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
1035
        if (pos<0){
1036
            av_log(s, AV_LOG_ERROR, "no main startcode found\n");
1037
            return -1;
1038
        }
1039
        if(decode_main_header(nut) >= 0)
1040
            break;
1041
    }
1042
    
1043
    
1044
    s->bit_rate = 0;
1045

    
1046
    nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);
1047

    
1048
    /* stream headers */
1049
    pos=0;
1050
    for(inited_stream_count=0; inited_stream_count < nut->stream_count;){
1051
        pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
1052
        if (pos<0){
1053
            av_log(s, AV_LOG_ERROR, "not all stream headers found\n");
1054
            return -1;
1055
        }
1056
        if(decode_stream_header(nut) >= 0)
1057
            inited_stream_count++;
1058
    }
1059

    
1060
    /* info headers */
1061
    pos=0;
1062
    for(;;){
1063
        uint64_t startcode= find_any_startcode(bc, pos);
1064
        pos= url_ftell(bc);
1065

    
1066
        if(startcode==0){
1067
            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
1068
            return -1;
1069
        }else if(startcode == KEYFRAME_STARTCODE){
1070
            nut->next_startcode= startcode;
1071
            break;
1072
        }else if(startcode != INFO_STARTCODE){
1073
            continue;
1074
        }
1075

    
1076
        decode_info_header(nut);
1077
    }
1078

    
1079
    return 0;
1080
}
1081

    
1082
static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code, int frame_type){
1083
    AVFormatContext *s= nut->avf;
1084
    StreamContext *stream;
1085
    ByteIOContext *bc = &s->pb;
1086
    int size, flags, size_mul, size_lsb, stream_id;
1087
    int key_frame = 0;
1088
    int64_t pts = 0;
1089
    const int prefix_len= frame_type == 2 ? 8+1 : 1;
1090
    const int64_t frame_start= url_ftell(bc) - prefix_len;
1091

    
1092
    flags= nut->frame_code[frame_code].flags;
1093
    size_mul= nut->frame_code[frame_code].size_mul;
1094
    size_lsb= nut->frame_code[frame_code].size_lsb;
1095
    stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
1096

    
1097
    if(flags & FLAG_FRAME_TYPE){
1098
        reset(s);
1099
        if(get_packetheader(nut, bc, prefix_len, 0) < 0)
1100
            return -1;
1101
        if(frame_type!=2)
1102
            frame_type= 1;
1103
    }
1104

    
1105
    if(stream_id==-1)
1106
        stream_id= get_v(bc);
1107
    if(stream_id >= s->nb_streams){
1108
        av_log(s, AV_LOG_ERROR, "illegal stream_id\n");
1109
        return -1;
1110
    }
1111
    stream= &nut->stream[stream_id];
1112

    
1113
//    av_log(s, AV_LOG_DEBUG, "ft:%d ppts:%d %d %d\n", frame_type, stream->lru_pts_delta[0], stream->lru_pts_delta[1], stream->lru_pts_delta[2]);
1114
    
1115
    if(flags & FLAG_PRED_KEY_FRAME){
1116
        if(flags & FLAG_KEY_FRAME)
1117
            key_frame= !stream->last_key_frame;
1118
        else
1119
            key_frame= stream->last_key_frame;
1120
    }else{
1121
        key_frame= !!(flags & FLAG_KEY_FRAME);
1122
    }
1123

    
1124
    if(flags & FLAG_PTS){
1125
        if(flags & FLAG_FULL_PTS){
1126
            pts= get_v(bc);
1127
            if(frame_type && key_frame){
1128
                av_add_index_entry(
1129
                    s->streams[stream_id], 
1130
                    frame_start, 
1131
                    pts, 
1132
                    frame_start - nut->stream[stream_id].last_sync_pos,
1133
                    AVINDEX_KEYFRAME);
1134
                nut->stream[stream_id].last_sync_pos= frame_start;
1135
                assert(nut->packet_start == frame_start);
1136
            }
1137
        }else{
1138
            int64_t mask = (1<<stream->msb_timestamp_shift)-1;
1139
            int64_t delta= stream->last_pts - mask/2;
1140
            pts= ((get_v(bc) - delta)&mask) + delta;
1141
        }
1142
    }else{
1143
        pts= stream->last_pts + stream->lru_pts_delta[(flags&12)>>2];
1144
    }
1145
  
1146
    if(size_mul <= size_lsb){
1147
        size= stream->lru_size[size_lsb - size_mul];
1148
    }else{
1149
        if(flags & FLAG_DATA_SIZE)
1150
            size= size_mul*get_v(bc) + size_lsb;
1151
        else
1152
            size= size_lsb;
1153
    }
1154
      
1155
//av_log(s, AV_LOG_DEBUG, "fs:%lld fc:%d ft:%d kf:%d pts:%lld size:%d\n", frame_start, frame_code, frame_type, key_frame, pts, size);
1156

    
1157
    if(url_ftell(bc) - nut->packet_start + size > nut->written_packet_size){
1158
        av_log(s, AV_LOG_ERROR, "frame size too large\n");
1159
        return -1;
1160
    }
1161
    
1162
    av_new_packet(pkt, size);
1163
    get_buffer(bc, pkt->data, size);
1164
    pkt->stream_index = stream_id;
1165
    if (key_frame)
1166
        pkt->flags |= PKT_FLAG_KEY;
1167
    pkt->pts = pts * AV_TIME_BASE * stream->rate_den / stream->rate_num;
1168

    
1169
    update(nut, stream_id, frame_start, frame_type, frame_code, key_frame, size, pts);
1170
    
1171
    return 0;
1172
}
1173

    
1174
static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1175
{
1176
    NUTContext *nut = s->priv_data;
1177
    ByteIOContext *bc = &s->pb;
1178
    int size, i, frame_code=0;
1179
    int64_t pos;
1180

    
1181
    for(;;){
1182
        int frame_type= 0;
1183
        uint64_t tmp= nut->next_startcode;
1184
        nut->next_startcode=0;
1185

    
1186
        if (url_feof(bc))
1187
            return -1;
1188

    
1189
        if(!tmp){
1190
            frame_code = get_byte(bc);
1191
            if(frame_code == 'N'){
1192
                tmp= frame_code;
1193
                for(i=1; i<8; i++)
1194
                    tmp = (tmp<<8) + get_byte(bc);
1195
            }
1196
        }
1197
        switch(tmp){
1198
        case MAIN_STARTCODE:
1199
        case STREAM_STARTCODE:
1200
        case INDEX_STARTCODE:
1201
            get_packetheader(nut, bc, 8, 0);
1202
            url_fseek(bc, nut->written_packet_size + nut->packet_start, SEEK_SET);
1203
            break;
1204
        case INFO_STARTCODE:
1205
            if(decode_info_header(nut)<0)
1206
                goto resync;
1207
            break;
1208
        case KEYFRAME_STARTCODE:
1209
            frame_type = 2;
1210
            frame_code = get_byte(bc);
1211
        case 0:
1212
            if(decode_frame(nut, pkt, frame_code, frame_type)>=0)
1213
                return 0;
1214
        default:
1215
resync:
1216
av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start+1);
1217
            tmp= find_any_startcode(bc, nut->packet_start+1);
1218
            if(tmp==0)
1219
                return -1;
1220
av_log(s, AV_LOG_DEBUG, "sync\n");
1221
            if(url_is_streamed(bc)){
1222
                nut->next_startcode= tmp;
1223
                break;
1224
            }
1225

    
1226
            pos= url_ftell(bc) - 8;
1227
av_log(s, AV_LOG_DEBUG, "at %lld code=%llX\n", pos, tmp);
1228
            if(tmp==KEYFRAME_STARTCODE){
1229
                get_byte(bc);
1230
            }
1231
            get_v(bc);
1232
            size= get_v(bc);
1233
            
1234
            while(size > 2 && size < 100000 && nut->packet_start < pos - size){
1235
                url_fseek(bc, pos - size, SEEK_SET);
1236
                frame_code= get_byte(bc);
1237
                if(!(nut->frame_code[ frame_code ].flags & FLAG_FRAME_TYPE))
1238
                    break;
1239
                if(get_v(bc) != size)
1240
                    break;
1241
                pos -= size;
1242
                size= get_v(bc);
1243
av_log(s, AV_LOG_DEBUG, "steping back to %lld next %d\n", pos, size);
1244
            }
1245
            url_fseek(bc, pos, SEEK_SET);
1246
            
1247
            nut->written_packet_size= -1;
1248
        }
1249
    }
1250
}
1251

    
1252
static int64_t read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
1253
    NUTContext *nut = s->priv_data;
1254
    ByteIOContext *bc = &s->pb;
1255
    int64_t pos, pts;
1256
    uint64_t code;
1257
    int frame_code,step, flags, stream_id, i;
1258
av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%lld,%lld)\n", stream_index, *pos_arg, pos_limit);
1259

    
1260
    if(*pos_arg < 0)
1261
        return AV_NOPTS_VALUE;
1262

    
1263
    // find a previous startcode, FIXME use forward search and follow backward pointers if undamaged stream
1264
    pos= *pos_arg;
1265
    step= FFMIN(16*1024, pos);
1266
    do{
1267
        pos-= step;
1268
        code= find_any_startcode(bc, pos);
1269

    
1270
        if(code && url_ftell(bc) - 8 < *pos_arg)
1271
            break;
1272
        step= FFMIN(2*step, pos);
1273
    }while(step);
1274

    
1275
    if(!code) //nothing found, not even after pos_arg
1276
        return AV_NOPTS_VALUE;
1277

    
1278
    url_fseek(bc, -8, SEEK_CUR);
1279
    for(i=0; i<s->nb_streams; i++)
1280
        nut->stream[i].last_sync_pos= url_ftell(bc);
1281
        
1282
    for(;;){
1283
        int64_t pos= url_ftell(bc);
1284
        uint64_t tmp=0;
1285
        int prefix_len=1;
1286
        
1287
        if(pos > pos_limit)
1288
            return AV_NOPTS_VALUE;
1289

    
1290
        frame_code = get_byte(bc);
1291
        if(frame_code == 'N'){
1292
            tmp= frame_code;
1293
            for(i=1; i<8; i++)
1294
                tmp = (tmp<<8) + get_byte(bc);
1295
        }
1296
//av_log(s, AV_LOG_DEBUG, "before switch %llX at=%lld\n", tmp, pos);
1297

    
1298
        switch(tmp){
1299
        case MAIN_STARTCODE:
1300
        case STREAM_STARTCODE:
1301
        case INDEX_STARTCODE:
1302
        case INFO_STARTCODE:
1303
            nut->written_packet_size= -1;
1304
            get_packetheader(nut, bc, 8, 0);
1305
            url_fseek(bc, nut->written_packet_size + nut->packet_start, SEEK_SET);
1306
            break;
1307
        case KEYFRAME_STARTCODE:
1308
            nut->written_packet_size= -1;
1309
            prefix_len+=8;
1310
            frame_code = get_byte(bc);
1311
        case 0:
1312
            flags= nut->frame_code[frame_code].flags;
1313
            stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
1314

    
1315
            if(get_packetheader(nut, bc, prefix_len, 0) < 0)
1316
                goto resync;
1317

    
1318
            if(!(flags & FLAG_FRAME_TYPE) || !(flags & FLAG_PTS) || !(flags & FLAG_FULL_PTS))
1319
                goto resync;
1320

    
1321
            if(stream_id==-1)
1322
                stream_id= get_v(bc);
1323
            if(stream_id >= s->nb_streams)
1324
                goto resync;
1325
                
1326
            pts= get_v(bc);
1327
    
1328
            if(flags & FLAG_KEY_FRAME){
1329
                av_add_index_entry(
1330
                    s->streams[stream_id], 
1331
                    pos, 
1332
                    pts, 
1333
                    pos - nut->stream[stream_id].last_sync_pos,
1334
                    AVINDEX_KEYFRAME);
1335
                nut->stream[stream_id].last_sync_pos= pos;
1336
            }
1337
            if(stream_id != stream_index || !(flags & FLAG_KEY_FRAME) || nut->packet_start < *pos_arg){
1338
                url_fseek(bc, nut->written_packet_size + nut->packet_start, SEEK_SET);
1339
                break;
1340
            }
1341
 
1342
            *pos_arg= nut->packet_start;
1343
            assert(nut->packet_start == pos);
1344
            return pts;
1345
        default:
1346
resync:
1347
av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start+1);
1348
            if(!find_any_startcode(bc, nut->packet_start+1))
1349
                return AV_NOPTS_VALUE;
1350

    
1351
            url_fseek(bc, -8, SEEK_CUR);
1352
        }
1353
    }
1354
    return AV_NOPTS_VALUE;
1355
}
1356

    
1357
#define DEBUG_SEEK
1358
static int nut_read_seek(AVFormatContext *s, int stream_index, int64_t target_ts){
1359
    NUTContext *nut = s->priv_data;
1360
    StreamContext *stream;
1361
    int64_t pos_min, pos_max, pos, pos_limit;
1362
    int64_t ts_min, ts_max, ts;
1363
    int64_t start_pos;
1364
    int index, no_change,i;
1365
    AVStream *st;
1366

    
1367
    if (stream_index < 0) {
1368
        stream_index = av_find_default_stream_index(s);
1369
        if (stream_index < 0)
1370
            return -1;
1371
    }
1372
    stream= &nut->stream[stream_index];
1373
    target_ts= (av_rescale(target_ts, stream->rate_num, stream->rate_den) + AV_TIME_BASE/2) / AV_TIME_BASE;
1374

    
1375
#ifdef DEBUG_SEEK
1376
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
1377
#endif
1378

    
1379
    ts_max=
1380
    ts_min= AV_NOPTS_VALUE;
1381
    pos_limit= -1; //gcc falsely says it may be uninitalized
1382

    
1383
    st= s->streams[stream_index];
1384
    if(st->index_entries){
1385
        AVIndexEntry *e;
1386

    
1387
        index= av_index_search_timestamp(st, target_ts);
1388
        e= &st->index_entries[index];
1389

    
1390
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1391
            pos_min= e->pos;
1392
            ts_min= e->timestamp;
1393
#ifdef DEBUG_SEEK
1394
        av_log(s, AV_LOG_DEBUG, "unsing cached pos_min=0x%llx dts_min=%lld\n", 
1395
               pos_min,ts_min);
1396
#endif
1397
        }else{
1398
            assert(index==0);
1399
        }
1400
        index++;
1401
        if(index < st->nb_index_entries){
1402
            e= &st->index_entries[index];
1403
            assert(e->timestamp >= target_ts);
1404
            pos_max= e->pos;
1405
            ts_max= e->timestamp;
1406
            pos_limit= pos_max - e->min_distance;
1407
#ifdef DEBUG_SEEK
1408
        av_log(s, AV_LOG_DEBUG, "unsing cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n", 
1409
               pos_max,pos_limit, ts_max);
1410
#endif
1411
        }
1412
    }
1413

    
1414
    if(ts_min == AV_NOPTS_VALUE){
1415
        pos_min = 0;
1416
        ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1417
        if (ts_min == AV_NOPTS_VALUE)
1418
            return -1;
1419
    }
1420

    
1421
    if(ts_max == AV_NOPTS_VALUE){
1422
        int step= 1024;
1423
        pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1424
        do{
1425
            pos_max -= step;
1426
            ts_max = read_timestamp(s, stream_index, &pos_max, pos_max + step);
1427
            step += step;
1428
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1429
        if (ts_max == AV_NOPTS_VALUE)
1430
            return -1;
1431
        
1432
        for(;;){
1433
            int64_t tmp_pos= pos_max + 1;
1434
            int64_t tmp_ts= read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1435
            if(tmp_ts == AV_NOPTS_VALUE)
1436
                break;
1437
            ts_max= tmp_ts;
1438
            pos_max= tmp_pos;
1439
        }
1440
        pos_limit= pos_max;
1441
    }
1442

    
1443
    no_change=0;
1444
    while (pos_min < pos_limit) {
1445
#ifdef DEBUG_SEEK
1446
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n", 
1447
               pos_min, pos_max,
1448
               ts_min, ts_max);
1449
#endif
1450
        assert(pos_limit <= pos_max);
1451

    
1452
        if(no_change==0){
1453
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1454
            // interpolate position (better than dichotomy)
1455
            pos = (int64_t)((double)(pos_max - pos_min) *
1456
                            (double)(target_ts - ts_min) /
1457
                            (double)(ts_max - ts_min)) + pos_min - approximate_keyframe_distance;
1458
        }else if(no_change==1){
1459
            // bisection, if interpolation failed to change min or max pos last time
1460
            pos = (pos_min + pos_limit)>>1;
1461
        }else{
1462
            // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1463
            pos=pos_min;
1464
        }
1465
        if(pos <= pos_min)
1466
            pos= pos_min + 1;
1467
        else if(pos > pos_limit)
1468
            pos= pos_limit;
1469
        start_pos= pos;
1470

    
1471
        ts = read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1472
        if(pos == pos_max)
1473
            no_change++;
1474
        else
1475
            no_change=0;
1476
#ifdef DEBUG_SEEK
1477
av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1478
#endif
1479
        assert(ts != AV_NOPTS_VALUE);
1480
        if (target_ts < ts) {
1481
            pos_limit = start_pos - 1;
1482
            pos_max = pos;
1483
            ts_max = ts;
1484
        } else {
1485
            pos_min = pos;
1486
            ts_min = ts;
1487
            /* check if we are lucky */
1488
            if (target_ts == ts)
1489
                break;
1490
        }
1491
    }
1492
    
1493
    pos = pos_min;
1494
#ifdef DEBUG_SEEK
1495
    pos_min = pos;
1496
    ts_min = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1497
    pos_min++;
1498
    ts_max = read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1499
    av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n", 
1500
           pos, ts_min, target_ts, ts_max);
1501
#endif
1502
    /* do the seek */
1503
    url_fseek(&s->pb, pos, SEEK_SET);
1504

    
1505
    nut->written_packet_size= -1;
1506
    for(i=0; i<s->nb_streams; i++)
1507
        nut->stream[i].last_sync_pos= pos;
1508

    
1509
    return 0;
1510
}
1511

    
1512
static int nut_read_close(AVFormatContext *s)
1513
{
1514
    NUTContext *nut = s->priv_data;
1515
    int i;
1516

    
1517
    for(i=0;i<s->nb_streams;i++) {
1518
        av_freep(&s->streams[i]->codec.extradata);
1519
    }
1520
    av_freep(&nut->stream);
1521

    
1522
    return 0;
1523
}
1524

    
1525
static AVInputFormat nut_iformat = {
1526
    "nut",
1527
    "nut format",
1528
    sizeof(NUTContext),
1529
    nut_probe,
1530
    nut_read_header,
1531
    nut_read_packet,
1532
    nut_read_close,
1533
    nut_read_seek,
1534
    .extensions = "nut",
1535
};
1536

    
1537
#ifdef CONFIG_ENCODERS
1538
static AVOutputFormat nut_oformat = {
1539
    "nut",
1540
    "nut format",
1541
    "video/x-nut",
1542
    "nut",
1543
    sizeof(NUTContext),
1544
#ifdef CONFIG_VORBIS
1545
    CODEC_ID_VORBIS,
1546
#elif defined(CONFIG_MP3LAME)
1547
    CODEC_ID_MP3,
1548
#else
1549
    CODEC_ID_MP2, /* AC3 needs liba52 decoder */
1550
#endif
1551
    CODEC_ID_MPEG4,
1552
    nut_write_header,
1553
    nut_write_packet,
1554
    nut_write_trailer,
1555
};
1556
#endif //CONFIG_ENCODERS
1557

    
1558
int nut_init(void)
1559
{
1560
    av_register_input_format(&nut_iformat);
1561
#ifdef CONFIG_ENCODERS
1562
    av_register_output_format(&nut_oformat);
1563
#endif //CONFIG_ENCODERS
1564
    return 0;
1565
}