libxvid: add some const fixing a warning
[libav.git] / libavformat / nutenc.c
CommitLineData
70ea1e69
MN
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
6a5d31ac 22#include "libavutil/intreadwrite.h"
245976da
DB
23#include "libavutil/tree.h"
24#include "libavcodec/mpegaudiodata.h"
70ea1e69 25#include "nut.h"
80b39e1c 26#include "internal.h"
a712d725
MN
27
28static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
29 int sample_rate= c->sample_rate;
30
31 if(size>4096)
32 return 0;
33
34 AV_WB24(out, 1);
35
36 if(c->codec_id == CODEC_ID_MPEG4){
37 if(key_frame){
38 return 3;
39 }else{
40 out[3]= 0xB6;
41 return 4;
42 }
43 }else if(c->codec_id == CODEC_ID_MPEG1VIDEO || c->codec_id == CODEC_ID_MPEG2VIDEO){
44 return 3;
45 }else if(c->codec_id == CODEC_ID_H264){
46 return 3;
47 }else if(c->codec_id == CODEC_ID_MP3 || c->codec_id == CODEC_ID_MP2){
48 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
49 int layer= c->codec_id == CODEC_ID_MP3 ? 3 : 2;
50 unsigned int header= 0xFFF00000;
51
52 lsf = sample_rate < (24000+32000)/2;
53 mpeg25 = sample_rate < (12000+16000)/2;
54 sample_rate <<= lsf + mpeg25;
55 if (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
56 else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
57 else sample_rate_index=1;
58
59 sample_rate= ff_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
60
61 for(bitrate_index=2; bitrate_index<30; bitrate_index++){
62 frame_size = ff_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
63 frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
64
65 if(frame_size == size)
66 break;
67 }
68
69 header |= (!lsf)<<19;
70 header |= (4-layer)<<17;
71 header |= 1<<16; //no crc
72 AV_WB32(out, header);
73 if(size <= 0)
7ce68923 74 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
a712d725
MN
75 if(bitrate_index == 30)
76 return -1; //something is wrong ...
77
78 header |= (bitrate_index>>1)<<12;
79 header |= sample_rate_index<<10;
80 header |= (bitrate_index&1)<<9;
81
82 return 2; //FIXME actually put the needed ones in build_elision_headers()
7ce68923
DB
83 return 3; //we guess that the private bit is not set
84//FIXME the above assumptions should be checked, if these turn out false too often something should be done
a712d725
MN
85 }
86 return 0;
87}
88
89static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
90 NUTContext *nut = s->priv_data;
91 uint8_t out[64];
92 int i;
93 int len= find_expected_header(c, size, frame_type, out);
94
95//av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
96
97 for(i=1; i<nut->header_count; i++){
98 if( len == nut->header_len[i]
99 && !memcmp(out, nut->header[i], len)){
100// av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
101 return i;
102 }
103 }
104// av_log(NULL, AV_LOG_ERROR, "nothing found\n");
105 return 0;
106}
107
108static void build_elision_headers(AVFormatContext *s){
109 NUTContext *nut = s->priv_data;
110 int i;
111 //FIXME this is lame
112 //FIXME write a 2pass mode to find the maximal headers
1bf6e565 113 static const uint8_t headers[][5]={
a712d725
MN
114 {3, 0x00, 0x00, 0x01},
115 {4, 0x00, 0x00, 0x01, 0xB6},
116 {2, 0xFF, 0xFA}, //mp3+crc
117 {2, 0xFF, 0xFB}, //mp3
118 {2, 0xFF, 0xFC}, //mp2+crc
119 {2, 0xFF, 0xFD}, //mp2
120 };
121
122 nut->header_count= 7;
123 for(i=1; i<nut->header_count; i++){
124 nut->header_len[i]= headers[i-1][0];
125 nut->header [i]= &headers[i-1][1];
126 }
127}
70ea1e69 128
70ea1e69
MN
129static void build_frame_code(AVFormatContext *s){
130 NUTContext *nut = s->priv_data;
131 int key_frame, index, pred, stream_id;
132 int start=1;
133 int end= 254;
134 int keyframe_0_esc= s->nb_streams > 2;
135 int pred_table[10];
0fcfa8eb
MN
136 FrameCode *ft;
137
138 ft= &nut->frame_code[start];
139 ft->flags= FLAG_CODED;
140 ft->size_mul=1;
141 ft->pts_delta=1;
142 start++;
70ea1e69
MN
143
144 if(keyframe_0_esc){
145 /* keyframe = 0 escape */
146 FrameCode *ft= &nut->frame_code[start];
147 ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
148 ft->size_mul=1;
149 start++;
150 }
151
152 for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
153 int start2= start + (end-start)*stream_id / s->nb_streams;
154 int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
155 AVCodecContext *codec = s->streams[stream_id]->codec;
72415b2a 156 int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
70ea1e69
MN
157 int intra_only= /*codec->intra_only || */is_audio;
158 int pred_count;
159
160 for(key_frame=0; key_frame<2; key_frame++){
161 if(intra_only && keyframe_0_esc && key_frame==0)
162 continue;
163
164 {
165 FrameCode *ft= &nut->frame_code[start2];
166 ft->flags= FLAG_KEY*key_frame;
167 ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
168 ft->stream_id= stream_id;
169 ft->size_mul=1;
a712d725
MN
170 if(is_audio)
171 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
70ea1e69
MN
172 start2++;
173 }
174 }
175
176 key_frame= intra_only;
177#if 1
178 if(is_audio){
179 int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
180 int pts;
181 for(pts=0; pts<2; pts++){
182 for(pred=0; pred<2; pred++){
183 FrameCode *ft= &nut->frame_code[start2];
184 ft->flags= FLAG_KEY*key_frame;
185 ft->stream_id= stream_id;
186 ft->size_mul=frame_bytes + 2;
187 ft->size_lsb=frame_bytes + pred;
188 ft->pts_delta=pts;
a712d725 189 ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
70ea1e69
MN
190 start2++;
191 }
192 }
193 }else{
194 FrameCode *ft= &nut->frame_code[start2];
195 ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
196 ft->stream_id= stream_id;
197 ft->size_mul=1;
198 ft->pts_delta=1;
199 start2++;
200 }
201#endif
202
203 if(codec->has_b_frames){
204 pred_count=5;
205 pred_table[0]=-2;
206 pred_table[1]=-1;
207 pred_table[2]=1;
208 pred_table[3]=3;
209 pred_table[4]=4;
210 }else if(codec->codec_id == CODEC_ID_VORBIS){
211 pred_count=3;
212 pred_table[0]=2;
213 pred_table[1]=9;
214 pred_table[2]=16;
215 }else{
216 pred_count=1;
217 pred_table[0]=1;
218 }
219
220 for(pred=0; pred<pred_count; pred++){
221 int start3= start2 + (end2-start2)*pred / pred_count;
222 int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
223
224 for(index=start3; index<end3; index++){
225 FrameCode *ft= &nut->frame_code[index];
226 ft->flags= FLAG_KEY*key_frame;
227 ft->flags|= FLAG_SIZE_MSB;
228 ft->stream_id= stream_id;
229//FIXME use single byte size and pred from last
230 ft->size_mul= end3-start3;
231 ft->size_lsb= index - start3;
232 ft->pts_delta= pred_table[pred];
a712d725
MN
233 if(is_audio)
234 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
70ea1e69
MN
235 }
236 }
237 }
238 memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
239 nut->frame_code[ 0].flags=
240 nut->frame_code[255].flags=
241 nut->frame_code['N'].flags= FLAG_INVALID;
242}
243
244/**
49bd8e4b 245 * Get the length in bytes which is needed to store val as v.
70ea1e69
MN
246 */
247static int get_length(uint64_t val){
248 int i=1;
249
250 while(val>>=7)
251 i++;
252
253 return i;
254}
255
256static void put_v(ByteIOContext *bc, uint64_t val){
257 int i= get_length(val);
258
259 while(--i>0)
260 put_byte(bc, 128 | (val>>(7*i)));
261
262 put_byte(bc, val&127);
263}
264
52afa376 265static void put_tt(NUTContext *nut, StreamContext *nus, ByteIOContext *bc, uint64_t val){
491216c6
MN
266 val *= nut->time_base_count;
267 val += nus->time_base - nut->time_base;
268 put_v(bc, val);
269}
270
70ea1e69 271/**
49bd8e4b 272 * Store a string as vb.
70ea1e69
MN
273 */
274static void put_str(ByteIOContext *bc, const char *string){
275 int len= strlen(string);
276
277 put_v(bc, len);
278 put_buffer(bc, string, len);
279}
280
281static void put_s(ByteIOContext *bc, int64_t val){
282 put_v(bc, 2*FFABS(val) - (val>0));
283}
284
285#ifdef TRACE
286static inline void put_v_trace(ByteIOContext *bc, uint64_t v, char *file, char *func, int line){
7a26da44 287 av_log(NULL, AV_LOG_DEBUG, "put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69
MN
288
289 put_v(bc, v);
290}
291
292static inline void put_s_trace(ByteIOContext *bc, int64_t v, char *file, char *func, int line){
7a26da44 293 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69
MN
294
295 put_s(bc, v);
296}
297#define put_v(bc, v) put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
298#define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
299#endif
300
34f8cc38 301//FIXME remove calculate_checksum
f0a9978c 302static void put_packet(NUTContext *nut, ByteIOContext *bc, ByteIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
8d9a3f7e
MN
303 uint8_t *dyn_buf=NULL;
304 int dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
6c666941
MN
305 int forw_ptr= dyn_size + 4*calculate_checksum;
306
307 if(forw_ptr > 4096)
992e78f5 308 init_checksum(bc, ff_crc04C11DB7_update, 0);
f0a9978c 309 put_be64(bc, startcode);
6c666941
MN
310 put_v(bc, forw_ptr);
311 if(forw_ptr > 4096)
312 put_le32(bc, get_checksum(bc));
70ea1e69
MN
313
314 if(calculate_checksum)
992e78f5 315 init_checksum(bc, ff_crc04C11DB7_update, 0);
8d9a3f7e 316 put_buffer(bc, dyn_buf, dyn_size);
70ea1e69 317 if(calculate_checksum)
8d9a3f7e 318 put_le32(bc, get_checksum(bc));
70ea1e69 319
8d9a3f7e 320 av_free(dyn_buf);
70ea1e69
MN
321}
322
97d5eb11 323static void write_mainheader(NUTContext *nut, ByteIOContext *bc){
a712d725
MN
324 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
325 int64_t tmp_match;
70ea1e69 326
a17e046a 327 put_v(bc, 3); /* version */
97d5eb11 328 put_v(bc, nut->avf->nb_streams);
82badd27 329 put_v(bc, nut->max_distance);
70ea1e69
MN
330 put_v(bc, nut->time_base_count);
331
332 for(i=0; i<nut->time_base_count; i++){
333 put_v(bc, nut->time_base[i].num);
334 put_v(bc, nut->time_base[i].den);
335 }
336
70ea1e69
MN
337 tmp_pts=0;
338 tmp_mul=1;
339 tmp_stream=0;
a712d725
MN
340 tmp_match= 1-(1LL<<62);
341 tmp_head_idx= 0;
70ea1e69
MN
342 for(i=0; i<256;){
343 tmp_fields=0;
344 tmp_size=0;
345// tmp_res=0;
346 if(tmp_pts != nut->frame_code[i].pts_delta) tmp_fields=1;
347 if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
348 if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
349 if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
350// if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
a712d725 351 if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
70ea1e69
MN
352
353 tmp_pts = nut->frame_code[i].pts_delta;
354 tmp_flags = nut->frame_code[i].flags;
355 tmp_stream= nut->frame_code[i].stream_id;
356 tmp_mul = nut->frame_code[i].size_mul;
357 tmp_size = nut->frame_code[i].size_lsb;
358// tmp_res = nut->frame_code[i].res;
a712d725 359 tmp_head_idx= nut->frame_code[i].header_idx;
70ea1e69
MN
360
361 for(j=0; i<256; j++,i++){
362 if(i == 'N'){
363 j--;
364 continue;
365 }
366 if(nut->frame_code[i].pts_delta != tmp_pts ) break;
367 if(nut->frame_code[i].flags != tmp_flags ) break;
368 if(nut->frame_code[i].stream_id != tmp_stream) break;
369 if(nut->frame_code[i].size_mul != tmp_mul ) break;
370 if(nut->frame_code[i].size_lsb != tmp_size+j) break;
371// if(nut->frame_code[i].res != tmp_res ) break;
a712d725 372 if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
70ea1e69
MN
373 }
374 if(j != tmp_mul - tmp_size) tmp_fields=6;
375
376 put_v(bc, tmp_flags);
377 put_v(bc, tmp_fields);
378 if(tmp_fields>0) put_s(bc, tmp_pts);
379 if(tmp_fields>1) put_v(bc, tmp_mul);
380 if(tmp_fields>2) put_v(bc, tmp_stream);
381 if(tmp_fields>3) put_v(bc, tmp_size);
382 if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);
383 if(tmp_fields>5) put_v(bc, j);
a712d725
MN
384 if(tmp_fields>6) put_v(bc, tmp_match);
385 if(tmp_fields>7) put_v(bc, tmp_head_idx);
386 }
387 put_v(bc, nut->header_count-1);
388 for(i=1; i<nut->header_count; i++){
389 put_v(bc, nut->header_len[i]);
390 put_buffer(bc, nut->header[i], nut->header_len[i]);
70ea1e69 391 }
97d5eb11 392}
70ea1e69 393
da9e6c42
SS
394static int write_streamheader(AVFormatContext *avctx, ByteIOContext *bc, AVStream *st, int i){
395 NUTContext *nut = avctx->priv_data;
59729451 396 AVCodecContext *codec = st->codec;
0809b51e
MN
397 put_v(bc, i);
398 switch(codec->codec_type){
72415b2a
SS
399 case AVMEDIA_TYPE_VIDEO: put_v(bc, 0); break;
400 case AVMEDIA_TYPE_AUDIO: put_v(bc, 1); break;
401 case AVMEDIA_TYPE_SUBTITLE: put_v(bc, 2); break;
0809b51e
MN
402 default : put_v(bc, 3); break;
403 }
404 put_v(bc, 4);
405 if (codec->codec_tag){
406 put_le32(bc, codec->codec_tag);
fa586439
SS
407 } else {
408 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
ffd5f098 409 return AVERROR(EINVAL);
fa586439 410 }
0809b51e 411
6e6cf116 412 put_v(bc, nut->stream[i].time_base - nut->time_base);
0809b51e
MN
413 put_v(bc, nut->stream[i].msb_pts_shift);
414 put_v(bc, nut->stream[i].max_pts_distance);
415 put_v(bc, codec->has_b_frames);
416 put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
417
418 put_v(bc, codec->extradata_size);
419 put_buffer(bc, codec->extradata, codec->extradata_size);
420
421 switch(codec->codec_type){
72415b2a 422 case AVMEDIA_TYPE_AUDIO:
0809b51e
MN
423 put_v(bc, codec->sample_rate);
424 put_v(bc, 1);
425 put_v(bc, codec->channels);
426 break;
72415b2a 427 case AVMEDIA_TYPE_VIDEO:
0809b51e
MN
428 put_v(bc, codec->width);
429 put_v(bc, codec->height);
0a5790d1 430
59729451 431 if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
0a5790d1
MN
432 put_v(bc, 0);
433 put_v(bc, 0);
434 }else{
59729451
AJ
435 put_v(bc, st->sample_aspect_ratio.num);
436 put_v(bc, st->sample_aspect_ratio.den);
0a5790d1 437 }
0809b51e
MN
438 put_v(bc, 0); /* csp type -- unknown */
439 break;
440 default:
441 break;
442 }
443 return 0;
444}
445
4cf97abb 446static int add_info(ByteIOContext *bc, const char *type, const char *value){
ead1939f
MN
447 put_str(bc, type);
448 put_s(bc, -1);
449 put_str(bc, value);
450 return 1;
451}
452
899681cd 453static int write_globalinfo(NUTContext *nut, ByteIOContext *bc){
ead1939f 454 AVFormatContext *s= nut->avf;
43382b5f 455 AVMetadataTag *t = NULL;
899681cd 456 ByteIOContext *dyn_bc;
ead1939f
MN
457 uint8_t *dyn_buf=NULL;
458 int count=0, dyn_size;
899681cd
BA
459 int ret = url_open_dyn_buf(&dyn_bc);
460 if(ret < 0)
461 return ret;
ead1939f 462
43382b5f
AK
463 while ((t = av_metadata_get(s->metadata, "", t, AV_METADATA_IGNORE_SUFFIX)))
464 count += add_info(dyn_bc, t->key, t->value);
ead1939f
MN
465
466 put_v(bc, 0); //stream_if_plus1
467 put_v(bc, 0); //chapter_id
468 put_v(bc, 0); //timestamp_start
469 put_v(bc, 0); //length
470
471 put_v(bc, count);
472
899681cd 473 dyn_size= url_close_dyn_buf(dyn_bc, &dyn_buf);
ead1939f
MN
474 put_buffer(bc, dyn_buf, dyn_size);
475 av_free(dyn_buf);
899681cd 476 return 0;
ead1939f
MN
477}
478
90c2295b
ES
479static int write_streaminfo(NUTContext *nut, ByteIOContext *bc, int stream_id){
480 AVFormatContext *s= nut->avf;
481 AVStream* st = s->streams[stream_id];
482 ByteIOContext *dyn_bc;
483 uint8_t *dyn_buf=NULL;
484 int count=0, dyn_size, i;
485 int ret = url_open_dyn_buf(&dyn_bc);
486 if(ret < 0)
487 return ret;
488
489 for (i=0; ff_nut_dispositions[i].flag; ++i) {
490 if (st->disposition & ff_nut_dispositions[i].flag)
491 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
492 }
493 dyn_size = url_close_dyn_buf(dyn_bc, &dyn_buf);
494
495 if (count) {
496 put_v(bc, stream_id + 1); //stream_id_plus1
497 put_v(bc, 0); //chapter_id
498 put_v(bc, 0); //timestamp_start
499 put_v(bc, 0); //length
500
501 put_v(bc, count);
502
503 put_buffer(bc, dyn_buf, dyn_size);
504 }
505
506 av_free(dyn_buf);
507 return count;
508}
509
da9e6c42
SS
510static int write_headers(AVFormatContext *avctx, ByteIOContext *bc){
511 NUTContext *nut = avctx->priv_data;
899681cd
BA
512 ByteIOContext *dyn_bc;
513 int i, ret;
7e506494 514
899681cd
BA
515 ret = url_open_dyn_buf(&dyn_bc);
516 if(ret < 0)
517 return ret;
518 write_mainheader(nut, dyn_bc);
519 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
7e506494
MN
520
521 for (i=0; i < nut->avf->nb_streams; i++){
899681cd
BA
522 ret = url_open_dyn_buf(&dyn_bc);
523 if(ret < 0)
524 return ret;
fc0c4124
SS
525 if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
526 return ret;
899681cd 527 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
7e506494 528 }
ead1939f 529
899681cd
BA
530 ret = url_open_dyn_buf(&dyn_bc);
531 if(ret < 0)
532 return ret;
533 write_globalinfo(nut, dyn_bc);
534 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
14b3f996 535
90c2295b
ES
536 for (i = 0; i < nut->avf->nb_streams; i++) {
537 ret = url_open_dyn_buf(&dyn_bc);
538 if(ret < 0)
539 return ret;
540 ret = write_streaminfo(nut, dyn_bc, i);
541 if (ret < 0)
542 return ret;
543 if (ret > 0)
544 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
545 else {
546 uint8_t* buf;
547 url_close_dyn_buf(dyn_bc, &buf);
548 av_free(buf);
549 }
550 }
551
14b3f996
MN
552 nut->last_syncpoint_pos= INT_MIN;
553 nut->header_count++;
899681cd 554 return 0;
7e506494
MN
555}
556
97d5eb11
MN
557static int write_header(AVFormatContext *s){
558 NUTContext *nut = s->priv_data;
899681cd 559 ByteIOContext *bc = s->pb;
fc0c4124 560 int i, j, ret;
97d5eb11
MN
561
562 nut->avf= s;
563
564 nut->stream = av_mallocz(sizeof(StreamContext)*s->nb_streams);
565 nut->time_base= av_mallocz(sizeof(AVRational )*s->nb_streams);
566
567 for(i=0; i<s->nb_streams; i++){
568 AVStream *st= s->streams[i];
569 int ssize;
570 AVRational time_base;
571 ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
572
573 av_set_pts_info(st, 64, time_base.num, time_base.den);
574
575 for(j=0; j<nut->time_base_count; j++){
576 if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
577 break;
578 }
579 }
580 nut->time_base[j]= time_base;
581 nut->stream[i].time_base= &nut->time_base[j];
582 if(j==nut->time_base_count)
583 nut->time_base_count++;
584
585 if(av_q2d(time_base) >= 0.001)
586 nut->stream[i].msb_pts_shift = 7;
587 else
588 nut->stream[i].msb_pts_shift = 14;
589 nut->stream[i].max_pts_distance= FFMAX(1/av_q2d(time_base), 1);
590 }
591
82badd27 592 nut->max_distance = MAX_DISTANCE;
a712d725 593 build_elision_headers(s);
97d5eb11
MN
594 build_frame_code(s);
595 assert(nut->frame_code['N'].flags == FLAG_INVALID);
596
597 put_buffer(bc, ID_STRING, strlen(ID_STRING));
598 put_byte(bc, 0);
599
fc0c4124
SS
600 if ((ret = write_headers(s, bc)) < 0)
601 return ret;
dcc9bde0 602
70ea1e69
MN
603 put_flush_packet(bc);
604
14b3f996 605 //FIXME index
70ea1e69
MN
606
607 return 0;
608}
609
e1249ba9
MN
610static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
611 int flags= 0;
612
cc947f04 613 if(pkt->flags & AV_PKT_FLAG_KEY ) flags |= FLAG_KEY;
e1249ba9
MN
614 if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
615 if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
616 if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
617 if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
618 if(FFABS(pkt->pts - nus->last_pts)
619 > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
a712d725
MN
620 if( pkt->size < nut->header_len[fc->header_idx]
621 || (pkt->size > 4096 && fc->header_idx)
622 || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
623 flags |= FLAG_HEADER_IDX;
e1249ba9 624
d2062ff6 625 return flags | (fc->flags & FLAG_CODED);
e1249ba9
MN
626}
627
a712d725
MN
628static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
629 int i;
630 int best_i = 0;
631 int best_len= 0;
632
633 if(pkt->size > 4096)
634 return 0;
635
636 for(i=1; i<nut->header_count; i++){
637 if( pkt->size >= nut->header_len[i]
638 && nut->header_len[i] > best_len
639 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
640 best_i= i;
641 best_len= nut->header_len[i];
642 }
643 }
644 return best_i;
645}
646
70ea1e69 647static int write_packet(AVFormatContext *s, AVPacket *pkt){
e1249ba9
MN
648 NUTContext *nut = s->priv_data;
649 StreamContext *nus= &nut->stream[pkt->stream_index];
899681cd 650 ByteIOContext *bc = s->pb, *dyn_bc;
e1249ba9
MN
651 FrameCode *fc;
652 int64_t coded_pts;
a712d725 653 int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
cc947f04 654 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
e1249ba9 655 int store_sp=0;
899681cd 656 int ret;
e1249ba9 657
f53dd468
MN
658 if(pkt->pts < 0)
659 return -1;
660
14b3f996 661 if(1LL<<(20+3*nut->header_count) <= url_ftell(bc))
da9e6c42 662 write_headers(s, bc);
14b3f996 663
02c986a8 664 if(key_frame && !(nus->last_flags & FLAG_KEY))
e1249ba9
MN
665 store_sp= 1;
666
667 if(pkt->size + 30/*FIXME check*/ + url_ftell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
668 store_sp= 1;
669
93951943 670//FIXME: Ensure store_sp is 1 in the first place.
e1249ba9
MN
671
672 if(store_sp){
52afa376 673 Syncpoint *sp, dummy= {.pos= INT64_MAX};
7c04134f 674
e1249ba9 675 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
7c04134f
MN
676 for(i=0; i<s->nb_streams; i++){
677 AVStream *st= s->streams[i];
4ddcc983
OS
678 int64_t dts_tb = av_rescale_rnd(pkt->dts,
679 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
680 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
681 AV_ROUND_DOWN);
682 int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
175e23e8 683 if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
7c04134f 684 }
175e23e8
MN
685 if(dummy.pos == INT64_MAX)
686 dummy.pos= 0;
f990f6e3
VS
687 sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
688 NULL);
e1249ba9
MN
689
690 nut->last_syncpoint_pos= url_ftell(bc);
899681cd
BA
691 ret = url_open_dyn_buf(&dyn_bc);
692 if(ret < 0)
693 return ret;
52afa376 694 put_tt(nut, nus, dyn_bc, pkt->dts);
899681cd
BA
695 put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
696 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
7c04134f
MN
697
698 ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
e1249ba9
MN
699 }
700 assert(nus->last_pts != AV_NOPTS_VALUE);
701
702 coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
703 if(ff_lsb2full(nus, coded_pts) != pkt->pts)
704 coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
705
a712d725
MN
706 best_header_idx= find_best_header_idx(nut, pkt);
707
e1249ba9
MN
708 best_length=INT_MAX;
709 frame_code= -1;
710 for(i=0; i<256; i++){
711 int length= 0;
712 FrameCode *fc= &nut->frame_code[i];
713 int flags= fc->flags;
714
715 if(flags & FLAG_INVALID)
716 continue;
717 needed_flags= get_needed_flags(nut, nus, fc, pkt);
718
719 if(flags & FLAG_CODED){
720 length++;
63dd9d0e 721 flags = needed_flags;
e1249ba9
MN
722 }
723
724 if((flags & needed_flags) != needed_flags)
725 continue;
726
727 if((flags ^ needed_flags) & FLAG_KEY)
728 continue;
729
730 if(flags & FLAG_STREAM_ID)
731 length+= get_length(pkt->stream_index);
732
733 if(pkt->size % fc->size_mul != fc->size_lsb)
734 continue;
735 if(flags & FLAG_SIZE_MSB)
736 length += get_length(pkt->size / fc->size_mul);
737
738 if(flags & FLAG_CHECKSUM)
739 length+=4;
740
741 if(flags & FLAG_CODED_PTS)
742 length += get_length(coded_pts);
743
a712d725
MN
744 if( (flags & FLAG_CODED)
745 && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
746 flags |= FLAG_HEADER_IDX;
747 }
748
749 if(flags & FLAG_HEADER_IDX){
750 length += 1 - nut->header_len[best_header_idx];
751 }else{
752 length -= nut->header_len[fc->header_idx];
753 }
754
e1249ba9
MN
755 length*=4;
756 length+= !(flags & FLAG_CODED_PTS);
757 length+= !(flags & FLAG_CHECKSUM);
758
759 if(length < best_length){
760 best_length= length;
761 frame_code=i;
762 }
763 }
764 assert(frame_code != -1);
765 fc= &nut->frame_code[frame_code];
766 flags= fc->flags;
767 needed_flags= get_needed_flags(nut, nus, fc, pkt);
a712d725 768 header_idx= fc->header_idx;
e1249ba9 769
992e78f5 770 init_checksum(bc, ff_crc04C11DB7_update, 0);
e1249ba9
MN
771 put_byte(bc, frame_code);
772 if(flags & FLAG_CODED){
773 put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
774 flags = needed_flags;
775 }
776 if(flags & FLAG_STREAM_ID) put_v(bc, pkt->stream_index);
777 if(flags & FLAG_CODED_PTS) put_v(bc, coded_pts);
778 if(flags & FLAG_SIZE_MSB) put_v(bc, pkt->size / fc->size_mul);
a712d725 779 if(flags & FLAG_HEADER_IDX) put_v(bc, header_idx= best_header_idx);
e1249ba9
MN
780
781 if(flags & FLAG_CHECKSUM) put_le32(bc, get_checksum(bc));
782 else get_checksum(bc);
783
a712d725 784 put_buffer(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
e1249ba9 785 nus->last_flags= flags;
e942293d 786 nus->last_pts= pkt->pts;
7c04134f
MN
787
788 //FIXME just store one per syncpoint
789 if(flags & FLAG_KEY)
790 av_add_index_entry(
791 s->streams[pkt->stream_index],
792 nut->last_syncpoint_pos,
793 pkt->pts,
794 0,
795 0,
796 AVINDEX_KEYFRAME);
797
70ea1e69
MN
798 return 0;
799}
800
bd533e6c
MN
801static int write_trailer(AVFormatContext *s){
802 NUTContext *nut= s->priv_data;
899681cd 803 ByteIOContext *bc= s->pb;
bd533e6c 804
14b3f996 805 while(nut->header_count<3)
da9e6c42 806 write_headers(s, bc);
bd533e6c 807 put_flush_packet(bc);
4b83fc0f 808 ff_nut_free_sp(nut);
27dbc47c
VS
809 av_freep(&nut->stream);
810 av_freep(&nut->time_base);
bd533e6c
MN
811
812 return 0;
813}
814
70ea1e69
MN
815AVOutputFormat nut_muxer = {
816 "nut",
bde15e74 817 NULL_IF_CONFIG_SMALL("NUT format"),
70ea1e69
MN
818 "video/x-nut",
819 "nut",
820 sizeof(NUTContext),
b250f9c6 821#if CONFIG_LIBVORBIS
70ea1e69 822 CODEC_ID_VORBIS,
b250f9c6 823#elif CONFIG_LIBMP3LAME
70ea1e69
MN
824 CODEC_ID_MP3,
825#else
2d47c3de 826 CODEC_ID_MP2,
70ea1e69
MN
827#endif
828 CODEC_ID_MPEG4,
829 write_header,
830 write_packet,
bd533e6c 831 write_trailer,
25918212 832 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
2e01def0 833 .codec_tag = (const AVCodecTag * const []){ ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags, ff_nut_subtitle_tags, 0 },
43382b5f 834 .metadata_conv = ff_nut_metadata_conv,
70ea1e69 835};