assdec: fix qsort() callback signature
[libav.git] / libavformat / nutenc.c
CommitLineData
70ea1e69
MN
1/*
2 * nut muxer
3 * Copyright (c) 2004-2007 Michael Niedermayer
4 *
2912e87a 5 * This file is part of Libav.
70ea1e69 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
70ea1e69
MN
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 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
70ea1e69
MN
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
2912e87a 18 * License along with Libav; if not, write to the Free Software
70ea1e69
MN
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
6a5d31ac 22#include "libavutil/intreadwrite.h"
0ebcdf5c 23#include "libavutil/mathematics.h"
245976da 24#include "libavutil/tree.h"
d2d67e42 25#include "libavutil/dict.h"
245976da 26#include "libavcodec/mpegaudiodata.h"
70ea1e69 27#include "nut.h"
80b39e1c 28#include "internal.h"
4c4427a7 29#include "avio_internal.h"
a712d725
MN
30
31static 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
36ef5369 39 if(c->codec_id == AV_CODEC_ID_MPEG4){
a712d725
MN
40 if(key_frame){
41 return 3;
42 }else{
43 out[3]= 0xB6;
44 return 4;
45 }
36ef5369 46 }else if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO || c->codec_id == AV_CODEC_ID_MPEG2VIDEO){
a712d725 47 return 3;
36ef5369 48 }else if(c->codec_id == AV_CODEC_ID_H264){
a712d725 49 return 3;
36ef5369 50 }else if(c->codec_id == AV_CODEC_ID_MP3 || c->codec_id == AV_CODEC_ID_MP2){
a712d725 51 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
36ef5369 52 int layer= c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
a712d725
MN
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
82ab61f9 62 sample_rate= avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
a712d725
MN
63
64 for(bitrate_index=2; bitrate_index<30; bitrate_index++){
82ab61f9 65 frame_size = avpriv_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
a712d725
MN
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)
7ce68923 77 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
a712d725
MN
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()
7ce68923
DB
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
a712d725
MN
88 }
89 return 0;
90}
91
92static 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
a712d725
MN
98 for(i=1; i<nut->header_count; i++){
99 if( len == nut->header_len[i]
100 && !memcmp(out, nut->header[i], len)){
a712d725
MN
101 return i;
102 }
103 }
a712d725
MN
104 return 0;
105}
106
107static 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
1bf6e565 112 static const uint8_t headers[][5]={
a712d725
MN
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}
70ea1e69 127
70ea1e69
MN
128static 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];
0fcfa8eb
MN
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++;
70ea1e69
MN
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;
72415b2a 155 int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
70ea1e69
MN
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;
a712d725
MN
169 if(is_audio)
170 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
70ea1e69
MN
171 start2++;
172 }
173 }
174
175 key_frame= intra_only;
70ea1e69
MN
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;
a712d725 187 ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
70ea1e69
MN
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 }
70ea1e69
MN
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;
36ef5369 207 }else if(codec->codec_id == AV_CODEC_ID_VORBIS){
70ea1e69
MN
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];
a712d725
MN
230 if(is_audio)
231 ft->header_idx= find_header_idx(s, codec, -1, key_frame);
70ea1e69
MN
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
073f8b10 241static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
491216c6 242 val *= nut->time_base_count;
073f8b10 243 val += time_base - nut->time_base;
f8280ff4 244 ff_put_v(bc, val);
491216c6
MN
245}
246
70ea1e69 247/**
49bd8e4b 248 * Store a string as vb.
70ea1e69 249 */
ae628ec1 250static void put_str(AVIOContext *bc, const char *string){
70ea1e69
MN
251 int len= strlen(string);
252
f8280ff4 253 ff_put_v(bc, len);
77eb5504 254 avio_write(bc, string, len);
70ea1e69
MN
255}
256
ae628ec1 257static void put_s(AVIOContext *bc, int64_t val){
f8280ff4 258 ff_put_v(bc, 2*FFABS(val) - (val>0));
70ea1e69
MN
259}
260
261#ifdef TRACE
bc66827f
DB
262static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
263 const char *func, int line)
264{
f8280ff4 265 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69 266
f8280ff4 267 ff_put_v(bc, v);
70ea1e69
MN
268}
269
bc66827f
DB
270static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
271 const char *func, int line)
272{
7a26da44 273 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69
MN
274
275 put_s(bc, v);
276}
f8280ff4 277#define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
70ea1e69
MN
278#define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
279#endif
280
34f8cc38 281//FIXME remove calculate_checksum
ae628ec1 282static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
8d9a3f7e 283 uint8_t *dyn_buf=NULL;
6dc7d80d 284 int dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
6c666941
MN
285 int forw_ptr= dyn_size + 4*calculate_checksum;
286
287 if(forw_ptr > 4096)
4c4427a7 288 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504 289 avio_wb64(bc, startcode);
f8280ff4 290 ff_put_v(bc, forw_ptr);
6c666941 291 if(forw_ptr > 4096)
b64030f2 292 avio_wl32(bc, ffio_get_checksum(bc));
70ea1e69
MN
293
294 if(calculate_checksum)
4c4427a7 295 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504 296 avio_write(bc, dyn_buf, dyn_size);
70ea1e69 297 if(calculate_checksum)
b64030f2 298 avio_wl32(bc, ffio_get_checksum(bc));
70ea1e69 299
8d9a3f7e 300 av_free(dyn_buf);
70ea1e69
MN
301}
302
ae628ec1 303static void write_mainheader(NUTContext *nut, AVIOContext *bc){
a712d725
MN
304 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
305 int64_t tmp_match;
70ea1e69 306
f8280ff4
MC
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);
70ea1e69
MN
311
312 for(i=0; i<nut->time_base_count; i++){
f8280ff4
MC
313 ff_put_v(bc, nut->time_base[i].num);
314 ff_put_v(bc, nut->time_base[i].den);
70ea1e69
MN
315 }
316
70ea1e69
MN
317 tmp_pts=0;
318 tmp_mul=1;
319 tmp_stream=0;
a712d725
MN
320 tmp_match= 1-(1LL<<62);
321 tmp_head_idx= 0;
70ea1e69
MN
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;
a712d725 331 if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
70ea1e69
MN
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;
a712d725 339 tmp_head_idx= nut->frame_code[i].header_idx;
70ea1e69
MN
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;
a712d725 352 if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
70ea1e69
MN
353 }
354 if(j != tmp_mul - tmp_size) tmp_fields=6;
355
f8280ff4
MC
356 ff_put_v(bc, tmp_flags);
357 ff_put_v(bc, tmp_fields);
70ea1e69 358 if(tmp_fields>0) put_s(bc, tmp_pts);
f8280ff4
MC
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);
a712d725 366 }
f8280ff4 367 ff_put_v(bc, nut->header_count-1);
a712d725 368 for(i=1; i<nut->header_count; i++){
f8280ff4 369 ff_put_v(bc, nut->header_len[i]);
77eb5504 370 avio_write(bc, nut->header[i], nut->header_len[i]);
70ea1e69 371 }
97d5eb11 372}
70ea1e69 373
ae628ec1 374static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
da9e6c42 375 NUTContext *nut = avctx->priv_data;
59729451 376 AVCodecContext *codec = st->codec;
1bd442c2
LB
377 unsigned codec_tag = av_codec_get_tag(ff_nut_codec_tags, codec->codec_id);
378
f8280ff4 379 ff_put_v(bc, i);
0809b51e 380 switch(codec->codec_type){
f8280ff4
MC
381 case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
382 case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
383 case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
384 default : ff_put_v(bc, 3); break;
0809b51e 385 }
f8280ff4 386 ff_put_v(bc, 4);
1bd442c2 387
21de6ba5 388 if (!codec_tag || codec->codec_id == AV_CODEC_ID_RAWVIDEO)
1bd442c2
LB
389 codec_tag = codec->codec_tag;
390
391 if (codec_tag) {
392 avio_wl32(bc, codec_tag);
fa586439
SS
393 } else {
394 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
ffd5f098 395 return AVERROR(EINVAL);
fa586439 396 }
0809b51e 397
f8280ff4
MC
398 ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
399 ff_put_v(bc, nut->stream[i].msb_pts_shift);
400 ff_put_v(bc, nut->stream[i].max_pts_distance);
401 ff_put_v(bc, codec->has_b_frames);
77eb5504 402 avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
0809b51e 403
f8280ff4 404 ff_put_v(bc, codec->extradata_size);
77eb5504 405 avio_write(bc, codec->extradata, codec->extradata_size);
0809b51e
MN
406
407 switch(codec->codec_type){
72415b2a 408 case AVMEDIA_TYPE_AUDIO:
f8280ff4
MC
409 ff_put_v(bc, codec->sample_rate);
410 ff_put_v(bc, 1);
411 ff_put_v(bc, codec->channels);
0809b51e 412 break;
72415b2a 413 case AVMEDIA_TYPE_VIDEO:
f8280ff4
MC
414 ff_put_v(bc, codec->width);
415 ff_put_v(bc, codec->height);
0a5790d1 416
59729451 417 if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
f8280ff4
MC
418 ff_put_v(bc, 0);
419 ff_put_v(bc, 0);
0a5790d1 420 }else{
f8280ff4
MC
421 ff_put_v(bc, st->sample_aspect_ratio.num);
422 ff_put_v(bc, st->sample_aspect_ratio.den);
0a5790d1 423 }
f8280ff4 424 ff_put_v(bc, 0); /* csp type -- unknown */
0809b51e
MN
425 break;
426 default:
427 break;
428 }
429 return 0;
430}
431
ae628ec1 432static int add_info(AVIOContext *bc, const char *type, const char *value){
ead1939f
MN
433 put_str(bc, type);
434 put_s(bc, -1);
435 put_str(bc, value);
436 return 1;
437}
438
ae628ec1 439static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
ead1939f 440 AVFormatContext *s= nut->avf;
d2d67e42 441 AVDictionaryEntry *t = NULL;
ae628ec1 442 AVIOContext *dyn_bc;
ead1939f
MN
443 uint8_t *dyn_buf=NULL;
444 int count=0, dyn_size;
b92c5452 445 int ret = avio_open_dyn_buf(&dyn_bc);
899681cd
BA
446 if(ret < 0)
447 return ret;
ead1939f 448
d2d67e42 449 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
43382b5f 450 count += add_info(dyn_bc, t->key, t->value);
ead1939f 451
f8280ff4
MC
452 ff_put_v(bc, 0); //stream_if_plus1
453 ff_put_v(bc, 0); //chapter_id
454 ff_put_v(bc, 0); //timestamp_start
455 ff_put_v(bc, 0); //length
ead1939f 456
f8280ff4 457 ff_put_v(bc, count);
ead1939f 458
6dc7d80d 459 dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
77eb5504 460 avio_write(bc, dyn_buf, dyn_size);
ead1939f 461 av_free(dyn_buf);
899681cd 462 return 0;
ead1939f
MN
463}
464
ae628ec1 465static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
90c2295b
ES
466 AVFormatContext *s= nut->avf;
467 AVStream* st = s->streams[stream_id];
ae628ec1 468 AVIOContext *dyn_bc;
90c2295b
ES
469 uint8_t *dyn_buf=NULL;
470 int count=0, dyn_size, i;
b92c5452 471 int ret = avio_open_dyn_buf(&dyn_bc);
90c2295b
ES
472 if(ret < 0)
473 return ret;
474
475 for (i=0; ff_nut_dispositions[i].flag; ++i) {
476 if (st->disposition & ff_nut_dispositions[i].flag)
477 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
478 }
6dc7d80d 479 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
90c2295b
ES
480
481 if (count) {
f8280ff4
MC
482 ff_put_v(bc, stream_id + 1); //stream_id_plus1
483 ff_put_v(bc, 0); //chapter_id
484 ff_put_v(bc, 0); //timestamp_start
485 ff_put_v(bc, 0); //length
90c2295b 486
f8280ff4 487 ff_put_v(bc, count);
90c2295b 488
77eb5504 489 avio_write(bc, dyn_buf, dyn_size);
90c2295b
ES
490 }
491
492 av_free(dyn_buf);
493 return count;
494}
495
073f8b10
AK
496static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
497{
498 AVIOContext *dyn_bc;
499 uint8_t *dyn_buf = NULL;
d2d67e42 500 AVDictionaryEntry *t = NULL;
073f8b10
AK
501 AVChapter *ch = nut->avf->chapters[id];
502 int ret, dyn_size, count = 0;
503
b92c5452 504 ret = avio_open_dyn_buf(&dyn_bc);
073f8b10
AK
505 if (ret < 0)
506 return ret;
507
508 ff_put_v(bc, 0); // stream_id_plus1
509 put_s(bc, id + 1); // chapter_id
510 put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
511 ff_put_v(bc, ch->end - ch->start); // chapter_len
512
d2d67e42 513 while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
073f8b10
AK
514 count += add_info(dyn_bc, t->key, t->value);
515
516 ff_put_v(bc, count);
517
6dc7d80d 518 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
073f8b10
AK
519 avio_write(bc, dyn_buf, dyn_size);
520 av_freep(&dyn_buf);
521 return 0;
522}
523
ae628ec1 524static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
da9e6c42 525 NUTContext *nut = avctx->priv_data;
ae628ec1 526 AVIOContext *dyn_bc;
899681cd 527 int i, ret;
7e506494 528
03700d39
AK
529 ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
530
b92c5452 531 ret = avio_open_dyn_buf(&dyn_bc);
899681cd
BA
532 if(ret < 0)
533 return ret;
534 write_mainheader(nut, dyn_bc);
535 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
7e506494
MN
536
537 for (i=0; i < nut->avf->nb_streams; i++){
b92c5452 538 ret = avio_open_dyn_buf(&dyn_bc);
899681cd
BA
539 if(ret < 0)
540 return ret;
fc0c4124
SS
541 if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
542 return ret;
899681cd 543 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
7e506494 544 }
ead1939f 545
b92c5452 546 ret = avio_open_dyn_buf(&dyn_bc);
899681cd
BA
547 if(ret < 0)
548 return ret;
549 write_globalinfo(nut, dyn_bc);
550 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
14b3f996 551
90c2295b 552 for (i = 0; i < nut->avf->nb_streams; i++) {
b92c5452 553 ret = avio_open_dyn_buf(&dyn_bc);
90c2295b
ES
554 if(ret < 0)
555 return ret;
556 ret = write_streaminfo(nut, dyn_bc, i);
557 if (ret < 0)
558 return ret;
559 if (ret > 0)
560 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
561 else {
562 uint8_t* buf;
6dc7d80d 563 avio_close_dyn_buf(dyn_bc, &buf);
90c2295b
ES
564 av_free(buf);
565 }
566 }
567
073f8b10 568 for (i = 0; i < nut->avf->nb_chapters; i++) {
b92c5452 569 ret = avio_open_dyn_buf(&dyn_bc);
073f8b10
AK
570 if (ret < 0)
571 return ret;
572 ret = write_chapter(nut, dyn_bc, i);
573 if (ret < 0) {
574 uint8_t *buf;
6dc7d80d 575 avio_close_dyn_buf(dyn_bc, &buf);
073f8b10
AK
576 av_freep(&buf);
577 return ret;
578 }
579 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
580 }
581
14b3f996
MN
582 nut->last_syncpoint_pos= INT_MIN;
583 nut->header_count++;
899681cd 584 return 0;
7e506494
MN
585}
586
5ee5dc4e 587static int nut_write_header(AVFormatContext *s){
97d5eb11 588 NUTContext *nut = s->priv_data;
ae628ec1 589 AVIOContext *bc = s->pb;
fc0c4124 590 int i, j, ret;
97d5eb11
MN
591
592 nut->avf= s;
593
594 nut->stream = av_mallocz(sizeof(StreamContext)*s->nb_streams);
25588d3b
RB
595 if (s->nb_chapters)
596 nut->chapter = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
073f8b10
AK
597 nut->time_base= av_mallocz(sizeof(AVRational )*(s->nb_streams +
598 s->nb_chapters));
76432655
RB
599 if (!nut->stream || (s->nb_chapters && !nut->chapter) || !nut->time_base) {
600 av_freep(&nut->stream);
601 av_freep(&nut->chapter);
602 av_freep(&nut->time_base);
603 return AVERROR(ENOMEM);
604 }
97d5eb11
MN
605
606 for(i=0; i<s->nb_streams; i++){
607 AVStream *st= s->streams[i];
608 int ssize;
609 AVRational time_base;
610 ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
611
c3f9ebf7 612 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
97d5eb11
MN
613
614 for(j=0; j<nut->time_base_count; j++){
615 if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
616 break;
617 }
618 }
619 nut->time_base[j]= time_base;
620 nut->stream[i].time_base= &nut->time_base[j];
621 if(j==nut->time_base_count)
622 nut->time_base_count++;
623
324d22b2 624 if(INT64_C(1000) * time_base.num >= time_base.den)
97d5eb11
MN
625 nut->stream[i].msb_pts_shift = 7;
626 else
627 nut->stream[i].msb_pts_shift = 14;
324d22b2 628 nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
97d5eb11
MN
629 }
630
073f8b10
AK
631 for (i = 0; i < s->nb_chapters; i++) {
632 AVChapter *ch = s->chapters[i];
633
634 for (j = 0; j < nut->time_base_count; j++) {
635 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
636 break;
637 }
638
639 nut->time_base[j] = ch->time_base;
640 nut->chapter[i].time_base = &nut->time_base[j];
641 if(j == nut->time_base_count)
642 nut->time_base_count++;
643 }
644
82badd27 645 nut->max_distance = MAX_DISTANCE;
a712d725 646 build_elision_headers(s);
97d5eb11
MN
647 build_frame_code(s);
648 assert(nut->frame_code['N'].flags == FLAG_INVALID);
649
77eb5504
AK
650 avio_write(bc, ID_STRING, strlen(ID_STRING));
651 avio_w8(bc, 0);
97d5eb11 652
fc0c4124
SS
653 if ((ret = write_headers(s, bc)) < 0)
654 return ret;
dcc9bde0 655
b7f2fdde 656 avio_flush(bc);
70ea1e69 657
14b3f996 658 //FIXME index
70ea1e69
MN
659
660 return 0;
661}
662
e1249ba9
MN
663static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
664 int flags= 0;
665
cc947f04 666 if(pkt->flags & AV_PKT_FLAG_KEY ) flags |= FLAG_KEY;
e1249ba9
MN
667 if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
668 if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
669 if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
670 if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
671 if(FFABS(pkt->pts - nus->last_pts)
672 > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
a712d725
MN
673 if( pkt->size < nut->header_len[fc->header_idx]
674 || (pkt->size > 4096 && fc->header_idx)
675 || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
676 flags |= FLAG_HEADER_IDX;
e1249ba9 677
d2062ff6 678 return flags | (fc->flags & FLAG_CODED);
e1249ba9
MN
679}
680
a712d725
MN
681static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
682 int i;
683 int best_i = 0;
684 int best_len= 0;
685
686 if(pkt->size > 4096)
687 return 0;
688
689 for(i=1; i<nut->header_count; i++){
690 if( pkt->size >= nut->header_len[i]
691 && nut->header_len[i] > best_len
692 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
693 best_i= i;
694 best_len= nut->header_len[i];
695 }
696 }
697 return best_i;
698}
699
5ee5dc4e 700static int nut_write_packet(AVFormatContext *s, AVPacket *pkt){
e1249ba9
MN
701 NUTContext *nut = s->priv_data;
702 StreamContext *nus= &nut->stream[pkt->stream_index];
ae628ec1 703 AVIOContext *bc = s->pb, *dyn_bc;
e1249ba9
MN
704 FrameCode *fc;
705 int64_t coded_pts;
a712d725 706 int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
cc947f04 707 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
e1249ba9 708 int store_sp=0;
899681cd 709 int ret;
e1249ba9 710
f53dd468
MN
711 if(pkt->pts < 0)
712 return -1;
713
a2704c97 714 if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
da9e6c42 715 write_headers(s, bc);
14b3f996 716
02c986a8 717 if(key_frame && !(nus->last_flags & FLAG_KEY))
e1249ba9
MN
718 store_sp= 1;
719
a2704c97 720 if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
e1249ba9
MN
721 store_sp= 1;
722
93951943 723//FIXME: Ensure store_sp is 1 in the first place.
e1249ba9
MN
724
725 if(store_sp){
52afa376 726 Syncpoint *sp, dummy= {.pos= INT64_MAX};
7c04134f 727
e1249ba9 728 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
7c04134f
MN
729 for(i=0; i<s->nb_streams; i++){
730 AVStream *st= s->streams[i];
4ddcc983
OS
731 int64_t dts_tb = av_rescale_rnd(pkt->dts,
732 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
733 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
734 AV_ROUND_DOWN);
735 int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
175e23e8 736 if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
7c04134f 737 }
175e23e8
MN
738 if(dummy.pos == INT64_MAX)
739 dummy.pos= 0;
f990f6e3
VS
740 sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
741 NULL);
e1249ba9 742
a2704c97 743 nut->last_syncpoint_pos= avio_tell(bc);
b92c5452 744 ret = avio_open_dyn_buf(&dyn_bc);
899681cd
BA
745 if(ret < 0)
746 return ret;
073f8b10 747 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
f8280ff4 748 ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
899681cd 749 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
7c04134f
MN
750
751 ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
e1249ba9
MN
752 }
753 assert(nus->last_pts != AV_NOPTS_VALUE);
754
755 coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
756 if(ff_lsb2full(nus, coded_pts) != pkt->pts)
757 coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
758
a712d725
MN
759 best_header_idx= find_best_header_idx(nut, pkt);
760
e1249ba9
MN
761 best_length=INT_MAX;
762 frame_code= -1;
763 for(i=0; i<256; i++){
764 int length= 0;
765 FrameCode *fc= &nut->frame_code[i];
766 int flags= fc->flags;
767
768 if(flags & FLAG_INVALID)
769 continue;
770 needed_flags= get_needed_flags(nut, nus, fc, pkt);
771
772 if(flags & FLAG_CODED){
773 length++;
63dd9d0e 774 flags = needed_flags;
e1249ba9
MN
775 }
776
777 if((flags & needed_flags) != needed_flags)
778 continue;
779
780 if((flags ^ needed_flags) & FLAG_KEY)
781 continue;
782
783 if(flags & FLAG_STREAM_ID)
f8280ff4 784 length+= ff_get_v_length(pkt->stream_index);
e1249ba9
MN
785
786 if(pkt->size % fc->size_mul != fc->size_lsb)
787 continue;
788 if(flags & FLAG_SIZE_MSB)
f8280ff4 789 length += ff_get_v_length(pkt->size / fc->size_mul);
e1249ba9
MN
790
791 if(flags & FLAG_CHECKSUM)
792 length+=4;
793
794 if(flags & FLAG_CODED_PTS)
f8280ff4 795 length += ff_get_v_length(coded_pts);
e1249ba9 796
a712d725
MN
797 if( (flags & FLAG_CODED)
798 && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
799 flags |= FLAG_HEADER_IDX;
800 }
801
802 if(flags & FLAG_HEADER_IDX){
803 length += 1 - nut->header_len[best_header_idx];
804 }else{
805 length -= nut->header_len[fc->header_idx];
806 }
807
e1249ba9
MN
808 length*=4;
809 length+= !(flags & FLAG_CODED_PTS);
810 length+= !(flags & FLAG_CHECKSUM);
811
812 if(length < best_length){
813 best_length= length;
814 frame_code=i;
815 }
816 }
817 assert(frame_code != -1);
818 fc= &nut->frame_code[frame_code];
819 flags= fc->flags;
820 needed_flags= get_needed_flags(nut, nus, fc, pkt);
a712d725 821 header_idx= fc->header_idx;
e1249ba9 822
4c4427a7 823 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504 824 avio_w8(bc, frame_code);
e1249ba9 825 if(flags & FLAG_CODED){
f8280ff4 826 ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
e1249ba9
MN
827 flags = needed_flags;
828 }
f8280ff4
MC
829 if(flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
830 if(flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
831 if(flags & FLAG_SIZE_MSB) ff_put_v(bc, pkt->size / fc->size_mul);
832 if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
e1249ba9 833
b64030f2
AK
834 if(flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
835 else ffio_get_checksum(bc);
e1249ba9 836
77eb5504 837 avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
e1249ba9 838 nus->last_flags= flags;
e942293d 839 nus->last_pts= pkt->pts;
7c04134f
MN
840
841 //FIXME just store one per syncpoint
842 if(flags & FLAG_KEY)
843 av_add_index_entry(
844 s->streams[pkt->stream_index],
845 nut->last_syncpoint_pos,
846 pkt->pts,
847 0,
848 0,
849 AVINDEX_KEYFRAME);
850
70ea1e69
MN
851 return 0;
852}
853
5ee5dc4e 854static int nut_write_trailer(AVFormatContext *s){
bd533e6c 855 NUTContext *nut= s->priv_data;
ae628ec1 856 AVIOContext *bc= s->pb;
bd533e6c 857
14b3f996 858 while(nut->header_count<3)
da9e6c42 859 write_headers(s, bc);
3b4bb19e 860
4b83fc0f 861 ff_nut_free_sp(nut);
27dbc47c 862 av_freep(&nut->stream);
2cface71 863 av_freep(&nut->chapter);
27dbc47c 864 av_freep(&nut->time_base);
bd533e6c
MN
865
866 return 0;
867}
868
c6610a21 869AVOutputFormat ff_nut_muxer = {
dfc2c4d9 870 .name = "nut",
6774247a 871 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
dfc2c4d9
AK
872 .mime_type = "video/x-nut",
873 .extensions = "nut",
874 .priv_data_size = sizeof(NUTContext),
36ef5369
AK
875 .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
876 CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
877 .video_codec = AV_CODEC_ID_MPEG4,
5ee5dc4e
LB
878 .write_header = nut_write_header,
879 .write_packet = nut_write_packet,
880 .write_trailer = nut_write_trailer,
20234a4b 881 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1bd442c2 882 .codec_tag = ff_nut_codec_tags,
70ea1e69 883};