avformat: Remove non-compiling and/or silly commented-out printf/av_log statements
[libav.git] / libavformat / nutenc.c
1 /*
2 * nut muxer
3 * Copyright (c) 2004-2007 Michael Niedermayer
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; 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/mathematics.h"
24 #include "libavutil/tree.h"
25 #include "libavutil/dict.h"
26 #include "libavcodec/mpegaudiodata.h"
27 #include "nut.h"
28 #include "internal.h"
29 #include "avio_internal.h"
30
31 static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
32 int sample_rate= c->sample_rate;
33
34 if(size>4096)
35 return 0;
36
37 AV_WB24(out, 1);
38
39 if(c->codec_id == AV_CODEC_ID_MPEG4){
40 if(key_frame){
41 return 3;
42 }else{
43 out[3]= 0xB6;
44 return 4;
45 }
46 }else if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO || c->codec_id == AV_CODEC_ID_MPEG2VIDEO){
47 return 3;
48 }else if(c->codec_id == AV_CODEC_ID_H264){
49 return 3;
50 }else if(c->codec_id == AV_CODEC_ID_MP3 || c->codec_id == AV_CODEC_ID_MP2){
51 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
52 int layer= c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
53 unsigned int header= 0xFFF00000;
54
55 lsf = sample_rate < (24000+32000)/2;
56 mpeg25 = sample_rate < (12000+16000)/2;
57 sample_rate <<= lsf + mpeg25;
58 if (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
59 else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
60 else sample_rate_index=1;
61
62 sample_rate= avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
63
64 for(bitrate_index=2; bitrate_index<30; bitrate_index++){
65 frame_size = avpriv_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
66 frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
67
68 if(frame_size == size)
69 break;
70 }
71
72 header |= (!lsf)<<19;
73 header |= (4-layer)<<17;
74 header |= 1<<16; //no crc
75 AV_WB32(out, header);
76 if(size <= 0)
77 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
78 if(bitrate_index == 30)
79 return -1; //something is wrong ...
80
81 header |= (bitrate_index>>1)<<12;
82 header |= sample_rate_index<<10;
83 header |= (bitrate_index&1)<<9;
84
85 return 2; //FIXME actually put the needed ones in build_elision_headers()
86 return 3; //we guess that the private bit is not set
87 //FIXME the above assumptions should be checked, if these turn out false too often something should be done
88 }
89 return 0;
90 }
91
92 static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
93 NUTContext *nut = s->priv_data;
94 uint8_t out[64];
95 int i;
96 int len= find_expected_header(c, size, frame_type, out);
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 return i;
102 }
103 }
104 return 0;
105 }
106
107 static void build_elision_headers(AVFormatContext *s){
108 NUTContext *nut = s->priv_data;
109 int i;
110 //FIXME this is lame
111 //FIXME write a 2pass mode to find the maximal headers
112 static const uint8_t headers[][5]={
113 {3, 0x00, 0x00, 0x01},
114 {4, 0x00, 0x00, 0x01, 0xB6},
115 {2, 0xFF, 0xFA}, //mp3+crc
116 {2, 0xFF, 0xFB}, //mp3
117 {2, 0xFF, 0xFC}, //mp2+crc
118 {2, 0xFF, 0xFD}, //mp2
119 };
120
121 nut->header_count= 7;
122 for(i=1; i<nut->header_count; i++){
123 nut->header_len[i]= headers[i-1][0];
124 nut->header [i]= &headers[i-1][1];
125 }
126 }
127
128 static void build_frame_code(AVFormatContext *s){
129 NUTContext *nut = s->priv_data;
130 int key_frame, index, pred, stream_id;
131 int start=1;
132 int end= 254;
133 int keyframe_0_esc= s->nb_streams > 2;
134 int pred_table[10];
135 FrameCode *ft;
136
137 ft= &nut->frame_code[start];
138 ft->flags= FLAG_CODED;
139 ft->size_mul=1;
140 ft->pts_delta=1;
141 start++;
142
143 if(keyframe_0_esc){
144 /* keyframe = 0 escape */
145 FrameCode *ft= &nut->frame_code[start];
146 ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
147 ft->size_mul=1;
148 start++;
149 }
150
151 for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
152 int start2= start + (end-start)*stream_id / s->nb_streams;
153 int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
154 AVCodecContext *codec = s->streams[stream_id]->codec;
155 int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
156 int intra_only= /*codec->intra_only || */is_audio;
157 int pred_count;
158
159 for(key_frame=0; key_frame<2; key_frame++){
160 if(intra_only && keyframe_0_esc && key_frame==0)
161 continue;
162
163 {
164 FrameCode *ft= &nut->frame_code[start2];
165 ft->flags= FLAG_KEY*key_frame;
166 ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
167 ft->stream_id= stream_id;
168 ft->size_mul=1;
169 if(is_audio)
170 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
171 start2++;
172 }
173 }
174
175 key_frame= intra_only;
176 if(is_audio){
177 int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
178 int pts;
179 for(pts=0; pts<2; pts++){
180 for(pred=0; pred<2; pred++){
181 FrameCode *ft= &nut->frame_code[start2];
182 ft->flags= FLAG_KEY*key_frame;
183 ft->stream_id= stream_id;
184 ft->size_mul=frame_bytes + 2;
185 ft->size_lsb=frame_bytes + pred;
186 ft->pts_delta=pts;
187 ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
188 start2++;
189 }
190 }
191 }else{
192 FrameCode *ft= &nut->frame_code[start2];
193 ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
194 ft->stream_id= stream_id;
195 ft->size_mul=1;
196 ft->pts_delta=1;
197 start2++;
198 }
199
200 if(codec->has_b_frames){
201 pred_count=5;
202 pred_table[0]=-2;
203 pred_table[1]=-1;
204 pred_table[2]=1;
205 pred_table[3]=3;
206 pred_table[4]=4;
207 }else if(codec->codec_id == AV_CODEC_ID_VORBIS){
208 pred_count=3;
209 pred_table[0]=2;
210 pred_table[1]=9;
211 pred_table[2]=16;
212 }else{
213 pred_count=1;
214 pred_table[0]=1;
215 }
216
217 for(pred=0; pred<pred_count; pred++){
218 int start3= start2 + (end2-start2)*pred / pred_count;
219 int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
220
221 for(index=start3; index<end3; index++){
222 FrameCode *ft= &nut->frame_code[index];
223 ft->flags= FLAG_KEY*key_frame;
224 ft->flags|= FLAG_SIZE_MSB;
225 ft->stream_id= stream_id;
226 //FIXME use single byte size and pred from last
227 ft->size_mul= end3-start3;
228 ft->size_lsb= index - start3;
229 ft->pts_delta= pred_table[pred];
230 if(is_audio)
231 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
232 }
233 }
234 }
235 memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
236 nut->frame_code[ 0].flags=
237 nut->frame_code[255].flags=
238 nut->frame_code['N'].flags= FLAG_INVALID;
239 }
240
241 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
242 val *= nut->time_base_count;
243 val += time_base - nut->time_base;
244 ff_put_v(bc, val);
245 }
246
247 /**
248 * Store a string as vb.
249 */
250 static void put_str(AVIOContext *bc, const char *string){
251 int len= strlen(string);
252
253 ff_put_v(bc, len);
254 avio_write(bc, string, len);
255 }
256
257 static void put_s(AVIOContext *bc, int64_t val){
258 ff_put_v(bc, 2*FFABS(val) - (val>0));
259 }
260
261 #ifdef TRACE
262 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
263 const char *func, int line)
264 {
265 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
266
267 ff_put_v(bc, v);
268 }
269
270 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
271 const char *func, int line)
272 {
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 AVDictionaryEntry *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_dict_get(s->metadata, "", t, AV_DICT_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 AVDictionaryEntry *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_dict_get(ch->metadata, "", t, AV_DICT_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 nut_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 if (s->nb_chapters)
590 nut->chapter = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
591 nut->time_base= av_mallocz(sizeof(AVRational )*(s->nb_streams +
592 s->nb_chapters));
593 if (!nut->stream || (s->nb_chapters && !nut->chapter) || !nut->time_base) {
594 av_freep(&nut->stream);
595 av_freep(&nut->chapter);
596 av_freep(&nut->time_base);
597 return AVERROR(ENOMEM);
598 }
599
600 for(i=0; i<s->nb_streams; i++){
601 AVStream *st= s->streams[i];
602 int ssize;
603 AVRational time_base;
604 ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
605
606 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
607
608 for(j=0; j<nut->time_base_count; j++){
609 if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
610 break;
611 }
612 }
613 nut->time_base[j]= time_base;
614 nut->stream[i].time_base= &nut->time_base[j];
615 if(j==nut->time_base_count)
616 nut->time_base_count++;
617
618 if(INT64_C(1000) * time_base.num >= time_base.den)
619 nut->stream[i].msb_pts_shift = 7;
620 else
621 nut->stream[i].msb_pts_shift = 14;
622 nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
623 }
624
625 for (i = 0; i < s->nb_chapters; i++) {
626 AVChapter *ch = s->chapters[i];
627
628 for (j = 0; j < nut->time_base_count; j++) {
629 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
630 break;
631 }
632
633 nut->time_base[j] = ch->time_base;
634 nut->chapter[i].time_base = &nut->time_base[j];
635 if(j == nut->time_base_count)
636 nut->time_base_count++;
637 }
638
639 nut->max_distance = MAX_DISTANCE;
640 build_elision_headers(s);
641 build_frame_code(s);
642 assert(nut->frame_code['N'].flags == FLAG_INVALID);
643
644 avio_write(bc, ID_STRING, strlen(ID_STRING));
645 avio_w8(bc, 0);
646
647 if ((ret = write_headers(s, bc)) < 0)
648 return ret;
649
650 avio_flush(bc);
651
652 //FIXME index
653
654 return 0;
655 }
656
657 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
658 int flags= 0;
659
660 if(pkt->flags & AV_PKT_FLAG_KEY ) flags |= FLAG_KEY;
661 if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
662 if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
663 if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
664 if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
665 if(FFABS(pkt->pts - nus->last_pts)
666 > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
667 if( pkt->size < nut->header_len[fc->header_idx]
668 || (pkt->size > 4096 && fc->header_idx)
669 || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
670 flags |= FLAG_HEADER_IDX;
671
672 return flags | (fc->flags & FLAG_CODED);
673 }
674
675 static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
676 int i;
677 int best_i = 0;
678 int best_len= 0;
679
680 if(pkt->size > 4096)
681 return 0;
682
683 for(i=1; i<nut->header_count; i++){
684 if( pkt->size >= nut->header_len[i]
685 && nut->header_len[i] > best_len
686 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
687 best_i= i;
688 best_len= nut->header_len[i];
689 }
690 }
691 return best_i;
692 }
693
694 static int nut_write_packet(AVFormatContext *s, AVPacket *pkt){
695 NUTContext *nut = s->priv_data;
696 StreamContext *nus= &nut->stream[pkt->stream_index];
697 AVIOContext *bc = s->pb, *dyn_bc;
698 FrameCode *fc;
699 int64_t coded_pts;
700 int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
701 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
702 int store_sp=0;
703 int ret;
704
705 if(pkt->pts < 0)
706 return -1;
707
708 if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
709 write_headers(s, bc);
710
711 if(key_frame && !(nus->last_flags & FLAG_KEY))
712 store_sp= 1;
713
714 if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
715 store_sp= 1;
716
717 //FIXME: Ensure store_sp is 1 in the first place.
718
719 if(store_sp){
720 Syncpoint *sp, dummy= {.pos= INT64_MAX};
721
722 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
723 for(i=0; i<s->nb_streams; i++){
724 AVStream *st= s->streams[i];
725 int64_t dts_tb = av_rescale_rnd(pkt->dts,
726 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
727 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
728 AV_ROUND_DOWN);
729 int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
730 if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
731 }
732 if(dummy.pos == INT64_MAX)
733 dummy.pos= 0;
734 sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
735 NULL);
736
737 nut->last_syncpoint_pos= avio_tell(bc);
738 ret = avio_open_dyn_buf(&dyn_bc);
739 if(ret < 0)
740 return ret;
741 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
742 ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
743 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
744
745 ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
746 }
747 assert(nus->last_pts != AV_NOPTS_VALUE);
748
749 coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
750 if(ff_lsb2full(nus, coded_pts) != pkt->pts)
751 coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
752
753 best_header_idx= find_best_header_idx(nut, pkt);
754
755 best_length=INT_MAX;
756 frame_code= -1;
757 for(i=0; i<256; i++){
758 int length= 0;
759 FrameCode *fc= &nut->frame_code[i];
760 int flags= fc->flags;
761
762 if(flags & FLAG_INVALID)
763 continue;
764 needed_flags= get_needed_flags(nut, nus, fc, pkt);
765
766 if(flags & FLAG_CODED){
767 length++;
768 flags = needed_flags;
769 }
770
771 if((flags & needed_flags) != needed_flags)
772 continue;
773
774 if((flags ^ needed_flags) & FLAG_KEY)
775 continue;
776
777 if(flags & FLAG_STREAM_ID)
778 length+= ff_get_v_length(pkt->stream_index);
779
780 if(pkt->size % fc->size_mul != fc->size_lsb)
781 continue;
782 if(flags & FLAG_SIZE_MSB)
783 length += ff_get_v_length(pkt->size / fc->size_mul);
784
785 if(flags & FLAG_CHECKSUM)
786 length+=4;
787
788 if(flags & FLAG_CODED_PTS)
789 length += ff_get_v_length(coded_pts);
790
791 if( (flags & FLAG_CODED)
792 && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
793 flags |= FLAG_HEADER_IDX;
794 }
795
796 if(flags & FLAG_HEADER_IDX){
797 length += 1 - nut->header_len[best_header_idx];
798 }else{
799 length -= nut->header_len[fc->header_idx];
800 }
801
802 length*=4;
803 length+= !(flags & FLAG_CODED_PTS);
804 length+= !(flags & FLAG_CHECKSUM);
805
806 if(length < best_length){
807 best_length= length;
808 frame_code=i;
809 }
810 }
811 assert(frame_code != -1);
812 fc= &nut->frame_code[frame_code];
813 flags= fc->flags;
814 needed_flags= get_needed_flags(nut, nus, fc, pkt);
815 header_idx= fc->header_idx;
816
817 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
818 avio_w8(bc, frame_code);
819 if(flags & FLAG_CODED){
820 ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
821 flags = needed_flags;
822 }
823 if(flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
824 if(flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
825 if(flags & FLAG_SIZE_MSB) ff_put_v(bc, pkt->size / fc->size_mul);
826 if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
827
828 if(flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
829 else ffio_get_checksum(bc);
830
831 avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
832 nus->last_flags= flags;
833 nus->last_pts= pkt->pts;
834
835 //FIXME just store one per syncpoint
836 if(flags & FLAG_KEY)
837 av_add_index_entry(
838 s->streams[pkt->stream_index],
839 nut->last_syncpoint_pos,
840 pkt->pts,
841 0,
842 0,
843 AVINDEX_KEYFRAME);
844
845 return 0;
846 }
847
848 static int nut_write_trailer(AVFormatContext *s){
849 NUTContext *nut= s->priv_data;
850 AVIOContext *bc= s->pb;
851
852 while(nut->header_count<3)
853 write_headers(s, bc);
854
855 ff_nut_free_sp(nut);
856 av_freep(&nut->stream);
857 av_freep(&nut->chapter);
858 av_freep(&nut->time_base);
859
860 return 0;
861 }
862
863 AVOutputFormat ff_nut_muxer = {
864 .name = "nut",
865 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
866 .mime_type = "video/x-nut",
867 .extensions = "nut",
868 .priv_data_size = sizeof(NUTContext),
869 .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
870 CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
871 .video_codec = AV_CODEC_ID_MPEG4,
872 .write_header = nut_write_header,
873 .write_packet = nut_write_packet,
874 .write_trailer = nut_write_trailer,
875 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
876 .codec_tag = (const AVCodecTag * const []){
877 ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags,
878 ff_nut_subtitle_tags, 0
879 },
880 };