29b6dcdaab5c5663aa7417e2ca91450d2a4bbb53
[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 //av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
99
100 for(i=1; i<nut->header_count; i++){
101 if( len == nut->header_len[i]
102 && !memcmp(out, nut->header[i], len)){
103 // av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
104 return i;
105 }
106 }
107 // av_log(NULL, AV_LOG_ERROR, "nothing found\n");
108 return 0;
109 }
110
111 static void build_elision_headers(AVFormatContext *s){
112 NUTContext *nut = s->priv_data;
113 int i;
114 //FIXME this is lame
115 //FIXME write a 2pass mode to find the maximal headers
116 static const uint8_t headers[][5]={
117 {3, 0x00, 0x00, 0x01},
118 {4, 0x00, 0x00, 0x01, 0xB6},
119 {2, 0xFF, 0xFA}, //mp3+crc
120 {2, 0xFF, 0xFB}, //mp3
121 {2, 0xFF, 0xFC}, //mp2+crc
122 {2, 0xFF, 0xFD}, //mp2
123 };
124
125 nut->header_count= 7;
126 for(i=1; i<nut->header_count; i++){
127 nut->header_len[i]= headers[i-1][0];
128 nut->header [i]= &headers[i-1][1];
129 }
130 }
131
132 static void build_frame_code(AVFormatContext *s){
133 NUTContext *nut = s->priv_data;
134 int key_frame, index, pred, stream_id;
135 int start=1;
136 int end= 254;
137 int keyframe_0_esc= s->nb_streams > 2;
138 int pred_table[10];
139 FrameCode *ft;
140
141 ft= &nut->frame_code[start];
142 ft->flags= FLAG_CODED;
143 ft->size_mul=1;
144 ft->pts_delta=1;
145 start++;
146
147 if(keyframe_0_esc){
148 /* keyframe = 0 escape */
149 FrameCode *ft= &nut->frame_code[start];
150 ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
151 ft->size_mul=1;
152 start++;
153 }
154
155 for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
156 int start2= start + (end-start)*stream_id / s->nb_streams;
157 int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
158 AVCodecContext *codec = s->streams[stream_id]->codec;
159 int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
160 int intra_only= /*codec->intra_only || */is_audio;
161 int pred_count;
162
163 for(key_frame=0; key_frame<2; key_frame++){
164 if(intra_only && keyframe_0_esc && key_frame==0)
165 continue;
166
167 {
168 FrameCode *ft= &nut->frame_code[start2];
169 ft->flags= FLAG_KEY*key_frame;
170 ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
171 ft->stream_id= stream_id;
172 ft->size_mul=1;
173 if(is_audio)
174 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
175 start2++;
176 }
177 }
178
179 key_frame= intra_only;
180 if(is_audio){
181 int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
182 int pts;
183 for(pts=0; pts<2; pts++){
184 for(pred=0; pred<2; pred++){
185 FrameCode *ft= &nut->frame_code[start2];
186 ft->flags= FLAG_KEY*key_frame;
187 ft->stream_id= stream_id;
188 ft->size_mul=frame_bytes + 2;
189 ft->size_lsb=frame_bytes + pred;
190 ft->pts_delta=pts;
191 ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
192 start2++;
193 }
194 }
195 }else{
196 FrameCode *ft= &nut->frame_code[start2];
197 ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
198 ft->stream_id= stream_id;
199 ft->size_mul=1;
200 ft->pts_delta=1;
201 start2++;
202 }
203
204 if(codec->has_b_frames){
205 pred_count=5;
206 pred_table[0]=-2;
207 pred_table[1]=-1;
208 pred_table[2]=1;
209 pred_table[3]=3;
210 pred_table[4]=4;
211 }else if(codec->codec_id == AV_CODEC_ID_VORBIS){
212 pred_count=3;
213 pred_table[0]=2;
214 pred_table[1]=9;
215 pred_table[2]=16;
216 }else{
217 pred_count=1;
218 pred_table[0]=1;
219 }
220
221 for(pred=0; pred<pred_count; pred++){
222 int start3= start2 + (end2-start2)*pred / pred_count;
223 int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
224
225 for(index=start3; index<end3; index++){
226 FrameCode *ft= &nut->frame_code[index];
227 ft->flags= FLAG_KEY*key_frame;
228 ft->flags|= FLAG_SIZE_MSB;
229 ft->stream_id= stream_id;
230 //FIXME use single byte size and pred from last
231 ft->size_mul= end3-start3;
232 ft->size_lsb= index - start3;
233 ft->pts_delta= pred_table[pred];
234 if(is_audio)
235 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
236 }
237 }
238 }
239 memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
240 nut->frame_code[ 0].flags=
241 nut->frame_code[255].flags=
242 nut->frame_code['N'].flags= FLAG_INVALID;
243 }
244
245 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
246 val *= nut->time_base_count;
247 val += time_base - nut->time_base;
248 ff_put_v(bc, val);
249 }
250
251 /**
252 * Store a string as vb.
253 */
254 static void put_str(AVIOContext *bc, const char *string){
255 int len= strlen(string);
256
257 ff_put_v(bc, len);
258 avio_write(bc, string, len);
259 }
260
261 static void put_s(AVIOContext *bc, int64_t val){
262 ff_put_v(bc, 2*FFABS(val) - (val>0));
263 }
264
265 #ifdef TRACE
266 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
267 const char *func, int line)
268 {
269 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
270
271 ff_put_v(bc, v);
272 }
273
274 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
275 const char *func, int line)
276 {
277 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
278
279 put_s(bc, v);
280 }
281 #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
282 #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
283 #endif
284
285 //FIXME remove calculate_checksum
286 static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
287 uint8_t *dyn_buf=NULL;
288 int dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
289 int forw_ptr= dyn_size + 4*calculate_checksum;
290
291 if(forw_ptr > 4096)
292 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
293 avio_wb64(bc, startcode);
294 ff_put_v(bc, forw_ptr);
295 if(forw_ptr > 4096)
296 avio_wl32(bc, ffio_get_checksum(bc));
297
298 if(calculate_checksum)
299 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
300 avio_write(bc, dyn_buf, dyn_size);
301 if(calculate_checksum)
302 avio_wl32(bc, ffio_get_checksum(bc));
303
304 av_free(dyn_buf);
305 }
306
307 static void write_mainheader(NUTContext *nut, AVIOContext *bc){
308 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
309 int64_t tmp_match;
310
311 ff_put_v(bc, 3); /* version */
312 ff_put_v(bc, nut->avf->nb_streams);
313 ff_put_v(bc, nut->max_distance);
314 ff_put_v(bc, nut->time_base_count);
315
316 for(i=0; i<nut->time_base_count; i++){
317 ff_put_v(bc, nut->time_base[i].num);
318 ff_put_v(bc, nut->time_base[i].den);
319 }
320
321 tmp_pts=0;
322 tmp_mul=1;
323 tmp_stream=0;
324 tmp_match= 1-(1LL<<62);
325 tmp_head_idx= 0;
326 for(i=0; i<256;){
327 tmp_fields=0;
328 tmp_size=0;
329 // tmp_res=0;
330 if(tmp_pts != nut->frame_code[i].pts_delta) tmp_fields=1;
331 if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
332 if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
333 if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
334 // if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
335 if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
336
337 tmp_pts = nut->frame_code[i].pts_delta;
338 tmp_flags = nut->frame_code[i].flags;
339 tmp_stream= nut->frame_code[i].stream_id;
340 tmp_mul = nut->frame_code[i].size_mul;
341 tmp_size = nut->frame_code[i].size_lsb;
342 // tmp_res = nut->frame_code[i].res;
343 tmp_head_idx= nut->frame_code[i].header_idx;
344
345 for(j=0; i<256; j++,i++){
346 if(i == 'N'){
347 j--;
348 continue;
349 }
350 if(nut->frame_code[i].pts_delta != tmp_pts ) break;
351 if(nut->frame_code[i].flags != tmp_flags ) break;
352 if(nut->frame_code[i].stream_id != tmp_stream) break;
353 if(nut->frame_code[i].size_mul != tmp_mul ) break;
354 if(nut->frame_code[i].size_lsb != tmp_size+j) break;
355 // if(nut->frame_code[i].res != tmp_res ) break;
356 if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
357 }
358 if(j != tmp_mul - tmp_size) tmp_fields=6;
359
360 ff_put_v(bc, tmp_flags);
361 ff_put_v(bc, tmp_fields);
362 if(tmp_fields>0) put_s(bc, tmp_pts);
363 if(tmp_fields>1) ff_put_v(bc, tmp_mul);
364 if(tmp_fields>2) ff_put_v(bc, tmp_stream);
365 if(tmp_fields>3) ff_put_v(bc, tmp_size);
366 if(tmp_fields>4) ff_put_v(bc, 0 /*tmp_res*/);
367 if(tmp_fields>5) ff_put_v(bc, j);
368 if(tmp_fields>6) ff_put_v(bc, tmp_match);
369 if(tmp_fields>7) ff_put_v(bc, tmp_head_idx);
370 }
371 ff_put_v(bc, nut->header_count-1);
372 for(i=1; i<nut->header_count; i++){
373 ff_put_v(bc, nut->header_len[i]);
374 avio_write(bc, nut->header[i], nut->header_len[i]);
375 }
376 }
377
378 static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
379 NUTContext *nut = avctx->priv_data;
380 AVCodecContext *codec = st->codec;
381 ff_put_v(bc, i);
382 switch(codec->codec_type){
383 case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
384 case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
385 case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
386 default : ff_put_v(bc, 3); break;
387 }
388 ff_put_v(bc, 4);
389 if (codec->codec_tag){
390 avio_wl32(bc, codec->codec_tag);
391 } else {
392 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
393 return AVERROR(EINVAL);
394 }
395
396 ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
397 ff_put_v(bc, nut->stream[i].msb_pts_shift);
398 ff_put_v(bc, nut->stream[i].max_pts_distance);
399 ff_put_v(bc, codec->has_b_frames);
400 avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
401
402 ff_put_v(bc, codec->extradata_size);
403 avio_write(bc, codec->extradata, codec->extradata_size);
404
405 switch(codec->codec_type){
406 case AVMEDIA_TYPE_AUDIO:
407 ff_put_v(bc, codec->sample_rate);
408 ff_put_v(bc, 1);
409 ff_put_v(bc, codec->channels);
410 break;
411 case AVMEDIA_TYPE_VIDEO:
412 ff_put_v(bc, codec->width);
413 ff_put_v(bc, codec->height);
414
415 if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
416 ff_put_v(bc, 0);
417 ff_put_v(bc, 0);
418 }else{
419 ff_put_v(bc, st->sample_aspect_ratio.num);
420 ff_put_v(bc, st->sample_aspect_ratio.den);
421 }
422 ff_put_v(bc, 0); /* csp type -- unknown */
423 break;
424 default:
425 break;
426 }
427 return 0;
428 }
429
430 static int add_info(AVIOContext *bc, const char *type, const char *value){
431 put_str(bc, type);
432 put_s(bc, -1);
433 put_str(bc, value);
434 return 1;
435 }
436
437 static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
438 AVFormatContext *s= nut->avf;
439 AVDictionaryEntry *t = NULL;
440 AVIOContext *dyn_bc;
441 uint8_t *dyn_buf=NULL;
442 int count=0, dyn_size;
443 int ret = avio_open_dyn_buf(&dyn_bc);
444 if(ret < 0)
445 return ret;
446
447 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
448 count += add_info(dyn_bc, t->key, t->value);
449
450 ff_put_v(bc, 0); //stream_if_plus1
451 ff_put_v(bc, 0); //chapter_id
452 ff_put_v(bc, 0); //timestamp_start
453 ff_put_v(bc, 0); //length
454
455 ff_put_v(bc, count);
456
457 dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
458 avio_write(bc, dyn_buf, dyn_size);
459 av_free(dyn_buf);
460 return 0;
461 }
462
463 static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
464 AVFormatContext *s= nut->avf;
465 AVStream* st = s->streams[stream_id];
466 AVIOContext *dyn_bc;
467 uint8_t *dyn_buf=NULL;
468 int count=0, dyn_size, i;
469 int ret = avio_open_dyn_buf(&dyn_bc);
470 if(ret < 0)
471 return ret;
472
473 for (i=0; ff_nut_dispositions[i].flag; ++i) {
474 if (st->disposition & ff_nut_dispositions[i].flag)
475 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
476 }
477 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
478
479 if (count) {
480 ff_put_v(bc, stream_id + 1); //stream_id_plus1
481 ff_put_v(bc, 0); //chapter_id
482 ff_put_v(bc, 0); //timestamp_start
483 ff_put_v(bc, 0); //length
484
485 ff_put_v(bc, count);
486
487 avio_write(bc, dyn_buf, dyn_size);
488 }
489
490 av_free(dyn_buf);
491 return count;
492 }
493
494 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
495 {
496 AVIOContext *dyn_bc;
497 uint8_t *dyn_buf = NULL;
498 AVDictionaryEntry *t = NULL;
499 AVChapter *ch = nut->avf->chapters[id];
500 int ret, dyn_size, count = 0;
501
502 ret = avio_open_dyn_buf(&dyn_bc);
503 if (ret < 0)
504 return ret;
505
506 ff_put_v(bc, 0); // stream_id_plus1
507 put_s(bc, id + 1); // chapter_id
508 put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
509 ff_put_v(bc, ch->end - ch->start); // chapter_len
510
511 while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
512 count += add_info(dyn_bc, t->key, t->value);
513
514 ff_put_v(bc, count);
515
516 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
517 avio_write(bc, dyn_buf, dyn_size);
518 av_freep(&dyn_buf);
519 return 0;
520 }
521
522 static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
523 NUTContext *nut = avctx->priv_data;
524 AVIOContext *dyn_bc;
525 int i, ret;
526
527 ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
528
529 ret = avio_open_dyn_buf(&dyn_bc);
530 if(ret < 0)
531 return ret;
532 write_mainheader(nut, dyn_bc);
533 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
534
535 for (i=0; i < nut->avf->nb_streams; i++){
536 ret = avio_open_dyn_buf(&dyn_bc);
537 if(ret < 0)
538 return ret;
539 if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
540 return ret;
541 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
542 }
543
544 ret = avio_open_dyn_buf(&dyn_bc);
545 if(ret < 0)
546 return ret;
547 write_globalinfo(nut, dyn_bc);
548 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
549
550 for (i = 0; i < nut->avf->nb_streams; i++) {
551 ret = avio_open_dyn_buf(&dyn_bc);
552 if(ret < 0)
553 return ret;
554 ret = write_streaminfo(nut, dyn_bc, i);
555 if (ret < 0)
556 return ret;
557 if (ret > 0)
558 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
559 else {
560 uint8_t* buf;
561 avio_close_dyn_buf(dyn_bc, &buf);
562 av_free(buf);
563 }
564 }
565
566 for (i = 0; i < nut->avf->nb_chapters; i++) {
567 ret = avio_open_dyn_buf(&dyn_bc);
568 if (ret < 0)
569 return ret;
570 ret = write_chapter(nut, dyn_bc, i);
571 if (ret < 0) {
572 uint8_t *buf;
573 avio_close_dyn_buf(dyn_bc, &buf);
574 av_freep(&buf);
575 return ret;
576 }
577 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
578 }
579
580 nut->last_syncpoint_pos= INT_MIN;
581 nut->header_count++;
582 return 0;
583 }
584
585 static int nut_write_header(AVFormatContext *s){
586 NUTContext *nut = s->priv_data;
587 AVIOContext *bc = s->pb;
588 int i, j, ret;
589
590 nut->avf= s;
591
592 nut->stream = av_mallocz(sizeof(StreamContext)*s->nb_streams);
593 if (s->nb_chapters)
594 nut->chapter = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
595 nut->time_base= av_mallocz(sizeof(AVRational )*(s->nb_streams +
596 s->nb_chapters));
597 if (!nut->stream || (s->nb_chapters && !nut->chapter) || !nut->time_base) {
598 av_freep(&nut->stream);
599 av_freep(&nut->chapter);
600 av_freep(&nut->time_base);
601 return AVERROR(ENOMEM);
602 }
603
604 for(i=0; i<s->nb_streams; i++){
605 AVStream *st= s->streams[i];
606 int ssize;
607 AVRational time_base;
608 ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
609
610 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
611
612 for(j=0; j<nut->time_base_count; j++){
613 if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
614 break;
615 }
616 }
617 nut->time_base[j]= time_base;
618 nut->stream[i].time_base= &nut->time_base[j];
619 if(j==nut->time_base_count)
620 nut->time_base_count++;
621
622 if(INT64_C(1000) * time_base.num >= time_base.den)
623 nut->stream[i].msb_pts_shift = 7;
624 else
625 nut->stream[i].msb_pts_shift = 14;
626 nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
627 }
628
629 for (i = 0; i < s->nb_chapters; i++) {
630 AVChapter *ch = s->chapters[i];
631
632 for (j = 0; j < nut->time_base_count; j++) {
633 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
634 break;
635 }
636
637 nut->time_base[j] = ch->time_base;
638 nut->chapter[i].time_base = &nut->time_base[j];
639 if(j == nut->time_base_count)
640 nut->time_base_count++;
641 }
642
643 nut->max_distance = MAX_DISTANCE;
644 build_elision_headers(s);
645 build_frame_code(s);
646 assert(nut->frame_code['N'].flags == FLAG_INVALID);
647
648 avio_write(bc, ID_STRING, strlen(ID_STRING));
649 avio_w8(bc, 0);
650
651 if ((ret = write_headers(s, bc)) < 0)
652 return ret;
653
654 avio_flush(bc);
655
656 //FIXME index
657
658 return 0;
659 }
660
661 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
662 int flags= 0;
663
664 if(pkt->flags & AV_PKT_FLAG_KEY ) flags |= FLAG_KEY;
665 if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
666 if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
667 if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
668 if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
669 if(FFABS(pkt->pts - nus->last_pts)
670 > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
671 if( pkt->size < nut->header_len[fc->header_idx]
672 || (pkt->size > 4096 && fc->header_idx)
673 || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
674 flags |= FLAG_HEADER_IDX;
675
676 return flags | (fc->flags & FLAG_CODED);
677 }
678
679 static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
680 int i;
681 int best_i = 0;
682 int best_len= 0;
683
684 if(pkt->size > 4096)
685 return 0;
686
687 for(i=1; i<nut->header_count; i++){
688 if( pkt->size >= nut->header_len[i]
689 && nut->header_len[i] > best_len
690 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
691 best_i= i;
692 best_len= nut->header_len[i];
693 }
694 }
695 return best_i;
696 }
697
698 static int nut_write_packet(AVFormatContext *s, AVPacket *pkt){
699 NUTContext *nut = s->priv_data;
700 StreamContext *nus= &nut->stream[pkt->stream_index];
701 AVIOContext *bc = s->pb, *dyn_bc;
702 FrameCode *fc;
703 int64_t coded_pts;
704 int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
705 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
706 int store_sp=0;
707 int ret;
708
709 if(pkt->pts < 0)
710 return -1;
711
712 if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
713 write_headers(s, bc);
714
715 if(key_frame && !(nus->last_flags & FLAG_KEY))
716 store_sp= 1;
717
718 if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
719 store_sp= 1;
720
721 //FIXME: Ensure store_sp is 1 in the first place.
722
723 if(store_sp){
724 Syncpoint *sp, dummy= {.pos= INT64_MAX};
725
726 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
727 for(i=0; i<s->nb_streams; i++){
728 AVStream *st= s->streams[i];
729 int64_t dts_tb = av_rescale_rnd(pkt->dts,
730 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
731 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
732 AV_ROUND_DOWN);
733 int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
734 if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
735 }
736 if(dummy.pos == INT64_MAX)
737 dummy.pos= 0;
738 sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
739 NULL);
740
741 nut->last_syncpoint_pos= avio_tell(bc);
742 ret = avio_open_dyn_buf(&dyn_bc);
743 if(ret < 0)
744 return ret;
745 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
746 ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
747 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
748
749 ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
750 }
751 assert(nus->last_pts != AV_NOPTS_VALUE);
752
753 coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
754 if(ff_lsb2full(nus, coded_pts) != pkt->pts)
755 coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
756
757 best_header_idx= find_best_header_idx(nut, pkt);
758
759 best_length=INT_MAX;
760 frame_code= -1;
761 for(i=0; i<256; i++){
762 int length= 0;
763 FrameCode *fc= &nut->frame_code[i];
764 int flags= fc->flags;
765
766 if(flags & FLAG_INVALID)
767 continue;
768 needed_flags= get_needed_flags(nut, nus, fc, pkt);
769
770 if(flags & FLAG_CODED){
771 length++;
772 flags = needed_flags;
773 }
774
775 if((flags & needed_flags) != needed_flags)
776 continue;
777
778 if((flags ^ needed_flags) & FLAG_KEY)
779 continue;
780
781 if(flags & FLAG_STREAM_ID)
782 length+= ff_get_v_length(pkt->stream_index);
783
784 if(pkt->size % fc->size_mul != fc->size_lsb)
785 continue;
786 if(flags & FLAG_SIZE_MSB)
787 length += ff_get_v_length(pkt->size / fc->size_mul);
788
789 if(flags & FLAG_CHECKSUM)
790 length+=4;
791
792 if(flags & FLAG_CODED_PTS)
793 length += ff_get_v_length(coded_pts);
794
795 if( (flags & FLAG_CODED)
796 && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
797 flags |= FLAG_HEADER_IDX;
798 }
799
800 if(flags & FLAG_HEADER_IDX){
801 length += 1 - nut->header_len[best_header_idx];
802 }else{
803 length -= nut->header_len[fc->header_idx];
804 }
805
806 length*=4;
807 length+= !(flags & FLAG_CODED_PTS);
808 length+= !(flags & FLAG_CHECKSUM);
809
810 if(length < best_length){
811 best_length= length;
812 frame_code=i;
813 }
814 }
815 assert(frame_code != -1);
816 fc= &nut->frame_code[frame_code];
817 flags= fc->flags;
818 needed_flags= get_needed_flags(nut, nus, fc, pkt);
819 header_idx= fc->header_idx;
820
821 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
822 avio_w8(bc, frame_code);
823 if(flags & FLAG_CODED){
824 ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
825 flags = needed_flags;
826 }
827 if(flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
828 if(flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
829 if(flags & FLAG_SIZE_MSB) ff_put_v(bc, pkt->size / fc->size_mul);
830 if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
831
832 if(flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
833 else ffio_get_checksum(bc);
834
835 avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
836 nus->last_flags= flags;
837 nus->last_pts= pkt->pts;
838
839 //FIXME just store one per syncpoint
840 if(flags & FLAG_KEY)
841 av_add_index_entry(
842 s->streams[pkt->stream_index],
843 nut->last_syncpoint_pos,
844 pkt->pts,
845 0,
846 0,
847 AVINDEX_KEYFRAME);
848
849 return 0;
850 }
851
852 static int nut_write_trailer(AVFormatContext *s){
853 NUTContext *nut= s->priv_data;
854 AVIOContext *bc= s->pb;
855
856 while(nut->header_count<3)
857 write_headers(s, bc);
858
859 ff_nut_free_sp(nut);
860 av_freep(&nut->stream);
861 av_freep(&nut->chapter);
862 av_freep(&nut->time_base);
863
864 return 0;
865 }
866
867 AVOutputFormat ff_nut_muxer = {
868 .name = "nut",
869 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
870 .mime_type = "video/x-nut",
871 .extensions = "nut",
872 .priv_data_size = sizeof(NUTContext),
873 .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
874 CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
875 .video_codec = AV_CODEC_ID_MPEG4,
876 .write_header = nut_write_header,
877 .write_packet = nut_write_packet,
878 .write_trailer = nut_write_trailer,
879 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
880 .codec_tag = (const AVCodecTag * const []){
881 ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags,
882 ff_nut_subtitle_tags, 0
883 },
884 };