lavf: add the notimestamps flag to the muxers missing it
[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 <stdint.h>
23
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/tree.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/time.h"
29 #include "libavutil/opt.h"
30 #include "libavcodec/mpegaudiodata.h"
31 #include "nut.h"
32 #include "internal.h"
33 #include "avio_internal.h"
34 #include "riff.h"
35
36 static int find_expected_header(AVCodecContext *c, int size, int key_frame,
37 uint8_t out[64])
38 {
39 int sample_rate = c->sample_rate;
40
41 if (size > 4096)
42 return 0;
43
44 AV_WB24(out, 1);
45
46 if (c->codec_id == AV_CODEC_ID_MPEG4) {
47 if (key_frame) {
48 return 3;
49 } else {
50 out[3] = 0xB6;
51 return 4;
52 }
53 } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
54 c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
55 return 3;
56 } else if (c->codec_id == AV_CODEC_ID_H264) {
57 return 3;
58 } else if (c->codec_id == AV_CODEC_ID_MP3 ||
59 c->codec_id == AV_CODEC_ID_MP2) {
60 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
61 int layer = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
62 unsigned int header = 0xFFF00000;
63
64 lsf = sample_rate < (24000 + 32000) / 2;
65 mpeg25 = sample_rate < (12000 + 16000) / 2;
66 sample_rate <<= lsf + mpeg25;
67 if (sample_rate < (32000 + 44100) / 2)
68 sample_rate_index = 2;
69 else if (sample_rate < (44100 + 48000) / 2)
70 sample_rate_index = 0;
71 else
72 sample_rate_index = 1;
73
74 sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
75
76 for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
77 frame_size =
78 avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
79 frame_size = (frame_size * 144000) / (sample_rate << lsf) +
80 (bitrate_index & 1);
81
82 if (frame_size == size)
83 break;
84 }
85
86 header |= (!lsf) << 19;
87 header |= (4 - layer) << 17;
88 header |= 1 << 16; //no crc
89 AV_WB32(out, header);
90 if (size <= 0)
91 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
92 if (bitrate_index == 30)
93 return -1; //something is wrong ...
94
95 header |= (bitrate_index >> 1) << 12;
96 header |= sample_rate_index << 10;
97 header |= (bitrate_index & 1) << 9;
98
99 return 2; //FIXME actually put the needed ones in build_elision_headers()
100 //return 3; //we guess that the private bit is not set
101 //FIXME the above assumptions should be checked, if these turn out false too often something should be done
102 }
103 return 0;
104 }
105
106 static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size,
107 int frame_type)
108 {
109 NUTContext *nut = s->priv_data;
110 uint8_t out[64];
111 int i;
112 int len = find_expected_header(c, size, frame_type, out);
113
114 for (i = 1; i < nut->header_count; i++) {
115 if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
116 return i;
117 }
118 }
119
120 return 0;
121 }
122
123 static void build_elision_headers(AVFormatContext *s)
124 {
125 NUTContext *nut = s->priv_data;
126 int i;
127 //FIXME this is lame
128 //FIXME write a 2pass mode to find the maximal headers
129 static const uint8_t headers[][5] = {
130 { 3, 0x00, 0x00, 0x01 },
131 { 4, 0x00, 0x00, 0x01, 0xB6},
132 { 2, 0xFF, 0xFA }, //mp3+crc
133 { 2, 0xFF, 0xFB }, //mp3
134 { 2, 0xFF, 0xFC }, //mp2+crc
135 { 2, 0xFF, 0xFD }, //mp2
136 };
137
138 nut->header_count = 7;
139 for (i = 1; i < nut->header_count; i++) {
140 nut->header_len[i] = headers[i - 1][0];
141 nut->header[i] = &headers[i - 1][1];
142 }
143 }
144
145 static void build_frame_code(AVFormatContext *s)
146 {
147 NUTContext *nut = s->priv_data;
148 int key_frame, index, pred, stream_id;
149 int start = 1;
150 int end = 254;
151 int keyframe_0_esc = s->nb_streams > 2;
152 int pred_table[10];
153 FrameCode *ft;
154
155 ft = &nut->frame_code[start];
156 ft->flags = FLAG_CODED;
157 ft->size_mul = 1;
158 ft->pts_delta = 1;
159 start++;
160
161 if (keyframe_0_esc) {
162 /* keyframe = 0 escape */
163 FrameCode *ft = &nut->frame_code[start];
164 ft->flags = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
165 ft->size_mul = 1;
166 start++;
167 }
168
169 for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
170 int start2 = start + (end - start) * stream_id / s->nb_streams;
171 int end2 = start + (end - start) * (stream_id + 1) / s->nb_streams;
172 AVCodecContext *codec = s->streams[stream_id]->codec;
173 int is_audio = codec->codec_type == AVMEDIA_TYPE_AUDIO;
174 int intra_only = /*codec->intra_only || */ is_audio;
175 int pred_count;
176
177 for (key_frame = 0; key_frame < 2; key_frame++) {
178 if (!intra_only || !keyframe_0_esc || key_frame != 0) {
179 FrameCode *ft = &nut->frame_code[start2];
180 ft->flags = FLAG_KEY * key_frame;
181 ft->flags |= FLAG_SIZE_MSB | FLAG_CODED_PTS;
182 ft->stream_id = stream_id;
183 ft->size_mul = 1;
184 if (is_audio)
185 ft->header_idx = find_header_idx(s, codec, -1, key_frame);
186 start2++;
187 }
188 }
189
190 key_frame = intra_only;
191 if (is_audio) {
192 int frame_bytes = codec->frame_size * (int64_t)codec->bit_rate /
193 (8 * codec->sample_rate);
194 int pts;
195 for (pts = 0; pts < 2; pts++)
196 for (pred = 0; pred < 2; pred++) {
197 FrameCode *ft = &nut->frame_code[start2];
198 ft->flags = FLAG_KEY * key_frame;
199 ft->stream_id = stream_id;
200 ft->size_mul = frame_bytes + 2;
201 ft->size_lsb = frame_bytes + pred;
202 ft->pts_delta = pts;
203 ft->header_idx = find_header_idx(s, codec, frame_bytes + pred, key_frame);
204 start2++;
205 }
206 } else {
207 FrameCode *ft = &nut->frame_code[start2];
208 ft->flags = FLAG_KEY | FLAG_SIZE_MSB;
209 ft->stream_id = stream_id;
210 ft->size_mul = 1;
211 ft->pts_delta = 1;
212 start2++;
213 }
214
215 if (codec->has_b_frames) {
216 pred_count = 5;
217 pred_table[0] = -2;
218 pred_table[1] = -1;
219 pred_table[2] = 1;
220 pred_table[3] = 3;
221 pred_table[4] = 4;
222 } else if (codec->codec_id == AV_CODEC_ID_VORBIS) {
223 pred_count = 3;
224 pred_table[0] = 2;
225 pred_table[1] = 9;
226 pred_table[2] = 16;
227 } else {
228 pred_count = 1;
229 pred_table[0] = 1;
230 }
231
232 for (pred = 0; pred < pred_count; pred++) {
233 int start3 = start2 + (end2 - start2) * pred / pred_count;
234 int end3 = start2 + (end2 - start2) * (pred + 1) / pred_count;
235
236 for (index = start3; index < end3; index++) {
237 FrameCode *ft = &nut->frame_code[index];
238 ft->flags = FLAG_KEY * key_frame;
239 ft->flags |= FLAG_SIZE_MSB;
240 ft->stream_id = stream_id;
241 //FIXME use single byte size and pred from last
242 ft->size_mul = end3 - start3;
243 ft->size_lsb = index - start3;
244 ft->pts_delta = pred_table[pred];
245 if (is_audio)
246 ft->header_idx = find_header_idx(s, codec, -1, key_frame);
247 }
248 }
249 }
250 memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'],
251 sizeof(FrameCode) * (255 - 'N'));
252 nut->frame_code[0].flags =
253 nut->frame_code[255].flags =
254 nut->frame_code['N'].flags = FLAG_INVALID;
255 }
256
257 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc,
258 uint64_t val)
259 {
260 val *= nut->time_base_count;
261 val += time_base - nut->time_base;
262 ff_put_v(bc, val);
263 }
264 /**
265 * Store a string as vb.
266 */
267 static void put_str(AVIOContext *bc, const char *string)
268 {
269 int len = strlen(string);
270
271 ff_put_v(bc, len);
272 avio_write(bc, string, len);
273 }
274
275 static void put_s(AVIOContext *bc, int64_t val)
276 {
277 ff_put_v(bc, 2 * FFABS(val) - (val > 0));
278 }
279
280 #ifdef TRACE
281 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
282 const char *func, int line)
283 {
284 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
285
286 ff_put_v(bc, v);
287 }
288
289 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file,
290 const char *func, int line)
291 {
292 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
293
294 put_s(bc, v);
295 }
296 #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
297 #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
298 #endif
299
300 //FIXME remove calculate_checksum
301 static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc,
302 int calculate_checksum, uint64_t startcode)
303 {
304 uint8_t *dyn_buf = NULL;
305 int dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
306 int forw_ptr = dyn_size + 4 * calculate_checksum;
307
308 if (forw_ptr > 4096)
309 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
310 avio_wb64(bc, startcode);
311 ff_put_v(bc, forw_ptr);
312 if (forw_ptr > 4096)
313 avio_wl32(bc, ffio_get_checksum(bc));
314
315 if (calculate_checksum)
316 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
317 avio_write(bc, dyn_buf, dyn_size);
318 if (calculate_checksum)
319 avio_wl32(bc, ffio_get_checksum(bc));
320
321 av_free(dyn_buf);
322 }
323
324 static void write_mainheader(NUTContext *nut, AVIOContext *bc)
325 {
326 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,
327 tmp_head_idx;
328 int64_t tmp_match;
329
330 ff_put_v(bc, nut->version);
331 ff_put_v(bc, nut->avf->nb_streams);
332 ff_put_v(bc, nut->max_distance);
333 ff_put_v(bc, nut->time_base_count);
334
335 for (i = 0; i < nut->time_base_count; i++) {
336 ff_put_v(bc, nut->time_base[i].num);
337 ff_put_v(bc, nut->time_base[i].den);
338 }
339
340 tmp_pts = 0;
341 tmp_mul = 1;
342 tmp_stream = 0;
343 tmp_match = 1 - (1LL << 62);
344 tmp_head_idx = 0;
345 for (i = 0; i < 256; ) {
346 tmp_fields = 0;
347 tmp_size = 0;
348 // tmp_res=0;
349 if (tmp_pts != nut->frame_code[i].pts_delta)
350 tmp_fields = 1;
351 if (tmp_mul != nut->frame_code[i].size_mul)
352 tmp_fields = 2;
353 if (tmp_stream != nut->frame_code[i].stream_id)
354 tmp_fields = 3;
355 if (tmp_size != nut->frame_code[i].size_lsb)
356 tmp_fields = 4;
357 // if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
358 if (tmp_head_idx != nut->frame_code[i].header_idx)
359 tmp_fields = 8;
360
361 tmp_pts = nut->frame_code[i].pts_delta;
362 tmp_flags = nut->frame_code[i].flags;
363 tmp_stream = nut->frame_code[i].stream_id;
364 tmp_mul = nut->frame_code[i].size_mul;
365 tmp_size = nut->frame_code[i].size_lsb;
366 // tmp_res = nut->frame_code[i].res;
367 tmp_head_idx = nut->frame_code[i].header_idx;
368
369 for (j = 0; i < 256; j++, i++) {
370 if (i == 'N') {
371 j--;
372 continue;
373 }
374 if (nut->frame_code[i].pts_delta != tmp_pts ||
375 nut->frame_code[i].flags != tmp_flags ||
376 nut->frame_code[i].stream_id != tmp_stream ||
377 nut->frame_code[i].size_mul != tmp_mul ||
378 nut->frame_code[i].size_lsb != tmp_size + j ||
379 // nut->frame_code[i].res != tmp_res ||
380 nut->frame_code[i].header_idx != tmp_head_idx)
381 break;
382 }
383 if (j != tmp_mul - tmp_size)
384 tmp_fields = 6;
385
386 ff_put_v(bc, tmp_flags);
387 ff_put_v(bc, tmp_fields);
388 if (tmp_fields > 0)
389 put_s(bc, tmp_pts);
390 if (tmp_fields > 1)
391 ff_put_v(bc, tmp_mul);
392 if (tmp_fields > 2)
393 ff_put_v(bc, tmp_stream);
394 if (tmp_fields > 3)
395 ff_put_v(bc, tmp_size);
396 if (tmp_fields > 4)
397 ff_put_v(bc, 0 /*tmp_res*/);
398 if (tmp_fields > 5)
399 ff_put_v(bc, j);
400 if (tmp_fields > 6)
401 ff_put_v(bc, tmp_match);
402 if (tmp_fields > 7)
403 ff_put_v(bc, tmp_head_idx);
404 }
405 ff_put_v(bc, nut->header_count - 1);
406 for (i = 1; i < nut->header_count; i++) {
407 ff_put_v(bc, nut->header_len[i]);
408 avio_write(bc, nut->header[i], nut->header_len[i]);
409 }
410 // flags had been effectively introduced in version 4
411 if (nut->version > NUT_STABLE_VERSION)
412 ff_put_v(bc, nut->flags);
413 }
414
415 static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
416 AVStream *st, int i)
417 {
418 NUTContext *nut = avctx->priv_data;
419 AVCodecContext *codec = st->codec;
420 unsigned codec_tag = av_codec_get_tag(ff_nut_codec_tags, codec->codec_id);
421
422 ff_put_v(bc, i);
423 switch (codec->codec_type) {
424 case AVMEDIA_TYPE_VIDEO:
425 ff_put_v(bc, 0);
426 break;
427 case AVMEDIA_TYPE_AUDIO:
428 ff_put_v(bc, 1);
429 break;
430 case AVMEDIA_TYPE_SUBTITLE:
431 ff_put_v(bc, 2);
432 break;
433 default:
434 ff_put_v(bc, 3);
435 break;
436 }
437 ff_put_v(bc, 4);
438
439 if (!codec_tag || codec->codec_id == AV_CODEC_ID_RAWVIDEO)
440 codec_tag = codec->codec_tag;
441
442 if (codec_tag) {
443 avio_wl32(bc, codec_tag);
444 } else {
445 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
446 return AVERROR(EINVAL);
447 }
448
449 ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
450 ff_put_v(bc, nut->stream[i].msb_pts_shift);
451 ff_put_v(bc, nut->stream[i].max_pts_distance);
452 ff_put_v(bc, codec->has_b_frames);
453 avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
454
455 ff_put_v(bc, codec->extradata_size);
456 avio_write(bc, codec->extradata, codec->extradata_size);
457
458 switch (codec->codec_type) {
459 case AVMEDIA_TYPE_AUDIO:
460 ff_put_v(bc, codec->sample_rate);
461 ff_put_v(bc, 1);
462 ff_put_v(bc, codec->channels);
463 break;
464 case AVMEDIA_TYPE_VIDEO:
465 ff_put_v(bc, codec->width);
466 ff_put_v(bc, codec->height);
467
468 if (st->sample_aspect_ratio.num <= 0 ||
469 st->sample_aspect_ratio.den <= 0) {
470 ff_put_v(bc, 0);
471 ff_put_v(bc, 0);
472 } else {
473 ff_put_v(bc, st->sample_aspect_ratio.num);
474 ff_put_v(bc, st->sample_aspect_ratio.den);
475 }
476 ff_put_v(bc, 0); /* csp type -- unknown */
477 break;
478 default:
479 break;
480 }
481 return 0;
482 }
483
484 static int add_info(AVIOContext *bc, const char *type, const char *value)
485 {
486 put_str(bc, type);
487 put_s(bc, -1);
488 put_str(bc, value);
489 return 1;
490 }
491
492 static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
493 {
494 AVFormatContext *s = nut->avf;
495 AVDictionaryEntry *t = NULL;
496 AVIOContext *dyn_bc;
497 uint8_t *dyn_buf = NULL;
498 int count = 0, dyn_size;
499 int ret = avio_open_dyn_buf(&dyn_bc);
500 if (ret < 0)
501 return ret;
502
503 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
504 count += add_info(dyn_bc, t->key, t->value);
505
506 ff_put_v(bc, 0); //stream_if_plus1
507 ff_put_v(bc, 0); //chapter_id
508 ff_put_v(bc, 0); //timestamp_start
509 ff_put_v(bc, 0); //length
510
511 ff_put_v(bc, count);
512
513 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
514 avio_write(bc, dyn_buf, dyn_size);
515 av_free(dyn_buf);
516 return 0;
517 }
518
519 static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
520 AVFormatContext *s= nut->avf;
521 AVStream* st = s->streams[stream_id];
522 AVIOContext *dyn_bc;
523 uint8_t *dyn_buf=NULL;
524 int count=0, dyn_size, i;
525 int ret = avio_open_dyn_buf(&dyn_bc);
526 if(ret < 0)
527 return ret;
528
529 for (i=0; ff_nut_dispositions[i].flag; ++i) {
530 if (st->disposition & ff_nut_dispositions[i].flag)
531 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
532 }
533 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
534
535 if (count) {
536 ff_put_v(bc, stream_id + 1); //stream_id_plus1
537 ff_put_v(bc, 0); //chapter_id
538 ff_put_v(bc, 0); //timestamp_start
539 ff_put_v(bc, 0); //length
540
541 ff_put_v(bc, count);
542
543 avio_write(bc, dyn_buf, dyn_size);
544 }
545
546 av_free(dyn_buf);
547 return count;
548 }
549
550 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
551 {
552 AVIOContext *dyn_bc;
553 uint8_t *dyn_buf = NULL;
554 AVDictionaryEntry *t = NULL;
555 AVChapter *ch = nut->avf->chapters[id];
556 int ret, dyn_size, count = 0;
557
558 ret = avio_open_dyn_buf(&dyn_bc);
559 if (ret < 0)
560 return ret;
561
562 ff_put_v(bc, 0); // stream_id_plus1
563 put_s(bc, id + 1); // chapter_id
564 put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
565 ff_put_v(bc, ch->end - ch->start); // chapter_len
566
567 while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
568 count += add_info(dyn_bc, t->key, t->value);
569
570 ff_put_v(bc, count);
571
572 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
573 avio_write(bc, dyn_buf, dyn_size);
574 av_freep(&dyn_buf);
575 return 0;
576 }
577
578 static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
579 {
580 NUTContext *nut = avctx->priv_data;
581 AVIOContext *dyn_bc;
582 int i, ret;
583
584 ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
585
586 ret = avio_open_dyn_buf(&dyn_bc);
587 if (ret < 0)
588 return ret;
589 write_mainheader(nut, dyn_bc);
590 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
591
592 for (i = 0; i < nut->avf->nb_streams; i++) {
593 ret = avio_open_dyn_buf(&dyn_bc);
594 if (ret < 0)
595 return ret;
596 ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
597 if (ret < 0)
598 return ret;
599 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
600 }
601
602 ret = avio_open_dyn_buf(&dyn_bc);
603 if (ret < 0)
604 return ret;
605 write_globalinfo(nut, dyn_bc);
606 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
607
608 for (i = 0; i < nut->avf->nb_streams; i++) {
609 ret = avio_open_dyn_buf(&dyn_bc);
610 if (ret < 0)
611 return ret;
612 ret = write_streaminfo(nut, dyn_bc, i);
613 if (ret < 0)
614 return ret;
615 if (ret > 0)
616 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
617 else {
618 uint8_t *buf;
619 avio_close_dyn_buf(dyn_bc, &buf);
620 av_free(buf);
621 }
622 }
623
624 for (i = 0; i < nut->avf->nb_chapters; i++) {
625 ret = avio_open_dyn_buf(&dyn_bc);
626 if (ret < 0)
627 return ret;
628 ret = write_chapter(nut, dyn_bc, i);
629 if (ret < 0) {
630 uint8_t *buf;
631 avio_close_dyn_buf(dyn_bc, &buf);
632 av_freep(&buf);
633 return ret;
634 }
635 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
636 }
637
638 nut->last_syncpoint_pos = INT_MIN;
639 nut->header_count++;
640 return 0;
641 }
642
643 static int nut_write_header(AVFormatContext *s)
644 {
645 NUTContext *nut = s->priv_data;
646 AVIOContext *bc = s->pb;
647 int i, j, ret;
648
649 nut->avf = s;
650
651 nut->version = NUT_STABLE_VERSION + !!nut->flags;
652 if (nut->flags && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
653 av_log(s, AV_LOG_ERROR,
654 "The additional syncpoint modes require version %d, "
655 "that is currently not finalized, "
656 "please set -f_strict experimental in order to enable it.\n",
657 nut->version);
658 return AVERROR_EXPERIMENTAL;
659 }
660
661 nut->stream = av_mallocz(sizeof(StreamContext) * s->nb_streams);
662 if (s->nb_chapters)
663 nut->chapter = av_mallocz(sizeof(ChapterContext) * s->nb_chapters);
664 nut->time_base = av_mallocz(sizeof(AVRational) * (s->nb_streams +
665 s->nb_chapters));
666 if (!nut->stream || (s->nb_chapters && !nut->chapter) || !nut->time_base) {
667 av_freep(&nut->stream);
668 av_freep(&nut->chapter);
669 av_freep(&nut->time_base);
670 return AVERROR(ENOMEM);
671 }
672
673 for (i = 0; i < s->nb_streams; i++) {
674 AVStream *st = s->streams[i];
675 int ssize;
676 AVRational time_base;
677 ff_parse_specific_params(st->codec, &time_base.den, &ssize,
678 &time_base.num);
679
680 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
681
682 for (j = 0; j < nut->time_base_count; j++)
683 if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
684 break;
685 }
686 nut->time_base[j] = time_base;
687 nut->stream[i].time_base = &nut->time_base[j];
688 if (j == nut->time_base_count)
689 nut->time_base_count++;
690
691 if (INT64_C(1000) * time_base.num >= time_base.den)
692 nut->stream[i].msb_pts_shift = 7;
693 else
694 nut->stream[i].msb_pts_shift = 14;
695 nut->stream[i].max_pts_distance =
696 FFMAX(time_base.den, time_base.num) / time_base.num;
697 }
698
699 for (i = 0; i < s->nb_chapters; i++) {
700 AVChapter *ch = s->chapters[i];
701
702 for (j = 0; j < nut->time_base_count; j++)
703 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
704 break;
705
706 nut->time_base[j] = ch->time_base;
707 nut->chapter[i].time_base = &nut->time_base[j];
708 if (j == nut->time_base_count)
709 nut->time_base_count++;
710 }
711
712 nut->max_distance = MAX_DISTANCE;
713 build_elision_headers(s);
714 build_frame_code(s);
715 assert(nut->frame_code['N'].flags == FLAG_INVALID);
716
717 avio_write(bc, ID_STRING, strlen(ID_STRING));
718 avio_w8(bc, 0);
719
720 if ((ret = write_headers(s, bc)) < 0)
721 return ret;
722
723 avio_flush(bc);
724
725 //FIXME index
726
727 return 0;
728 }
729
730 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc,
731 AVPacket *pkt)
732 {
733 int flags = 0;
734
735 if (pkt->flags & AV_PKT_FLAG_KEY)
736 flags |= FLAG_KEY;
737 if (pkt->stream_index != fc->stream_id)
738 flags |= FLAG_STREAM_ID;
739 if (pkt->size / fc->size_mul)
740 flags |= FLAG_SIZE_MSB;
741 if (pkt->pts - nus->last_pts != fc->pts_delta)
742 flags |= FLAG_CODED_PTS;
743 if (pkt->size > 2 * nut->max_distance)
744 flags |= FLAG_CHECKSUM;
745 if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
746 flags |= FLAG_CHECKSUM;
747 if (pkt->size < nut->header_len[fc->header_idx] ||
748 (pkt->size > 4096 && fc->header_idx) ||
749 memcmp(pkt->data, nut->header[fc->header_idx],
750 nut->header_len[fc->header_idx]))
751 flags |= FLAG_HEADER_IDX;
752
753 return flags | (fc->flags & FLAG_CODED);
754 }
755
756 static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
757 {
758 int i;
759 int best_i = 0;
760 int best_len = 0;
761
762 if (pkt->size > 4096)
763 return 0;
764
765 for (i = 1; i < nut->header_count; i++)
766 if (pkt->size >= nut->header_len[i]
767 && nut->header_len[i] > best_len
768 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
769 best_i = i;
770 best_len = nut->header_len[i];
771 }
772 return best_i;
773 }
774
775 static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
776 {
777 NUTContext *nut = s->priv_data;
778 StreamContext *nus = &nut->stream[pkt->stream_index];
779 AVIOContext *bc = s->pb, *dyn_bc;
780 FrameCode *fc;
781 int64_t coded_pts;
782 int best_length, frame_code, flags, needed_flags, i, header_idx,
783 best_header_idx;
784 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
785 int store_sp = 0;
786 int ret;
787
788 if (pkt->pts < 0) {
789 av_log(s, AV_LOG_ERROR,
790 "Negative pts not supported stream %d, pts %"PRId64"\n",
791 pkt->stream_index, pkt->pts);
792 return AVERROR_INVALIDDATA;
793 }
794
795 if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
796 write_headers(s, bc);
797
798 if (key_frame && !(nus->last_flags & FLAG_KEY))
799 store_sp = 1;
800
801 if (pkt->size + 30 /*FIXME check*/ + avio_tell(bc) >=
802 nut->last_syncpoint_pos + nut->max_distance)
803 store_sp = 1;
804
805 //FIXME: Ensure store_sp is 1 in the first place.
806
807 if (store_sp &&
808 (!(nut->flags & NUT_PIPE) || nut->last_syncpoint_pos == INT_MIN)) {
809 Syncpoint *sp, dummy = { .pos = INT64_MAX };
810
811 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
812 for (i = 0; i < s->nb_streams; i++) {
813 AVStream *st = s->streams[i];
814 int64_t dts_tb = av_rescale_rnd(pkt->dts,
815 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
816 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
817 AV_ROUND_DOWN);
818 int index = av_index_search_timestamp(st, dts_tb,
819 AVSEEK_FLAG_BACKWARD);
820 if (index >= 0)
821 dummy.pos = FFMIN(dummy.pos, st->index_entries[index].pos);
822 }
823 if (dummy.pos == INT64_MAX)
824 dummy.pos = 0;
825 sp = av_tree_find(nut->syncpoints, &dummy, (void *)ff_nut_sp_pos_cmp,
826 NULL);
827
828 nut->last_syncpoint_pos = avio_tell(bc);
829 ret = avio_open_dyn_buf(&dyn_bc);
830 if (ret < 0)
831 return ret;
832 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
833 ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos) >> 4 : 0);
834
835 if (nut->flags & NUT_BROADCAST) {
836 put_tt(nut, nus->time_base, dyn_bc,
837 av_rescale_q(av_gettime(), AV_TIME_BASE_Q, *nus->time_base));
838 }
839 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
840
841 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
842 return ret;
843 }
844 assert(nus->last_pts != AV_NOPTS_VALUE);
845
846 coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
847 if (ff_lsb2full(nus, coded_pts) != pkt->pts)
848 coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
849
850 best_header_idx = find_best_header_idx(nut, pkt);
851
852 best_length = INT_MAX;
853 frame_code = -1;
854 for (i = 0; i < 256; i++) {
855 int length = 0;
856 FrameCode *fc = &nut->frame_code[i];
857 int flags = fc->flags;
858
859 if (flags & FLAG_INVALID)
860 continue;
861 needed_flags = get_needed_flags(nut, nus, fc, pkt);
862
863 if (flags & FLAG_CODED) {
864 length++;
865 flags = needed_flags;
866 }
867
868 if ((flags & needed_flags) != needed_flags)
869 continue;
870
871 if ((flags ^ needed_flags) & FLAG_KEY)
872 continue;
873
874 if (flags & FLAG_STREAM_ID)
875 length += ff_get_v_length(pkt->stream_index);
876
877 if (pkt->size % fc->size_mul != fc->size_lsb)
878 continue;
879 if (flags & FLAG_SIZE_MSB)
880 length += ff_get_v_length(pkt->size / fc->size_mul);
881
882 if (flags & FLAG_CHECKSUM)
883 length += 4;
884
885 if (flags & FLAG_CODED_PTS)
886 length += ff_get_v_length(coded_pts);
887
888 if ((flags & FLAG_CODED)
889 && nut->header_len[best_header_idx] >
890 nut->header_len[fc->header_idx] + 1) {
891 flags |= FLAG_HEADER_IDX;
892 }
893
894 if (flags & FLAG_HEADER_IDX) {
895 length += 1 - nut->header_len[best_header_idx];
896 } else {
897 length -= nut->header_len[fc->header_idx];
898 }
899
900 length *= 4;
901 length += !(flags & FLAG_CODED_PTS);
902 length += !(flags & FLAG_CHECKSUM);
903
904 if (length < best_length) {
905 best_length = length;
906 frame_code = i;
907 }
908 }
909 assert(frame_code != -1);
910 fc = &nut->frame_code[frame_code];
911 flags = fc->flags;
912 needed_flags = get_needed_flags(nut, nus, fc, pkt);
913 header_idx = fc->header_idx;
914
915 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
916 avio_w8(bc, frame_code);
917 if (flags & FLAG_CODED) {
918 ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
919 flags = needed_flags;
920 }
921 if (flags & FLAG_STREAM_ID)
922 ff_put_v(bc, pkt->stream_index);
923 if (flags & FLAG_CODED_PTS)
924 ff_put_v(bc, coded_pts);
925 if (flags & FLAG_SIZE_MSB)
926 ff_put_v(bc, pkt->size / fc->size_mul);
927 if (flags & FLAG_HEADER_IDX)
928 ff_put_v(bc, header_idx = best_header_idx);
929
930 if (flags & FLAG_CHECKSUM)
931 avio_wl32(bc, ffio_get_checksum(bc));
932 else
933 ffio_get_checksum(bc);
934
935 avio_write(bc, pkt->data + nut->header_len[header_idx],
936 pkt->size - nut->header_len[header_idx]);
937 nus->last_flags = flags;
938 nus->last_pts = pkt->pts;
939
940 //FIXME just store one per syncpoint
941 if (flags & FLAG_KEY && !(nut->flags & NUT_PIPE))
942 av_add_index_entry(
943 s->streams[pkt->stream_index],
944 nut->last_syncpoint_pos,
945 pkt->pts,
946 0,
947 0,
948 AVINDEX_KEYFRAME);
949
950 return 0;
951 }
952
953 static int nut_write_trailer(AVFormatContext *s)
954 {
955 NUTContext *nut = s->priv_data;
956 AVIOContext *bc = s->pb;
957
958 while (nut->header_count < 3)
959 write_headers(s, bc);
960
961 ff_nut_free_sp(nut);
962 av_freep(&nut->stream);
963 av_freep(&nut->chapter);
964 av_freep(&nut->time_base);
965
966 return 0;
967 }
968
969 #define OFFSET(x) offsetof(NUTContext, x)
970 #define E AV_OPT_FLAG_ENCODING_PARAM
971 static const AVOption options[] = {
972 { "syncpoints", "NUT syncpoint behaviour", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
973 { "default", "", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
974 { "none", "Disable syncpoints, low overhead and unseekable", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_PIPE}, INT_MIN, INT_MAX, E, "syncpoints" },
975 { "timestamped", "Extend syncpoints with a wallclock timestamp", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_BROADCAST}, INT_MIN, INT_MAX, E, "syncpoints" },
976 { NULL },
977 };
978
979 static const AVClass class = {
980 .class_name = "nutenc",
981 .item_name = av_default_item_name,
982 .option = options,
983 .version = LIBAVUTIL_VERSION_INT,
984 };
985
986 AVOutputFormat ff_nut_muxer = {
987 .name = "nut",
988 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
989 .mime_type = "video/x-nut",
990 .extensions = "nut",
991 .priv_data_size = sizeof(NUTContext),
992 .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
993 CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
994 .video_codec = AV_CODEC_ID_MPEG4,
995 .write_header = nut_write_header,
996 .write_packet = nut_write_packet,
997 .write_trailer = nut_write_trailer,
998 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
999 .codec_tag = ff_nut_codec_tags,
1000 .priv_class = &class,
1001 };