Statistics
| Branch: | Revision:

ffmpeg / libavformat / nutenc.c @ 6266c515

History | View | Annotate | Download (27.8 KB)

1
/*
2
 * nut muxer
3
 * Copyright (c) 2004-2007 Michael Niedermayer
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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 1
179
        if(is_audio){
180
            int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
181
            int pts;
182
            for(pts=0; pts<2; pts++){
183
                for(pred=0; pred<2; pred++){
184
                    FrameCode *ft= &nut->frame_code[start2];
185
                    ft->flags= FLAG_KEY*key_frame;
186
                    ft->stream_id= stream_id;
187
                    ft->size_mul=frame_bytes + 2;
188
                    ft->size_lsb=frame_bytes + pred;
189
                    ft->pts_delta=pts;
190
                    ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
191
                    start2++;
192
                }
193
            }
194
        }else{
195
            FrameCode *ft= &nut->frame_code[start2];
196
            ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
197
            ft->stream_id= stream_id;
198
            ft->size_mul=1;
199
            ft->pts_delta=1;
200
            start2++;
201
        }
202
#endif
203

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

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

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

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

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

    
257
    ff_put_v(bc, len);
258
    avio_write(bc, string, len);
259
}
260

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

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

    
269
    ff_put_v(bc, v);
270
}
271

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

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

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

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

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

    
300
    av_free(dyn_buf);
301
}
302

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

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

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

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

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

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

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

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

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

    
398
    ff_put_v(bc, codec->extradata_size);
399
    avio_write(bc, codec->extradata, codec->extradata_size);
400

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

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

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

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

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

    
446
    ff_put_v(bc, 0); //stream_if_plus1
447
    ff_put_v(bc, 0); //chapter_id
448
    ff_put_v(bc, 0); //timestamp_start
449
    ff_put_v(bc, 0); //length
450

    
451
    ff_put_v(bc, count);
452

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

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

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

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

    
481
        ff_put_v(bc, count);
482

    
483
        avio_write(bc, dyn_buf, dyn_size);
484
    }
485

    
486
    av_free(dyn_buf);
487
    return count;
488
}
489

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

    
498
    ret = avio_open_dyn_buf(&dyn_bc);
499
    if (ret < 0)
500
        return ret;
501

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

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

    
510
    ff_put_v(bc, count);
511

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

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

    
523
    ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
524

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

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

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

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

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

    
576
    nut->last_syncpoint_pos= INT_MIN;
577
    nut->header_count++;
578
    return 0;
579
}
580

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

    
586
    nut->avf= s;
587

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

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

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

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

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

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

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

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

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

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

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

    
649
    avio_flush(bc);
650

    
651
    //FIXME index
652

    
653
    return 0;
654
}
655

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
752
    best_header_idx= find_best_header_idx(nut, pkt);
753

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
844
    return 0;
845
}
846

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

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

    
859
    return 0;
860
}
861

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