Statistics
| Branch: | Revision:

ffmpeg / libavformat / nut.c @ 7c5934ed

History | View | Annotate | Download (33.8 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
 * - startcode searching for broken streams
32
*/
33

    
34
//#define DEBUG 1
35

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

    
41
#undef NDEBUG
42
#include <assert.h>
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 MAX_TYPE1_DISTANCE (1024*16-1)
53
#define MAX_TYPE2_DISTANCE (1024*64-1)
54

    
55
#define MAX_SIZE_LRU 2
56
#define MAX_PTS_LRU 3
57

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

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

    
72
typedef struct {
73
    int last_key_frame;
74
    int msb_timestamp_shift;
75
    int rate_num;
76
    int rate_den;
77
    int64_t last_pts;
78
    int64_t last_full_pts;
79
    int lru_pts_delta[MAX_PTS_LRU];
80
    int lru_size[MAX_SIZE_LRU];
81
    int initial_pts_predictor[MAX_PTS_LRU];
82
    int initial_size_predictor[MAX_SIZE_LRU];
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
    StreamContext *stream;
95
} NUTContext;
96

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

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

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

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

    
129
    lru[0]= current;
130
}
131

    
132
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){
133
    StreamContext *stream= &nut->stream[stream_index];
134
    
135
    stream->last_key_frame= key_frame;
136
    nut->last_frame_start[ frame_type ]= frame_start;
137
    update_lru(stream->lru_pts_delta, pts - stream->last_pts, 3);
138
    update_lru(stream->lru_size     ,                   size, 2);
139
    stream->last_pts= pts;
140
    if(    nut->frame_code[frame_code].flags & FLAG_PTS 
141
        && nut->frame_code[frame_code].flags & FLAG_FULL_PTS)
142
        stream->last_full_pts= pts;
143
}
144

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

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

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

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

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

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

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

    
247
static int bytes_left(ByteIOContext *bc)
248
{
249
    return bc->buf_end - bc->buf_ptr;
250
}
251

    
252
static uint64_t get_v(ByteIOContext *bc)
253
{
254
    uint64_t val = 0;
255

    
256
    for(; bytes_left(bc) > 0; )
257
    {
258
        int tmp = get_byte(bc);
259

    
260
        if (tmp&0x80)
261
            val= (val<<7) + tmp - 0x80;
262
        else
263
            return (val<<7) + tmp;
264
    }
265
    return -1;
266
}
267

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

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

    
287
static int get_packetheader(NUTContext *nut, ByteIOContext *bc, int prefix_length, int calculate_checksum)
288
{
289
    int64_t start, size, last_size;
290
    start= url_ftell(bc) - prefix_length;
291

    
292
    if(start != nut->packet_start + nut->written_packet_size){
293
        av_log(nut->avf, AV_LOG_ERROR, "get_packetheader called at weird position\n");
294
        return -1;
295
    }
296
    
297
    if(calculate_checksum)
298
        init_checksum(bc, update_adler32, 0);
299

    
300
    size= get_v(bc);
301
    last_size= get_v(bc);
302
    if(nut->written_packet_size != last_size){
303
        av_log(nut->avf, AV_LOG_ERROR, "packet size missmatch %d != %lld at %lld\n", nut->written_packet_size, last_size, start);
304
        return -1;
305
    }
306

    
307
    nut->last_packet_start = nut->packet_start;
308
    nut->packet_start = start;
309
    nut->written_packet_size= size;
310

    
311
    return size;
312
}
313

    
314
static int check_checksum(ByteIOContext *bc){
315
    unsigned long checksum= get_checksum(bc);
316
    return checksum != get_be32(bc);
317
}
318

    
319
/**
320
 * 
321
 */
322
static int get_length(uint64_t val){
323
    int i;
324

    
325
    for (i=7; ; i+=7)
326
        if ((val>>i) == 0)
327
            return i;
328

    
329
    return 7; //not reached
330
}
331

    
332
static uint64_t find_any_startcode(ByteIOContext *bc, int64_t pos){
333
    uint64_t state=0;
334
    
335
    if(pos >= 0)
336
        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
337

    
338
    while(bytes_left(bc)){
339
        state= (state<<8) | get_byte(bc);
340
        if((state>>56) != 'N')
341
            continue;
342
        switch(state){
343
        case MAIN_STARTCODE:
344
        case STREAM_STARTCODE:
345
        case KEYFRAME_STARTCODE:
346
        case INFO_STARTCODE:
347
        case INDEX_STARTCODE:
348
            return state;
349
        }
350
    }
351
    return 0;
352
}
353

    
354
static int find_startcode(ByteIOContext *bc, uint64_t code, int64_t pos){
355
    for(;;){
356
        uint64_t startcode= find_any_startcode(bc, pos);
357
        if(startcode == code)
358
            return 0;
359
        else if(startcode == 0)
360
            return -1;
361
        pos=-1;
362
    }
363
}
364

    
365
#ifdef CONFIG_ENCODERS
366
static int put_v(ByteIOContext *bc, uint64_t val)
367
{
368
    int i;
369
//    if (bytes_left(s)*8 < 9)
370
//        return -1;
371

    
372
    if (bytes_left(bc) < 1)
373
        return -1;
374

    
375
    val &= 0x7FFFFFFFFFFFFFFFULL; // FIXME can only encode upto 63 bits currently
376
    i= get_length(val);
377

    
378
    for (i-=7; i>0; i-=7){
379
        put_byte(bc, 0x80 | (val>>i));
380
    }
381

    
382
    put_byte(bc, val&0x7f);
383

    
384
    return 0;
385
}
386

    
387
static int put_str(ByteIOContext *bc, const char *string){
388
    int len= strlen(string);
389
    
390
    put_v(bc, len);
391
    put_buffer(bc, string, len);
392
    
393
    return 0;
394
}
395

    
396
static int put_packetheader(NUTContext *nut, ByteIOContext *bc, int max_size, int calculate_checksum)
397
{
398
    put_flush_packet(bc);
399
    nut->last_packet_start= nut->packet_start;
400
    nut->packet_start+= nut->written_packet_size;
401
    nut->packet_size_pos = url_ftell(bc);
402
    nut->written_packet_size = max_size;
403
    
404
    if(calculate_checksum)
405
        init_checksum(bc, update_adler32, 0);
406

    
407
    /* packet header */
408
    put_v(bc, nut->written_packet_size); /* forward ptr */
409
    put_v(bc, nut->packet_start - nut->last_packet_start); /* backward ptr */
410

    
411
    return 0;
412
}
413

    
414
static int update_packetheader(NUTContext *nut, ByteIOContext *bc, int additional_size, int calculate_checksum){
415
    int64_t start= nut->packet_start;
416
    int64_t cur= url_ftell(bc);
417
    int size= cur - start + additional_size;
418
    
419
    if(calculate_checksum)
420
        size += 4;
421
    
422
    if(size != nut->written_packet_size){
423
        int i;
424

    
425
        assert( size <= nut->written_packet_size );
426
    
427
        url_fseek(bc, nut->packet_size_pos, SEEK_SET);
428
        for(i=get_length(size); i < get_length(nut->written_packet_size); i+=7)
429
            put_byte(bc, 0x80);
430
        put_v(bc, size);
431

    
432
        url_fseek(bc, cur, SEEK_SET);
433
        nut->written_packet_size= size; //FIXME may fail if multiple updates with differing sizes, as get_length may differ
434
        
435
        if(calculate_checksum)
436
            put_be32(bc, get_checksum(bc));
437
    }
438
    
439
    return 0;
440
}
441

    
442
static int nut_write_header(AVFormatContext *s)
443
{
444
    NUTContext *nut = s->priv_data;
445
    ByteIOContext *bc = &s->pb;
446
    AVCodecContext *codec;
447
    int i, j;
448

    
449
    nut->avf= s;
450
    
451
    nut->stream =        
452
        av_mallocz(sizeof(StreamContext)*s->nb_streams);
453
    
454
    av_set_pts_info(s, 60, 1, AV_TIME_BASE);
455
    
456
    /* main header */
457
    put_be64(bc, MAIN_STARTCODE);
458
    put_packetheader(nut, bc, 120+5*256, 1);
459
    put_v(bc, 1); /* version */
460
    put_v(bc, s->nb_streams);
461
    put_v(bc, 3);
462
    
463
    build_frame_code(s);
464
    assert(nut->frame_code['N'].flags == 1);
465
    for(i=0; i<256;){
466
        int tmp_flags = nut->frame_code[i].flags;
467
        int tmp_stream= nut->frame_code[i].stream_id_plus1;
468
        int tmp_mul   = nut->frame_code[i].size_mul;
469
        int tmp_size  = nut->frame_code[i].size_lsb;
470
        put_v(bc, tmp_flags);
471
        put_v(bc, tmp_stream);
472
        put_v(bc, tmp_mul);
473
        put_v(bc, tmp_size);
474

    
475
        for(j=0; i<256; j++,i++){
476
            if(nut->frame_code[i].flags           != tmp_flags ) break;
477
            if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;
478
            if(nut->frame_code[i].size_mul        != tmp_mul   ) break;
479
            if(nut->frame_code[i].size_lsb        != tmp_size  ) break;
480
            if(++tmp_size >= tmp_mul){
481
                tmp_size=0;
482
                tmp_stream++;
483
            }
484
        }
485
        put_v(bc, j);
486
    }
487

    
488
    update_packetheader(nut, bc, 0, 1);
489
    
490
    /* stream headers */
491
    for (i = 0; i < s->nb_streams; i++)
492
    {
493
        int nom, denom, gcd;
494

    
495
        codec = &s->streams[i]->codec;
496
        
497
        put_be64(bc, STREAM_STARTCODE);
498
        put_packetheader(nut, bc, 120 + codec->extradata_size, 1);
499
        put_v(bc, i /*s->streams[i]->index*/);
500
        put_v(bc, (codec->codec_type == CODEC_TYPE_AUDIO) ? 32 : 0);
501
        if (codec->codec_tag)
502
            put_v(bc, codec->codec_tag);
503
        else if (codec->codec_type == CODEC_TYPE_VIDEO)
504
        {
505
            put_v(bc, codec_get_bmp_tag(codec->codec_id));
506
        }
507
        else if (codec->codec_type == CODEC_TYPE_AUDIO)
508
        {
509
            put_v(bc, codec_get_wav_tag(codec->codec_id));
510
        }
511
        else
512
            put_v(bc, 0);
513

    
514
        if (codec->codec_type == CODEC_TYPE_VIDEO)
515
        {
516
            nom = codec->frame_rate;
517
            denom = codec->frame_rate_base;
518
        }
519
        else
520
        {
521
            nom = codec->sample_rate;
522
            if(codec->frame_size>0)
523
                denom= codec->frame_size;
524
            else
525
                denom= 1; //unlucky
526
        }
527
        gcd= ff_gcd(nom, denom);
528
        nom   /= gcd;
529
        denom /= gcd;
530
        nut->stream[i].rate_num= nom;
531
        nut->stream[i].rate_den= denom;
532

    
533
        put_v(bc, codec->bit_rate);
534
        put_v(bc, 0); /* no language code */
535
        put_v(bc, nom);
536
        put_v(bc, denom);
537
        if(nom / denom < 1000)
538
            nut->stream[i].msb_timestamp_shift = 7;
539
        else
540
            nut->stream[i].msb_timestamp_shift = 14;
541
        put_v(bc, nut->stream[i].msb_timestamp_shift);
542
        for(j=0; j<3; j++)
543
                put_v(bc, nut->stream[i].initial_pts_predictor[j]);
544
        for(j=0; j<2; j++)
545
                put_v(bc, nut->stream[i].initial_size_predictor[j]);
546
        put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
547
        
548
        if(codec->extradata_size){
549
            put_v(bc, 1);
550
            put_v(bc, codec->extradata_size);
551
            put_buffer(bc, codec->extradata, codec->extradata_size);            
552
        }
553
        put_v(bc, 0); /* end of codec specific headers */
554
        
555
        switch(codec->codec_type)
556
        {
557
            case CODEC_TYPE_AUDIO:
558
                put_v(bc, (codec->sample_rate * denom) / nom);
559
                put_v(bc, codec->channels);
560
                break;
561
            case CODEC_TYPE_VIDEO:
562
                put_v(bc, codec->width);
563
                put_v(bc, codec->height);
564
                put_v(bc, codec->sample_aspect_ratio.num);
565
                put_v(bc, codec->sample_aspect_ratio.den);
566
                put_v(bc, 0); /* csp type -- unknown */
567
                break;
568
            default:
569
                break;
570
        }
571
        update_packetheader(nut, bc, 0, 1);
572
    }
573

    
574
    /* info header */
575
    put_be64(bc, INFO_STARTCODE);
576
    put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+
577
        strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1); 
578
    if (s->author[0])
579
    {
580
        put_v(bc, 9); /* type */
581
        put_str(bc, s->author);
582
    }
583
    if (s->title[0])
584
    {
585
        put_v(bc, 10); /* type */
586
        put_str(bc, s->title);
587
    }
588
    if (s->comment[0])
589
    {
590
        put_v(bc, 11); /* type */
591
        put_str(bc, s->comment);
592
    }
593
    if (s->copyright[0])
594
    {
595
        put_v(bc, 12); /* type */
596
        put_str(bc, s->copyright);
597
    }
598
    /* encoder */
599
    put_v(bc, 13); /* type */
600
    put_str(bc, LIBAVFORMAT_IDENT);
601
    
602
    put_v(bc, 0); /* eof info */
603
    update_packetheader(nut, bc, 0, 1);
604
        
605
    put_flush_packet(bc);
606
    
607
    return 0;
608
}
609

    
610
static int nut_write_packet(AVFormatContext *s, int stream_index, 
611
                            const uint8_t *buf, int size, int64_t pts)
612
{
613
    NUTContext *nut = s->priv_data;
614
    StreamContext *stream= &nut->stream[stream_index];
615
    ByteIOContext *bc = &s->pb;
616
    int key_frame = 0, full_pts=0;
617
    AVCodecContext *enc;
618
    int64_t lsb_pts, delta_pts;
619
    int frame_type, best_length, frame_code, flags, i, size_mul, size_lsb;
620
    const int64_t frame_start= url_ftell(bc);
621

    
622
    if (stream_index > s->nb_streams)
623
        return 1;
624
        
625
    pts= (av_rescale(pts, stream->rate_num, stream->rate_den) + AV_TIME_BASE/2) / AV_TIME_BASE;
626

    
627
    enc = &s->streams[stream_index]->codec;
628
    key_frame = enc->coded_frame->key_frame;
629
    delta_pts= pts - stream->last_pts;
630
    
631
    frame_type=0;
632
    if(frame_start + size + 20 - FFMAX(nut->last_frame_start[1], nut->last_frame_start[2]) > MAX_TYPE1_DISTANCE)
633
        frame_type=1;
634
    if(key_frame){
635
        if(frame_type==1 && frame_start + size - nut->last_frame_start[2] > MAX_TYPE2_DISTANCE)
636
            frame_type=2;
637
        if(!stream->last_key_frame)
638
            frame_type=2;
639
    }
640

    
641
    if(frame_type>0){
642
        update_packetheader(nut, bc, 0, 0);
643
        reset(s);
644
        full_pts=1;
645
    }
646
    //FIXME ensure that the timestamp can be represented by either delta or lsb or full_pts=1
647

    
648
    lsb_pts = pts & ((1 << stream->msb_timestamp_shift)-1);
649

    
650
    best_length=INT_MAX;
651
    frame_code= -1;
652
    for(i=0; i<256; i++){
653
        int stream_id_plus1= nut->frame_code[i].stream_id_plus1;
654
        int fc_key_frame= stream->last_key_frame;
655
        int length=0;
656
        size_mul= nut->frame_code[i].size_mul;
657
        size_lsb= nut->frame_code[i].size_lsb;
658
        flags= nut->frame_code[i].flags;
659

    
660
        if(stream_id_plus1 == 0) length+= get_length(stream_index);
661
        else if(stream_id_plus1 - 1 != stream_index)
662
            continue;
663
        if(flags & FLAG_PRED_KEY_FRAME){
664
            if(flags & FLAG_KEY_FRAME)
665
                fc_key_frame= !fc_key_frame;
666
        }else{
667
            fc_key_frame= !!(flags & FLAG_KEY_FRAME);
668
        }
669
        assert(key_frame==0 || key_frame==1);
670
        if(fc_key_frame != key_frame)
671
            continue;
672

    
673
        if((!!(flags & FLAG_FRAME_TYPE)) != (frame_type > 0))
674
            continue;
675
        
676
        if(size_mul <= size_lsb){
677
            int p= stream->lru_size[size_lsb - size_mul];
678
            if(p != size)
679
                continue;
680
        }else{
681
            if(size % size_mul != size_lsb)
682
                continue;
683
            if(flags & FLAG_DATA_SIZE)
684
                length += get_length(size / size_mul);
685
            else if(size/size_mul)
686
                continue;
687
        }
688

    
689
        if(full_pts != ((flags & FLAG_PTS) && (flags & FLAG_FULL_PTS)))
690
            continue;
691
            
692
        if(flags&FLAG_PTS){
693
            if(flags&FLAG_FULL_PTS){
694
                length += get_length(pts);
695
            }else{
696
                length += get_length(lsb_pts);
697
            }
698
        }else{
699
            int delta= stream->lru_pts_delta[(flags & 12)>>2];
700
            if(delta != pts - stream->last_pts)
701
                continue;
702
            assert(frame_type == 0);
703
        }
704

    
705
        if(length < best_length){
706
            best_length= length;
707
            frame_code=i;
708
        }
709
//    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);
710
    }
711

    
712
    assert(frame_code != -1);
713
    flags= nut->frame_code[frame_code].flags;
714
    size_mul= nut->frame_code[frame_code].size_mul;
715
    size_lsb= nut->frame_code[frame_code].size_lsb;
716
#if 0
717
    best_length /= 7;
718
    best_length ++; //frame_code
719
    if(frame_type>0){
720
        best_length += 4; //packet header
721
        if(frame_type>1)
722
            best_length += 8; // startcode
723
    }
724
    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));
725
#endif
726

    
727
    if (frame_type==2)
728
        put_be64(bc, KEYFRAME_STARTCODE);
729
    put_byte(bc, frame_code);
730

    
731
    if(frame_type>0)
732
        put_packetheader(nut, bc, FFMAX(size+20, MAX_TYPE1_DISTANCE), 0);
733
    if(nut->frame_code[frame_code].stream_id_plus1 == 0)
734
        put_v(bc, stream_index);
735
    if (flags & FLAG_PTS){
736
        if (flags & FLAG_FULL_PTS)
737
            put_v(bc, pts);
738
        else
739
            put_v(bc, lsb_pts);
740
    }
741
    if(flags & FLAG_DATA_SIZE)
742
        put_v(bc, size / size_mul);
743
    if(size > MAX_TYPE1_DISTANCE){
744
        assert(frame_type > 0);
745
        update_packetheader(nut, bc, size, 0);
746
    }
747
    
748
    put_buffer(bc, buf, size);
749

    
750
    update(nut, stream_index, frame_start, frame_type, frame_code, key_frame, size, pts);
751
    
752
    return 0;
753
}
754

    
755
static int nut_write_trailer(AVFormatContext *s)
756
{
757
    NUTContext *nut = s->priv_data;
758
    ByteIOContext *bc = &s->pb;
759

    
760
    update_packetheader(nut, bc, 0, 0);
761

    
762
#if 0
763
    int i;
764

765
    /* WRITE INDEX */
766

767
    for (i = 0; s->nb_streams; i++)
768
    {
769
        put_be64(bc, INDEX_STARTCODE);
770
        put_packetheader(nut, bc, 64, 1);
771
        put_v(bc, s->streams[i]->id);
772
        put_v(bc, ...);
773
        update_packetheader(nut, bc, 0, 1);
774
    }
775
#endif
776

    
777
    put_flush_packet(bc);
778
    
779
    av_freep(&nut->stream);
780

    
781
    return 0;
782
}
783
#endif //CONFIG_ENCODERS
784

    
785
static int nut_probe(AVProbeData *p)
786
{
787
    int i;
788
    uint64_t code;
789

    
790
    code = 0xff;
791
    for (i = 0; i < p->buf_size; i++) {
792
        int c = p->buf[i];
793
        code = (code << 8) | c;
794
        if (code == MAIN_STARTCODE)
795
            return AVPROBE_SCORE_MAX;
796
    }
797
    return 0;
798
}
799

    
800
static int decode_main_header(NUTContext *nut){
801
    AVFormatContext *s= nut->avf;
802
    ByteIOContext *bc = &s->pb;
803
    uint64_t tmp;
804
    int i, j;
805
    
806
    get_packetheader(nut, bc, 8, 1);
807

    
808
    tmp = get_v(bc);
809
    if (tmp != 1){
810
        av_log(s, AV_LOG_ERROR, "bad version (%Ld)\n", tmp);
811
        return -1;
812
    }
813
    
814
    nut->stream_count = get_v(bc);
815
    get_v(bc); //checksum threshold
816

    
817
    for(i=0; i<256;){
818
        int tmp_flags = get_v(bc);
819
        int tmp_stream= get_v(bc);
820
        int tmp_mul   = get_v(bc);
821
        int tmp_size  = get_v(bc);
822
        int count     = get_v(bc);
823

    
824
        if(count == 0 || i+count > 256){
825
            av_log(s, AV_LOG_ERROR, "illegal count %d at %d\n", count, i);
826
            return -1;
827
        }
828

    
829
        if((tmp_flags & FLAG_FRAME_TYPE) && tmp_flags != 1){
830
            if(tmp_flags & FLAG_PRED_KEY_FRAME){
831
                av_log(s, AV_LOG_ERROR, "keyframe prediction in non 0 frame type\n");
832
                return -1;
833
            }
834
            if(!(tmp_flags & FLAG_PTS) || !(tmp_flags & FLAG_FULL_PTS) ){
835
                av_log(s, AV_LOG_ERROR, "no full pts in non 0 frame type\n");
836
                return -1;
837
            }
838
        }
839

    
840
        for(j=0; j<count; j++,i++){
841
            if(tmp_stream > nut->stream_count + 1){
842
                av_log(s, AV_LOG_ERROR, "illegal stream number\n");
843
                return -1;
844
            }
845

    
846
            nut->frame_code[i].flags           = tmp_flags ;
847
            nut->frame_code[i].stream_id_plus1 = tmp_stream;
848
            nut->frame_code[i].size_mul        = tmp_mul   ;
849
            nut->frame_code[i].size_lsb        = tmp_size  ;
850
            if(++tmp_size >= tmp_mul){
851
                tmp_size=0;
852
                tmp_stream++;
853
            }
854
        }
855
    }
856
    if(nut->frame_code['N'].flags != 1){
857
        av_log(s, AV_LOG_ERROR, "illegal frame_code table\n");
858
        return -1;
859
    }
860

    
861
    if(check_checksum(bc)){
862
        av_log(s, AV_LOG_ERROR, "Main header checksum missmatch\n");
863
        return -1;
864
    }
865

    
866
    return 0;
867
}
868

    
869
static int decode_stream_header(NUTContext *nut){
870
    AVFormatContext *s= nut->avf;
871
    ByteIOContext *bc = &s->pb;
872
    int class, nom, denom, stream_id, i;
873
    uint64_t tmp;
874
    AVStream *st;
875
    
876
    get_packetheader(nut, bc, 8, 1);
877
    stream_id= get_v(bc);
878
    if(stream_id >= nut->stream_count || s->streams[stream_id])
879
        return -1;
880
    
881
    st = av_new_stream(s, stream_id);
882
    if (!st)
883
        return AVERROR_NOMEM;
884
    class = get_v(bc);
885
    tmp = get_v(bc);
886
    switch(class)
887
    {
888
        case 0:
889
            st->codec.codec_type = CODEC_TYPE_VIDEO;
890
            st->codec.codec_id = codec_get_bmp_id(tmp);
891
            if (st->codec.codec_id == CODEC_ID_NONE)
892
                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
893
            break;
894
        case 32:
895
            st->codec.codec_type = CODEC_TYPE_AUDIO;
896
            st->codec.codec_id = codec_get_wav_id(tmp);
897
            if (st->codec.codec_id == CODEC_ID_NONE)
898
                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");
899
            break;
900
        default:
901
            av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);
902
            return -1;
903
    }
904
    s->bit_rate += get_v(bc);
905
    get_v(bc); /* language code */
906
    nom = get_v(bc);
907
    denom = get_v(bc);
908
    nut->stream[stream_id].msb_timestamp_shift = get_v(bc);
909
    for(i=0; i<3; i++)
910
            nut->stream[stream_id].initial_pts_predictor[i]= get_v(bc);
911
    for(i=0; i<2; i++)
912
            nut->stream[stream_id].initial_size_predictor[i]= get_v(bc);
913
    get_byte(bc); /* flags */
914

    
915
    /* codec specific data headers */
916
    while(get_v(bc) != 0){
917
        st->codec.extradata_size= get_v(bc);
918
        st->codec.extradata= av_mallocz(st->codec.extradata_size);
919
        get_buffer(bc, st->codec.extradata, st->codec.extradata_size);            
920
//            url_fskip(bc, get_v(bc));
921
    }
922
    
923
    if (class == 0) /* VIDEO */
924
    {
925
        st->codec.width = get_v(bc);
926
        st->codec.height = get_v(bc);
927
        st->codec.sample_aspect_ratio.num= get_v(bc);
928
        st->codec.sample_aspect_ratio.den= get_v(bc);
929
        get_v(bc); /* csp type */
930

    
931
        st->codec.frame_rate = nom;
932
        st->codec.frame_rate_base = denom;
933
    }
934
    if (class == 32) /* AUDIO */
935
    {
936
        st->codec.sample_rate = (get_v(bc) * nom) / denom;
937
        st->codec.channels = get_v(bc);
938
    }
939
    if(check_checksum(bc)){
940
        av_log(s, AV_LOG_ERROR, "Stream header %d checksum missmatch\n", stream_id);
941
        return -1;
942
    }
943
    nut->stream[stream_id].rate_num= nom;
944
    nut->stream[stream_id].rate_den= denom;
945
    return 0;
946
}
947

    
948
static int decode_info_header(NUTContext *nut){
949
    AVFormatContext *s= nut->avf;
950
    ByteIOContext *bc = &s->pb;
951
    
952
    get_packetheader(nut, bc, 8, 1);
953

    
954
    for(;;){
955
        int id= get_v(bc);
956
        char *name, *type, custom_name[256], custom_type[256];
957

    
958
        if(!id)
959
            break;
960
        else if(id >= sizeof(info_table)/sizeof(info_table[0])){
961
            av_log(s, AV_LOG_ERROR, "info id is too large %d %d\n", id, sizeof(info_table)/sizeof(info_table[0]));
962
            return -1;
963
        }
964

    
965
        type= info_table[id][1];
966
        name= info_table[id][0];
967
//av_log(s, AV_LOG_DEBUG, "%d %s %s\n", id, type, name);
968

    
969
        if(!type){
970
            get_str(bc, custom_type, sizeof(custom_type));
971
            type= custom_type;
972
        }
973
        if(!name){
974
            get_str(bc, custom_name, sizeof(custom_name));
975
            name= custom_name;
976
        }
977
        
978
        if(!strcmp(type, "v")){
979
            int value= get_v(bc);
980
        }else{
981
            if(!strcmp(name, "Author"))
982
                get_str(bc, s->author, sizeof(s->author));
983
            else if(!strcmp(name, "Title"))
984
                get_str(bc, s->title, sizeof(s->title));
985
            else if(!strcmp(name, "Copyright"))
986
                get_str(bc, s->copyright, sizeof(s->copyright));
987
            else if(!strcmp(name, "Description"))
988
                get_str(bc, s->comment, sizeof(s->comment));
989
            else
990
                get_str(bc, NULL, 0);
991
        }
992
    }
993
    if(check_checksum(bc)){
994
        av_log(s, AV_LOG_ERROR, "Info header checksum missmatch\n");
995
        return -1;
996
    }
997
    return 0;
998
}
999

    
1000
static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)
1001
{
1002
    NUTContext *nut = s->priv_data;
1003
    ByteIOContext *bc = &s->pb;
1004
    int64_t pos;
1005
    int inited_stream_count;
1006

    
1007
    nut->avf= s;
1008
    
1009
    av_set_pts_info(s, 60, 1, AV_TIME_BASE);
1010

    
1011
    /* main header */
1012
    pos=0;
1013
    for(;;){
1014
        if (find_startcode(bc, MAIN_STARTCODE, pos)<0){
1015
            av_log(s, AV_LOG_ERROR, "no main startcode found\n");
1016
            return -1;
1017
        }
1018
        pos= url_ftell(bc);
1019
        if(decode_main_header(nut) >= 0)
1020
            break;
1021
    }
1022
    
1023
    
1024
    s->bit_rate = 0;
1025

    
1026
    nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);
1027

    
1028
    /* stream headers */
1029
    pos=0;
1030
    for(inited_stream_count=0; inited_stream_count < nut->stream_count;){
1031
        if (find_startcode(bc, STREAM_STARTCODE, pos)<0){
1032
            av_log(s, AV_LOG_ERROR, "not all stream headers found\n");
1033
            return -1;
1034
        }
1035
        pos= url_ftell(bc);
1036
        if(decode_stream_header(nut) >= 0)
1037
            inited_stream_count++;
1038
    }
1039

    
1040
    /* info headers */
1041
    pos=0;
1042
    for(;;){
1043
        uint64_t startcode= find_any_startcode(bc, pos);
1044
        pos= url_ftell(bc);
1045

    
1046
        if(startcode==0){
1047
            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");
1048
            return -1;
1049
        }else if(startcode == KEYFRAME_STARTCODE){
1050
            url_fseek(bc, -8, SEEK_CUR); //FIXME
1051
            break;
1052
        }else if(startcode != INFO_STARTCODE){
1053
            continue;
1054
        }
1055

    
1056
        decode_info_header(nut);
1057
    }
1058

    
1059
    return 0;
1060
}
1061

    
1062
static int nut_read_packet(AVFormatContext *s, AVPacket *pkt)
1063
{
1064
    NUTContext *nut = s->priv_data;
1065
    StreamContext *stream;
1066
    ByteIOContext *bc = &s->pb;
1067
    int size, frame_code, flags, size_mul, size_lsb, stream_id;
1068
    int key_frame = 0;
1069
    int frame_type= 0;
1070
    int64_t pts = 0;
1071
    const int64_t frame_start= url_ftell(bc);
1072

    
1073
    if (url_feof(bc))
1074
        return -1;
1075
    
1076
    frame_code = get_byte(bc);
1077
    if(frame_code == 'N'){
1078
        uint64_t tmp= frame_code;
1079
        tmp<<=8 ; tmp |= get_byte(bc);
1080
        tmp<<=16; tmp |= get_be16(bc);
1081
        tmp<<=32; tmp |= get_be32(bc);
1082
        if (tmp == KEYFRAME_STARTCODE)
1083
        {
1084
            frame_code = get_byte(bc);
1085
            frame_type = 2;
1086
        }
1087
        else
1088
            av_log(s, AV_LOG_ERROR, "error in zero bit / startcode %LX\n", tmp);
1089
    }
1090
    flags= nut->frame_code[frame_code].flags;
1091
    size_mul= nut->frame_code[frame_code].size_mul;
1092
    size_lsb= nut->frame_code[frame_code].size_lsb;
1093
    stream_id= nut->frame_code[frame_code].stream_id_plus1 - 1;
1094

    
1095
    if(flags & FLAG_FRAME_TYPE){
1096
        reset(s);
1097
        if(frame_type==2){
1098
            get_packetheader(nut, bc, 8+1, 0);
1099
        }else{
1100
            get_packetheader(nut, bc, 1, 0);
1101
            frame_type= 1;
1102
        }
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
    if(flags & FLAG_PRED_KEY_FRAME){
1114
        if(flags & FLAG_KEY_FRAME)
1115
            key_frame= !stream->last_key_frame;
1116
        else
1117
            key_frame= stream->last_key_frame;
1118
    }else{
1119
        key_frame= !!(flags & FLAG_KEY_FRAME);
1120
    }
1121

    
1122
    if(flags & FLAG_PTS){
1123
        if(flags & FLAG_FULL_PTS){
1124
            pts= get_v(bc);
1125
        }else{
1126
            int64_t mask = (1<<stream->msb_timestamp_shift)-1;
1127
            int64_t delta= stream->last_pts - mask/2;
1128
            pts= ((get_v(bc) - delta)&mask) + delta;
1129
        }
1130
    }else{
1131
        pts= stream->last_pts + stream->lru_pts_delta[(flags&12)>>2];
1132
    }
1133
  
1134
    if(size_mul <= size_lsb){
1135
        size= stream->lru_size[size_lsb - size_mul];
1136
    }else{
1137
        if(flags & FLAG_DATA_SIZE)
1138
            size= size_mul*get_v(bc) + size_lsb;
1139
        else
1140
            size= size_lsb;
1141
    }
1142
      
1143
//av_log(s, AV_LOG_DEBUG, "fs:%lld fc:%d ft:%d kf:%d pts:%lld\n", frame_start, frame_code, frame_type, key_frame, pts);
1144
    
1145
    av_new_packet(pkt, size);
1146
    get_buffer(bc, pkt->data, size);
1147
    pkt->stream_index = stream_id;
1148
    if (key_frame)
1149
        pkt->flags |= PKT_FLAG_KEY;
1150
    pkt->pts = pts * AV_TIME_BASE * stream->rate_den / stream->rate_num;
1151

    
1152
    update(nut, stream_id, frame_start, frame_type, frame_code, key_frame, size, pts);
1153

    
1154
    return 0;
1155
}
1156

    
1157
static int nut_read_close(AVFormatContext *s)
1158
{
1159
    NUTContext *nut = s->priv_data;
1160
    int i;
1161

    
1162
    for(i=0;i<s->nb_streams;i++) {
1163
        av_freep(&s->streams[i]->codec.extradata);
1164
    }
1165
    av_freep(&nut->stream);
1166

    
1167
    return 0;
1168
}
1169

    
1170
static AVInputFormat nut_iformat = {
1171
    "nut",
1172
    "nut format",
1173
    sizeof(NUTContext),
1174
    nut_probe,
1175
    nut_read_header,
1176
    nut_read_packet,
1177
    nut_read_close,
1178
//    nut_read_seek,
1179
    .extensions = "nut",
1180
};
1181

    
1182
#ifdef CONFIG_ENCODERS
1183
static AVOutputFormat nut_oformat = {
1184
    "nut",
1185
    "nut format",
1186
    "video/x-nut",
1187
    "nut",
1188
    sizeof(NUTContext),
1189
#ifdef CONFIG_VORBIS
1190
    CODEC_ID_VORBIS,
1191
#elif defined(CONFIG_MP3LAME)
1192
    CODEC_ID_MP3,
1193
#else
1194
    CODEC_ID_MP2, /* AC3 needs liba52 decoder */
1195
#endif
1196
    CODEC_ID_MPEG4,
1197
    nut_write_header,
1198
    nut_write_packet,
1199
    nut_write_trailer,
1200
};
1201
#endif //CONFIG_ENCODERS
1202

    
1203
int nut_init(void)
1204
{
1205
    av_register_input_format(&nut_iformat);
1206
#ifdef CONFIG_ENCODERS
1207
    av_register_output_format(&nut_oformat);
1208
#endif //CONFIG_ENCODERS
1209
    return 0;
1210
}