Statistics
| Branch: | Revision:

ffmpeg / libavformat / nutenc.c @ 2912e87a

History | View | Annotate | Download (27.6 KB)

1 70ea1e69 Michael Niedermayer
/*
2
 * nut muxer
3
 * Copyright (c) 2004-2007 Michael Niedermayer
4
 *
5 2912e87a Mans Rullgard
 * This file is part of Libav.
6 70ea1e69 Michael Niedermayer
 *
7 2912e87a Mans Rullgard
 * Libav is free software; you can redistribute it and/or
8 70ea1e69 Michael Niedermayer
 * 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 2912e87a Mans Rullgard
 * Libav is distributed in the hope that it will be useful,
13 70ea1e69 Michael Niedermayer
 * 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 2912e87a Mans Rullgard
 * License along with Libav; if not, write to the Free Software
19 70ea1e69 Michael Niedermayer
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22 6a5d31ac Diego Biurrun
#include "libavutil/intreadwrite.h"
23 245976da Diego Biurrun
#include "libavutil/tree.h"
24
#include "libavcodec/mpegaudiodata.h"
25 70ea1e69 Michael Niedermayer
#include "nut.h"
26 80b39e1c Francesco Lavra
#include "internal.h"
27 a712d725 Michael Niedermayer
28
static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
29
    int sample_rate= c->sample_rate;
30
31
    if(size>4096)
32
        return 0;
33
34
    AV_WB24(out, 1);
35
36
    if(c->codec_id == CODEC_ID_MPEG4){
37
        if(key_frame){
38
            return 3;
39
        }else{
40
            out[3]= 0xB6;
41
            return 4;
42
        }
43
    }else if(c->codec_id == CODEC_ID_MPEG1VIDEO || c->codec_id == CODEC_ID_MPEG2VIDEO){
44
        return 3;
45
    }else if(c->codec_id == CODEC_ID_H264){
46
        return 3;
47
    }else if(c->codec_id == CODEC_ID_MP3 || c->codec_id == CODEC_ID_MP2){
48
        int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
49
        int layer= c->codec_id == CODEC_ID_MP3 ? 3 : 2;
50
        unsigned int header= 0xFFF00000;
51
52
        lsf     = sample_rate < (24000+32000)/2;
53
        mpeg25  = sample_rate < (12000+16000)/2;
54
        sample_rate <<= lsf + mpeg25;
55
        if     (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
56
        else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
57
        else                                     sample_rate_index=1;
58
59
        sample_rate= ff_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
60
61
        for(bitrate_index=2; bitrate_index<30; bitrate_index++){
62
            frame_size = ff_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
63
            frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
64
65
            if(frame_size == size)
66
                break;
67
        }
68
69
        header |= (!lsf)<<19;
70
        header |= (4-layer)<<17;
71
        header |= 1<<16; //no crc
72
        AV_WB32(out, header);
73
        if(size <= 0)
74 7ce68923 Diego Biurrun
            return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
75 a712d725 Michael Niedermayer
        if(bitrate_index == 30)
76
            return -1; //something is wrong ...
77
78
        header |= (bitrate_index>>1)<<12;
79
        header |= sample_rate_index<<10;
80
        header |= (bitrate_index&1)<<9;
81
82
        return 2; //FIXME actually put the needed ones in build_elision_headers()
83 7ce68923 Diego Biurrun
        return 3; //we guess that the private bit is not set
84
//FIXME the above assumptions should be checked, if these turn out false too often something should be done
85 a712d725 Michael Niedermayer
    }
86
    return 0;
87
}
88
89
static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
90
    NUTContext *nut = s->priv_data;
91
    uint8_t out[64];
92
    int i;
93
    int len= find_expected_header(c, size, frame_type, out);
94
95
//av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
96
97
    for(i=1; i<nut->header_count; i++){
98
        if(   len == nut->header_len[i]
99
           && !memcmp(out, nut->header[i], len)){
100
//    av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
101
            return i;
102
        }
103
    }
104
//    av_log(NULL, AV_LOG_ERROR, "nothing found\n");
105
    return 0;
106
}
107
108
static void build_elision_headers(AVFormatContext *s){
109
    NUTContext *nut = s->priv_data;
110
    int i;
111
    //FIXME this is lame
112
    //FIXME write a 2pass mode to find the maximal headers
113 1bf6e565 Diego Biurrun
    static const uint8_t headers[][5]={
114 a712d725 Michael Niedermayer
        {3, 0x00, 0x00, 0x01},
115
        {4, 0x00, 0x00, 0x01, 0xB6},
116
        {2, 0xFF, 0xFA}, //mp3+crc
117
        {2, 0xFF, 0xFB}, //mp3
118
        {2, 0xFF, 0xFC}, //mp2+crc
119
        {2, 0xFF, 0xFD}, //mp2
120
    };
121
122
    nut->header_count= 7;
123
    for(i=1; i<nut->header_count; i++){
124
        nut->header_len[i]=  headers[i-1][0];
125
        nut->header    [i]= &headers[i-1][1];
126
    }
127
}
128 70ea1e69 Michael Niedermayer
129
static void build_frame_code(AVFormatContext *s){
130
    NUTContext *nut = s->priv_data;
131
    int key_frame, index, pred, stream_id;
132
    int start=1;
133
    int end= 254;
134
    int keyframe_0_esc= s->nb_streams > 2;
135
    int pred_table[10];
136 0fcfa8eb Michael Niedermayer
    FrameCode *ft;
137
138
    ft= &nut->frame_code[start];
139
    ft->flags= FLAG_CODED;
140
    ft->size_mul=1;
141
    ft->pts_delta=1;
142
    start++;
143 70ea1e69 Michael Niedermayer
144
    if(keyframe_0_esc){
145
        /* keyframe = 0 escape */
146
        FrameCode *ft= &nut->frame_code[start];
147
        ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
148
        ft->size_mul=1;
149
        start++;
150
    }
151
152
    for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
153
        int start2= start + (end-start)*stream_id / s->nb_streams;
154
        int end2  = start + (end-start)*(stream_id+1) / s->nb_streams;
155
        AVCodecContext *codec = s->streams[stream_id]->codec;
156 72415b2a Stefano Sabatini
        int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
157 70ea1e69 Michael Niedermayer
        int intra_only= /*codec->intra_only || */is_audio;
158
        int pred_count;
159
160
        for(key_frame=0; key_frame<2; key_frame++){
161
            if(intra_only && keyframe_0_esc && key_frame==0)
162
                continue;
163
164
            {
165
                FrameCode *ft= &nut->frame_code[start2];
166
                ft->flags= FLAG_KEY*key_frame;
167
                ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
168
                ft->stream_id= stream_id;
169
                ft->size_mul=1;
170 a712d725 Michael Niedermayer
                if(is_audio)
171
                    ft->header_idx= find_header_idx(s, codec, -1, key_frame);
172 70ea1e69 Michael Niedermayer
                start2++;
173
            }
174
        }
175
176
        key_frame= intra_only;
177
#if 1
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 a712d725 Michael Niedermayer
                    ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
190 70ea1e69 Michael Niedermayer
                    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
#endif
202
203
        if(codec->has_b_frames){
204
            pred_count=5;
205
            pred_table[0]=-2;
206
            pred_table[1]=-1;
207
            pred_table[2]=1;
208
            pred_table[3]=3;
209
            pred_table[4]=4;
210
        }else if(codec->codec_id == CODEC_ID_VORBIS){
211
            pred_count=3;
212
            pred_table[0]=2;
213
            pred_table[1]=9;
214
            pred_table[2]=16;
215
        }else{
216
            pred_count=1;
217
            pred_table[0]=1;
218
        }
219
220
        for(pred=0; pred<pred_count; pred++){
221
            int start3= start2 + (end2-start2)*pred / pred_count;
222
            int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
223
224
            for(index=start3; index<end3; index++){
225
                FrameCode *ft= &nut->frame_code[index];
226
                ft->flags= FLAG_KEY*key_frame;
227
                ft->flags|= FLAG_SIZE_MSB;
228
                ft->stream_id= stream_id;
229
//FIXME use single byte size and pred from last
230
                ft->size_mul= end3-start3;
231
                ft->size_lsb= index - start3;
232
                ft->pts_delta= pred_table[pred];
233 a712d725 Michael Niedermayer
                if(is_audio)
234
                    ft->header_idx= find_header_idx(s, codec, -1, key_frame);
235 70ea1e69 Michael Niedermayer
            }
236
        }
237
    }
238
    memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
239
    nut->frame_code[  0].flags=
240
    nut->frame_code[255].flags=
241
    nut->frame_code['N'].flags= FLAG_INVALID;
242
}
243
244 073f8b10 Anton Khirnov
static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
245 491216c6 Michael Niedermayer
    val *= nut->time_base_count;
246 073f8b10 Anton Khirnov
    val += time_base - nut->time_base;
247 f8280ff4 Michael Chinen
    ff_put_v(bc, val);
248 491216c6 Michael Niedermayer
}
249
250 70ea1e69 Michael Niedermayer
/**
251 49bd8e4b Måns Rullgård
 * Store a string as vb.
252 70ea1e69 Michael Niedermayer
 */
253 ae628ec1 Anton Khirnov
static void put_str(AVIOContext *bc, const char *string){
254 70ea1e69 Michael Niedermayer
    int len= strlen(string);
255
256 f8280ff4 Michael Chinen
    ff_put_v(bc, len);
257 77eb5504 Anton Khirnov
    avio_write(bc, string, len);
258 70ea1e69 Michael Niedermayer
}
259
260 ae628ec1 Anton Khirnov
static void put_s(AVIOContext *bc, int64_t val){
261 f8280ff4 Michael Chinen
    ff_put_v(bc, 2*FFABS(val) - (val>0));
262 70ea1e69 Michael Niedermayer
}
263
264
#ifdef TRACE
265 ae628ec1 Anton Khirnov
static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, char *file, char *func, int line){
266 f8280ff4 Michael Chinen
    av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
267 70ea1e69 Michael Niedermayer
268 f8280ff4 Michael Chinen
    ff_put_v(bc, v);
269 70ea1e69 Michael Niedermayer
}
270
271 ae628ec1 Anton Khirnov
static inline void put_s_trace(AVIOContext *bc, int64_t v, char *file, char *func, int line){
272 7a26da44 Michael Niedermayer
    av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
273 70ea1e69 Michael Niedermayer
274
    put_s(bc, v);
275
}
276 f8280ff4 Michael Chinen
#define ff_put_v(bc, v)  ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
277 70ea1e69 Michael Niedermayer
#define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
278
#endif
279
280 34f8cc38 Michael Niedermayer
//FIXME remove calculate_checksum
281 ae628ec1 Anton Khirnov
static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
282 8d9a3f7e Michael Niedermayer
    uint8_t *dyn_buf=NULL;
283
    int dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
284 6c666941 Michael Niedermayer
    int forw_ptr= dyn_size + 4*calculate_checksum;
285
286
    if(forw_ptr > 4096)
287 992e78f5 Baptiste Coudurier
        init_checksum(bc, ff_crc04C11DB7_update, 0);
288 77eb5504 Anton Khirnov
    avio_wb64(bc, startcode);
289 f8280ff4 Michael Chinen
    ff_put_v(bc, forw_ptr);
290 6c666941 Michael Niedermayer
    if(forw_ptr > 4096)
291 77eb5504 Anton Khirnov
        avio_wl32(bc, get_checksum(bc));
292 70ea1e69 Michael Niedermayer
293
    if(calculate_checksum)
294 992e78f5 Baptiste Coudurier
        init_checksum(bc, ff_crc04C11DB7_update, 0);
295 77eb5504 Anton Khirnov
    avio_write(bc, dyn_buf, dyn_size);
296 70ea1e69 Michael Niedermayer
    if(calculate_checksum)
297 77eb5504 Anton Khirnov
        avio_wl32(bc, get_checksum(bc));
298 70ea1e69 Michael Niedermayer
299 8d9a3f7e Michael Niedermayer
    av_free(dyn_buf);
300 70ea1e69 Michael Niedermayer
}
301
302 ae628ec1 Anton Khirnov
static void write_mainheader(NUTContext *nut, AVIOContext *bc){
303 a712d725 Michael Niedermayer
    int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
304
    int64_t tmp_match;
305 70ea1e69 Michael Niedermayer
306 f8280ff4 Michael Chinen
    ff_put_v(bc, 3); /* version */
307
    ff_put_v(bc, nut->avf->nb_streams);
308
    ff_put_v(bc, nut->max_distance);
309
    ff_put_v(bc, nut->time_base_count);
310 70ea1e69 Michael Niedermayer
311
    for(i=0; i<nut->time_base_count; i++){
312 f8280ff4 Michael Chinen
        ff_put_v(bc, nut->time_base[i].num);
313
        ff_put_v(bc, nut->time_base[i].den);
314 70ea1e69 Michael Niedermayer
    }
315
316
    tmp_pts=0;
317
    tmp_mul=1;
318
    tmp_stream=0;
319 a712d725 Michael Niedermayer
    tmp_match= 1-(1LL<<62);
320
    tmp_head_idx= 0;
321 70ea1e69 Michael Niedermayer
    for(i=0; i<256;){
322
        tmp_fields=0;
323
        tmp_size=0;
324
//        tmp_res=0;
325
        if(tmp_pts    != nut->frame_code[i].pts_delta) tmp_fields=1;
326
        if(tmp_mul    != nut->frame_code[i].size_mul ) tmp_fields=2;
327
        if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
328
        if(tmp_size   != nut->frame_code[i].size_lsb ) tmp_fields=4;
329
//        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
330 a712d725 Michael Niedermayer
        if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
331 70ea1e69 Michael Niedermayer
332
        tmp_pts   = nut->frame_code[i].pts_delta;
333
        tmp_flags = nut->frame_code[i].flags;
334
        tmp_stream= nut->frame_code[i].stream_id;
335
        tmp_mul   = nut->frame_code[i].size_mul;
336
        tmp_size  = nut->frame_code[i].size_lsb;
337
//        tmp_res   = nut->frame_code[i].res;
338 a712d725 Michael Niedermayer
        tmp_head_idx= nut->frame_code[i].header_idx;
339 70ea1e69 Michael Niedermayer
340
        for(j=0; i<256; j++,i++){
341
            if(i == 'N'){
342
                j--;
343
                continue;
344
            }
345
            if(nut->frame_code[i].pts_delta != tmp_pts   ) break;
346
            if(nut->frame_code[i].flags     != tmp_flags ) break;
347
            if(nut->frame_code[i].stream_id != tmp_stream) break;
348
            if(nut->frame_code[i].size_mul  != tmp_mul   ) break;
349
            if(nut->frame_code[i].size_lsb  != tmp_size+j) break;
350
//            if(nut->frame_code[i].res       != tmp_res   ) break;
351 a712d725 Michael Niedermayer
            if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
352 70ea1e69 Michael Niedermayer
        }
353
        if(j != tmp_mul - tmp_size) tmp_fields=6;
354
355 f8280ff4 Michael Chinen
        ff_put_v(bc, tmp_flags);
356
        ff_put_v(bc, tmp_fields);
357 70ea1e69 Michael Niedermayer
        if(tmp_fields>0) put_s(bc, tmp_pts);
358 f8280ff4 Michael Chinen
        if(tmp_fields>1) ff_put_v(bc, tmp_mul);
359
        if(tmp_fields>2) ff_put_v(bc, tmp_stream);
360
        if(tmp_fields>3) ff_put_v(bc, tmp_size);
361
        if(tmp_fields>4) ff_put_v(bc, 0 /*tmp_res*/);
362
        if(tmp_fields>5) ff_put_v(bc, j);
363
        if(tmp_fields>6) ff_put_v(bc, tmp_match);
364
        if(tmp_fields>7) ff_put_v(bc, tmp_head_idx);
365 a712d725 Michael Niedermayer
    }
366 f8280ff4 Michael Chinen
    ff_put_v(bc, nut->header_count-1);
367 a712d725 Michael Niedermayer
    for(i=1; i<nut->header_count; i++){
368 f8280ff4 Michael Chinen
        ff_put_v(bc, nut->header_len[i]);
369 77eb5504 Anton Khirnov
        avio_write(bc, nut->header[i], nut->header_len[i]);
370 70ea1e69 Michael Niedermayer
    }
371 97d5eb11 Michael Niedermayer
}
372 70ea1e69 Michael Niedermayer
373 ae628ec1 Anton Khirnov
static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
374 da9e6c42 Stefano Sabatini
    NUTContext *nut = avctx->priv_data;
375 59729451 Aurelien Jacobs
    AVCodecContext *codec = st->codec;
376 f8280ff4 Michael Chinen
    ff_put_v(bc, i);
377 0809b51e Michael Niedermayer
    switch(codec->codec_type){
378 f8280ff4 Michael Chinen
    case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
379
    case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
380
    case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
381
    default              : ff_put_v(bc, 3); break;
382 0809b51e Michael Niedermayer
    }
383 f8280ff4 Michael Chinen
    ff_put_v(bc, 4);
384 0809b51e Michael Niedermayer
    if (codec->codec_tag){
385 77eb5504 Anton Khirnov
        avio_wl32(bc, codec->codec_tag);
386 fa586439 Stefano Sabatini
    } else {
387
        av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
388 ffd5f098 Stefano Sabatini
        return AVERROR(EINVAL);
389 fa586439 Stefano Sabatini
    }
390 0809b51e Michael Niedermayer
391 f8280ff4 Michael Chinen
    ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
392
    ff_put_v(bc, nut->stream[i].msb_pts_shift);
393
    ff_put_v(bc, nut->stream[i].max_pts_distance);
394
    ff_put_v(bc, codec->has_b_frames);
395 77eb5504 Anton Khirnov
    avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
396 0809b51e Michael Niedermayer
397 f8280ff4 Michael Chinen
    ff_put_v(bc, codec->extradata_size);
398 77eb5504 Anton Khirnov
    avio_write(bc, codec->extradata, codec->extradata_size);
399 0809b51e Michael Niedermayer
400
    switch(codec->codec_type){
401 72415b2a Stefano Sabatini
    case AVMEDIA_TYPE_AUDIO:
402 f8280ff4 Michael Chinen
        ff_put_v(bc, codec->sample_rate);
403
        ff_put_v(bc, 1);
404
        ff_put_v(bc, codec->channels);
405 0809b51e Michael Niedermayer
        break;
406 72415b2a Stefano Sabatini
    case AVMEDIA_TYPE_VIDEO:
407 f8280ff4 Michael Chinen
        ff_put_v(bc, codec->width);
408
        ff_put_v(bc, codec->height);
409 0a5790d1 Michael Niedermayer
410 59729451 Aurelien Jacobs
        if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
411 f8280ff4 Michael Chinen
            ff_put_v(bc, 0);
412
            ff_put_v(bc, 0);
413 0a5790d1 Michael Niedermayer
        }else{
414 f8280ff4 Michael Chinen
            ff_put_v(bc, st->sample_aspect_ratio.num);
415
            ff_put_v(bc, st->sample_aspect_ratio.den);
416 0a5790d1 Michael Niedermayer
        }
417 f8280ff4 Michael Chinen
        ff_put_v(bc, 0); /* csp type -- unknown */
418 0809b51e Michael Niedermayer
        break;
419
    default:
420
        break;
421
    }
422
    return 0;
423
}
424
425 ae628ec1 Anton Khirnov
static int add_info(AVIOContext *bc, const char *type, const char *value){
426 ead1939f Michael Niedermayer
    put_str(bc, type);
427
    put_s(bc, -1);
428
    put_str(bc, value);
429
    return 1;
430
}
431
432 ae628ec1 Anton Khirnov
static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
433 ead1939f Michael Niedermayer
    AVFormatContext *s= nut->avf;
434 43382b5f Anton Khirnov
    AVMetadataTag *t = NULL;
435 ae628ec1 Anton Khirnov
    AVIOContext *dyn_bc;
436 ead1939f Michael Niedermayer
    uint8_t *dyn_buf=NULL;
437
    int count=0, dyn_size;
438 899681cd Björn Axelsson
    int ret = url_open_dyn_buf(&dyn_bc);
439
    if(ret < 0)
440
        return ret;
441 ead1939f Michael Niedermayer
442 43382b5f Anton Khirnov
    while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
443
        count += add_info(dyn_bc, t->key, t->value);
444 ead1939f Michael Niedermayer
445 f8280ff4 Michael Chinen
    ff_put_v(bc, 0); //stream_if_plus1
446
    ff_put_v(bc, 0); //chapter_id
447
    ff_put_v(bc, 0); //timestamp_start
448
    ff_put_v(bc, 0); //length
449 ead1939f Michael Niedermayer
450 f8280ff4 Michael Chinen
    ff_put_v(bc, count);
451 ead1939f Michael Niedermayer
452 899681cd Björn Axelsson
    dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
453 77eb5504 Anton Khirnov
    avio_write(bc, dyn_buf, dyn_size);
454 ead1939f Michael Niedermayer
    av_free(dyn_buf);
455 899681cd Björn Axelsson
    return 0;
456 ead1939f Michael Niedermayer
}
457
458 ae628ec1 Anton Khirnov
static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
459 90c2295b Evgeniy Stepanov
    AVFormatContext *s= nut->avf;
460
    AVStream* st = s->streams[stream_id];
461 ae628ec1 Anton Khirnov
    AVIOContext *dyn_bc;
462 90c2295b Evgeniy Stepanov
    uint8_t *dyn_buf=NULL;
463
    int count=0, dyn_size, i;
464
    int ret = url_open_dyn_buf(&dyn_bc);
465
    if(ret < 0)
466
        return ret;
467
468
    for (i=0; ff_nut_dispositions[i].flag; ++i) {
469
        if (st->disposition & ff_nut_dispositions[i].flag)
470
            count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
471
    }
472
    dyn_size = url_close_dyn_buf(dyn_bc, &dyn_buf);
473
474
    if (count) {
475 f8280ff4 Michael Chinen
        ff_put_v(bc, stream_id + 1); //stream_id_plus1
476
        ff_put_v(bc, 0); //chapter_id
477
        ff_put_v(bc, 0); //timestamp_start
478
        ff_put_v(bc, 0); //length
479 90c2295b Evgeniy Stepanov
480 f8280ff4 Michael Chinen
        ff_put_v(bc, count);
481 90c2295b Evgeniy Stepanov
482 77eb5504 Anton Khirnov
        avio_write(bc, dyn_buf, dyn_size);
483 90c2295b Evgeniy Stepanov
    }
484
485
    av_free(dyn_buf);
486
    return count;
487
}
488
489 073f8b10 Anton Khirnov
static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
490
{
491
    AVIOContext *dyn_bc;
492
    uint8_t *dyn_buf = NULL;
493
    AVMetadataTag *t = NULL;
494
    AVChapter *ch    = nut->avf->chapters[id];
495
    int ret, dyn_size, count = 0;
496
497
    ret = url_open_dyn_buf(&dyn_bc);
498
    if (ret < 0)
499
        return ret;
500
501
    ff_put_v(bc, 0);                                        // stream_id_plus1
502
    put_s(bc, id + 1);                                      // chapter_id
503
    put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
504
    ff_put_v(bc, ch->end - ch->start);                      // chapter_len
505
506
    while ((t = av_metadata_get(ch->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
507
        count += add_info(dyn_bc, t->key, t->value);
508
509
    ff_put_v(bc, count);
510
511
    dyn_size = url_close_dyn_buf(dyn_bc, &dyn_buf);
512
    avio_write(bc, dyn_buf, dyn_size);
513
    av_freep(&dyn_buf);
514
    return 0;
515
}
516
517 ae628ec1 Anton Khirnov
static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
518 da9e6c42 Stefano Sabatini
    NUTContext *nut = avctx->priv_data;
519 ae628ec1 Anton Khirnov
    AVIOContext *dyn_bc;
520 899681cd Björn Axelsson
    int i, ret;
521 7e506494 Michael Niedermayer
522 03700d39 Anton Khirnov
    ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
523
524 899681cd Björn Axelsson
    ret = url_open_dyn_buf(&dyn_bc);
525
    if(ret < 0)
526
        return ret;
527
    write_mainheader(nut, dyn_bc);
528
    put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
529 7e506494 Michael Niedermayer
530
    for (i=0; i < nut->avf->nb_streams; i++){
531 899681cd Björn Axelsson
        ret = url_open_dyn_buf(&dyn_bc);
532
        if(ret < 0)
533
            return ret;
534 fc0c4124 Stefano Sabatini
        if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
535
            return ret;
536 899681cd Björn Axelsson
        put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
537 7e506494 Michael Niedermayer
    }
538 ead1939f Michael Niedermayer
539 899681cd Björn Axelsson
    ret = url_open_dyn_buf(&dyn_bc);
540
    if(ret < 0)
541
        return ret;
542
    write_globalinfo(nut, dyn_bc);
543
    put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
544 14b3f996 Michael Niedermayer
545 90c2295b Evgeniy Stepanov
    for (i = 0; i < nut->avf->nb_streams; i++) {
546
        ret = url_open_dyn_buf(&dyn_bc);
547
        if(ret < 0)
548
            return ret;
549
        ret = write_streaminfo(nut, dyn_bc, i);
550
        if (ret < 0)
551
            return ret;
552
        if (ret > 0)
553
            put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
554
        else {
555
            uint8_t* buf;
556
            url_close_dyn_buf(dyn_bc, &buf);
557
            av_free(buf);
558
        }
559
    }
560
561 073f8b10 Anton Khirnov
    for (i = 0; i < nut->avf->nb_chapters; i++) {
562
        ret = url_open_dyn_buf(&dyn_bc);
563
        if (ret < 0)
564
            return ret;
565
        ret = write_chapter(nut, dyn_bc, i);
566
        if (ret < 0) {
567
            uint8_t *buf;
568
            url_close_dyn_buf(dyn_bc, &buf);
569
            av_freep(&buf);
570
            return ret;
571
        }
572
        put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
573
    }
574
575 14b3f996 Michael Niedermayer
    nut->last_syncpoint_pos= INT_MIN;
576
    nut->header_count++;
577 899681cd Björn Axelsson
    return 0;
578 7e506494 Michael Niedermayer
}
579
580 97d5eb11 Michael Niedermayer
static int write_header(AVFormatContext *s){
581
    NUTContext *nut = s->priv_data;
582 ae628ec1 Anton Khirnov
    AVIOContext *bc = s->pb;
583 fc0c4124 Stefano Sabatini
    int i, j, ret;
584 97d5eb11 Michael Niedermayer
585
    nut->avf= s;
586
587
    nut->stream   = av_mallocz(sizeof(StreamContext)*s->nb_streams);
588 073f8b10 Anton Khirnov
    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 97d5eb11 Michael Niedermayer
592
    for(i=0; i<s->nb_streams; i++){
593
        AVStream *st= s->streams[i];
594
        int ssize;
595
        AVRational time_base;
596
        ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
597
598
        av_set_pts_info(st, 64, time_base.num, time_base.den);
599
600
        for(j=0; j<nut->time_base_count; j++){
601
            if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
602
                break;
603
            }
604
        }
605
        nut->time_base[j]= time_base;
606
        nut->stream[i].time_base= &nut->time_base[j];
607
        if(j==nut->time_base_count)
608
            nut->time_base_count++;
609
610 324d22b2 Måns Rullgård
        if(INT64_C(1000) * time_base.num >= time_base.den)
611 97d5eb11 Michael Niedermayer
            nut->stream[i].msb_pts_shift = 7;
612
        else
613
            nut->stream[i].msb_pts_shift = 14;
614 324d22b2 Måns Rullgård
        nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
615 97d5eb11 Michael Niedermayer
    }
616
617 073f8b10 Anton Khirnov
    for (i = 0; i < s->nb_chapters; i++) {
618
        AVChapter *ch = s->chapters[i];
619
620
        for (j = 0; j < nut->time_base_count; j++) {
621
            if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
622
                break;
623
        }
624
625
        nut->time_base[j] = ch->time_base;
626
        nut->chapter[i].time_base = &nut->time_base[j];
627
        if(j == nut->time_base_count)
628
            nut->time_base_count++;
629
    }
630
631 82badd27 Oded Shimon
    nut->max_distance = MAX_DISTANCE;
632 a712d725 Michael Niedermayer
    build_elision_headers(s);
633 97d5eb11 Michael Niedermayer
    build_frame_code(s);
634
    assert(nut->frame_code['N'].flags == FLAG_INVALID);
635
636 77eb5504 Anton Khirnov
    avio_write(bc, ID_STRING, strlen(ID_STRING));
637
    avio_w8(bc, 0);
638 97d5eb11 Michael Niedermayer
639 fc0c4124 Stefano Sabatini
    if ((ret = write_headers(s, bc)) < 0)
640
        return ret;
641 dcc9bde0 Michael Niedermayer
642 b7f2fdde Anton Khirnov
    avio_flush(bc);
643 70ea1e69 Michael Niedermayer
644 14b3f996 Michael Niedermayer
    //FIXME index
645 70ea1e69 Michael Niedermayer
646
    return 0;
647
}
648
649 e1249ba9 Michael Niedermayer
static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
650
    int flags= 0;
651
652 cc947f04 Jean-Daniel Dupas
    if(pkt->flags & AV_PKT_FLAG_KEY             ) flags |= FLAG_KEY;
653 e1249ba9 Michael Niedermayer
    if(pkt->stream_index != fc->stream_id       ) flags |= FLAG_STREAM_ID;
654
    if(pkt->size / fc->size_mul                 ) flags |= FLAG_SIZE_MSB;
655
    if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
656
    if(pkt->size > 2*nut->max_distance          ) flags |= FLAG_CHECKSUM;
657
    if(FFABS(pkt->pts - nus->last_pts)
658
                         > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
659 a712d725 Michael Niedermayer
    if(   pkt->size < nut->header_len[fc->header_idx]
660
       || (pkt->size > 4096 && fc->header_idx)
661
       || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
662
                                                  flags |= FLAG_HEADER_IDX;
663 e1249ba9 Michael Niedermayer
664 d2062ff6 Michael Niedermayer
    return flags | (fc->flags & FLAG_CODED);
665 e1249ba9 Michael Niedermayer
}
666
667 a712d725 Michael Niedermayer
static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
668
    int i;
669
    int best_i  = 0;
670
    int best_len= 0;
671
672
    if(pkt->size > 4096)
673
        return 0;
674
675
    for(i=1; i<nut->header_count; i++){
676
        if(   pkt->size >= nut->header_len[i]
677
           &&  nut->header_len[i] > best_len
678
           && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
679
            best_i= i;
680
            best_len= nut->header_len[i];
681
        }
682
    }
683
    return best_i;
684
}
685
686 70ea1e69 Michael Niedermayer
static int write_packet(AVFormatContext *s, AVPacket *pkt){
687 e1249ba9 Michael Niedermayer
    NUTContext *nut = s->priv_data;
688
    StreamContext *nus= &nut->stream[pkt->stream_index];
689 ae628ec1 Anton Khirnov
    AVIOContext *bc = s->pb, *dyn_bc;
690 e1249ba9 Michael Niedermayer
    FrameCode *fc;
691
    int64_t coded_pts;
692 a712d725 Michael Niedermayer
    int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
693 cc947f04 Jean-Daniel Dupas
    int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
694 e1249ba9 Michael Niedermayer
    int store_sp=0;
695 899681cd Björn Axelsson
    int ret;
696 e1249ba9 Michael Niedermayer
697 f53dd468 Michael Niedermayer
    if(pkt->pts < 0)
698
        return -1;
699
700 a2704c97 Anton Khirnov
    if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
701 da9e6c42 Stefano Sabatini
        write_headers(s, bc);
702 14b3f996 Michael Niedermayer
703 02c986a8 Oded Shimon
    if(key_frame && !(nus->last_flags & FLAG_KEY))
704 e1249ba9 Michael Niedermayer
        store_sp= 1;
705
706 a2704c97 Anton Khirnov
    if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
707 e1249ba9 Michael Niedermayer
        store_sp= 1;
708
709 93951943 Diego Biurrun
//FIXME: Ensure store_sp is 1 in the first place.
710 e1249ba9 Michael Niedermayer
711
    if(store_sp){
712 52afa376 Michael Niedermayer
        Syncpoint *sp, dummy= {.pos= INT64_MAX};
713 7c04134f Michael Niedermayer
714 e1249ba9 Michael Niedermayer
        ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
715 7c04134f Michael Niedermayer
        for(i=0; i<s->nb_streams; i++){
716
            AVStream *st= s->streams[i];
717 4ddcc983 Oded Shimon
            int64_t dts_tb = av_rescale_rnd(pkt->dts,
718
                nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
719
                nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
720
                AV_ROUND_DOWN);
721
            int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
722 175e23e8 Michael Niedermayer
            if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
723 7c04134f Michael Niedermayer
        }
724 175e23e8 Michael Niedermayer
        if(dummy.pos == INT64_MAX)
725
            dummy.pos= 0;
726 f990f6e3 Vitor Sessak
        sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
727
                         NULL);
728 e1249ba9 Michael Niedermayer
729 a2704c97 Anton Khirnov
        nut->last_syncpoint_pos= avio_tell(bc);
730 899681cd Björn Axelsson
        ret = url_open_dyn_buf(&dyn_bc);
731
        if(ret < 0)
732
            return ret;
733 073f8b10 Anton Khirnov
        put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
734 f8280ff4 Michael Chinen
        ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
735 899681cd Björn Axelsson
        put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
736 7c04134f Michael Niedermayer
737
        ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
738 e1249ba9 Michael Niedermayer
    }
739
    assert(nus->last_pts != AV_NOPTS_VALUE);
740
741
    coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
742
    if(ff_lsb2full(nus, coded_pts) != pkt->pts)
743
        coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
744
745 a712d725 Michael Niedermayer
    best_header_idx= find_best_header_idx(nut, pkt);
746
747 e1249ba9 Michael Niedermayer
    best_length=INT_MAX;
748
    frame_code= -1;
749
    for(i=0; i<256; i++){
750
        int length= 0;
751
        FrameCode *fc= &nut->frame_code[i];
752
        int flags= fc->flags;
753
754
        if(flags & FLAG_INVALID)
755
            continue;
756
        needed_flags= get_needed_flags(nut, nus, fc, pkt);
757
758
        if(flags & FLAG_CODED){
759
            length++;
760 63dd9d0e Michael Niedermayer
            flags = needed_flags;
761 e1249ba9 Michael Niedermayer
        }
762
763
        if((flags & needed_flags) != needed_flags)
764
            continue;
765
766
        if((flags ^ needed_flags) & FLAG_KEY)
767
            continue;
768
769
        if(flags & FLAG_STREAM_ID)
770 f8280ff4 Michael Chinen
            length+= ff_get_v_length(pkt->stream_index);
771 e1249ba9 Michael Niedermayer
772
        if(pkt->size % fc->size_mul != fc->size_lsb)
773
            continue;
774
        if(flags & FLAG_SIZE_MSB)
775 f8280ff4 Michael Chinen
            length += ff_get_v_length(pkt->size / fc->size_mul);
776 e1249ba9 Michael Niedermayer
777
        if(flags & FLAG_CHECKSUM)
778
            length+=4;
779
780
        if(flags & FLAG_CODED_PTS)
781 f8280ff4 Michael Chinen
            length += ff_get_v_length(coded_pts);
782 e1249ba9 Michael Niedermayer
783 a712d725 Michael Niedermayer
        if(   (flags & FLAG_CODED)
784
           && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
785
            flags |= FLAG_HEADER_IDX;
786
        }
787
788
        if(flags & FLAG_HEADER_IDX){
789
            length += 1 - nut->header_len[best_header_idx];
790
        }else{
791
            length -= nut->header_len[fc->header_idx];
792
        }
793
794 e1249ba9 Michael Niedermayer
        length*=4;
795
        length+= !(flags & FLAG_CODED_PTS);
796
        length+= !(flags & FLAG_CHECKSUM);
797
798
        if(length < best_length){
799
            best_length= length;
800
            frame_code=i;
801
        }
802
    }
803
    assert(frame_code != -1);
804
    fc= &nut->frame_code[frame_code];
805
    flags= fc->flags;
806
    needed_flags= get_needed_flags(nut, nus, fc, pkt);
807 a712d725 Michael Niedermayer
    header_idx= fc->header_idx;
808 e1249ba9 Michael Niedermayer
809 992e78f5 Baptiste Coudurier
    init_checksum(bc, ff_crc04C11DB7_update, 0);
810 77eb5504 Anton Khirnov
    avio_w8(bc, frame_code);
811 e1249ba9 Michael Niedermayer
    if(flags & FLAG_CODED){
812 f8280ff4 Michael Chinen
        ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
813 e1249ba9 Michael Niedermayer
        flags = needed_flags;
814
    }
815 f8280ff4 Michael Chinen
    if(flags & FLAG_STREAM_ID)  ff_put_v(bc, pkt->stream_index);
816
    if(flags & FLAG_CODED_PTS)  ff_put_v(bc, coded_pts);
817
    if(flags & FLAG_SIZE_MSB)   ff_put_v(bc, pkt->size / fc->size_mul);
818
    if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
819 e1249ba9 Michael Niedermayer
820 77eb5504 Anton Khirnov
    if(flags & FLAG_CHECKSUM)   avio_wl32(bc, get_checksum(bc));
821 e1249ba9 Michael Niedermayer
    else                        get_checksum(bc);
822
823 77eb5504 Anton Khirnov
    avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
824 e1249ba9 Michael Niedermayer
    nus->last_flags= flags;
825 e942293d Michael Niedermayer
    nus->last_pts= pkt->pts;
826 7c04134f Michael Niedermayer
827
    //FIXME just store one per syncpoint
828
    if(flags & FLAG_KEY)
829
        av_add_index_entry(
830
            s->streams[pkt->stream_index],
831
            nut->last_syncpoint_pos,
832
            pkt->pts,
833
            0,
834
            0,
835
            AVINDEX_KEYFRAME);
836
837 70ea1e69 Michael Niedermayer
    return 0;
838
}
839
840 bd533e6c Michael Niedermayer
static int write_trailer(AVFormatContext *s){
841
    NUTContext *nut= s->priv_data;
842 ae628ec1 Anton Khirnov
    AVIOContext *bc= s->pb;
843 bd533e6c Michael Niedermayer
844 14b3f996 Michael Niedermayer
    while(nut->header_count<3)
845 da9e6c42 Stefano Sabatini
        write_headers(s, bc);
846 b7f2fdde Anton Khirnov
    avio_flush(bc);
847 4b83fc0f Vitor Sessak
    ff_nut_free_sp(nut);
848 27dbc47c Vitor Sessak
    av_freep(&nut->stream);
849 2cface71 Anton Khirnov
    av_freep(&nut->chapter);
850 27dbc47c Vitor Sessak
    av_freep(&nut->time_base);
851 bd533e6c Michael Niedermayer
852
    return 0;
853
}
854
855 c6610a21 Diego Elio Pettenò
AVOutputFormat ff_nut_muxer = {
856 70ea1e69 Michael Niedermayer
    "nut",
857 bde15e74 Stefano Sabatini
    NULL_IF_CONFIG_SMALL("NUT format"),
858 70ea1e69 Michael Niedermayer
    "video/x-nut",
859
    "nut",
860
    sizeof(NUTContext),
861 b250f9c6 Aurelien Jacobs
#if   CONFIG_LIBVORBIS
862 70ea1e69 Michael Niedermayer
    CODEC_ID_VORBIS,
863 b250f9c6 Aurelien Jacobs
#elif CONFIG_LIBMP3LAME
864 70ea1e69 Michael Niedermayer
    CODEC_ID_MP3,
865
#else
866 2d47c3de Justin Ruggles
    CODEC_ID_MP2,
867 70ea1e69 Michael Niedermayer
#endif
868
    CODEC_ID_MPEG4,
869
    write_header,
870
    write_packet,
871 bd533e6c Michael Niedermayer
    write_trailer,
872 25918212 Michael Niedermayer
    .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
873 2e01def0 Stefano Sabatini
    .codec_tag = (const AVCodecTag * const []){ ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
874 70ea1e69 Michael Niedermayer
};