forw_ptr CRC
[ffmpeg.git] / libavformat / nutenc.c
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 "nut.h"
23
24 #define TRACE
25
26 static void build_frame_code(AVFormatContext *s){
27     NUTContext *nut = s->priv_data;
28     int key_frame, index, pred, stream_id;
29     int start=1;
30     int end= 254;
31     int keyframe_0_esc= s->nb_streams > 2;
32     int pred_table[10];
33
34     if(keyframe_0_esc){
35         /* keyframe = 0 escape */
36         FrameCode *ft= &nut->frame_code[start];
37         ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
38         ft->size_mul=1;
39         start++;
40     }
41
42     for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
43         int start2= start + (end-start)*stream_id / s->nb_streams;
44         int end2  = start + (end-start)*(stream_id+1) / s->nb_streams;
45         AVCodecContext *codec = s->streams[stream_id]->codec;
46         int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
47         int intra_only= /*codec->intra_only || */is_audio;
48         int pred_count;
49
50         for(key_frame=0; key_frame<2; key_frame++){
51             if(intra_only && keyframe_0_esc && key_frame==0)
52                 continue;
53
54             {
55                 FrameCode *ft= &nut->frame_code[start2];
56                 ft->flags= FLAG_KEY*key_frame;
57                 ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
58                 ft->stream_id= stream_id;
59                 ft->size_mul=1;
60                 start2++;
61             }
62         }
63
64         key_frame= intra_only;
65 #if 1
66         if(is_audio){
67             int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
68             int pts;
69             for(pts=0; pts<2; pts++){
70                 for(pred=0; pred<2; pred++){
71                     FrameCode *ft= &nut->frame_code[start2];
72                     ft->flags= FLAG_KEY*key_frame;
73                     ft->stream_id= stream_id;
74                     ft->size_mul=frame_bytes + 2;
75                     ft->size_lsb=frame_bytes + pred;
76                     ft->pts_delta=pts;
77                     start2++;
78                 }
79             }
80         }else{
81             FrameCode *ft= &nut->frame_code[start2];
82             ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
83             ft->stream_id= stream_id;
84             ft->size_mul=1;
85             ft->pts_delta=1;
86             start2++;
87         }
88 #endif
89
90         if(codec->has_b_frames){
91             pred_count=5;
92             pred_table[0]=-2;
93             pred_table[1]=-1;
94             pred_table[2]=1;
95             pred_table[3]=3;
96             pred_table[4]=4;
97         }else if(codec->codec_id == CODEC_ID_VORBIS){
98             pred_count=3;
99             pred_table[0]=2;
100             pred_table[1]=9;
101             pred_table[2]=16;
102         }else{
103             pred_count=1;
104             pred_table[0]=1;
105         }
106
107         for(pred=0; pred<pred_count; pred++){
108             int start3= start2 + (end2-start2)*pred / pred_count;
109             int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
110
111             for(index=start3; index<end3; index++){
112                 FrameCode *ft= &nut->frame_code[index];
113                 ft->flags= FLAG_KEY*key_frame;
114                 ft->flags|= FLAG_SIZE_MSB;
115                 ft->stream_id= stream_id;
116 //FIXME use single byte size and pred from last
117                 ft->size_mul= end3-start3;
118                 ft->size_lsb= index - start3;
119                 ft->pts_delta= pred_table[pred];
120             }
121         }
122     }
123     memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
124     nut->frame_code[  0].flags=
125     nut->frame_code[255].flags=
126     nut->frame_code['N'].flags= FLAG_INVALID;
127 }
128
129 /**
130  * Gets the length in bytes which is needed to store val as v.
131  */
132 static int get_length(uint64_t val){
133     int i=1;
134
135     while(val>>=7)
136         i++;
137
138     return i;
139 }
140
141 static void put_v(ByteIOContext *bc, uint64_t val){
142     int i= get_length(val);
143
144     while(--i>0)
145         put_byte(bc, 128 | (val>>(7*i)));
146
147     put_byte(bc, val&127);
148 }
149
150 /**
151  * stores a string as vb.
152  */
153 static void put_str(ByteIOContext *bc, const char *string){
154     int len= strlen(string);
155
156     put_v(bc, len);
157     put_buffer(bc, string, len);
158 }
159
160 static void put_s(ByteIOContext *bc, int64_t val){
161     put_v(bc, 2*FFABS(val) - (val>0));
162 }
163
164 #ifdef TRACE
165 static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
166     printf("get_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
167
168     put_v(bc, v);
169 }
170
171 static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
172     printf("get_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
173
174     put_s(bc, v);
175 }
176 #define put_v(bc, v)  put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
177 #define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
178 #endif
179
180 static void put_packet(NUTContext *nut, ByteIOContext *bc, ByteIOContext *dyn_bc, int calculate_checksum){
181     uint8_t *dyn_buf=NULL;
182     int dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
183     int forw_ptr= dyn_size + 4*calculate_checksum;
184
185     if(forw_ptr > 4096)
186         init_checksum(bc, av_crc04C11DB7_update, 0);
187     put_v(bc, forw_ptr);
188     if(forw_ptr > 4096)
189         put_le32(bc, get_checksum(bc));
190
191     if(calculate_checksum)
192         init_checksum(bc, av_crc04C11DB7_update, 0);
193     put_buffer(bc, dyn_buf, dyn_size);
194     if(calculate_checksum)
195         put_le32(bc, get_checksum(bc));
196
197     av_free(dyn_buf);
198 }
199
200 static void write_mainheader(NUTContext *nut, ByteIOContext *bc){
201     int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields;
202
203     put_v(bc, 2); /* version */
204     put_v(bc, nut->avf->nb_streams);
205     put_v(bc, MAX_DISTANCE);
206     put_v(bc, nut->time_base_count);
207
208     for(i=0; i<nut->time_base_count; i++){
209         put_v(bc, nut->time_base[i].num);
210         put_v(bc, nut->time_base[i].den);
211     }
212
213     tmp_pts=0;
214     tmp_mul=1;
215     tmp_stream=0;
216     for(i=0; i<256;){
217         tmp_fields=0;
218         tmp_size=0;
219 //        tmp_res=0;
220         if(tmp_pts    != nut->frame_code[i].pts_delta) tmp_fields=1;
221         if(tmp_mul    != nut->frame_code[i].size_mul ) tmp_fields=2;
222         if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
223         if(tmp_size   != nut->frame_code[i].size_lsb ) tmp_fields=4;
224 //        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
225
226         tmp_pts   = nut->frame_code[i].pts_delta;
227         tmp_flags = nut->frame_code[i].flags;
228         tmp_stream= nut->frame_code[i].stream_id;
229         tmp_mul   = nut->frame_code[i].size_mul;
230         tmp_size  = nut->frame_code[i].size_lsb;
231 //        tmp_res   = nut->frame_code[i].res;
232
233         for(j=0; i<256; j++,i++){
234             if(i == 'N'){
235                 j--;
236                 continue;
237             }
238             if(nut->frame_code[i].pts_delta != tmp_pts   ) break;
239             if(nut->frame_code[i].flags     != tmp_flags ) break;
240             if(nut->frame_code[i].stream_id != tmp_stream) break;
241             if(nut->frame_code[i].size_mul  != tmp_mul   ) break;
242             if(nut->frame_code[i].size_lsb  != tmp_size+j) break;
243 //            if(nut->frame_code[i].res       != tmp_res   ) break;
244         }
245         if(j != tmp_mul - tmp_size) tmp_fields=6;
246
247         put_v(bc, tmp_flags);
248         put_v(bc, tmp_fields);
249         if(tmp_fields>0) put_s(bc, tmp_pts);
250         if(tmp_fields>1) put_v(bc, tmp_mul);
251         if(tmp_fields>2) put_v(bc, tmp_stream);
252         if(tmp_fields>3) put_v(bc, tmp_size);
253         if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
254         if(tmp_fields>5) put_v(bc, j);
255     }
256 }
257
258 static int write_streamheader(NUTContext *nut, ByteIOContext *bc, AVCodecContext *codec, int i){
259     put_v(bc, i);
260     switch(codec->codec_type){
261     case CODEC_TYPE_VIDEO: put_v(bc, 0); break;
262     case CODEC_TYPE_AUDIO: put_v(bc, 1); break;
263 //    case CODEC_TYPE_TEXT : put_v(bc, 2); break;
264     default              : put_v(bc, 3); break;
265     }
266     put_v(bc, 4);
267     if (codec->codec_tag){
268         put_le32(bc, codec->codec_tag);
269     }else
270         return -1;
271
272     put_v(bc, (nut->stream[i].time_base - nut->time_base)/sizeof(AVRational));
273     put_v(bc, nut->stream[i].msb_pts_shift);
274     put_v(bc, nut->stream[i].max_pts_distance);
275     put_v(bc, codec->has_b_frames);
276     put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
277
278     put_v(bc, codec->extradata_size);
279     put_buffer(bc, codec->extradata, codec->extradata_size);
280
281     switch(codec->codec_type){
282     case CODEC_TYPE_AUDIO:
283         put_v(bc, codec->sample_rate);
284         put_v(bc, 1);
285         put_v(bc, codec->channels);
286         break;
287     case CODEC_TYPE_VIDEO:
288         put_v(bc, codec->width);
289         put_v(bc, codec->height);
290         put_v(bc, codec->sample_aspect_ratio.num);
291         put_v(bc, codec->sample_aspect_ratio.den);
292         put_v(bc, 0); /* csp type -- unknown */
293         break;
294     default:
295         break;
296     }
297     return 0;
298 }
299
300 static int write_header(AVFormatContext *s){
301     NUTContext *nut = s->priv_data;
302     ByteIOContext *bc = &s->pb, dyn_bc;
303     AVCodecContext *codec;
304     int i, j;
305
306     nut->avf= s;
307
308     nut->stream   = av_mallocz(sizeof(StreamContext)*s->nb_streams);
309     nut->time_base= av_mallocz(sizeof(AVRational   )*s->nb_streams);
310
311     for(i=0; i<s->nb_streams; i++){
312         AVStream *st= s->streams[i];
313         int ssize;
314         AVRational time_base;
315         ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
316
317         av_set_pts_info(st, 64, time_base.num, time_base.den);
318
319         for(j=0; j<nut->time_base_count; j++){
320             if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
321                 break;
322             }
323         }
324         nut->time_base[j]= time_base;
325         nut->stream[i].time_base= &nut->time_base[j];
326         if(j==nut->time_base_count)
327             nut->time_base_count++;
328
329         if(av_q2d(time_base) >= 0.001)
330             nut->stream[i].msb_pts_shift = 7;
331         else
332             nut->stream[i].msb_pts_shift = 14;
333         nut->stream[i].max_pts_distance= FFMAX(1/av_q2d(time_base), 1);
334     }
335
336     build_frame_code(s);
337     assert(nut->frame_code['N'].flags == FLAG_INVALID);
338
339     put_buffer(bc, ID_STRING, strlen(ID_STRING));
340     put_byte(bc, 0);
341
342     /* main header */
343     put_be64(bc, MAIN_STARTCODE);
344     url_open_dyn_buf(&dyn_bc);
345     write_mainheader(nut, &dyn_bc);
346     put_packet(nut, bc, &dyn_bc, 1);
347
348     for (i=0; i < s->nb_streams; i++){
349         codec = s->streams[i]->codec;
350
351         put_be64(bc, STREAM_STARTCODE);
352         url_open_dyn_buf(&dyn_bc);
353         write_streamheader(nut, &dyn_bc, codec, i);
354         put_packet(nut, bc, &dyn_bc, 1);
355     }
356
357     put_flush_packet(bc);
358
359     //FIXME info header, header repeation, ...
360
361     return 0;
362 }
363
364 static int write_packet(AVFormatContext *s, AVPacket *pkt){
365     //FIXME
366     return 0;
367 }
368
369 AVOutputFormat nut_muxer = {
370     "nut",
371     "nut format",
372     "video/x-nut",
373     "nut",
374     sizeof(NUTContext),
375 #ifdef CONFIG_LIBVORBIS
376     CODEC_ID_VORBIS,
377 #elif defined(CONFIG_LIBMP3LAME)
378     CODEC_ID_MP3,
379 #else
380     CODEC_ID_MP2, /* AC3 needs liba52 decoder */
381 #endif
382     CODEC_ID_MPEG4,
383     write_header,
384     write_packet,
385 //    write_trailer,
386     .flags = AVFMT_GLOBALHEADER,
387     .codec_tag= (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
388 };