Statistics
| Branch: | Revision:

ffmpeg / libavformat / nutenc.c @ 76432655

History | View | Annotate | Download (27.9 KB)

1
/*
2
 * nut muxer
3
 * Copyright (c) 2004-2007 Michael Niedermayer
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * Libav is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
#include "libavutil/intreadwrite.h"
23
#include "libavutil/tree.h"
24
#include "libavcodec/mpegaudiodata.h"
25
#include "nut.h"
26
#include "internal.h"
27
#include "avio_internal.h"
28

    
29
static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
30
    int sample_rate= c->sample_rate;
31

    
32
    if(size>4096)
33
        return 0;
34

    
35
    AV_WB24(out, 1);
36

    
37
    if(c->codec_id == CODEC_ID_MPEG4){
38
        if(key_frame){
39
            return 3;
40
        }else{
41
            out[3]= 0xB6;
42
            return 4;
43
        }
44
    }else if(c->codec_id == CODEC_ID_MPEG1VIDEO || c->codec_id == CODEC_ID_MPEG2VIDEO){
45
        return 3;
46
    }else if(c->codec_id == CODEC_ID_H264){
47
        return 3;
48
    }else if(c->codec_id == CODEC_ID_MP3 || c->codec_id == CODEC_ID_MP2){
49
        int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
50
        int layer= c->codec_id == CODEC_ID_MP3 ? 3 : 2;
51
        unsigned int header= 0xFFF00000;
52

    
53
        lsf     = sample_rate < (24000+32000)/2;
54
        mpeg25  = sample_rate < (12000+16000)/2;
55
        sample_rate <<= lsf + mpeg25;
56
        if     (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
57
        else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
58
        else                                     sample_rate_index=1;
59

    
60
        sample_rate= ff_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
61

    
62
        for(bitrate_index=2; bitrate_index<30; bitrate_index++){
63
            frame_size = ff_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
64
            frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
65

    
66
            if(frame_size == size)
67
                break;
68
        }
69

    
70
        header |= (!lsf)<<19;
71
        header |= (4-layer)<<17;
72
        header |= 1<<16; //no crc
73
        AV_WB32(out, header);
74
        if(size <= 0)
75
            return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
76
        if(bitrate_index == 30)
77
            return -1; //something is wrong ...
78

    
79
        header |= (bitrate_index>>1)<<12;
80
        header |= sample_rate_index<<10;
81
        header |= (bitrate_index&1)<<9;
82

    
83
        return 2; //FIXME actually put the needed ones in build_elision_headers()
84
        return 3; //we guess that the private bit is not set
85
//FIXME the above assumptions should be checked, if these turn out false too often something should be done
86
    }
87
    return 0;
88
}
89

    
90
static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
91
    NUTContext *nut = s->priv_data;
92
    uint8_t out[64];
93
    int i;
94
    int len= find_expected_header(c, size, frame_type, out);
95

    
96
//av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
97

    
98
    for(i=1; i<nut->header_count; i++){
99
        if(   len == nut->header_len[i]
100
           && !memcmp(out, nut->header[i], len)){
101
//    av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
102
            return i;
103
        }
104
    }
105
//    av_log(NULL, AV_LOG_ERROR, "nothing found\n");
106
    return 0;
107
}
108

    
109
static void build_elision_headers(AVFormatContext *s){
110
    NUTContext *nut = s->priv_data;
111
    int i;
112
    //FIXME this is lame
113
    //FIXME write a 2pass mode to find the maximal headers
114
    static const uint8_t headers[][5]={
115
        {3, 0x00, 0x00, 0x01},
116
        {4, 0x00, 0x00, 0x01, 0xB6},
117
        {2, 0xFF, 0xFA}, //mp3+crc
118
        {2, 0xFF, 0xFB}, //mp3
119
        {2, 0xFF, 0xFC}, //mp2+crc
120
        {2, 0xFF, 0xFD}, //mp2
121
    };
122

    
123
    nut->header_count= 7;
124
    for(i=1; i<nut->header_count; i++){
125
        nut->header_len[i]=  headers[i-1][0];
126
        nut->header    [i]= &headers[i-1][1];
127
    }
128
}
129

    
130
static void build_frame_code(AVFormatContext *s){
131
    NUTContext *nut = s->priv_data;
132
    int key_frame, index, pred, stream_id;
133
    int start=1;
134
    int end= 254;
135
    int keyframe_0_esc= s->nb_streams > 2;
136
    int pred_table[10];
137
    FrameCode *ft;
138

    
139
    ft= &nut->frame_code[start];
140
    ft->flags= FLAG_CODED;
141
    ft->size_mul=1;
142
    ft->pts_delta=1;
143
    start++;
144

    
145
    if(keyframe_0_esc){
146
        /* keyframe = 0 escape */
147
        FrameCode *ft= &nut->frame_code[start];
148
        ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
149
        ft->size_mul=1;
150
        start++;
151
    }
152

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

    
161
        for(key_frame=0; key_frame<2; key_frame++){
162
            if(intra_only && keyframe_0_esc && key_frame==0)
163
                continue;
164

    
165
            {
166
                FrameCode *ft= &nut->frame_code[start2];
167
                ft->flags= FLAG_KEY*key_frame;
168
                ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
169
                ft->stream_id= stream_id;
170
                ft->size_mul=1;
171
                if(is_audio)
172
                    ft->header_idx= find_header_idx(s, codec, -1, key_frame);
173
                start2++;
174
            }
175
        }
176

    
177
        key_frame= intra_only;
178
        if(is_audio){
179
            int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
180
            int pts;
181
            for(pts=0; pts<2; pts++){
182
                for(pred=0; pred<2; pred++){
183
                    FrameCode *ft= &nut->frame_code[start2];
184
                    ft->flags= FLAG_KEY*key_frame;
185
                    ft->stream_id= stream_id;
186
                    ft->size_mul=frame_bytes + 2;
187
                    ft->size_lsb=frame_bytes + pred;
188
                    ft->pts_delta=pts;
189
                    ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
190
                    start2++;
191
                }
192
            }
193
        }else{
194
            FrameCode *ft= &nut->frame_code[start2];
195
            ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
196
            ft->stream_id= stream_id;
197
            ft->size_mul=1;
198
            ft->pts_delta=1;
199
            start2++;
200
        }
201

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

    
219
        for(pred=0; pred<pred_count; pred++){
220
            int start3= start2 + (end2-start2)*pred / pred_count;
221
            int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
222

    
223
            for(index=start3; index<end3; index++){
224
                FrameCode *ft= &nut->frame_code[index];
225
                ft->flags= FLAG_KEY*key_frame;
226
                ft->flags|= FLAG_SIZE_MSB;
227
                ft->stream_id= stream_id;
228
//FIXME use single byte size and pred from last
229
                ft->size_mul= end3-start3;
230
                ft->size_lsb= index - start3;
231
                ft->pts_delta= pred_table[pred];
232
                if(is_audio)
233
                    ft->header_idx= find_header_idx(s, codec, -1, key_frame);
234
            }
235
        }
236
    }
237
    memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
238
    nut->frame_code[  0].flags=
239
    nut->frame_code[255].flags=
240
    nut->frame_code['N'].flags= FLAG_INVALID;
241
}
242

    
243
static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
244
    val *= nut->time_base_count;
245
    val += time_base - nut->time_base;
246
    ff_put_v(bc, val);
247
}
248

    
249
/**
250
 * Store a string as vb.
251
 */
252
static void put_str(AVIOContext *bc, const char *string){
253
    int len= strlen(string);
254

    
255
    ff_put_v(bc, len);
256
    avio_write(bc, string, len);
257
}
258

    
259
static void put_s(AVIOContext *bc, int64_t val){
260
    ff_put_v(bc, 2*FFABS(val) - (val>0));
261
}
262

    
263
#ifdef TRACE
264
static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, char *file, char *func, int line){
265
    av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
266

    
267
    ff_put_v(bc, v);
268
}
269

    
270
static inline void put_s_trace(AVIOContext *bc, int64_t v, char *file, char *func, int line){
271
    av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
272

    
273
    put_s(bc, v);
274
}
275
#define ff_put_v(bc, v)  ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
276
#define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
277
#endif
278

    
279
//FIXME remove calculate_checksum
280
static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
281
    uint8_t *dyn_buf=NULL;
282
    int dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
283
    int forw_ptr= dyn_size + 4*calculate_checksum;
284

    
285
    if(forw_ptr > 4096)
286
        ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
287
    avio_wb64(bc, startcode);
288
    ff_put_v(bc, forw_ptr);
289
    if(forw_ptr > 4096)
290
        avio_wl32(bc, ffio_get_checksum(bc));
291

    
292
    if(calculate_checksum)
293
        ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
294
    avio_write(bc, dyn_buf, dyn_size);
295
    if(calculate_checksum)
296
        avio_wl32(bc, ffio_get_checksum(bc));
297

    
298
    av_free(dyn_buf);
299
}
300

    
301
static void write_mainheader(NUTContext *nut, AVIOContext *bc){
302
    int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
303
    int64_t tmp_match;
304

    
305
    ff_put_v(bc, 3); /* version */
306
    ff_put_v(bc, nut->avf->nb_streams);
307
    ff_put_v(bc, nut->max_distance);
308
    ff_put_v(bc, nut->time_base_count);
309

    
310
    for(i=0; i<nut->time_base_count; i++){
311
        ff_put_v(bc, nut->time_base[i].num);
312
        ff_put_v(bc, nut->time_base[i].den);
313
    }
314

    
315
    tmp_pts=0;
316
    tmp_mul=1;
317
    tmp_stream=0;
318
    tmp_match= 1-(1LL<<62);
319
    tmp_head_idx= 0;
320
    for(i=0; i<256;){
321
        tmp_fields=0;
322
        tmp_size=0;
323
//        tmp_res=0;
324
        if(tmp_pts    != nut->frame_code[i].pts_delta) tmp_fields=1;
325
        if(tmp_mul    != nut->frame_code[i].size_mul ) tmp_fields=2;
326
        if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
327
        if(tmp_size   != nut->frame_code[i].size_lsb ) tmp_fields=4;
328
//        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
329
        if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
330

    
331
        tmp_pts   = nut->frame_code[i].pts_delta;
332
        tmp_flags = nut->frame_code[i].flags;
333
        tmp_stream= nut->frame_code[i].stream_id;
334
        tmp_mul   = nut->frame_code[i].size_mul;
335
        tmp_size  = nut->frame_code[i].size_lsb;
336
//        tmp_res   = nut->frame_code[i].res;
337
        tmp_head_idx= nut->frame_code[i].header_idx;
338

    
339
        for(j=0; i<256; j++,i++){
340
            if(i == 'N'){
341
                j--;
342
                continue;
343
            }
344
            if(nut->frame_code[i].pts_delta != tmp_pts   ) break;
345
            if(nut->frame_code[i].flags     != tmp_flags ) break;
346
            if(nut->frame_code[i].stream_id != tmp_stream) break;
347
            if(nut->frame_code[i].size_mul  != tmp_mul   ) break;
348
            if(nut->frame_code[i].size_lsb  != tmp_size+j) break;
349
//            if(nut->frame_code[i].res       != tmp_res   ) break;
350
            if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
351
        }
352
        if(j != tmp_mul - tmp_size) tmp_fields=6;
353

    
354
        ff_put_v(bc, tmp_flags);
355
        ff_put_v(bc, tmp_fields);
356
        if(tmp_fields>0) put_s(bc, tmp_pts);
357
        if(tmp_fields>1) ff_put_v(bc, tmp_mul);
358
        if(tmp_fields>2) ff_put_v(bc, tmp_stream);
359
        if(tmp_fields>3) ff_put_v(bc, tmp_size);
360
        if(tmp_fields>4) ff_put_v(bc, 0 /*tmp_res*/);
361
        if(tmp_fields>5) ff_put_v(bc, j);
362
        if(tmp_fields>6) ff_put_v(bc, tmp_match);
363
        if(tmp_fields>7) ff_put_v(bc, tmp_head_idx);
364
    }
365
    ff_put_v(bc, nut->header_count-1);
366
    for(i=1; i<nut->header_count; i++){
367
        ff_put_v(bc, nut->header_len[i]);
368
        avio_write(bc, nut->header[i], nut->header_len[i]);
369
    }
370
}
371

    
372
static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
373
    NUTContext *nut = avctx->priv_data;
374
    AVCodecContext *codec = st->codec;
375
    ff_put_v(bc, i);
376
    switch(codec->codec_type){
377
    case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
378
    case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
379
    case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
380
    default              : ff_put_v(bc, 3); break;
381
    }
382
    ff_put_v(bc, 4);
383
    if (codec->codec_tag){
384
        avio_wl32(bc, codec->codec_tag);
385
    } else {
386
        av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
387
        return AVERROR(EINVAL);
388
    }
389

    
390
    ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
391
    ff_put_v(bc, nut->stream[i].msb_pts_shift);
392
    ff_put_v(bc, nut->stream[i].max_pts_distance);
393
    ff_put_v(bc, codec->has_b_frames);
394
    avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
395

    
396
    ff_put_v(bc, codec->extradata_size);
397
    avio_write(bc, codec->extradata, codec->extradata_size);
398

    
399
    switch(codec->codec_type){
400
    case AVMEDIA_TYPE_AUDIO:
401
        ff_put_v(bc, codec->sample_rate);
402
        ff_put_v(bc, 1);
403
        ff_put_v(bc, codec->channels);
404
        break;
405
    case AVMEDIA_TYPE_VIDEO:
406
        ff_put_v(bc, codec->width);
407
        ff_put_v(bc, codec->height);
408

    
409
        if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
410
            ff_put_v(bc, 0);
411
            ff_put_v(bc, 0);
412
        }else{
413
            ff_put_v(bc, st->sample_aspect_ratio.num);
414
            ff_put_v(bc, st->sample_aspect_ratio.den);
415
        }
416
        ff_put_v(bc, 0); /* csp type -- unknown */
417
        break;
418
    default:
419
        break;
420
    }
421
    return 0;
422
}
423

    
424
static int add_info(AVIOContext *bc, const char *type, const char *value){
425
    put_str(bc, type);
426
    put_s(bc, -1);
427
    put_str(bc, value);
428
    return 1;
429
}
430

    
431
static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
432
    AVFormatContext *s= nut->avf;
433
    AVMetadataTag *t = NULL;
434
    AVIOContext *dyn_bc;
435
    uint8_t *dyn_buf=NULL;
436
    int count=0, dyn_size;
437
    int ret = avio_open_dyn_buf(&dyn_bc);
438
    if(ret < 0)
439
        return ret;
440

    
441
    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
442
        count += add_info(dyn_bc, t->key, t->value);
443

    
444
    ff_put_v(bc, 0); //stream_if_plus1
445
    ff_put_v(bc, 0); //chapter_id
446
    ff_put_v(bc, 0); //timestamp_start
447
    ff_put_v(bc, 0); //length
448

    
449
    ff_put_v(bc, count);
450

    
451
    dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
452
    avio_write(bc, dyn_buf, dyn_size);
453
    av_free(dyn_buf);
454
    return 0;
455
}
456

    
457
static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
458
    AVFormatContext *s= nut->avf;
459
    AVStream* st = s->streams[stream_id];
460
    AVIOContext *dyn_bc;
461
    uint8_t *dyn_buf=NULL;
462
    int count=0, dyn_size, i;
463
    int ret = avio_open_dyn_buf(&dyn_bc);
464
    if(ret < 0)
465
        return ret;
466

    
467
    for (i=0; ff_nut_dispositions[i].flag; ++i) {
468
        if (st->disposition & ff_nut_dispositions[i].flag)
469
            count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
470
    }
471
    dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
472

    
473
    if (count) {
474
        ff_put_v(bc, stream_id + 1); //stream_id_plus1
475
        ff_put_v(bc, 0); //chapter_id
476
        ff_put_v(bc, 0); //timestamp_start
477
        ff_put_v(bc, 0); //length
478

    
479
        ff_put_v(bc, count);
480

    
481
        avio_write(bc, dyn_buf, dyn_size);
482
    }
483

    
484
    av_free(dyn_buf);
485
    return count;
486
}
487

    
488
static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
489
{
490
    AVIOContext *dyn_bc;
491
    uint8_t *dyn_buf = NULL;
492
    AVMetadataTag *t = NULL;
493
    AVChapter *ch    = nut->avf->chapters[id];
494
    int ret, dyn_size, count = 0;
495

    
496
    ret = avio_open_dyn_buf(&dyn_bc);
497
    if (ret < 0)
498
        return ret;
499

    
500
    ff_put_v(bc, 0);                                        // stream_id_plus1
501
    put_s(bc, id + 1);                                      // chapter_id
502
    put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
503
    ff_put_v(bc, ch->end - ch->start);                      // chapter_len
504

    
505
    while ((t = av_metadata_get(ch->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
506
        count += add_info(dyn_bc, t->key, t->value);
507

    
508
    ff_put_v(bc, count);
509

    
510
    dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
511
    avio_write(bc, dyn_buf, dyn_size);
512
    av_freep(&dyn_buf);
513
    return 0;
514
}
515

    
516
static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
517
    NUTContext *nut = avctx->priv_data;
518
    AVIOContext *dyn_bc;
519
    int i, ret;
520

    
521
    ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
522

    
523
    ret = avio_open_dyn_buf(&dyn_bc);
524
    if(ret < 0)
525
        return ret;
526
    write_mainheader(nut, dyn_bc);
527
    put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
528

    
529
    for (i=0; i < nut->avf->nb_streams; i++){
530
        ret = avio_open_dyn_buf(&dyn_bc);
531
        if(ret < 0)
532
            return ret;
533
        if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
534
            return ret;
535
        put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
536
    }
537

    
538
    ret = avio_open_dyn_buf(&dyn_bc);
539
    if(ret < 0)
540
        return ret;
541
    write_globalinfo(nut, dyn_bc);
542
    put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
543

    
544
    for (i = 0; i < nut->avf->nb_streams; i++) {
545
        ret = avio_open_dyn_buf(&dyn_bc);
546
        if(ret < 0)
547
            return ret;
548
        ret = write_streaminfo(nut, dyn_bc, i);
549
        if (ret < 0)
550
            return ret;
551
        if (ret > 0)
552
            put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
553
        else {
554
            uint8_t* buf;
555
            avio_close_dyn_buf(dyn_bc, &buf);
556
            av_free(buf);
557
        }
558
    }
559

    
560
    for (i = 0; i < nut->avf->nb_chapters; i++) {
561
        ret = avio_open_dyn_buf(&dyn_bc);
562
        if (ret < 0)
563
            return ret;
564
        ret = write_chapter(nut, dyn_bc, i);
565
        if (ret < 0) {
566
            uint8_t *buf;
567
            avio_close_dyn_buf(dyn_bc, &buf);
568
            av_freep(&buf);
569
            return ret;
570
        }
571
        put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
572
    }
573

    
574
    nut->last_syncpoint_pos= INT_MIN;
575
    nut->header_count++;
576
    return 0;
577
}
578

    
579
static int write_header(AVFormatContext *s){
580
    NUTContext *nut = s->priv_data;
581
    AVIOContext *bc = s->pb;
582
    int i, j, ret;
583

    
584
    nut->avf= s;
585

    
586
    nut->stream   = av_mallocz(sizeof(StreamContext)*s->nb_streams);
587
    if (s->nb_chapters)
588
        nut->chapter  = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
589
    nut->time_base= av_mallocz(sizeof(AVRational   )*(s->nb_streams +
590
                                                      s->nb_chapters));
591
    if (!nut->stream || (s->nb_chapters && !nut->chapter) || !nut->time_base) {
592
        av_freep(&nut->stream);
593
        av_freep(&nut->chapter);
594
        av_freep(&nut->time_base);
595
        return AVERROR(ENOMEM);
596
    }
597

    
598
    for(i=0; i<s->nb_streams; i++){
599
        AVStream *st= s->streams[i];
600
        int ssize;
601
        AVRational time_base;
602
        ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
603

    
604
        av_set_pts_info(st, 64, time_base.num, time_base.den);
605

    
606
        for(j=0; j<nut->time_base_count; j++){
607
            if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
608
                break;
609
            }
610
        }
611
        nut->time_base[j]= time_base;
612
        nut->stream[i].time_base= &nut->time_base[j];
613
        if(j==nut->time_base_count)
614
            nut->time_base_count++;
615

    
616
        if(INT64_C(1000) * time_base.num >= time_base.den)
617
            nut->stream[i].msb_pts_shift = 7;
618
        else
619
            nut->stream[i].msb_pts_shift = 14;
620
        nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
621
    }
622

    
623
    for (i = 0; i < s->nb_chapters; i++) {
624
        AVChapter *ch = s->chapters[i];
625

    
626
        for (j = 0; j < nut->time_base_count; j++) {
627
            if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
628
                break;
629
        }
630

    
631
        nut->time_base[j] = ch->time_base;
632
        nut->chapter[i].time_base = &nut->time_base[j];
633
        if(j == nut->time_base_count)
634
            nut->time_base_count++;
635
    }
636

    
637
    nut->max_distance = MAX_DISTANCE;
638
    build_elision_headers(s);
639
    build_frame_code(s);
640
    assert(nut->frame_code['N'].flags == FLAG_INVALID);
641

    
642
    avio_write(bc, ID_STRING, strlen(ID_STRING));
643
    avio_w8(bc, 0);
644

    
645
    if ((ret = write_headers(s, bc)) < 0)
646
        return ret;
647

    
648
    avio_flush(bc);
649

    
650
    //FIXME index
651

    
652
    return 0;
653
}
654

    
655
static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
656
    int flags= 0;
657

    
658
    if(pkt->flags & AV_PKT_FLAG_KEY             ) flags |= FLAG_KEY;
659
    if(pkt->stream_index != fc->stream_id       ) flags |= FLAG_STREAM_ID;
660
    if(pkt->size / fc->size_mul                 ) flags |= FLAG_SIZE_MSB;
661
    if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
662
    if(pkt->size > 2*nut->max_distance          ) flags |= FLAG_CHECKSUM;
663
    if(FFABS(pkt->pts - nus->last_pts)
664
                         > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
665
    if(   pkt->size < nut->header_len[fc->header_idx]
666
       || (pkt->size > 4096 && fc->header_idx)
667
       || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
668
                                                  flags |= FLAG_HEADER_IDX;
669

    
670
    return flags | (fc->flags & FLAG_CODED);
671
}
672

    
673
static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
674
    int i;
675
    int best_i  = 0;
676
    int best_len= 0;
677

    
678
    if(pkt->size > 4096)
679
        return 0;
680

    
681
    for(i=1; i<nut->header_count; i++){
682
        if(   pkt->size >= nut->header_len[i]
683
           &&  nut->header_len[i] > best_len
684
           && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
685
            best_i= i;
686
            best_len= nut->header_len[i];
687
        }
688
    }
689
    return best_i;
690
}
691

    
692
static int write_packet(AVFormatContext *s, AVPacket *pkt){
693
    NUTContext *nut = s->priv_data;
694
    StreamContext *nus= &nut->stream[pkt->stream_index];
695
    AVIOContext *bc = s->pb, *dyn_bc;
696
    FrameCode *fc;
697
    int64_t coded_pts;
698
    int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
699
    int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
700
    int store_sp=0;
701
    int ret;
702

    
703
    if(pkt->pts < 0)
704
        return -1;
705

    
706
    if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
707
        write_headers(s, bc);
708

    
709
    if(key_frame && !(nus->last_flags & FLAG_KEY))
710
        store_sp= 1;
711

    
712
    if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
713
        store_sp= 1;
714

    
715
//FIXME: Ensure store_sp is 1 in the first place.
716

    
717
    if(store_sp){
718
        Syncpoint *sp, dummy= {.pos= INT64_MAX};
719

    
720
        ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
721
        for(i=0; i<s->nb_streams; i++){
722
            AVStream *st= s->streams[i];
723
            int64_t dts_tb = av_rescale_rnd(pkt->dts,
724
                nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
725
                nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
726
                AV_ROUND_DOWN);
727
            int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
728
            if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
729
        }
730
        if(dummy.pos == INT64_MAX)
731
            dummy.pos= 0;
732
        sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
733
                         NULL);
734

    
735
        nut->last_syncpoint_pos= avio_tell(bc);
736
        ret = avio_open_dyn_buf(&dyn_bc);
737
        if(ret < 0)
738
            return ret;
739
        put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
740
        ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
741
        put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
742

    
743
        ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
744
    }
745
    assert(nus->last_pts != AV_NOPTS_VALUE);
746

    
747
    coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
748
    if(ff_lsb2full(nus, coded_pts) != pkt->pts)
749
        coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
750

    
751
    best_header_idx= find_best_header_idx(nut, pkt);
752

    
753
    best_length=INT_MAX;
754
    frame_code= -1;
755
    for(i=0; i<256; i++){
756
        int length= 0;
757
        FrameCode *fc= &nut->frame_code[i];
758
        int flags= fc->flags;
759

    
760
        if(flags & FLAG_INVALID)
761
            continue;
762
        needed_flags= get_needed_flags(nut, nus, fc, pkt);
763

    
764
        if(flags & FLAG_CODED){
765
            length++;
766
            flags = needed_flags;
767
        }
768

    
769
        if((flags & needed_flags) != needed_flags)
770
            continue;
771

    
772
        if((flags ^ needed_flags) & FLAG_KEY)
773
            continue;
774

    
775
        if(flags & FLAG_STREAM_ID)
776
            length+= ff_get_v_length(pkt->stream_index);
777

    
778
        if(pkt->size % fc->size_mul != fc->size_lsb)
779
            continue;
780
        if(flags & FLAG_SIZE_MSB)
781
            length += ff_get_v_length(pkt->size / fc->size_mul);
782

    
783
        if(flags & FLAG_CHECKSUM)
784
            length+=4;
785

    
786
        if(flags & FLAG_CODED_PTS)
787
            length += ff_get_v_length(coded_pts);
788

    
789
        if(   (flags & FLAG_CODED)
790
           && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
791
            flags |= FLAG_HEADER_IDX;
792
        }
793

    
794
        if(flags & FLAG_HEADER_IDX){
795
            length += 1 - nut->header_len[best_header_idx];
796
        }else{
797
            length -= nut->header_len[fc->header_idx];
798
        }
799

    
800
        length*=4;
801
        length+= !(flags & FLAG_CODED_PTS);
802
        length+= !(flags & FLAG_CHECKSUM);
803

    
804
        if(length < best_length){
805
            best_length= length;
806
            frame_code=i;
807
        }
808
    }
809
    assert(frame_code != -1);
810
    fc= &nut->frame_code[frame_code];
811
    flags= fc->flags;
812
    needed_flags= get_needed_flags(nut, nus, fc, pkt);
813
    header_idx= fc->header_idx;
814

    
815
    ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
816
    avio_w8(bc, frame_code);
817
    if(flags & FLAG_CODED){
818
        ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
819
        flags = needed_flags;
820
    }
821
    if(flags & FLAG_STREAM_ID)  ff_put_v(bc, pkt->stream_index);
822
    if(flags & FLAG_CODED_PTS)  ff_put_v(bc, coded_pts);
823
    if(flags & FLAG_SIZE_MSB)   ff_put_v(bc, pkt->size / fc->size_mul);
824
    if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
825

    
826
    if(flags & FLAG_CHECKSUM)   avio_wl32(bc, ffio_get_checksum(bc));
827
    else                        ffio_get_checksum(bc);
828

    
829
    avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
830
    nus->last_flags= flags;
831
    nus->last_pts= pkt->pts;
832

    
833
    //FIXME just store one per syncpoint
834
    if(flags & FLAG_KEY)
835
        av_add_index_entry(
836
            s->streams[pkt->stream_index],
837
            nut->last_syncpoint_pos,
838
            pkt->pts,
839
            0,
840
            0,
841
            AVINDEX_KEYFRAME);
842

    
843
    return 0;
844
}
845

    
846
static int write_trailer(AVFormatContext *s){
847
    NUTContext *nut= s->priv_data;
848
    AVIOContext *bc= s->pb;
849

    
850
    while(nut->header_count<3)
851
        write_headers(s, bc);
852
    avio_flush(bc);
853
    ff_nut_free_sp(nut);
854
    av_freep(&nut->stream);
855
    av_freep(&nut->chapter);
856
    av_freep(&nut->time_base);
857

    
858
    return 0;
859
}
860

    
861
AVOutputFormat ff_nut_muxer = {
862
    "nut",
863
    NULL_IF_CONFIG_SMALL("NUT format"),
864
    "video/x-nut",
865
    "nut",
866
    sizeof(NUTContext),
867
#if   CONFIG_LIBVORBIS
868
    CODEC_ID_VORBIS,
869
#elif CONFIG_LIBMP3LAME
870
    CODEC_ID_MP3,
871
#else
872
    CODEC_ID_MP2,
873
#endif
874
    CODEC_ID_MPEG4,
875
    write_header,
876
    write_packet,
877
    write_trailer,
878
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
879
    .codec_tag = (const AVCodecTag * const []){ ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
880
};