Statistics
| Branch: | Revision:

ffmpeg / libavformat / nut.c @ 01bd1ed2

History | View | Annotate | Download (42.1 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
 * - index writing
29
 * - index packet reading support
30
*/
31

    
32
//#define DEBUG 1
33

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

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

    
42
//#define TRACE
43

    
44
//from /dev/random
45

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

    
52
#define ID_STRING "nut/multimedia container\0"
53

    
54
#define MAX_DISTANCE (1024*16-1)
55
#define MAX_SHORT_DISTANCE (1024*4-1)
56

    
57
#define FLAG_DATA_SIZE       1
58
#define FLAG_KEY_FRAME       2
59
#define FLAG_INVALID         4
60

    
61
typedef struct {
62
    uint8_t flags;
63
    uint8_t stream_id_plus1;
64
    uint16_t size_mul;
65
    uint16_t size_lsb;
66
    int16_t timestamp_delta;
67
    uint8_t reserved_count;
68
} FrameCode;
69

    
70
typedef struct {
71
    int last_key_frame;
72
    int msb_timestamp_shift;
73
    int rate_num;
74
    int rate_den;
75
    int64_t last_pts;
76
    int64_t last_sync_pos;                    ///<pos of last 1/2 type frame
77
    int decode_delay;
78
} StreamContext;
79

    
80
typedef struct {
81
    AVFormatContext *avf;
82
    int written_packet_size;
83
    int64_t packet_start[3]; //0-> startcode less, 1-> short startcode 2-> long startcodes
84
    FrameCode frame_code[256];
85
    unsigned int stream_count;
86
    uint64_t next_startcode;     ///< stores the next startcode if it has alraedy been parsed but the stream isnt seekable
87
    StreamContext *stream;
88
    int max_distance;
89
    int max_short_distance;
90
    int rate_num;
91
    int rate_den;
92
    int short_startcode;
93
} NUTContext;
94

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

    
115
void ff_parse_specific_params(AVCodecContext *stream, int *au_rate, int *au_ssize, int *au_scale);
116

    
117
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){
118
    StreamContext *stream= &nut->stream[stream_index];
119
    
120
    stream->last_key_frame= key_frame;
121
    nut->packet_start[ frame_type ]= frame_start;
122
    stream->last_pts= pts;
123
}
124

    
125
static void reset(AVFormatContext *s, int64_t global_ts){
126
    NUTContext *nut = s->priv_data;
127
    int i;
128
    
129
    for(i=0; i<s->nb_streams; i++){
130
        StreamContext *stream= &nut->stream[i];
131
    
132
        stream->last_key_frame= 1;
133

    
134
        stream->last_pts= av_rescale(global_ts, stream->rate_num*(int64_t)nut->rate_den, stream->rate_den*(int64_t)nut->rate_num);
135
    }
136
}
137

    
138
static void build_frame_code(AVFormatContext *s){
139
    NUTContext *nut = s->priv_data;
140
    int key_frame, index, pred, stream_id;
141
    int start=0;
142
    int end= 255;
143
    int keyframe_0_esc= s->nb_streams > 2;
144
    int pred_table[10];
145

    
146
    if(keyframe_0_esc){
147
        /* keyframe = 0 escape */
148
        FrameCode *ft= &nut->frame_code[start];
149
        ft->flags= FLAG_DATA_SIZE;
150
        ft->stream_id_plus1= 0;
151
        ft->size_mul=1;
152
        ft->timestamp_delta=0;
153
        start++;
154
    }
155

    
156
    for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
157
        int start2= start + (end-start)*stream_id / s->nb_streams;
158
        int end2  = start + (end-start)*(stream_id+1) / s->nb_streams;
159
        AVCodecContext *codec = &s->streams[stream_id]->codec;
160
        int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
161
        int intra_only= /*codec->intra_only || */is_audio;
162
        int pred_count;
163

    
164
        for(key_frame=0; key_frame<2; key_frame++){
165
            if(intra_only && keyframe_0_esc && key_frame==0)
166
                continue;
167
            
168
            {
169
                FrameCode *ft= &nut->frame_code[start2];
170
                ft->flags= FLAG_KEY_FRAME*key_frame;
171
                ft->flags|= FLAG_DATA_SIZE;
172
                ft->stream_id_plus1= stream_id + 1;
173
                ft->size_mul=1;
174
                ft->timestamp_delta=0;
175
                start2++;
176
            }
177
        }
178

    
179
        key_frame= intra_only;
180
#if 1
181
        if(is_audio){
182
            int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
183
            int pts;
184
            for(pts=0; pts<2; pts++){
185
                for(pred=0; pred<2; pred++){
186
                    FrameCode *ft= &nut->frame_code[start2];
187
                    ft->flags= FLAG_KEY_FRAME*key_frame;
188
                    ft->stream_id_plus1= stream_id + 1;
189
                    ft->size_mul=frame_bytes + 2;
190
                    ft->size_lsb=frame_bytes + pred;
191
                    ft->timestamp_delta=pts;
192
                    start2++;
193
                }
194
            }
195
        }else{
196
            FrameCode *ft= &nut->frame_code[start2];
197
            ft->flags= FLAG_KEY_FRAME | FLAG_DATA_SIZE;
198
            ft->stream_id_plus1= stream_id + 1;
199
            ft->size_mul=1;
200
            ft->timestamp_delta=1;
201
            start2++;
202
        }
203
#endif
204

    
205
        if(codec->has_b_frames){
206
            pred_count=5;
207
            pred_table[0]=-2;
208
            pred_table[1]=-1;
209
            pred_table[2]=1;
210
            pred_table[3]=3;
211
            pred_table[4]=4;
212
        }else if(codec->codec_id == CODEC_ID_VORBIS){
213
            pred_count=3;
214
            pred_table[0]=2;
215
            pred_table[1]=9;
216
            pred_table[2]=16;
217
        }else{
218
            pred_count=1;
219
            pred_table[0]=1;
220
        }
221

    
222
        for(pred=0; pred<pred_count; pred++){
223
            int start3= start2 + (end2-start2)*pred / pred_count;
224
            int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
225

    
226
            for(index=start3; index<end3; index++){
227
                FrameCode *ft= &nut->frame_code[index];
228
                ft->flags= FLAG_KEY_FRAME*key_frame;
229
                ft->flags|= FLAG_DATA_SIZE;
230
                ft->stream_id_plus1= stream_id + 1;
231
//FIXME use single byte size and pred from last
232
                ft->size_mul= end3-start3;
233
                ft->size_lsb= index - start3;
234
                ft->timestamp_delta= pred_table[pred];
235
            }
236
        }
237
    }
238
    memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
239
    nut->frame_code['N'].flags= FLAG_INVALID;
240
}
241

    
242
static uint64_t get_v(ByteIOContext *bc)
243
{
244
    uint64_t val = 0;
245

    
246
    for(;;)
247
    {
248
        int tmp = get_byte(bc);
249

    
250
        if (tmp&0x80)
251
            val= (val<<7) + tmp - 0x80;
252
        else{
253
//av_log(NULL, AV_LOG_DEBUG, "get_v()= %lld\n", (val<<7) + tmp);
254
            return (val<<7) + tmp;
255
        }
256
    }
257
    return -1;
258
}
259

    
260
static int get_str(ByteIOContext *bc, char *string, unsigned int maxlen){
261
    unsigned int len= get_v(bc);
262
    
263
    if(len && maxlen)
264
        get_buffer(bc, string, FFMIN(len, maxlen));
265
    while(len > maxlen){
266
        get_byte(bc);
267
        len--;
268
    }
269

    
270
    if(maxlen)
271
        string[FFMIN(len, maxlen-1)]= 0;
272
    
273
    if(maxlen == len)
274
        return -1;
275
    else
276
        return 0;
277
}
278

    
279
static int64_t get_s(ByteIOContext *bc){
280
    int64_t v = get_v(bc) + 1;
281

    
282
    if (v&1) return -(v>>1);
283
    else     return  (v>>1);
284
}
285

    
286
static uint64_t get_vb(ByteIOContext *bc){
287
    uint64_t val=0;
288
    unsigned int i= get_v(bc);
289
    
290
    if(i>8)
291
        return UINT64_MAX;
292
    
293
    while(i--)
294
        val = (val<<8) + get_byte(bc);
295
    
296
//av_log(NULL, AV_LOG_DEBUG, "get_vb()= %lld\n", val);
297
    return val;
298
}
299

    
300
#ifdef TRACE
301
static inline uint64_t get_v_trace(ByteIOContext *bc, char *file, char *func, int line){
302
    uint64_t v= get_v(bc);
303

    
304
    printf("get_v %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
305
    return v;
306
}
307

    
308
static inline int64_t get_s_trace(ByteIOContext *bc, char *file, char *func, int line){
309
    int64_t v= get_s(bc);
310

    
311
    printf("get_s %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
312
    return v;
313
}
314

    
315
static inline uint64_t get_vb_trace(ByteIOContext *bc, char *file, char *func, int line){
316
    uint64_t v= get_vb(bc);
317

    
318
    printf("get_vb %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
319
    return v;
320
}
321
#define get_v(bc)  get_v_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
322
#define get_s(bc)  get_s_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
323
#define get_vb(bc)  get_vb_trace(bc, __FILE__, __PRETTY_FUNCTION__, __LINE__)
324
#endif
325

    
326

    
327
static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int calculate_checksum)
328
{
329
    int64_t start, size;
330
    start= url_ftell(bc) - 8;
331

    
332
    init_checksum(bc, calculate_checksum ? update_adler32 : NULL, 0);
333

    
334
    size= get_v(bc);
335

    
336
    nut->packet_start[2] = start;
337
    nut->written_packet_size= size;
338

    
339
    return size;
340
}
341

    
342
static int check_checksum(ByteIOContext *bc){
343
    unsigned long checksum= get_checksum(bc);
344
    return checksum != get_be32(bc);
345
}
346

    
347
/**
348
 * 
349
 */
350
static int get_length(uint64_t val){
351
    int i;
352

    
353
    for (i=7; val>>i; i+=7);
354

    
355
    return i;
356
}
357

    
358
static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
359
    uint64_t state=0;
360
    
361
    if(pos >= 0)
362
        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
363

    
364
    while(!url_feof(bc)){
365
        state= (state<<8) | get_byte(bc);
366
        if((state>>56) != 'N')
367
            continue;
368
        switch(state){
369
        case MAIN_STARTCODE:
370
        case STREAM_STARTCODE:
371
        case KEYFRAME_STARTCODE:
372
        case INFO_STARTCODE:
373
        case INDEX_STARTCODE:
374
            return state;
375
        }
376
    }
377

    
378
    return 0;
379
}
380

    
381
/**
382
 * find the given startcode.
383
 * @param code the startcode
384
 * @param pos the start position of the search, or -1 if the current position
385
 * @returns the position of the startcode or -1 if not found
386
 */
387
static int64_t find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
388
    for(;;){
389
        uint64_t startcode= find_any_startcode(bc, pos);
390
        if(startcode == code)
391
            return url_ftell(bc) - 8;
392
        else if(startcode == 0)
393
            return -1;
394
        pos=-1;
395
    }
396
}
397

    
398
#ifdef CONFIG_ENCODERS
399

    
400
static void put_v(ByteIOContext *bc, uint64_t val)
401
{
402
    int i;
403

    
404
//av_log(NULL, AV_LOG_DEBUG, "put_v()= %lld\n", val);
405
    val &= 0x7FFFFFFFFFFFFFFFULL; // FIXME can only encode upto 63 bits currently
406
    i= get_length(val);
407

    
408
    for (i-=7; i>0; i-=7){
409
        put_byte(bc, 0x80 | (val>>i));
410
    }
411

    
412
    put_byte(bc, val&0x7f);
413
}
414

    
415
/**
416
 * stores a string as vb.
417
 */
418
static void put_str(ByteIOContext *bc, const char *string){
419
    int len= strlen(string);
420
    
421
    put_v(bc, len);
422
    put_buffer(bc, string, len);
423
}
424

    
425
static void put_s(ByteIOContext *bc, int64_t val){
426
    if (val<=0) put_v(bc, -2*val  );
427
    else        put_v(bc,  2*val-1);
428
}
429

    
430
static void put_vb(ByteIOContext *bc, uint64_t val){
431
    int i;
432
    
433
    for (i=8; val>>i; i+=8);
434

    
435
    put_v(bc, i>>3);
436
    for(i-=8; i>=0; i-=8)
437
        put_byte(bc, (val>>i)&0xFF);
438
}
439

    
440
#ifdef TRACE
441
static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
442
    printf("get_v %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
443
    
444
    put_v(bc, v);
445
}
446

    
447
static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
448
    printf("get_s %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
449
    
450
    put_s(bc, v);
451
}
452

    
453
static inline void put_vb_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
454
    printf("get_vb %5lld / %llX in %s %s:%d\n", v, v, file, func, line);
455
    
456
    put_vb(bc, v);
457
}
458
#define put_v(bc, v)  put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
459
#define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
460
#define put_vb(bc, v)  put_vb_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
461
#endif
462

    
463
static int put_packetheader(NUTContext *nut, ByteIOContext *bc, int max_size, int calculate_checksum)
464
{
465
    put_flush_packet(bc);
466
    nut->packet_start[2]+= nut->written_packet_size;
467
    assert(url_ftell(bc) - 8 == nut->packet_start[2]);
468
    nut->written_packet_size = max_size;
469
    
470
    if(calculate_checksum)
471
        init_checksum(bc, update_adler32, 0);
472

    
473
    /* packet header */
474
    put_v(bc, nut->written_packet_size); /* forward ptr */
475

    
476
    return 0;
477
}
478

    
479
static int update_packetheader(NUTContext *nut, ByteIOContext *bc, int additional_size, int calculate_checksum){
480
    int64_t start= nut->packet_start[2];
481
    int64_t cur= url_ftell(bc);
482
    int size= cur - start + additional_size;
483
    
484
    if(calculate_checksum)
485
        size += 4;
486
    
487
    if(size != nut->written_packet_size){
488
        int i;
489

    
490
        assert( size <= nut->written_packet_size );
491
    
492
        url_fseek(bc, start + 8, SEEK_SET);
493
        for(i=get_length(size); i < get_length(nut->written_packet_size); i+=7)
494
            put_byte(bc, 0x80);
495
        put_v(bc, size);
496

    
497
        url_fseek(bc, cur, SEEK_SET);
498
        nut->written_packet_size= size; //FIXME may fail if multiple updates with differing sizes, as get_length may differ
499
        
500
        if(calculate_checksum)
501
            put_be32(bc, get_checksum(bc));
502
    }
503
    
504
    return 0;
505
}
506

    
507
static int nut_write_header(AVFormatContext *s)
508
{
509
    NUTContext *nut = s->priv_data;
510
    ByteIOContext *bc = &s->pb;
511
    AVCodecContext *codec;
512
    int i, j, tmp_time, tmp_flags,tmp_stream, tmp_mul, tmp_size, tmp_fields;
513

    
514
    nut->avf= s;
515
    
516
    nut->stream =        
517
        av_mallocz(sizeof(StreamContext)*s->nb_streams);
518
        
519

    
520
    put_buffer(bc, ID_STRING, strlen(ID_STRING));
521
    put_byte(bc, 0);
522
    nut->packet_start[2]= url_ftell(bc);
523
    
524
    /* main header */
525
    put_be64(bc, MAIN_STARTCODE);
526
    put_packetheader(nut, bc, 120+5*256, 1);
527
    put_v(bc, 2); /* version */
528
    put_v(bc, s->nb_streams);
529
    put_v(bc, MAX_DISTANCE);
530
    put_v(bc, MAX_SHORT_DISTANCE);
531
    
532
    put_v(bc, nut->rate_num=1);
533
    put_v(bc, nut->rate_den=2);
534
    put_v(bc, nut->short_startcode=0x4EFE79);
535
    
536
    build_frame_code(s);
537
    assert(nut->frame_code['N'].flags == FLAG_INVALID);
538
    
539
    tmp_time= tmp_flags= tmp_stream= tmp_mul= tmp_size= /*tmp_res=*/ INT_MAX;
540
    for(i=0; i<256;){
541
        tmp_fields=0;
542
        tmp_size= 0;
543
        if(tmp_time   != nut->frame_code[i].timestamp_delta) tmp_fields=1;
544
        if(tmp_mul    != nut->frame_code[i].size_mul       ) tmp_fields=2;
545
        if(tmp_stream != nut->frame_code[i].stream_id_plus1) tmp_fields=3;
546
        if(tmp_size   != nut->frame_code[i].size_lsb       ) tmp_fields=4;
547
//        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
548

    
549
        tmp_time  = nut->frame_code[i].timestamp_delta;
550
        tmp_flags = nut->frame_code[i].flags;
551
        tmp_stream= nut->frame_code[i].stream_id_plus1;
552
        tmp_mul   = nut->frame_code[i].size_mul;
553
        tmp_size  = nut->frame_code[i].size_lsb;
554
//        tmp_res   = nut->frame_code[i].res;
555
        
556
        for(j=0; i<256; j++,i++){
557
            if(nut->frame_code[i].timestamp_delta != tmp_time  ) break;
558
            if(nut->frame_code[i].flags           != tmp_flags ) break;
559
            if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;
560
            if(nut->frame_code[i].size_mul        != tmp_mul   ) break;
561
            if(nut->frame_code[i].size_lsb        != tmp_size+j) break;
562
//            if(nut->frame_code[i].res             != tmp_res   ) break;
563
        }
564
        if(j != tmp_mul - tmp_size) tmp_fields=6;
565

    
566
        put_v(bc, tmp_flags);
567
        put_v(bc, tmp_fields);
568
        if(tmp_fields>0) put_s(bc, tmp_time);
569
        if(tmp_fields>1) put_v(bc, tmp_mul);
570
        if(tmp_fields>2) put_v(bc, tmp_stream);
571
        if(tmp_fields>3) put_v(bc, tmp_size);
572
        if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
573
        if(tmp_fields>5) put_v(bc, j);
574
    }
575

    
576
    update_packetheader(nut, bc, 0, 1);
577
    
578
    /* stream headers */
579
    for (i = 0; i < s->nb_streams; i++)
580
    {
581
        int nom, denom, ssize;
582

    
583
        codec = &s->streams[i]->codec;
584
        
585
        put_be64(bc, STREAM_STARTCODE);
586
        put_packetheader(nut, bc, 120 + codec->extradata_size, 1);
587
        put_v(bc, i /*s->streams[i]->index*/);
588
        switch(codec->codec_type){
589
        case CODEC_TYPE_VIDEO: put_v(bc, 0); break;
590
        case CODEC_TYPE_AUDIO: put_v(bc, 1); break;
591
//        case CODEC_TYPE_TEXT : put_v(bc, 2); break;
592
        case CODEC_TYPE_DATA : put_v(bc, 3); break;
593
        default: return -1;
594
        }
595
        if (codec->codec_tag)
596
            put_vb(bc, codec->codec_tag);
597
        else if (codec->codec_type == CODEC_TYPE_VIDEO)
598
        {
599
            put_vb(bc, codec_get_bmp_tag(codec->codec_id));
600
        }
601
        else if (codec->codec_type == CODEC_TYPE_AUDIO)
602
        {
603
            put_vb(bc, codec_get_wav_tag(codec->codec_id));
604
        }
605
        else
606
            put_vb(bc, 0);
607
        
608
        ff_parse_specific_params(codec, &nom, &ssize, &denom);
609

    
610
        nut->stream[i].rate_num= nom;
611
        nut->stream[i].rate_den= denom;
612
        av_set_pts_info(s->streams[i], 60, denom, nom);
613

    
614
        put_v(bc, codec->bit_rate);
615
        put_vb(bc, 0); /* no language code */
616
        put_v(bc, nom);
617
        put_v(bc, denom);
618
        if(nom / denom < 1000)
619
            nut->stream[i].msb_timestamp_shift = 7;
620
        else
621
            nut->stream[i].msb_timestamp_shift = 14;
622
        put_v(bc, nut->stream[i].msb_timestamp_shift);
623
        put_v(bc, codec->has_b_frames);
624
        put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
625
        
626
        if(codec->extradata_size){
627
            put_v(bc, 1);
628
            put_v(bc, codec->extradata_size);
629
            put_buffer(bc, codec->extradata, codec->extradata_size);            
630
        }
631
        put_v(bc, 0); /* end of codec specific headers */
632
        
633
        switch(codec->codec_type)
634
        {
635
            case CODEC_TYPE_AUDIO:
636
                put_v(bc, codec->sample_rate);
637
                put_v(bc, 1);
638
                put_v(bc, codec->channels);
639
                break;
640
            case CODEC_TYPE_VIDEO:
641
                put_v(bc, codec->width);
642
                put_v(bc, codec->height);
643
                put_v(bc, codec->sample_aspect_ratio.num);
644
                put_v(bc, codec->sample_aspect_ratio.den);
645
                put_v(bc, 0); /* csp type -- unknown */
646
                break;
647
            default:
648
                break;
649
        }
650
        update_packetheader(nut, bc, 0, 1);
651
    }
652

    
653
    /* info header */
654
    put_be64(bc, INFO_STARTCODE);
655
    put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+
656
        strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1); 
657
    if (s->author[0])
658
    {
659
        put_v(bc, 9); /* type */
660
        put_str(bc, s->author);
661
    }
662
    if (s->title[0])
663
    {
664
        put_v(bc, 10); /* type */
665
        put_str(bc, s->title);
666
    }
667
    if (s->comment[0])
668
    {
669
        put_v(bc, 11); /* type */
670
        put_str(bc, s->comment);
671
    }
672
    if (s->copyright[0])
673
    {
674
        put_v(bc, 12); /* type */
675
        put_str(bc, s->copyright);
676
    }
677
    /* encoder */
678
    if(!(s->streams[0]->codec.flags & CODEC_FLAG_BITEXACT)){
679
        put_v(bc, 13); /* type */
680
        put_str(bc, LIBAVFORMAT_IDENT);
681
    }
682
    
683
    put_v(bc, 0); /* eof info */
684
    update_packetheader(nut, bc, 0, 1);
685
        
686
    put_flush_packet(bc);
687
    
688
    return 0;
689
}
690

    
691
static int64_t lsb2full(StreamContext *stream, int64_t lsb){
692
    int64_t mask = (1<<stream->msb_timestamp_shift)-1;
693
    int64_t delta= stream->last_pts - mask/2;
694
    return  ((lsb - delta)&mask) + delta;
695
}
696

    
697
static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
698
{
699
    NUTContext *nut = s->priv_data;
700
    StreamContext *stream= &nut->stream[pkt->stream_index];
701
    ByteIOContext *bc = &s->pb;
702
    int key_frame = 0, full_pts=0;
703
    AVCodecContext *enc;
704
    int64_t coded_pts;
705
    int frame_type, best_length, frame_code, flags, i, size_mul, size_lsb, time_delta;
706
    const int64_t frame_start= url_ftell(bc);
707
    int64_t pts= pkt->pts;
708
    int size= pkt->size;
709
    int stream_index= pkt->stream_index;
710

    
711
    enc = &s->streams[stream_index]->codec;
712
    key_frame = !!(pkt->flags & PKT_FLAG_KEY);
713
    
714
    frame_type=0;
715
    if(frame_start + size + 20 - FFMAX(nut->packet_start[1], nut->packet_start[2]) > MAX_DISTANCE)
716
        frame_type=2;
717
    if(key_frame && !stream->last_key_frame)
718
        frame_type=2;
719

    
720
    if(frame_type>1){
721
        int64_t global_ts= av_rescale(pts, stream->rate_den*(int64_t)nut->rate_num, stream->rate_num*(int64_t)nut->rate_den);
722
        reset(s, global_ts);
723
        put_be64(bc, KEYFRAME_STARTCODE);
724
        put_v(bc, global_ts);
725
    }
726
    assert(stream->last_pts != AV_NOPTS_VALUE);
727
    coded_pts = pts & ((1<<stream->msb_timestamp_shift)-1);
728
    if(lsb2full(stream, coded_pts) != pts)
729
        full_pts=1;
730

    
731
    if(full_pts)
732
        coded_pts= pts + (1<<stream->msb_timestamp_shift);
733

    
734
    best_length=INT_MAX;
735
    frame_code= -1;
736
    for(i=0; i<256; i++){
737
        int stream_id_plus1= nut->frame_code[i].stream_id_plus1;
738
        int fc_key_frame;
739
        int length=0;
740
        size_mul= nut->frame_code[i].size_mul;
741
        size_lsb= nut->frame_code[i].size_lsb;
742
        time_delta= nut->frame_code[i].timestamp_delta;
743
        flags= nut->frame_code[i].flags;
744

    
745
        assert(size_mul > size_lsb);
746
        
747
        if(stream_id_plus1 == 0) length+= get_length(stream_index);
748
        else if(stream_id_plus1 - 1 != stream_index)
749
            continue;
750
        fc_key_frame= !!(flags & FLAG_KEY_FRAME);
751

    
752
        assert(key_frame==0 || key_frame==1);
753
        if(fc_key_frame != key_frame)
754
            continue;
755

    
756
        if(flags & FLAG_DATA_SIZE){
757
            if(size % size_mul != size_lsb)
758
                continue;
759
            length += get_length(size / size_mul);
760
        }else if(size != size_lsb)
761
            continue;
762

    
763
        if(full_pts && time_delta)
764
            continue;
765
            
766
        if(!time_delta){
767
            length += get_length(coded_pts);
768
        }else{
769
            if(time_delta != pts - stream->last_pts)
770
                continue;
771
        }
772

    
773
        if(length < best_length){
774
            best_length= length;
775
            frame_code=i;
776
        }
777
//    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);
778
    }
779

    
780
    assert(frame_code != -1);
781
    flags= nut->frame_code[frame_code].flags;
782
    size_mul= nut->frame_code[frame_code].size_mul;
783
    size_lsb= nut->frame_code[frame_code].size_lsb;
784
    time_delta= nut->frame_code[frame_code].timestamp_delta;
785
#ifdef TRACE
786
    best_length /= 7;
787
    best_length ++; //frame_code
788
    if(frame_type==2){
789
        best_length += 8; // startcode
790
    }
791
    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 pts:%lld fs:%lld\n", key_frame, frame_type, full_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), pts, frame_start);
792
//    av_log(s, AV_LOG_DEBUG, "%d %d %d\n", stream->lru_pts_delta[0], stream->lru_pts_delta[1], stream->lru_pts_delta[2]);
793
#endif
794

    
795
    assert(frame_type != 1); //short startcode not implemented yet
796
    put_byte(bc, frame_code);
797

    
798
    if(nut->frame_code[frame_code].stream_id_plus1 == 0)
799
        put_v(bc, stream_index);
800
    if (!time_delta){
801
        put_v(bc, coded_pts);
802
    }
803
    if(flags & FLAG_DATA_SIZE)
804
        put_v(bc, size / size_mul);
805
    else
806
        assert(size == size_lsb);
807
    if(size > MAX_DISTANCE){
808
        assert(frame_type > 1);
809
    }
810
    
811
    put_buffer(bc, pkt->data, size);
812

    
813
    update(nut, stream_index, frame_start, frame_type, frame_code, key_frame, size, pts);
814
    
815
    return 0;
816
}
817

    
818
static int nut_write_trailer(AVFormatContext *s)
819
{
820
    NUTContext *nut = s->priv_data;
821
    ByteIOContext *bc = &s->pb;
822

    
823
#if 0
824
    int i;
825

826
    /* WRITE INDEX */
827

828
    for (i = 0; s->nb_streams; i++)
829
    {
830
        put_be64(bc, INDEX_STARTCODE);
831
        put_packetheader(nut, bc, 64, 1);
832
        put_v(bc, s->streams[i]->id);
833
        put_v(bc, ...);
834
        update_packetheader(nut, bc, 0, 1);
835
    }
836
#endif
837

    
838
    put_flush_packet(bc);
839
    
840
    av_freep(&nut->stream);
841

    
842
    return 0;
843
}
844
#endif //CONFIG_ENCODERS
845

    
846
static int nut_probe(AVProbeData *p)
847
{
848
    int i;
849
    uint64_t code= 0xff;
850

    
851
    for (i = 0; i < p->buf_size; i++) {
852
        code = (code << 8) | p->buf[i];
853
        if (code == MAIN_STARTCODE)
854
            return AVPROBE_SCORE_MAX;
855
    }
856
    return 0;
857
}
858

    
859
static int decode_main_header(NUTContext *nut){
860
    AVFormatContext *s= nut->avf;
861
    ByteIOContext *bc = &s->pb;
862
    uint64_t tmp;
863
    int i, j, tmp_stream, tmp_mul, tmp_time, tmp_size, count, tmp_res;
864
    
865
    get_packetheader(nut, bc, 1);
866

    
867
    tmp = get_v(bc);
868
    if (tmp != 2){
869
        av_log(s, AV_LOG_ERROR, "bad version (%Ld)\n", tmp);
870
        return -1;
871
    }
872
    
873
    nut->stream_count = get_v(bc);
874
    if(nut->stream_count > MAX_STREAMS){
875
        av_log(s, AV_LOG_ERROR, "too many streams\n");
876
        return -1;
877
    }
878
    nut->max_distance = get_v(bc);
879
    nut->max_short_distance = get_v(bc);
880
    nut->rate_num= get_v(bc);
881
    nut->rate_den= get_v(bc);
882
    nut->short_startcode= get_v(bc);
883
    if(nut->short_startcode>>16 != 'N'){
884
        av_log(s, AV_LOG_ERROR, "invalid short startcode %X\n", nut->short_startcode);
885
        return -1;
886
    }
887
    
888
    for(i=0; i<256;){
889
        int tmp_flags = get_v(bc);
890
        int tmp_fields= get_v(bc);
891
        if(tmp_fields>0) tmp_time  = get_s(bc);
892
        if(tmp_fields>1) tmp_mul   = get_v(bc);
893
        if(tmp_fields>2) tmp_stream= get_v(bc);
894
        if(tmp_fields>3) tmp_size  = get_v(bc);
895
        else             tmp_size  = 0;
896
        if(tmp_fields>4) tmp_res   = get_v(bc);
897
        else             tmp_res   = 0;
898
        if(tmp_fields>5) count     = get_v(bc);
899
        else             count     = tmp_mul - tmp_size;
900
        
901
        while(tmp_fields-- > 6) 
902
           get_v(bc);
903
        
904
        if(count == 0 || i+count > 256){
905
            av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
906
            return -1;
907
        }
908
        if(tmp_stream > nut->stream_count + 1){
909
            av_log(s, AV_LOG_ERROR, "illegal stream number\n");
910
            return -1;
911
        }
912

    
913
        for(j=0; j<count; j++,i++){
914
            nut->frame_code[i].flags           = tmp_flags ;
915
            nut->frame_code[i].timestamp_delta = tmp_time  ;
916
            nut->frame_code[i].stream_id_plus1 = tmp_stream;
917
            nut->frame_code[i].size_mul        = tmp_mul   ;
918
            nut->frame_code[i].size_lsb        = tmp_size+j;
919
            nut->frame_code[i].reserved_count  = tmp_res   ;
920
        }
921
    }
922
    if(nut->frame_code['N'].flags != FLAG_INVALID){
923
        av_log(s, AV_LOG_ERROR, "illegal frame_code table\n");
924
        return -1;
925
    }
926

    
927
    if(check_checksum(bc)){
928
        av_log(s, AV_LOG_ERROR, "Main header checksum mismatch\n");
929
        return -1;
930
    }
931

    
932
    return 0;
933
}
934

    
935
static int decode_stream_header(NUTContext *nut){
936
    AVFormatContext *s= nut->avf;
937
    ByteIOContext *bc = &s->pb;
938
    int class, nom, denom, stream_id;
939
    uint64_t tmp;
940
    AVStream *st;
941
    
942
    get_packetheader(nut, bc, 1);
943
    stream_id= get_v(bc);
944
    if(stream_id >= nut->stream_count || s->streams[stream_id])
945
        return -1;
946
    
947
    st = av_new_stream(s, stream_id);
948
    if (!st)
949
        return AVERROR_NOMEM;
950

    
951
    class = get_v(bc);
952
    tmp = get_vb(bc);
953
    st->codec.codec_tag= tmp;
954
    switch(class)
955
    {
956
        case 0:
957
            st->codec.codec_type = CODEC_TYPE_VIDEO;
958
            st->codec.codec_id = codec_get_bmp_id(tmp);
959
            if (st->codec.codec_id == CODEC_ID_NONE)
960
                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
961
            break;
962
        case 1:
963
        case 32: //compatibility
964
            st->codec.codec_type = CODEC_TYPE_AUDIO;
965
            st->codec.codec_id = codec_get_wav_id(tmp);
966
            if (st->codec.codec_id == CODEC_ID_NONE)
967
                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
968
            break;
969
        case 2:
970
//            st->codec.codec_type = CODEC_TYPE_TEXT;
971
//            break;
972
        case 3:
973
            st->codec.codec_type = CODEC_TYPE_DATA;
974
            break;
975
        default:
976
            av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);
977
            return -1;
978
    }
979
    s->bit_rate += get_v(bc);
980
    get_vb(bc); /* language code */
981
    nom = get_v(bc);
982
    denom = get_v(bc);
983
    nut->stream[stream_id].msb_timestamp_shift = get_v(bc);
984
    st->codec.has_b_frames=
985
    nut->stream[stream_id].decode_delay= get_v(bc);
986
    get_byte(bc); /* flags */
987

    
988
    /* codec specific data headers */
989
    while(get_v(bc) != 0){
990
        st->codec.extradata_size= get_v(bc);
991
        if((unsigned)st->codec.extradata_size > (1<<30))
992
            return -1;
993
        st->codec.extradata= av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
994
        get_buffer(bc, st->codec.extradata, st->codec.extradata_size);            
995
//            url_fskip(bc, get_v(bc));
996
    }
997
    
998
    if (st->codec.codec_type == CODEC_TYPE_VIDEO) /* VIDEO */
999
    {
1000
        st->codec.width = get_v(bc);
1001
        st->codec.height = get_v(bc);
1002
        st->codec.sample_aspect_ratio.num= get_v(bc);
1003
        st->codec.sample_aspect_ratio.den= get_v(bc);
1004
        get_v(bc); /* csp type */
1005
    }
1006
    if (st->codec.codec_type == CODEC_TYPE_AUDIO) /* AUDIO */
1007
    {
1008
        st->codec.sample_rate = get_v(bc);
1009
        get_v(bc); // samplerate_den
1010
        st->codec.channels = get_v(bc);
1011
    }
1012
    if(check_checksum(bc)){
1013
        av_log(s, AV_LOG_ERROR, "Stream header %d checksum mismatch\n", stream_id);
1014
        return -1;
1015
    }
1016
    av_set_pts_info(s->streams[stream_id], 60, denom, nom);
1017
    nut->stream[stream_id].rate_num= nom;
1018
    nut->stream[stream_id].rate_den= denom;
1019
    return 0;
1020
}
1021

    
1022
static int decode_info_header(NUTContext *nut){
1023
    AVFormatContext *s= nut->avf;
1024
    ByteIOContext *bc = &s->pb;
1025
    
1026
    get_packetheader(nut, bc, 1);
1027

    
1028
    for(;;){
1029
        int id= get_v(bc);
1030
        char *name, *type, custom_name[256], custom_type[256];
1031

    
1032
        if(!id)
1033
            break;
1034
        else if(id >= sizeof(info_table)/sizeof(info_table[0])){
1035
            av_log(s, AV_LOG_ERROR, "info id is too large %d %d\n", id, sizeof(info_table)/sizeof(info_table[0]));
1036
            return -1;
1037
        }
1038

    
1039
        type= info_table[id][1];
1040
        name= info_table[id][0];
1041
//av_log(s, AV_LOG_DEBUG, "%d %s %s\n", id, type, name);
1042

    
1043
        if(!type){
1044
            get_str(bc, custom_type, sizeof(custom_type));
1045
            type= custom_type;
1046
        }
1047
        if(!name){
1048
            get_str(bc, custom_name, sizeof(custom_name));
1049
            name= custom_name;
1050
        }
1051
        
1052
        if(!strcmp(type, "v")){
1053
            get_v(bc);
1054
        }else{
1055
            if(!strcmp(name, "Author"))
1056
                get_str(bc, s->author, sizeof(s->author));
1057
            else if(!strcmp(name, "Title"))
1058
                get_str(bc, s->title, sizeof(s->title));
1059
            else if(!strcmp(name, "Copyright"))
1060
                get_str(bc, s->copyright, sizeof(s->copyright));
1061
            else if(!strcmp(name, "Description"))
1062
                get_str(bc, s->comment, sizeof(s->comment));
1063
            else
1064
                get_str(bc, NULL, 0);
1065
        }
1066
    }
1067
    if(check_checksum(bc)){
1068
        av_log(s, AV_LOG_ERROR, "Info header checksum mismatch\n");
1069
        return -1;
1070
    }
1071
    return 0;
1072
}
1073

    
1074
static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
1075
{
1076
    NUTContext *nut = s->priv_data;
1077
    ByteIOContext *bc = &s->pb;
1078
    int64_t pos;
1079
    int inited_stream_count;
1080

    
1081
    nut->avf= s;
1082
    
1083
    /* main header */
1084
    pos=0;
1085
    for(;;){
1086
        pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;
1087
        if (pos<0){
1088
            av_log(s, AV_LOG_ERROR, "no main startcode found\n");
1089
            return -1;
1090
        }
1091
        if(decode_main_header(nut) >= 0)
1092
            break;
1093
    }
1094
    
1095
    
1096
    s->bit_rate = 0;
1097

    
1098
    nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);
1099

    
1100
    /* stream headers */
1101
    pos=0;
1102
    for(inited_stream_count=0; inited_stream_count < nut->stream_count;){
1103
        pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;
1104
        if (pos<0+1){
1105
            av_log(s, AV_LOG_ERROR, "not all stream headers found\n");
1106
            return -1;
1107
        }
1108
        if(decode_stream_header(nut) >= 0)
1109
            inited_stream_count++;
1110
    }
1111

    
1112
    /* info headers */
1113
    pos=0;
1114
    for(;;){
1115
        uint64_t startcode= find_any_startcode(bc, pos);
1116
        pos= url_ftell(bc);
1117

    
1118
        if(startcode==0){
1119
            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
1120
            return -1;
1121
        }else if(startcode == KEYFRAME_STARTCODE){
1122
            nut->next_startcode= startcode;
1123
            break;
1124
        }else if(startcode != INFO_STARTCODE){
1125
            continue;
1126
        }
1127

    
1128
        decode_info_header(nut);
1129
    }
1130

    
1131
    return 0;
1132
}
1133

    
1134
static int decode_frame_header(NUTContext *nut, int *key_frame_ret, int64_t *pts_ret, int *stream_id_ret, int frame_code, int frame_type, int64_t frame_start){
1135
    AVFormatContext *s= nut->avf;
1136
    StreamContext *stream;
1137
    ByteIOContext *bc = &s->pb;
1138
    int size, flags, size_mul, size_lsb, stream_id, time_delta;
1139
    int64_t pts = 0;
1140

    
1141
    if(frame_type < 2 && frame_start - nut->packet_start[2] > nut->max_distance){
1142
        av_log(s, AV_LOG_ERROR, "last frame must have been damaged\n");
1143
        return -1;
1144
    }
1145

    
1146
    if(frame_type)
1147
        nut->packet_start[ frame_type ]= frame_start; //otherwise 1 goto 1 may happen
1148
    
1149
    flags= nut->frame_code[frame_code].flags;
1150
    size_mul= nut->frame_code[frame_code].size_mul;
1151
    size_lsb= nut->frame_code[frame_code].size_lsb;
1152
    stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
1153
    time_delta= nut->frame_code[frame_code].timestamp_delta;
1154
    
1155
    if(stream_id==-1)
1156
        stream_id= get_v(bc);
1157
    if(stream_id >= s->nb_streams){
1158
        av_log(s, AV_LOG_ERROR, "illegal stream_id\n");
1159
        return -1;
1160
    }
1161
    stream= &nut->stream[stream_id];
1162

    
1163
//    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]);
1164

    
1165
    *key_frame_ret= !!(flags & FLAG_KEY_FRAME);
1166

    
1167
    if(!time_delta){
1168
        int64_t mask = (1<<stream->msb_timestamp_shift)-1;
1169
        pts= get_v(bc);
1170
        if(pts > mask){
1171
            pts -= mask+1;
1172
        }else{
1173
            if(stream->last_pts == AV_NOPTS_VALUE){
1174
                av_log(s, AV_LOG_ERROR, "no reference pts available\n");
1175
                return -1;
1176
            }
1177
            pts= lsb2full(stream, pts);
1178
        }
1179
    }else{
1180
        if(stream->last_pts == AV_NOPTS_VALUE){
1181
            av_log(s, AV_LOG_ERROR, "no reference pts available\n");
1182
            return -1;
1183
        }
1184
        pts= stream->last_pts + time_delta;
1185
    }
1186

    
1187
    if(*key_frame_ret){
1188
//        av_log(s, AV_LOG_DEBUG, "stream:%d start:%lld pts:%lld length:%lld\n",stream_id, frame_start, av_pts, frame_start - nut->stream[stream_id].last_sync_pos);
1189
        av_add_index_entry(
1190
            s->streams[stream_id], 
1191
            frame_start, 
1192
            pts, 
1193
            frame_start - nut->stream[stream_id].last_sync_pos,
1194
            AVINDEX_KEYFRAME);
1195
        nut->stream[stream_id].last_sync_pos= frame_start;
1196
//                assert(nut->packet_start == frame_start);
1197
    }
1198

    
1199
    assert(size_mul > size_lsb);
1200
    size= size_lsb;
1201
    if(flags & FLAG_DATA_SIZE)
1202
        size+= size_mul*get_v(bc);
1203
      
1204
#ifdef TRACE
1205
av_log(s, AV_LOG_DEBUG, "fs:%lld fc:%d ft:%d kf:%d pts:%lld size:%d mul:%d lsb:%d flags:%d delta:%d\n", frame_start, frame_code, frame_type, *key_frame_ret, pts, size, size_mul, size_lsb, flags, time_delta);
1206
#endif
1207

    
1208
    if(frame_type==0 && url_ftell(bc) - nut->packet_start[2] + size > nut->max_distance){
1209
        av_log(s, AV_LOG_ERROR, "frame size too large\n");
1210
        return -1;
1211
    }
1212
    
1213
    *stream_id_ret = stream_id;
1214
    *pts_ret = pts;
1215

    
1216
    update(nut, stream_id, frame_start, frame_type, frame_code, *key_frame_ret, size, pts);
1217

    
1218
    return size;
1219
}
1220

    
1221
static int decode_frame(NUTContext *nut, AVPacket *pkt, int frame_code, int frame_type, int64_t frame_start){
1222
    AVFormatContext *s= nut->avf;
1223
    ByteIOContext *bc = &s->pb;
1224
    int size, stream_id, key_frame, discard;
1225
    int64_t pts, last_IP_pts;
1226
    
1227
    size= decode_frame_header(nut, &key_frame, &pts, &stream_id, frame_code, frame_type, frame_start);
1228
    if(size < 0)
1229
        return -1;
1230

    
1231
    discard= s->streams[ stream_id ]->discard;
1232
    last_IP_pts= s->streams[ stream_id ]->last_IP_pts;
1233
    if(  (discard >= AVDISCARD_NONKEY && !key_frame)
1234
       ||(discard >= AVDISCARD_BIDIR && last_IP_pts != AV_NOPTS_VALUE && last_IP_pts > pts)
1235
       || discard >= AVDISCARD_ALL){
1236
        url_fskip(bc, size);
1237
        return 1;
1238
    }
1239

    
1240
    av_get_packet(bc, pkt, size);
1241
    pkt->stream_index = stream_id;
1242
    if (key_frame)
1243
        pkt->flags |= PKT_FLAG_KEY;
1244
    pkt->pts = pts;
1245

    
1246
    return 0;
1247
}
1248

    
1249
static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1250
{
1251
    NUTContext *nut = s->priv_data;
1252
    ByteIOContext *bc = &s->pb;
1253
    int i, frame_code=0, ret;
1254

    
1255
    for(;;){
1256
        int64_t pos= url_ftell(bc);
1257
        int frame_type= 0;
1258
        uint64_t tmp= nut->next_startcode;
1259
        nut->next_startcode=0;
1260

    
1261
        if (url_feof(bc))
1262
            return -1;
1263

    
1264
        if(tmp){
1265
            pos-=8;
1266
        }else{
1267
            frame_code = get_byte(bc);
1268
            if(frame_code == 'N'){
1269
                tmp= frame_code;
1270
                for(i=1; i<8; i++)
1271
                    tmp = (tmp<<8) + get_byte(bc);
1272
            }
1273
        }
1274
        switch(tmp){
1275
        case MAIN_STARTCODE:
1276
        case STREAM_STARTCODE:
1277
        case INDEX_STARTCODE:
1278
            get_packetheader(nut, bc, 0);
1279
            assert(nut->packet_start[2] == pos);
1280
            url_fseek(bc, nut->written_packet_size + nut->packet_start[2], SEEK_SET);
1281
            break;
1282
        case INFO_STARTCODE:
1283
            if(decode_info_header(nut)<0)
1284
                goto resync;
1285
            break;
1286
        case KEYFRAME_STARTCODE:
1287
            frame_type = 2;
1288
            reset(s, get_v(bc));
1289
            frame_code = get_byte(bc);
1290
        case 0:
1291
            ret= decode_frame(nut, pkt, frame_code, frame_type, pos);
1292
            if(ret==0)
1293
                return 0;
1294
            else if(ret==1) //ok but discard packet
1295
                break;
1296
        default:
1297
resync:
1298
av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start[2]+1);
1299
            tmp= find_any_startcode(bc, nut->packet_start[2]+1);
1300
            if(tmp==0)
1301
                return -1;
1302
av_log(s, AV_LOG_DEBUG, "sync\n");
1303
            nut->next_startcode= tmp;
1304
        }
1305
    }
1306
}
1307

    
1308
static int64_t nut_read_timestamp(AVFormatContext *s, int stream_index, int64_t *pos_arg, int64_t pos_limit){
1309
    NUTContext *nut = s->priv_data;
1310
    StreamContext *stream;
1311
    ByteIOContext *bc = &s->pb;
1312
    int64_t pos, pts;
1313
    uint64_t code;
1314
    int frame_code,step, stream_id, i,size, key_frame;
1315
av_log(s, AV_LOG_DEBUG, "read_timestamp(X,%d,%lld,%lld)\n", stream_index, *pos_arg, pos_limit);
1316

    
1317
    if(*pos_arg < 0)
1318
        return AV_NOPTS_VALUE;
1319

    
1320
    pos= *pos_arg;
1321
    step= FFMIN(16*1024, pos);
1322
    do{
1323
        pos-= step;
1324
        code= find_any_startcode(bc, pos);
1325

    
1326
        if(code && url_ftell(bc) - 8 <= *pos_arg)
1327
            break;
1328
        step= FFMIN(2*step, pos);
1329
    }while(step);
1330

    
1331
    if(!code) //nothing found, not even after pos_arg
1332
        return AV_NOPTS_VALUE;
1333

    
1334
    url_fseek(bc, -8, SEEK_CUR);
1335
    for(i=0; i<s->nb_streams; i++)
1336
        nut->stream[i].last_sync_pos= url_ftell(bc);
1337
        
1338
    for(;;){
1339
        int frame_type=0;
1340
        int64_t pos= url_ftell(bc);
1341
        uint64_t tmp=0;
1342
        
1343
        if(pos > pos_limit || url_feof(bc))
1344
            return AV_NOPTS_VALUE;
1345

    
1346
        frame_code = get_byte(bc);
1347
        if(frame_code == 'N'){
1348
            tmp= frame_code;
1349
            for(i=1; i<8; i++)
1350
                tmp = (tmp<<8) + get_byte(bc);
1351
        }
1352
//av_log(s, AV_LOG_DEBUG, "before switch %llX at=%lld\n", tmp, pos);
1353

    
1354
        switch(tmp){
1355
        case MAIN_STARTCODE:
1356
        case STREAM_STARTCODE:
1357
        case INDEX_STARTCODE:
1358
        case INFO_STARTCODE:
1359
            get_packetheader(nut, bc, 0);
1360
            assert(nut->packet_start[2]==pos);
1361
            url_fseek(bc, nut->written_packet_size + pos, SEEK_SET);
1362
            break;
1363
        case KEYFRAME_STARTCODE:
1364
            frame_type=2;
1365
            reset(s, get_v(bc));
1366
            frame_code = get_byte(bc);
1367
        case 0:
1368
            size= decode_frame_header(nut, &key_frame, &pts, &stream_id, frame_code, frame_type, pos);
1369
            if(size < 0)
1370
                goto resync;
1371
                
1372
            stream= &nut->stream[stream_id];
1373
            if(stream_id != stream_index || !key_frame || pos < *pos_arg){
1374
                url_fseek(bc, size, SEEK_CUR);
1375
                break;
1376
            }
1377
 
1378
            *pos_arg= pos;
1379
            return pts;
1380
        default:
1381
resync:
1382
av_log(s, AV_LOG_DEBUG, "syncing from %lld\n", nut->packet_start[2]+1);
1383
            if(!find_any_startcode(bc, nut->packet_start[2]+1))
1384
                return AV_NOPTS_VALUE;
1385

    
1386
            url_fseek(bc, -8, SEEK_CUR);
1387
        }
1388
    }
1389
    return AV_NOPTS_VALUE;
1390
}
1391

    
1392
static int nut_read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1393
//    NUTContext *nut = s->priv_data;
1394
    int64_t pos;
1395

    
1396
    if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1397
        return -1;
1398

    
1399
    pos= url_ftell(&s->pb);
1400
    nut_read_timestamp(s, stream_index, &pos, pos-1);
1401

    
1402
    return 0;
1403
}
1404

    
1405
static int nut_read_close(AVFormatContext *s)
1406
{
1407
    NUTContext *nut = s->priv_data;
1408
    int i;
1409

    
1410
    for(i=0;i<s->nb_streams;i++) {
1411
        av_freep(&s->streams[i]->codec.extradata);
1412
    }
1413
    av_freep(&nut->stream);
1414

    
1415
    return 0;
1416
}
1417

    
1418
static AVInputFormat nut_iformat = {
1419
    "nut",
1420
    "nut format",
1421
    sizeof(NUTContext),
1422
    nut_probe,
1423
    nut_read_header,
1424
    nut_read_packet,
1425
    nut_read_close,
1426
    nut_read_seek,
1427
    nut_read_timestamp,
1428
    .extensions = "nut",
1429
};
1430

    
1431
#ifdef CONFIG_ENCODERS
1432
static AVOutputFormat nut_oformat = {
1433
    "nut",
1434
    "nut format",
1435
    "video/x-nut",
1436
    "nut",
1437
    sizeof(NUTContext),
1438
#ifdef CONFIG_LIBVORBIS
1439
    CODEC_ID_VORBIS,
1440
#elif defined(CONFIG_MP3LAME)
1441
    CODEC_ID_MP3,
1442
#else
1443
    CODEC_ID_MP2, /* AC3 needs liba52 decoder */
1444
#endif
1445
    CODEC_ID_MPEG4,
1446
    nut_write_header,
1447
    nut_write_packet,
1448
    nut_write_trailer,
1449
};
1450
#endif //CONFIG_ENCODERS
1451

    
1452
int nut_init(void)
1453
{
1454
    av_register_input_format(&nut_iformat);
1455
#ifdef CONFIG_ENCODERS
1456
    av_register_output_format(&nut_oformat);
1457
#endif //CONFIG_ENCODERS
1458
    return 0;
1459
}