muxer should now be spec compliant (though it likely still contains bugs!)
[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 #include "tree.h"
24
25 #define TRACE
26
27 static void build_frame_code(AVFormatContext *s){
28     NUTContext *nut = s->priv_data;
29     int key_frame, index, pred, stream_id;
30     int start=1;
31     int end= 254;
32     int keyframe_0_esc= s->nb_streams > 2;
33     int pred_table[10];
34     FrameCode *ft;
35
36     ft= &nut->frame_code[start];
37     ft->flags= FLAG_CODED;
38     ft->size_mul=1;
39     ft->pts_delta=1;
40     start++;
41
42     if(keyframe_0_esc){
43         /* keyframe = 0 escape */
44         FrameCode *ft= &nut->frame_code[start];
45         ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
46         ft->size_mul=1;
47         start++;
48     }
49
50     for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
51         int start2= start + (end-start)*stream_id / s->nb_streams;
52         int end2  = start + (end-start)*(stream_id+1) / s->nb_streams;
53         AVCodecContext *codec = s->streams[stream_id]->codec;
54         int is_audio= codec->codec_type == CODEC_TYPE_AUDIO;
55         int intra_only= /*codec->intra_only || */is_audio;
56         int pred_count;
57
58         for(key_frame=0; key_frame<2; key_frame++){
59             if(intra_only && keyframe_0_esc && key_frame==0)
60                 continue;
61
62             {
63                 FrameCode *ft= &nut->frame_code[start2];
64                 ft->flags= FLAG_KEY*key_frame;
65                 ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
66                 ft->stream_id= stream_id;
67                 ft->size_mul=1;
68                 start2++;
69             }
70         }
71
72         key_frame= intra_only;
73 #if 1
74         if(is_audio){
75             int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
76             int pts;
77             for(pts=0; pts<2; pts++){
78                 for(pred=0; pred<2; pred++){
79                     FrameCode *ft= &nut->frame_code[start2];
80                     ft->flags= FLAG_KEY*key_frame;
81                     ft->stream_id= stream_id;
82                     ft->size_mul=frame_bytes + 2;
83                     ft->size_lsb=frame_bytes + pred;
84                     ft->pts_delta=pts;
85                     start2++;
86                 }
87             }
88         }else{
89             FrameCode *ft= &nut->frame_code[start2];
90             ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
91             ft->stream_id= stream_id;
92             ft->size_mul=1;
93             ft->pts_delta=1;
94             start2++;
95         }
96 #endif
97
98         if(codec->has_b_frames){
99             pred_count=5;
100             pred_table[0]=-2;
101             pred_table[1]=-1;
102             pred_table[2]=1;
103             pred_table[3]=3;
104             pred_table[4]=4;
105         }else if(codec->codec_id == CODEC_ID_VORBIS){
106             pred_count=3;
107             pred_table[0]=2;
108             pred_table[1]=9;
109             pred_table[2]=16;
110         }else{
111             pred_count=1;
112             pred_table[0]=1;
113         }
114
115         for(pred=0; pred<pred_count; pred++){
116             int start3= start2 + (end2-start2)*pred / pred_count;
117             int end3  = start2 + (end2-start2)*(pred+1) / pred_count;
118
119             for(index=start3; index<end3; index++){
120                 FrameCode *ft= &nut->frame_code[index];
121                 ft->flags= FLAG_KEY*key_frame;
122                 ft->flags|= FLAG_SIZE_MSB;
123                 ft->stream_id= stream_id;
124 //FIXME use single byte size and pred from last
125                 ft->size_mul= end3-start3;
126                 ft->size_lsb= index - start3;
127                 ft->pts_delta= pred_table[pred];
128             }
129         }
130     }
131     memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
132     nut->frame_code[  0].flags=
133     nut->frame_code[255].flags=
134     nut->frame_code['N'].flags= FLAG_INVALID;
135 }
136
137 /**
138  * Gets the length in bytes which is needed to store val as v.
139  */
140 static int get_length(uint64_t val){
141     int i=1;
142
143     while(val>>=7)
144         i++;
145
146     return i;
147 }
148
149 static void put_v(ByteIOContext *bc, uint64_t val){
150     int i= get_length(val);
151
152     while(--i>0)
153         put_byte(bc, 128 | (val>>(7*i)));
154
155     put_byte(bc, val&127);
156 }
157
158 static void put_t(NUTContext *nut, StreamContext *nus, ByteIOContext *bc, uint64_t val){
159     val *= nut->time_base_count;
160     val += nus->time_base - nut->time_base;
161     put_v(bc, val);
162 }
163
164 /**
165  * stores a string as vb.
166  */
167 static void put_str(ByteIOContext *bc, const char *string){
168     int len= strlen(string);
169
170     put_v(bc, len);
171     put_buffer(bc, string, len);
172 }
173
174 static void put_s(ByteIOContext *bc, int64_t val){
175     put_v(bc, 2*FFABS(val) - (val>0));
176 }
177
178 #ifdef TRACE
179 static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
180     av_log(NULL, AV_LOG_DEBUG, "put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
181
182     put_v(bc, v);
183 }
184
185 static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
186     av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
187
188     put_s(bc, v);
189 }
190 #define put_v(bc, v)  put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
191 #define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
192 #endif
193
194 //FIXME remove calculate_checksum
195 static void put_packet(NUTContext *nut, ByteIOContext *bc, ByteIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
196     uint8_t *dyn_buf=NULL;
197     int dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
198     int forw_ptr= dyn_size + 4*calculate_checksum;
199
200     if(forw_ptr > 4096)
201         init_checksum(bc, av_crc04C11DB7_update, 0);
202     put_be64(bc, startcode);
203     put_v(bc, forw_ptr);
204     if(forw_ptr > 4096)
205         put_le32(bc, get_checksum(bc));
206
207     if(calculate_checksum)
208         init_checksum(bc, av_crc04C11DB7_update, 0);
209     put_buffer(bc, dyn_buf, dyn_size);
210     if(calculate_checksum)
211         put_le32(bc, get_checksum(bc));
212
213     av_free(dyn_buf);
214 }
215
216 static void write_mainheader(NUTContext *nut, ByteIOContext *bc){
217     int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields;
218
219     put_v(bc, 3); /* version */
220     put_v(bc, nut->avf->nb_streams);
221     put_v(bc, MAX_DISTANCE);
222     put_v(bc, nut->time_base_count);
223
224     for(i=0; i<nut->time_base_count; i++){
225         put_v(bc, nut->time_base[i].num);
226         put_v(bc, nut->time_base[i].den);
227     }
228
229     tmp_pts=0;
230     tmp_mul=1;
231     tmp_stream=0;
232     for(i=0; i<256;){
233         tmp_fields=0;
234         tmp_size=0;
235 //        tmp_res=0;
236         if(tmp_pts    != nut->frame_code[i].pts_delta) tmp_fields=1;
237         if(tmp_mul    != nut->frame_code[i].size_mul ) tmp_fields=2;
238         if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
239         if(tmp_size   != nut->frame_code[i].size_lsb ) tmp_fields=4;
240 //        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
241
242         tmp_pts   = nut->frame_code[i].pts_delta;
243         tmp_flags = nut->frame_code[i].flags;
244         tmp_stream= nut->frame_code[i].stream_id;
245         tmp_mul   = nut->frame_code[i].size_mul;
246         tmp_size  = nut->frame_code[i].size_lsb;
247 //        tmp_res   = nut->frame_code[i].res;
248
249         for(j=0; i<256; j++,i++){
250             if(i == 'N'){
251                 j--;
252                 continue;
253             }
254             if(nut->frame_code[i].pts_delta != tmp_pts   ) break;
255             if(nut->frame_code[i].flags     != tmp_flags ) break;
256             if(nut->frame_code[i].stream_id != tmp_stream) break;
257             if(nut->frame_code[i].size_mul  != tmp_mul   ) break;
258             if(nut->frame_code[i].size_lsb  != tmp_size+j) break;
259 //            if(nut->frame_code[i].res       != tmp_res   ) break;
260         }
261         if(j != tmp_mul - tmp_size) tmp_fields=6;
262
263         put_v(bc, tmp_flags);
264         put_v(bc, tmp_fields);
265         if(tmp_fields>0) put_s(bc, tmp_pts);
266         if(tmp_fields>1) put_v(bc, tmp_mul);
267         if(tmp_fields>2) put_v(bc, tmp_stream);
268         if(tmp_fields>3) put_v(bc, tmp_size);
269         if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
270         if(tmp_fields>5) put_v(bc, j);
271     }
272 }
273
274 static int write_streamheader(NUTContext *nut, ByteIOContext *bc, AVCodecContext *codec, int i){
275     put_v(bc, i);
276     switch(codec->codec_type){
277     case CODEC_TYPE_VIDEO: put_v(bc, 0); break;
278     case CODEC_TYPE_AUDIO: put_v(bc, 1); break;
279 //    case CODEC_TYPE_TEXT : put_v(bc, 2); break;
280     default              : put_v(bc, 3); break;
281     }
282     put_v(bc, 4);
283     if (codec->codec_tag){
284         put_le32(bc, codec->codec_tag);
285     }else
286         return -1;
287
288     put_v(bc, nut->stream[i].time_base - nut->time_base);
289     put_v(bc, nut->stream[i].msb_pts_shift);
290     put_v(bc, nut->stream[i].max_pts_distance);
291     put_v(bc, codec->has_b_frames);
292     put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
293
294     put_v(bc, codec->extradata_size);
295     put_buffer(bc, codec->extradata, codec->extradata_size);
296
297     switch(codec->codec_type){
298     case CODEC_TYPE_AUDIO:
299         put_v(bc, codec->sample_rate);
300         put_v(bc, 1);
301         put_v(bc, codec->channels);
302         break;
303     case CODEC_TYPE_VIDEO:
304         put_v(bc, codec->width);
305         put_v(bc, codec->height);
306         put_v(bc, codec->sample_aspect_ratio.num);
307         put_v(bc, codec->sample_aspect_ratio.den);
308         put_v(bc, 0); /* csp type -- unknown */
309         break;
310     default:
311         break;
312     }
313     return 0;
314 }
315
316 static int add_info(ByteIOContext *bc, char *type, char *value){
317     put_str(bc, type);
318     put_s(bc, -1);
319     put_str(bc, value);
320     return 1;
321 }
322
323 static void write_globalinfo(NUTContext *nut, ByteIOContext *bc){
324     AVFormatContext *s= nut->avf;
325     ByteIOContext dyn_bc;
326     uint8_t *dyn_buf=NULL;
327     int count=0, dyn_size;
328
329     url_open_dyn_buf(&dyn_bc);
330
331     if(s->title    [0]) count+= add_info(&dyn_bc, "Title"    , s->title);
332     if(s->author   [0]) count+= add_info(&dyn_bc, "Author"   , s->author);
333     if(s->copyright[0]) count+= add_info(&dyn_bc, "Copyright", s->copyright);
334     if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
335                         count+= add_info(&dyn_bc, "Encoder"  , LIBAVFORMAT_IDENT);
336
337     put_v(bc, 0); //stream_if_plus1
338     put_v(bc, 0); //chapter_id
339     put_v(bc, 0); //timestamp_start
340     put_v(bc, 0); //length
341
342     put_v(bc, count);
343
344     dyn_size= url_close_dyn_buf(&dyn_bc, &dyn_buf);
345     put_buffer(bc, dyn_buf, dyn_size);
346     av_free(dyn_buf);
347 }
348
349 static void write_headers(NUTContext *nut, ByteIOContext *bc){
350     ByteIOContext dyn_bc;
351     int i;
352
353     url_open_dyn_buf(&dyn_bc);
354     write_mainheader(nut, &dyn_bc);
355     put_packet(nut, bc, &dyn_bc, 1, MAIN_STARTCODE);
356
357     for (i=0; i < nut->avf->nb_streams; i++){
358         AVCodecContext *codec = nut->avf->streams[i]->codec;
359
360         url_open_dyn_buf(&dyn_bc);
361         write_streamheader(nut, &dyn_bc, codec, i);
362         put_packet(nut, bc, &dyn_bc, 1, STREAM_STARTCODE);
363     }
364
365     url_open_dyn_buf(&dyn_bc);
366     write_globalinfo(nut, &dyn_bc);
367     put_packet(nut, bc, &dyn_bc, 1, INFO_STARTCODE);
368
369     nut->last_syncpoint_pos= INT_MIN;
370     nut->header_count++;
371 }
372
373 static int write_header(AVFormatContext *s){
374     NUTContext *nut = s->priv_data;
375     ByteIOContext *bc = &s->pb;
376     int i, j;
377
378     nut->avf= s;
379
380     nut->stream   = av_mallocz(sizeof(StreamContext)*s->nb_streams);
381     nut->time_base= av_mallocz(sizeof(AVRational   )*s->nb_streams);
382
383     for(i=0; i<s->nb_streams; i++){
384         AVStream *st= s->streams[i];
385         int ssize;
386         AVRational time_base;
387         ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
388
389         av_set_pts_info(st, 64, time_base.num, time_base.den);
390
391         for(j=0; j<nut->time_base_count; j++){
392             if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
393                 break;
394             }
395         }
396         nut->time_base[j]= time_base;
397         nut->stream[i].time_base= &nut->time_base[j];
398         if(j==nut->time_base_count)
399             nut->time_base_count++;
400
401         if(av_q2d(time_base) >= 0.001)
402             nut->stream[i].msb_pts_shift = 7;
403         else
404             nut->stream[i].msb_pts_shift = 14;
405         nut->stream[i].max_pts_distance= FFMAX(1/av_q2d(time_base), 1);
406     }
407
408     build_frame_code(s);
409     assert(nut->frame_code['N'].flags == FLAG_INVALID);
410
411     put_buffer(bc, ID_STRING, strlen(ID_STRING));
412     put_byte(bc, 0);
413
414     write_headers(nut, bc);
415
416     put_flush_packet(bc);
417
418     //FIXME index
419
420     return 0;
421 }
422
423 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
424     int flags= 0;
425
426     if(pkt->flags & PKT_FLAG_KEY                ) flags |= FLAG_KEY;
427     if(pkt->stream_index != fc->stream_id       ) flags |= FLAG_STREAM_ID;
428     if(pkt->size / fc->size_mul                 ) flags |= FLAG_SIZE_MSB;
429     if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
430     if(pkt->size > 2*nut->max_distance          ) flags |= FLAG_CHECKSUM;
431     if(FFABS(pkt->pts - nus->last_pts)
432                          > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
433
434     return flags;
435 }
436
437 static int write_packet(AVFormatContext *s, AVPacket *pkt){
438     NUTContext *nut = s->priv_data;
439     StreamContext *nus= &nut->stream[pkt->stream_index];
440     ByteIOContext *bc = &s->pb, dyn_bc;
441     FrameCode *fc;
442     int64_t coded_pts;
443     int best_length, frame_code, flags, needed_flags, i;
444     int key_frame = !!(pkt->flags & PKT_FLAG_KEY);
445     int store_sp=0;
446
447     if(1LL<<(20+3*nut->header_count) <= url_ftell(bc))
448         write_headers(nut, bc);
449
450     if(key_frame && !!(nus->last_flags & FLAG_KEY))
451         store_sp= 1;
452
453     if(pkt->size + 30/*FIXME check*/ + url_ftell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
454         store_sp= 1;
455
456 //FIXME ensure store_sp is 1 for the first thing
457
458     if(store_sp){
459         syncpoint_t *sp, dummy= {.pos= INT64_MAX};
460
461         ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
462         for(i=0; i<s->nb_streams; i++){
463             AVStream *st= s->streams[i];
464             int index= av_index_search_timestamp(st, pkt->dts, AVSEEK_FLAG_BACKWARD);
465             if(index<0) dummy.pos=0;
466             else        dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
467         }
468         sp= av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp, NULL);
469
470         nut->last_syncpoint_pos= url_ftell(bc);
471         url_open_dyn_buf(&dyn_bc);
472         put_t(nut, nus, &dyn_bc, pkt->dts);
473         put_v(&dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
474         put_packet(nut, bc, &dyn_bc, 1, SYNCPOINT_STARTCODE);
475
476         ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
477     }
478     assert(nus->last_pts != AV_NOPTS_VALUE);
479
480     coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
481     if(ff_lsb2full(nus, coded_pts) != pkt->pts)
482         coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
483
484     best_length=INT_MAX;
485     frame_code= -1;
486     for(i=0; i<256; i++){
487         int length= 0;
488         FrameCode *fc= &nut->frame_code[i];
489         int flags= fc->flags;
490
491         if(flags & FLAG_INVALID)
492             continue;
493         needed_flags= get_needed_flags(nut, nus, fc, pkt);
494
495         if(flags & FLAG_CODED){
496             length++;
497             flags &= ~needed_flags;
498             flags |=  needed_flags;
499         }
500
501         if((flags & needed_flags) != needed_flags)
502             continue;
503
504         if((flags ^ needed_flags) & FLAG_KEY)
505             continue;
506
507         if(flags & FLAG_STREAM_ID)
508             length+= get_length(pkt->stream_index);
509
510         if(pkt->size % fc->size_mul != fc->size_lsb)
511             continue;
512         if(flags & FLAG_SIZE_MSB)
513             length += get_length(pkt->size / fc->size_mul);
514
515         if(flags & FLAG_CHECKSUM)
516             length+=4;
517
518         if(flags & FLAG_CODED_PTS)
519             length += get_length(coded_pts);
520
521         length*=4;
522         length+= !(flags & FLAG_CODED_PTS);
523         length+= !(flags & FLAG_CHECKSUM);
524
525         if(length < best_length){
526             best_length= length;
527             frame_code=i;
528         }
529     }
530     assert(frame_code != -1);
531     fc= &nut->frame_code[frame_code];
532     flags= fc->flags;
533     needed_flags= get_needed_flags(nut, nus, fc, pkt);
534
535     init_checksum(bc, av_crc04C11DB7_update, 0);
536     put_byte(bc, frame_code);
537     if(flags & FLAG_CODED){
538         put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
539         flags = needed_flags;
540     }
541     if(flags & FLAG_STREAM_ID)  put_v(bc, pkt->stream_index);
542     if(flags & FLAG_CODED_PTS)  put_v(bc, coded_pts);
543     if(flags & FLAG_SIZE_MSB)   put_v(bc, pkt->size / fc->size_mul);
544
545     if(flags & FLAG_CHECKSUM)   put_le32(bc, get_checksum(bc));
546     else                        get_checksum(bc);
547
548     put_buffer(bc, pkt->data, pkt->size);
549     nus->last_flags= flags;
550
551     //FIXME just store one per syncpoint
552     if(flags & FLAG_KEY)
553         av_add_index_entry(
554             s->streams[pkt->stream_index],
555             nut->last_syncpoint_pos,
556             pkt->pts,
557             0,
558             0,
559             AVINDEX_KEYFRAME);
560
561     return 0;
562 }
563
564 static int write_trailer(AVFormatContext *s){
565     NUTContext *nut= s->priv_data;
566     ByteIOContext *bc= &s->pb;
567
568     while(nut->header_count<3)
569         write_headers(nut, bc);
570     put_flush_packet(bc);
571
572     return 0;
573 }
574
575 AVOutputFormat nut_muxer = {
576     "nut",
577     "nut format",
578     "video/x-nut",
579     "nut",
580     sizeof(NUTContext),
581 #ifdef CONFIG_LIBVORBIS
582     CODEC_ID_VORBIS,
583 #elif defined(CONFIG_LIBMP3LAME)
584     CODEC_ID_MP3,
585 #else
586     CODEC_ID_MP2, /* AC3 needs liba52 decoder */
587 #endif
588     CODEC_ID_MPEG4,
589     write_header,
590     write_packet,
591     write_trailer,
592     .flags = AVFMT_GLOBALHEADER,
593     .codec_tag= (const AVCodecTag*[]){codec_bmp_tags, codec_wav_tags, 0},
594 };