3 * Copyright (c) 2004-2007 Michael Niedermayer
5 * This file is part of FFmpeg.
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.
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.
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
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/mathematics.h"
26 #include "libavutil/tree.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/time.h"
30 #include "libavutil/opt.h"
31 #include "libavcodec/bytestream.h"
32 #include "libavcodec/mpegaudiodata.h"
35 #include "avio_internal.h"
38 static int find_expected_header(AVCodecContext *c, int size, int key_frame,
41 int sample_rate = c->sample_rate;
48 if (c->codec_id == AV_CODEC_ID_MPEG4) {
55 } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
56 c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
58 } else if (c->codec_id == AV_CODEC_ID_H264) {
60 } else if (c->codec_id == AV_CODEC_ID_MP3 ||
61 c->codec_id == AV_CODEC_ID_MP2) {
62 int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
63 int layer = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
64 unsigned int header = 0xFFF00000;
66 lsf = sample_rate < (24000 + 32000) / 2;
67 mpeg25 = sample_rate < (12000 + 16000) / 2;
68 sample_rate <<= lsf + mpeg25;
69 if (sample_rate < (32000 + 44100) / 2) sample_rate_index = 2;
70 else if (sample_rate < (44100 + 48000) / 2) sample_rate_index = 0;
71 else sample_rate_index = 1;
73 sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
75 for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
77 avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
78 frame_size = (frame_size * 144000) / (sample_rate << lsf) +
81 if (frame_size == size)
85 header |= (!lsf) << 19;
86 header |= (4 - layer) << 17;
87 header |= 1 << 16; //no crc
90 return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
91 if (bitrate_index == 30)
92 return -1; //something is wrong ...
94 header |= (bitrate_index >> 1) << 12;
95 header |= sample_rate_index << 10;
96 header |= (bitrate_index & 1) << 9;
98 return 2; //FIXME actually put the needed ones in build_elision_headers()
99 //return 3; //we guess that the private bit is not set
100 //FIXME the above assumptions should be checked, if these turn out false too often something should be done
105 static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type)
107 NUTContext *nut = s->priv_data;
110 int len = find_expected_header(c, size, frame_type, out);
112 for (i = 1; i < nut->header_count; i++) {
113 if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
121 static void build_elision_headers(AVFormatContext *s)
123 NUTContext *nut = s->priv_data;
126 //FIXME write a 2pass mode to find the maximal headers
127 static const uint8_t headers[][5] = {
128 { 3, 0x00, 0x00, 0x01 },
129 { 4, 0x00, 0x00, 0x01, 0xB6},
130 { 2, 0xFF, 0xFA }, //mp3+crc
131 { 2, 0xFF, 0xFB }, //mp3
132 { 2, 0xFF, 0xFC }, //mp2+crc
133 { 2, 0xFF, 0xFD }, //mp2
136 nut->header_count = 7;
137 for (i = 1; i < nut->header_count; i++) {
138 nut->header_len[i] = headers[i - 1][0];
139 nut->header[i] = &headers[i - 1][1];
143 static void build_frame_code(AVFormatContext *s)
145 NUTContext *nut = s->priv_data;
146 int key_frame, index, pred, stream_id;
149 int keyframe_0_esc = s->nb_streams > 2;
153 ft = &nut->frame_code[start];
154 ft->flags = FLAG_CODED;
159 if (keyframe_0_esc) {
160 /* keyframe = 0 escape */
161 FrameCode *ft = &nut->frame_code[start];
162 ft->flags = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
167 for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
168 int start2 = start + (end - start) * stream_id / s->nb_streams;
169 int end2 = start + (end - start) * (stream_id + 1) / s->nb_streams;
170 AVCodecContext *codec = s->streams[stream_id]->codec;
171 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
172 int is_audio = codec->codec_type == AVMEDIA_TYPE_AUDIO;
173 int intra_only = /*codec->intra_only || */ is_audio;
177 if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
178 frame_size = av_get_audio_frame_duration(codec, 0);
179 if (codec->codec_id == AV_CODEC_ID_VORBIS && !frame_size)
182 AVRational f = av_div_q(codec->time_base, *nut->stream[stream_id].time_base);
183 if (f.den == 1 && f.num>0)
189 for (key_frame = 0; key_frame < 2; key_frame++) {
190 if (!intra_only || !keyframe_0_esc || key_frame != 0) {
191 FrameCode *ft = &nut->frame_code[start2];
192 ft->flags = FLAG_KEY * key_frame;
193 ft->flags |= FLAG_SIZE_MSB | FLAG_CODED_PTS;
194 ft->stream_id = stream_id;
197 ft->header_idx = find_header_idx(s, codec, -1, key_frame);
202 key_frame = intra_only;
205 int frame_bytes = codec->frame_size * (int64_t)codec->bit_rate /
206 (8 * codec->sample_rate);
208 for (pts = 0; pts < 2; pts++) {
209 for (pred = 0; pred < 2; pred++) {
210 FrameCode *ft = &nut->frame_code[start2];
211 ft->flags = FLAG_KEY * key_frame;
212 ft->stream_id = stream_id;
213 ft->size_mul = frame_bytes + 2;
214 ft->size_lsb = frame_bytes + pred;
215 ft->pts_delta = pts * frame_size;
216 ft->header_idx = find_header_idx(s, codec, frame_bytes + pred, key_frame);
221 FrameCode *ft = &nut->frame_code[start2];
222 ft->flags = FLAG_KEY | FLAG_SIZE_MSB;
223 ft->stream_id = stream_id;
225 ft->pts_delta = frame_size;
230 if (codec->has_b_frames) {
237 } else if (codec->codec_id == AV_CODEC_ID_VORBIS) {
247 for (pred = 0; pred < pred_count; pred++) {
248 int start3 = start2 + (end2 - start2) * pred / pred_count;
249 int end3 = start2 + (end2 - start2) * (pred + 1) / pred_count;
251 pred_table[pred] *= frame_size;
253 for (index = start3; index < end3; index++) {
254 FrameCode *ft = &nut->frame_code[index];
255 ft->flags = FLAG_KEY * key_frame;
256 ft->flags |= FLAG_SIZE_MSB;
257 ft->stream_id = stream_id;
258 //FIXME use single byte size and pred from last
259 ft->size_mul = end3 - start3;
260 ft->size_lsb = index - start3;
261 ft->pts_delta = pred_table[pred];
263 ft->header_idx = find_header_idx(s, codec, -1, key_frame);
267 memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'], sizeof(FrameCode) * (255 - 'N'));
268 nut->frame_code[0].flags =
269 nut->frame_code[255].flags =
270 nut->frame_code['N'].flags = FLAG_INVALID;
273 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val)
275 val *= nut->time_base_count;
276 val += time_base - nut->time_base;
280 * Store a string as vb.
282 static void put_str(AVIOContext *bc, const char *string)
284 int len = strlen(string);
287 avio_write(bc, string, len);
290 static void put_s(AVIOContext *bc, int64_t val)
292 ff_put_v(bc, 2 * FFABS(val) - (val > 0));
296 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
297 const char *func, int line)
299 av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
304 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file, const char *func, int line)
306 av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
310 #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
311 #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
314 //FIXME remove calculate_checksum
315 static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc,
316 int calculate_checksum, uint64_t startcode)
318 uint8_t *dyn_buf = NULL;
319 int dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
320 int forw_ptr = dyn_size + 4 * calculate_checksum;
323 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
324 avio_wb64(bc, startcode);
325 ff_put_v(bc, forw_ptr);
327 avio_wl32(bc, ffio_get_checksum(bc));
329 if (calculate_checksum)
330 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
331 avio_write(bc, dyn_buf, dyn_size);
332 if (calculate_checksum)
333 avio_wl32(bc, ffio_get_checksum(bc));
338 static void write_mainheader(NUTContext *nut, AVIOContext *bc)
340 int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,
344 ff_put_v(bc, nut->version);
345 if (nut->version > 3)
346 ff_put_v(bc, nut->minor_version = 1);
347 ff_put_v(bc, nut->avf->nb_streams);
348 ff_put_v(bc, nut->max_distance);
349 ff_put_v(bc, nut->time_base_count);
351 for (i = 0; i < nut->time_base_count; i++) {
352 ff_put_v(bc, nut->time_base[i].num);
353 ff_put_v(bc, nut->time_base[i].den);
359 tmp_match = 1 - (1LL << 62);
361 for (i = 0; i < 256; ) {
365 if (tmp_pts != nut->frame_code[i].pts_delta ) tmp_fields = 1;
366 if (tmp_mul != nut->frame_code[i].size_mul ) tmp_fields = 2;
367 if (tmp_stream != nut->frame_code[i].stream_id ) tmp_fields = 3;
368 if (tmp_size != nut->frame_code[i].size_lsb ) tmp_fields = 4;
369 // if (tmp_res != nut->frame_code[i].res ) tmp_fields=5;
370 if (tmp_head_idx != nut->frame_code[i].header_idx) tmp_fields = 8;
372 tmp_pts = nut->frame_code[i].pts_delta;
373 tmp_flags = nut->frame_code[i].flags;
374 tmp_stream = nut->frame_code[i].stream_id;
375 tmp_mul = nut->frame_code[i].size_mul;
376 tmp_size = nut->frame_code[i].size_lsb;
377 // tmp_res = nut->frame_code[i].res;
378 tmp_head_idx = nut->frame_code[i].header_idx;
380 for (j = 0; i < 256; j++, i++) {
385 if (nut->frame_code[i].pts_delta != tmp_pts ||
386 nut->frame_code[i].flags != tmp_flags ||
387 nut->frame_code[i].stream_id != tmp_stream ||
388 nut->frame_code[i].size_mul != tmp_mul ||
389 nut->frame_code[i].size_lsb != tmp_size + j ||
390 // nut->frame_code[i].res != tmp_res ||
391 nut->frame_code[i].header_idx != tmp_head_idx)
394 if (j != tmp_mul - tmp_size)
397 ff_put_v(bc, tmp_flags);
398 ff_put_v(bc, tmp_fields);
399 if (tmp_fields > 0) put_s(bc, tmp_pts);
400 if (tmp_fields > 1) ff_put_v(bc, tmp_mul);
401 if (tmp_fields > 2) ff_put_v(bc, tmp_stream);
402 if (tmp_fields > 3) ff_put_v(bc, tmp_size);
403 if (tmp_fields > 4) ff_put_v(bc, 0 /*tmp_res*/);
404 if (tmp_fields > 5) ff_put_v(bc, j);
405 if (tmp_fields > 6) ff_put_v(bc, tmp_match);
406 if (tmp_fields > 7) ff_put_v(bc, tmp_head_idx);
408 ff_put_v(bc, nut->header_count - 1);
409 for (i = 1; i < nut->header_count; i++) {
410 ff_put_v(bc, nut->header_len[i]);
411 avio_write(bc, nut->header[i], nut->header_len[i]);
413 // flags had been effectively introduced in version 4
414 if (nut->version > 3)
415 ff_put_v(bc, nut->flags);
418 static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
421 NUTContext *nut = avctx->priv_data;
422 AVCodecContext *codec = st->codec;
423 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec->codec_id);
426 switch (codec->codec_type) {
427 case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
428 case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
429 case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
430 default: ff_put_v(bc, 3); break;
433 if (codec->codec_tag) {
434 avio_wl32(bc, codec->codec_tag);
436 av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
437 return AVERROR(EINVAL);
440 ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
441 ff_put_v(bc, nut->stream[i].msb_pts_shift);
442 ff_put_v(bc, nut->stream[i].max_pts_distance);
443 ff_put_v(bc, codec->has_b_frames);
444 avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
446 ff_put_v(bc, codec->extradata_size);
447 avio_write(bc, codec->extradata, codec->extradata_size);
449 switch (codec->codec_type) {
450 case AVMEDIA_TYPE_AUDIO:
451 ff_put_v(bc, codec->sample_rate);
453 ff_put_v(bc, codec->channels);
455 case AVMEDIA_TYPE_VIDEO:
456 ff_put_v(bc, codec->width);
457 ff_put_v(bc, codec->height);
459 if (st->sample_aspect_ratio.num <= 0 ||
460 st->sample_aspect_ratio.den <= 0) {
464 ff_put_v(bc, st->sample_aspect_ratio.num);
465 ff_put_v(bc, st->sample_aspect_ratio.den);
467 ff_put_v(bc, 0); /* csp type -- unknown */
475 static int add_info(AVIOContext *bc, const char *type, const char *value)
483 static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
485 AVFormatContext *s = nut->avf;
486 AVDictionaryEntry *t = NULL;
488 uint8_t *dyn_buf = NULL;
489 int count = 0, dyn_size;
490 int ret = avio_open_dyn_buf(&dyn_bc);
494 while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
495 count += add_info(dyn_bc, t->key, t->value);
497 ff_put_v(bc, 0); //stream_if_plus1
498 ff_put_v(bc, 0); //chapter_id
499 ff_put_v(bc, 0); //timestamp_start
500 ff_put_v(bc, 0); //length
504 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
505 avio_write(bc, dyn_buf, dyn_size);
510 static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id) {
511 AVFormatContext *s= nut->avf;
512 AVStream* st = s->streams[stream_id];
513 AVDictionaryEntry *t = NULL;
515 uint8_t *dyn_buf=NULL;
516 int count=0, dyn_size, i;
517 int ret = avio_open_dyn_buf(&dyn_bc);
521 while ((t = av_dict_get(st->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
522 count += add_info(dyn_bc, t->key, t->value);
523 for (i=0; ff_nut_dispositions[i].flag; ++i) {
524 if (st->disposition & ff_nut_dispositions[i].flag)
525 count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
527 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
529 if (st->r_frame_rate.num>0 && st->r_frame_rate.den>0)
530 snprintf(buf, sizeof(buf), "%d/%d", st->r_frame_rate.num, st->r_frame_rate.den);
532 snprintf(buf, sizeof(buf), "%d/%d", st->codec->time_base.den, st->codec->time_base.num);
533 count += add_info(dyn_bc, "r_frame_rate", buf);
535 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
538 ff_put_v(bc, stream_id + 1); //stream_id_plus1
539 ff_put_v(bc, 0); //chapter_id
540 ff_put_v(bc, 0); //timestamp_start
541 ff_put_v(bc, 0); //length
545 avio_write(bc, dyn_buf, dyn_size);
552 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
555 uint8_t *dyn_buf = NULL;
556 AVDictionaryEntry *t = NULL;
557 AVChapter *ch = nut->avf->chapters[id];
558 int ret, dyn_size, count = 0;
560 ret = avio_open_dyn_buf(&dyn_bc);
564 ff_put_v(bc, 0); // stream_id_plus1
565 put_s(bc, id + 1); // chapter_id
566 put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
567 ff_put_v(bc, ch->end - ch->start); // chapter_len
569 while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
570 count += add_info(dyn_bc, t->key, t->value);
574 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
575 avio_write(bc, dyn_buf, dyn_size);
580 static int write_index(NUTContext *nut, AVIOContext *bc) {
582 Syncpoint dummy= { .pos= 0 };
583 Syncpoint *next_node[2] = { NULL };
584 int64_t startpos = avio_tell(bc);
585 int64_t payload_size;
587 put_tt(nut, nut->max_pts_tb, bc, nut->max_pts);
589 ff_put_v(bc, nut->sp_count);
591 for (i=0; i<nut->sp_count; i++) {
592 av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp, (void**)next_node);
593 ff_put_v(bc, (next_node[1]->pos >> 4) - (dummy.pos>>4));
594 dummy.pos = next_node[1]->pos;
597 for (i=0; i<nut->avf->nb_streams; i++) {
598 StreamContext *nus= &nut->stream[i];
599 int64_t last_pts= -1;
601 for (j=0; j<nut->sp_count; j++) {
605 if (j && nus->keyframe_pts[j] == nus->keyframe_pts[j-1]) {
606 av_log(nut->avf, AV_LOG_WARNING, "Multiple keyframes with same PTS\n");
607 nus->keyframe_pts[j] = AV_NOPTS_VALUE;
610 flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
611 for (; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
614 ff_put_v(bc, 1 + 2*flag + 4*n);
615 for (k= j - n; k<=j && k<nut->sp_count; k++) {
616 if (nus->keyframe_pts[k] == AV_NOPTS_VALUE)
618 av_assert0(nus->keyframe_pts[k] > last_pts);
619 ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
620 last_pts = nus->keyframe_pts[k];
625 payload_size = avio_tell(bc) - startpos + 8 + 4;
627 avio_wb64(bc, 8 + payload_size + av_log2(payload_size) / 7 + 1 + 4*(payload_size > 4096));
632 static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
634 NUTContext *nut = avctx->priv_data;
638 ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
640 ret = avio_open_dyn_buf(&dyn_bc);
643 write_mainheader(nut, dyn_bc);
644 put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
646 for (i = 0; i < nut->avf->nb_streams; i++) {
647 ret = avio_open_dyn_buf(&dyn_bc);
650 ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
653 put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
656 ret = avio_open_dyn_buf(&dyn_bc);
659 write_globalinfo(nut, dyn_bc);
660 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
662 for (i = 0; i < nut->avf->nb_streams; i++) {
663 ret = avio_open_dyn_buf(&dyn_bc);
666 ret = write_streaminfo(nut, dyn_bc, i);
670 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
673 avio_close_dyn_buf(dyn_bc, &buf);
678 for (i = 0; i < nut->avf->nb_chapters; i++) {
679 ret = avio_open_dyn_buf(&dyn_bc);
682 ret = write_chapter(nut, dyn_bc, i);
685 avio_close_dyn_buf(dyn_bc, &buf);
689 put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
692 nut->last_syncpoint_pos = INT_MIN;
697 static int nut_write_header(AVFormatContext *s)
699 NUTContext *nut = s->priv_data;
700 AVIOContext *bc = s->pb;
705 nut->version = FFMAX(NUT_STABLE_VERSION, 3 + !!nut->flags);
706 if (nut->version > 3 && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
707 av_log(s, AV_LOG_ERROR,
708 "The additional syncpoint modes require version %d, "
709 "that is currently not finalized, "
710 "please set -f_strict experimental in order to enable it.\n",
712 return AVERROR_EXPERIMENTAL;
715 nut->stream = av_calloc(s->nb_streams, sizeof(*nut->stream ));
716 nut->chapter = av_calloc(s->nb_chapters, sizeof(*nut->chapter));
717 nut->time_base= av_calloc(s->nb_streams +
718 s->nb_chapters, sizeof(*nut->time_base));
719 if (!nut->stream || !nut->chapter || !nut->time_base) {
720 av_freep(&nut->stream);
721 av_freep(&nut->chapter);
722 av_freep(&nut->time_base);
723 return AVERROR(ENOMEM);
726 for (i = 0; i < s->nb_streams; i++) {
727 AVStream *st = s->streams[i];
729 AVRational time_base;
730 ff_parse_specific_params(st, &time_base.den, &ssize, &time_base.num);
732 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->sample_rate) {
733 time_base = (AVRational) {1, st->codec->sample_rate};
735 time_base = ff_choose_timebase(s, st, 48000);
738 avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
740 for (j = 0; j < nut->time_base_count; j++)
741 if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
744 nut->time_base[j] = time_base;
745 nut->stream[i].time_base = &nut->time_base[j];
746 if (j == nut->time_base_count)
747 nut->time_base_count++;
749 if (INT64_C(1000) * time_base.num >= time_base.den)
750 nut->stream[i].msb_pts_shift = 7;
752 nut->stream[i].msb_pts_shift = 14;
753 nut->stream[i].max_pts_distance =
754 FFMAX(time_base.den, time_base.num) / time_base.num;
757 for (i = 0; i < s->nb_chapters; i++) {
758 AVChapter *ch = s->chapters[i];
760 for (j = 0; j < nut->time_base_count; j++)
761 if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
764 nut->time_base[j] = ch->time_base;
765 nut->chapter[i].time_base = &nut->time_base[j];
766 if (j == nut->time_base_count)
767 nut->time_base_count++;
770 nut->max_distance = MAX_DISTANCE;
771 build_elision_headers(s);
773 av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
775 avio_write(bc, ID_STRING, strlen(ID_STRING));
778 if ((ret = write_headers(s, bc)) < 0)
781 if (s->avoid_negative_ts < 0)
782 s->avoid_negative_ts = 1;
789 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc,
794 if (pkt->flags & AV_PKT_FLAG_KEY)
796 if (pkt->stream_index != fc->stream_id)
797 flags |= FLAG_STREAM_ID;
798 if (pkt->size / fc->size_mul)
799 flags |= FLAG_SIZE_MSB;
800 if (pkt->pts - nus->last_pts != fc->pts_delta)
801 flags |= FLAG_CODED_PTS;
802 if (pkt->side_data_elems && nut->version > 3)
803 flags |= FLAG_SM_DATA;
804 if (pkt->size > 2 * nut->max_distance)
805 flags |= FLAG_CHECKSUM;
806 if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
807 flags |= FLAG_CHECKSUM;
808 if (pkt->size < nut->header_len[fc->header_idx] ||
809 (pkt->size > 4096 && fc->header_idx) ||
810 memcmp(pkt->data, nut->header[fc->header_idx],
811 nut->header_len[fc->header_idx]))
812 flags |= FLAG_HEADER_IDX;
814 return flags | (fc->flags & FLAG_CODED);
817 static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
823 if (pkt->size > 4096)
826 for (i = 1; i < nut->header_count; i++)
827 if (pkt->size >= nut->header_len[i]
828 && nut->header_len[i] > best_len
829 && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
831 best_len = nut->header_len[i];
836 static int write_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta)
838 int ret, i, dyn_size;
841 int sm_data_count = 0;
845 ret = avio_open_dyn_buf(&dyn_bc);
849 for (i = 0; i<pkt->side_data_elems; i++) {
850 const uint8_t *data = pkt->side_data[i].data;
851 int size = pkt->side_data[i].size;
852 const uint8_t *data_end = data + size;
855 if ( pkt->side_data[i].type == AV_PKT_DATA_METADATA_UPDATE
856 || pkt->side_data[i].type == AV_PKT_DATA_STRINGS_METADATA) {
857 if (!size || data[size-1]) {
858 ret = AVERROR(EINVAL);
861 while (data < data_end) {
862 const uint8_t *key = data;
863 const uint8_t *val = data + strlen(key) + 1;
865 if(val >= data_end) {
866 ret = AVERROR(EINVAL);
869 put_str(dyn_bc, key);
871 put_str(dyn_bc, val);
872 data = val + strlen(val) + 1;
877 switch (pkt->side_data[i].type) {
878 case AV_PKT_DATA_PALETTE:
879 case AV_PKT_DATA_NEW_EXTRADATA:
880 case AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL:
882 if (pkt->side_data[i].type == AV_PKT_DATA_PALETTE) {
883 put_str(dyn_bc, "Palette");
884 } else if(pkt->side_data[i].type == AV_PKT_DATA_NEW_EXTRADATA) {
885 put_str(dyn_bc, "Extradata");
886 } else if(pkt->side_data[i].type == AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL) {
887 snprintf(tmp, sizeof(tmp), "CodecSpecificSide%"PRId64"", AV_RB64(data));
888 put_str(dyn_bc, tmp);
890 snprintf(tmp, sizeof(tmp), "UserData%s-SD-%d",
891 (s->flags & AVFMT_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT,
892 pkt->side_data[i].type);
893 put_str(dyn_bc, tmp);
896 put_str(dyn_bc, "bin");
897 ff_put_v(dyn_bc, pkt->side_data[i].size);
898 avio_write(dyn_bc, data, pkt->side_data[i].size);
901 case AV_PKT_DATA_PARAM_CHANGE:
902 flags = bytestream_get_le32(&data);
903 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
904 put_str(dyn_bc, "Channels");
905 put_s(dyn_bc, bytestream_get_le32(&data));
908 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
909 put_str(dyn_bc, "ChannelLayout");
911 put_str(dyn_bc, "u64");
913 avio_write(dyn_bc, data, 8); data+=8;
916 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
917 put_str(dyn_bc, "SampleRate");
918 put_s(dyn_bc, bytestream_get_le32(&data));
921 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
922 put_str(dyn_bc, "Width");
923 put_s(dyn_bc, bytestream_get_le32(&data));
924 put_str(dyn_bc, "Height");
925 put_s(dyn_bc, bytestream_get_le32(&data));
929 case AV_PKT_DATA_SKIP_SAMPLES:
931 put_str(dyn_bc, "SkipStart");
932 put_s(dyn_bc, (unsigned)AV_RL32(data));
935 if (AV_RL32(data+4)) {
936 put_str(dyn_bc, "SkipEnd");
937 put_s(dyn_bc, (unsigned)AV_RL32(data+4));
941 case AV_PKT_DATA_METADATA_UPDATE:
942 case AV_PKT_DATA_STRINGS_METADATA:
943 // belongs into meta, not side data
950 ff_put_v(bc, sm_data_count);
951 dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
952 avio_write(bc, dyn_buf, dyn_size);
958 static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
960 NUTContext *nut = s->priv_data;
961 StreamContext *nus = &nut->stream[pkt->stream_index];
962 AVIOContext *bc = s->pb, *dyn_bc, *sm_bc = NULL;
965 int best_length, frame_code, flags, needed_flags, i, header_idx;
967 int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
971 int data_size = pkt->size;
972 uint8_t *sm_buf = NULL;
975 av_log(s, AV_LOG_ERROR,
976 "Negative pts not supported stream %d, pts %"PRId64"\n",
977 pkt->stream_index, pkt->pts);
978 if (pkt->pts == AV_NOPTS_VALUE)
979 av_log(s, AV_LOG_ERROR, "Try to enable the genpts flag\n");
980 return AVERROR(EINVAL);
983 if (pkt->side_data_elems && nut->version > 3) {
984 ret = avio_open_dyn_buf(&sm_bc);
987 ret = write_sm_data(s, sm_bc, pkt, 0);
989 ret = write_sm_data(s, sm_bc, pkt, 1);
990 sm_size = avio_close_dyn_buf(sm_bc, &sm_buf);
993 data_size += sm_size;
996 if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
997 write_headers(s, bc);
999 if (key_frame && !(nus->last_flags & FLAG_KEY))
1002 if (data_size + 30 /*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
1005 //FIXME: Ensure store_sp is 1 in the first place.
1008 (!(nut->flags & NUT_PIPE) || nut->last_syncpoint_pos == INT_MIN)) {
1009 int64_t sp_pos = INT64_MAX;
1011 ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
1012 for (i = 0; i < s->nb_streams; i++) {
1013 AVStream *st = s->streams[i];
1014 int64_t dts_tb = av_rescale_rnd(pkt->dts,
1015 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
1016 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
1018 int index = av_index_search_timestamp(st, dts_tb,
1019 AVSEEK_FLAG_BACKWARD);
1021 sp_pos = FFMIN(sp_pos, st->index_entries[index].pos);
1022 if (!nut->write_index && 2*index > st->nb_index_entries) {
1023 memmove(st->index_entries,
1024 st->index_entries + index,
1025 sizeof(*st->index_entries) * (st->nb_index_entries - index));
1026 st->nb_index_entries -= index;
1031 nut->last_syncpoint_pos = avio_tell(bc);
1032 ret = avio_open_dyn_buf(&dyn_bc);
1035 put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
1036 ff_put_v(dyn_bc, sp_pos != INT64_MAX ? (nut->last_syncpoint_pos - sp_pos) >> 4 : 0);
1038 if (nut->flags & NUT_BROADCAST) {
1039 put_tt(nut, nus->time_base, dyn_bc,
1040 av_rescale_q(av_gettime(), AV_TIME_BASE_Q, *nus->time_base));
1042 put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
1044 if (nut->write_index) {
1045 if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
1048 if ((1ll<<60) % nut->sp_count == 0)
1049 for (i=0; i<s->nb_streams; i++) {
1051 StreamContext *nus = &nut->stream[i];
1052 av_reallocp_array(&nus->keyframe_pts, 2*nut->sp_count, sizeof(*nus->keyframe_pts));
1053 if (!nus->keyframe_pts) {
1054 ret = AVERROR(ENOMEM);
1057 for (j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
1058 nus->keyframe_pts[j] = AV_NOPTS_VALUE;
1062 av_assert0(nus->last_pts != AV_NOPTS_VALUE);
1064 coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
1065 if (ff_lsb2full(nus, coded_pts) != pkt->pts)
1066 coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
1068 best_header_idx = find_best_header_idx(nut, pkt);
1070 best_length = INT_MAX;
1072 for (i = 0; i < 256; i++) {
1074 FrameCode *fc = &nut->frame_code[i];
1075 int flags = fc->flags;
1077 if (flags & FLAG_INVALID)
1079 needed_flags = get_needed_flags(nut, nus, fc, pkt);
1081 if (flags & FLAG_CODED) {
1083 flags = needed_flags;
1086 if ((flags & needed_flags) != needed_flags)
1089 if ((flags ^ needed_flags) & FLAG_KEY)
1092 if (flags & FLAG_STREAM_ID)
1093 length += ff_get_v_length(pkt->stream_index);
1095 if (data_size % fc->size_mul != fc->size_lsb)
1097 if (flags & FLAG_SIZE_MSB)
1098 length += ff_get_v_length(data_size / fc->size_mul);
1100 if (flags & FLAG_CHECKSUM)
1103 if (flags & FLAG_CODED_PTS)
1104 length += ff_get_v_length(coded_pts);
1106 if ( (flags & FLAG_CODED)
1107 && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx] + 1) {
1108 flags |= FLAG_HEADER_IDX;
1111 if (flags & FLAG_HEADER_IDX) {
1112 length += 1 - nut->header_len[best_header_idx];
1114 length -= nut->header_len[fc->header_idx];
1118 length += !(flags & FLAG_CODED_PTS);
1119 length += !(flags & FLAG_CHECKSUM);
1121 if (length < best_length) {
1122 best_length = length;
1126 av_assert0(frame_code != -1);
1128 fc = &nut->frame_code[frame_code];
1130 needed_flags = get_needed_flags(nut, nus, fc, pkt);
1131 header_idx = fc->header_idx;
1133 ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
1134 avio_w8(bc, frame_code);
1135 if (flags & FLAG_CODED) {
1136 ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
1137 flags = needed_flags;
1139 if (flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
1140 if (flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
1141 if (flags & FLAG_SIZE_MSB ) ff_put_v(bc, data_size / fc->size_mul);
1142 if (flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx = best_header_idx);
1144 if (flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
1145 else ffio_get_checksum(bc);
1147 if (flags & FLAG_SM_DATA) {
1148 avio_write(bc, sm_buf, sm_size);
1150 avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
1152 nus->last_flags = flags;
1153 nus->last_pts = pkt->pts;
1155 //FIXME just store one per syncpoint
1156 if (flags & FLAG_KEY && !(nut->flags & NUT_PIPE)) {
1158 s->streams[pkt->stream_index],
1159 nut->last_syncpoint_pos,
1164 if (nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
1165 nus->keyframe_pts[nut->sp_count] = pkt->pts;
1168 if (!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
1169 nut->max_pts = pkt->pts;
1170 nut->max_pts_tb = nus->time_base;
1179 static int nut_write_trailer(AVFormatContext *s)
1181 NUTContext *nut = s->priv_data;
1182 AVIOContext *bc = s->pb, *dyn_bc;
1185 while (nut->header_count < 3)
1186 write_headers(s, bc);
1188 ret = avio_open_dyn_buf(&dyn_bc);
1189 if (ret >= 0 && nut->sp_count) {
1190 av_assert1(nut->write_index);
1191 write_index(nut, dyn_bc);
1192 put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
1195 ff_nut_free_sp(nut);
1196 for (i=0; i<s->nb_streams; i++)
1197 av_freep(&nut->stream[i].keyframe_pts);
1199 av_freep(&nut->stream);
1200 av_freep(&nut->chapter);
1201 av_freep(&nut->time_base);
1206 #define OFFSET(x) offsetof(NUTContext, x)
1207 #define E AV_OPT_FLAG_ENCODING_PARAM
1208 static const AVOption options[] = {
1209 { "syncpoints", "NUT syncpoint behaviour", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
1210 { "default", "", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, E, "syncpoints" },
1211 { "none", "Disable syncpoints, low overhead and unseekable", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_PIPE}, INT_MIN, INT_MAX, E, "syncpoints" },
1212 { "timestamped", "Extend syncpoints with a wallclock timestamp", 0, AV_OPT_TYPE_CONST, {.i64 = NUT_BROADCAST}, INT_MIN, INT_MAX, E, "syncpoints" },
1213 { "write_index", "Write index", OFFSET(write_index), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E, },
1217 static const AVClass class = {
1218 .class_name = "nutenc",
1219 .item_name = av_default_item_name,
1221 .version = LIBAVUTIL_VERSION_INT,
1224 AVOutputFormat ff_nut_muxer = {
1226 .long_name = NULL_IF_CONFIG_SMALL("NUT"),
1227 .mime_type = "video/x-nut",
1228 .extensions = "nut",
1229 .priv_data_size = sizeof(NUTContext),
1230 .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
1231 CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
1232 .video_codec = AV_CODEC_ID_MPEG4,
1233 .write_header = nut_write_header,
1234 .write_packet = nut_write_packet,
1235 .write_trailer = nut_write_trailer,
1236 .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1237 .codec_tag = ff_nut_codec_tags,
1238 .priv_class = &class,