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