libavformat/nutenc.c
70ea1e69
 /*
  * nut muxer
  * Copyright (c) 2004-2007 Michael Niedermayer
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
8f8bc923
 #include <stdint.h>
 
6a5d31ac
 #include "libavutil/intreadwrite.h"
0ebcdf5c
 #include "libavutil/mathematics.h"
245976da
 #include "libavutil/tree.h"
d2d67e42
 #include "libavutil/dict.h"
4a6d790a
 #include "libavutil/avassert.h"
8113e838
 #include "libavcodec/bytestream.h"
245976da
 #include "libavcodec/mpegaudiodata.h"
70ea1e69
 #include "nut.h"
80b39e1c
 #include "internal.h"
4c4427a7
 #include "avio_internal.h"
bfe5454c
 #include "riff.h"
a712d725
 
fce4450d
 static int find_expected_header(AVCodecContext *c, int size, int key_frame,
                                 uint8_t out[64])
 {
     int sample_rate = c->sample_rate;
a712d725
 
fce4450d
     if (size > 4096)
a712d725
         return 0;
 
     AV_WB24(out, 1);
 
fce4450d
     if (c->codec_id == AV_CODEC_ID_MPEG4) {
         if (key_frame) {
a712d725
             return 3;
fce4450d
         } else {
             out[3] = 0xB6;
a712d725
             return 4;
         }
fce4450d
     } else if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
                c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
a712d725
         return 3;
fce4450d
     } else if (c->codec_id == AV_CODEC_ID_H264) {
a712d725
         return 3;
fce4450d
     } else if (c->codec_id == AV_CODEC_ID_MP3 ||
                c->codec_id == AV_CODEC_ID_MP2) {
a712d725
         int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
fce4450d
         int layer           = c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
         unsigned int header = 0xFFF00000;
a712d725
 
fce4450d
         lsf           = sample_rate < (24000 + 32000) / 2;
         mpeg25        = sample_rate < (12000 + 16000) / 2;
a712d725
         sample_rate <<= lsf + mpeg25;
c73fcc8d
         if      (sample_rate < (32000 + 44100) / 2) sample_rate_index = 2;
         else if (sample_rate < (44100 + 48000) / 2) sample_rate_index = 0;
         else                                        sample_rate_index = 1;
a712d725
 
fce4450d
         sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
a712d725
 
fce4450d
         for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
             frame_size =
                 avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
             frame_size = (frame_size * 144000) / (sample_rate << lsf) +
                 (bitrate_index & 1);
a712d725
 
fce4450d
             if (frame_size == size)
a712d725
                 break;
         }
 
fce4450d
         header |= (!lsf) << 19;
         header |= (4 - layer) << 17;
         header |= 1 << 16; //no crc
a712d725
         AV_WB32(out, header);
fce4450d
         if (size <= 0)
             return 2;  //we guess there is no crc, if there is one the user clearly does not care about overhead
         if (bitrate_index == 30)
             return -1;  //something is wrong ...
a712d725
 
fce4450d
         header |= (bitrate_index >> 1) << 12;
         header |= sample_rate_index << 10;
         header |= (bitrate_index & 1) << 9;
a712d725
 
         return 2; //FIXME actually put the needed ones in build_elision_headers()
6ff15cd5
         //return 3; //we guess that the private bit is not set
7ce68923
 //FIXME the above assumptions should be checked, if these turn out false too often something should be done
a712d725
     }
     return 0;
 }
 
c73fcc8d
 static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type)
fce4450d
 {
a712d725
     NUTContext *nut = s->priv_data;
     uint8_t out[64];
     int i;
fce4450d
     int len = find_expected_header(c, size, frame_type, out);
a712d725
 
fce4450d
     for (i = 1; i < nut->header_count; i++) {
         if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
a712d725
             return i;
         }
     }
fce4450d
 
a712d725
     return 0;
 }
 
fce4450d
 static void build_elision_headers(AVFormatContext *s)
 {
a712d725
     NUTContext *nut = s->priv_data;
     int i;
     //FIXME this is lame
     //FIXME write a 2pass mode to find the maximal headers
fce4450d
     static const uint8_t headers[][5] = {
         { 3, 0x00, 0x00, 0x01 },
         { 4, 0x00, 0x00, 0x01, 0xB6},
         { 2, 0xFF, 0xFA }, //mp3+crc
         { 2, 0xFF, 0xFB }, //mp3
         { 2, 0xFF, 0xFC }, //mp2+crc
         { 2, 0xFF, 0xFD }, //mp2
a712d725
     };
 
fce4450d
     nut->header_count = 7;
     for (i = 1; i < nut->header_count; i++) {
         nut->header_len[i] = headers[i - 1][0];
         nut->header[i]     = &headers[i - 1][1];
a712d725
     }
 }
70ea1e69
 
fce4450d
 static void build_frame_code(AVFormatContext *s)
 {
70ea1e69
     NUTContext *nut = s->priv_data;
     int key_frame, index, pred, stream_id;
fce4450d
     int start = 1;
     int end   = 254;
     int keyframe_0_esc = s->nb_streams > 2;
70ea1e69
     int pred_table[10];
0fcfa8eb
     FrameCode *ft;
 
fce4450d
     ft            = &nut->frame_code[start];
     ft->flags     = FLAG_CODED;
     ft->size_mul  = 1;
     ft->pts_delta = 1;
0fcfa8eb
     start++;
70ea1e69
 
fce4450d
     if (keyframe_0_esc) {
70ea1e69
         /* keyframe = 0 escape */
fce4450d
         FrameCode *ft = &nut->frame_code[start];
         ft->flags    = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
         ft->size_mul = 1;
70ea1e69
         start++;
     }
 
fce4450d
     for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
         int start2 = start + (end - start) * stream_id       / s->nb_streams;
         int end2   = start + (end - start) * (stream_id + 1) / s->nb_streams;
70ea1e69
         AVCodecContext *codec = s->streams[stream_id]->codec;
fce4450d
         int is_audio          = codec->codec_type == AVMEDIA_TYPE_AUDIO;
         int intra_only        = /*codec->intra_only || */ is_audio;
70ea1e69
         int pred_count;
4abc411b
         int frame_size = 0;
 
         if (codec->codec_type == AVMEDIA_TYPE_AUDIO) {
             frame_size = av_get_audio_frame_duration(codec, 0);
             if (codec->codec_id == AV_CODEC_ID_VORBIS && !frame_size)
                 frame_size = 64;
         } else {
             AVRational f = av_div_q(codec->time_base, *nut->stream[stream_id].time_base);
c73fcc8d
             if (f.den == 1 && f.num>0)
4abc411b
                 frame_size = f.num;
4eb0f5f6
         }
c73fcc8d
         if (!frame_size)
4eb0f5f6
             frame_size = 1;
70ea1e69
 
fce4450d
         for (key_frame = 0; key_frame < 2; key_frame++) {
             if (!intra_only || !keyframe_0_esc || key_frame != 0) {
                 FrameCode *ft = &nut->frame_code[start2];
                 ft->flags     = FLAG_KEY * key_frame;
                 ft->flags    |= FLAG_SIZE_MSB | FLAG_CODED_PTS;
                 ft->stream_id = stream_id;
                 ft->size_mul  = 1;
                 if (is_audio)
                     ft->header_idx = find_header_idx(s, codec, -1, key_frame);
70ea1e69
                 start2++;
             }
         }
 
fce4450d
         key_frame = intra_only;
7b9e9817
 #if 1
fce4450d
         if (is_audio) {
             int frame_bytes = codec->frame_size * (int64_t)codec->bit_rate /
                               (8 * codec->sample_rate);
70ea1e69
             int pts;
c73fcc8d
             for (pts = 0; pts < 2; pts++) {
fce4450d
                 for (pred = 0; pred < 2; pred++) {
c73fcc8d
                     FrameCode *ft  = &nut->frame_code[start2];
fce4450d
                     ft->flags      = FLAG_KEY * key_frame;
                     ft->stream_id  = stream_id;
                     ft->size_mul   = frame_bytes + 2;
                     ft->size_lsb   = frame_bytes + pred;
c73fcc8d
                     ft->pts_delta  = pts * frame_size;
fce4450d
                     ft->header_idx = find_header_idx(s, codec, frame_bytes + pred, key_frame);
70ea1e69
                     start2++;
                 }
             }
fce4450d
         } else {
             FrameCode *ft = &nut->frame_code[start2];
             ft->flags     = FLAG_KEY | FLAG_SIZE_MSB;
             ft->stream_id = stream_id;
             ft->size_mul  = 1;
c73fcc8d
             ft->pts_delta = frame_size;
70ea1e69
             start2++;
         }
7b9e9817
 #endif
70ea1e69
 
fce4450d
         if (codec->has_b_frames) {
             pred_count    = 5;
             pred_table[0] = -2;
             pred_table[1] = -1;
             pred_table[2] = 1;
             pred_table[3] = 3;
             pred_table[4] = 4;
         } else if (codec->codec_id == AV_CODEC_ID_VORBIS) {
             pred_count    = 3;
             pred_table[0] = 2;
             pred_table[1] = 9;
             pred_table[2] = 16;
         } else {
             pred_count    = 1;
             pred_table[0] = 1;
70ea1e69
         }
 
fce4450d
         for (pred = 0; pred < pred_count; pred++) {
             int start3 = start2 + (end2 - start2) * pred / pred_count;
             int end3   = start2 + (end2 - start2) * (pred + 1) / pred_count;
70ea1e69
 
4eb0f5f6
             pred_table[pred] *= frame_size;
 
fce4450d
             for (index = start3; index < end3; index++) {
                 FrameCode *ft = &nut->frame_code[index];
                 ft->flags     = FLAG_KEY * key_frame;
                 ft->flags    |= FLAG_SIZE_MSB;
                 ft->stream_id = stream_id;
70ea1e69
 //FIXME use single byte size and pred from last
fce4450d
                 ft->size_mul  = end3 - start3;
                 ft->size_lsb  = index - start3;
                 ft->pts_delta = pred_table[pred];
                 if (is_audio)
                     ft->header_idx = find_header_idx(s, codec, -1, key_frame);
70ea1e69
             }
         }
     }
c73fcc8d
     memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'], sizeof(FrameCode) * (255 - 'N'));
fce4450d
     nut->frame_code[0].flags       =
         nut->frame_code[255].flags =
         nut->frame_code['N'].flags = FLAG_INVALID;
70ea1e69
 }
 
c73fcc8d
 static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val)
fce4450d
 {
491216c6
     val *= nut->time_base_count;
073f8b10
     val += time_base - nut->time_base;
f8280ff4
     ff_put_v(bc, val);
491216c6
 }
70ea1e69
 /**
49bd8e4b
  * Store a string as vb.
70ea1e69
  */
fce4450d
 static void put_str(AVIOContext *bc, const char *string)
 {
     int len = strlen(string);
70ea1e69
 
f8280ff4
     ff_put_v(bc, len);
77eb5504
     avio_write(bc, string, len);
70ea1e69
 }
 
fce4450d
 static void put_s(AVIOContext *bc, int64_t val)
 {
     ff_put_v(bc, 2 * FFABS(val) - (val > 0));
70ea1e69
 }
 
 #ifdef TRACE
bc66827f
 static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, const char *file,
                                   const char *func, int line)
 {
f8280ff4
     av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69
 
f8280ff4
     ff_put_v(bc, v);
70ea1e69
 }
 
c73fcc8d
 static inline void put_s_trace(AVIOContext *bc, int64_t v, const char *file, const char *func, int line)
bc66827f
 {
7a26da44
     av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
70ea1e69
 
     put_s(bc, v);
 }
f8280ff4
 #define ff_put_v(bc, v)  ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
70ea1e69
 #define put_s(bc, v)  put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
 #endif
 
34f8cc38
 //FIXME remove calculate_checksum
fce4450d
 static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc,
                        int calculate_checksum, uint64_t startcode)
 {
     uint8_t *dyn_buf = NULL;
     int dyn_size     = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     int forw_ptr     = dyn_size + 4 * calculate_checksum;
6c666941
 
fce4450d
     if (forw_ptr > 4096)
4c4427a7
         ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504
     avio_wb64(bc, startcode);
f8280ff4
     ff_put_v(bc, forw_ptr);
fce4450d
     if (forw_ptr > 4096)
b64030f2
         avio_wl32(bc, ffio_get_checksum(bc));
70ea1e69
 
fce4450d
     if (calculate_checksum)
4c4427a7
         ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504
     avio_write(bc, dyn_buf, dyn_size);
fce4450d
     if (calculate_checksum)
b64030f2
         avio_wl32(bc, ffio_get_checksum(bc));
70ea1e69
 
8d9a3f7e
     av_free(dyn_buf);
70ea1e69
 }
 
fce4450d
 static void write_mainheader(NUTContext *nut, AVIOContext *bc)
 {
     int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,
         tmp_head_idx;
a712d725
     int64_t tmp_match;
70ea1e69
 
6aa50374
     ff_put_v(bc, nut->version = NUT_VERSION);
804ea14b
     if (nut->version > 3)
         ff_put_v(bc, nut->minor_version);
f8280ff4
     ff_put_v(bc, nut->avf->nb_streams);
     ff_put_v(bc, nut->max_distance);
     ff_put_v(bc, nut->time_base_count);
70ea1e69
 
fce4450d
     for (i = 0; i < nut->time_base_count; i++) {
f8280ff4
         ff_put_v(bc, nut->time_base[i].num);
         ff_put_v(bc, nut->time_base[i].den);
70ea1e69
     }
 
fce4450d
     tmp_pts      = 0;
     tmp_mul      = 1;
     tmp_stream   = 0;
     tmp_match    = 1 - (1LL << 62);
     tmp_head_idx = 0;
     for (i = 0; i < 256; ) {
         tmp_fields = 0;
         tmp_size   = 0;
70ea1e69
 //        tmp_res=0;
c73fcc8d
         if (tmp_pts      != nut->frame_code[i].pts_delta ) tmp_fields = 1;
         if (tmp_mul      != nut->frame_code[i].size_mul  ) tmp_fields = 2;
         if (tmp_stream   != nut->frame_code[i].stream_id ) tmp_fields = 3;
         if (tmp_size     != nut->frame_code[i].size_lsb  ) tmp_fields = 4;
 //        if (tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
         if (tmp_head_idx != nut->frame_code[i].header_idx) tmp_fields = 8;
fce4450d
 
         tmp_pts    = nut->frame_code[i].pts_delta;
         tmp_flags  = nut->frame_code[i].flags;
         tmp_stream = nut->frame_code[i].stream_id;
         tmp_mul    = nut->frame_code[i].size_mul;
         tmp_size   = nut->frame_code[i].size_lsb;
70ea1e69
 //        tmp_res   = nut->frame_code[i].res;
fce4450d
         tmp_head_idx = nut->frame_code[i].header_idx;
70ea1e69
 
fce4450d
         for (j = 0; i < 256; j++, i++) {
             if (i == 'N') {
70ea1e69
                 j--;
                 continue;
             }
fce4450d
             if (nut->frame_code[i].pts_delta  != tmp_pts      ||
                 nut->frame_code[i].flags      != tmp_flags    ||
                 nut->frame_code[i].stream_id  != tmp_stream   ||
                 nut->frame_code[i].size_mul   != tmp_mul      ||
                 nut->frame_code[i].size_lsb   != tmp_size + j ||
 //              nut->frame_code[i].res        != tmp_res      ||
                 nut->frame_code[i].header_idx != tmp_head_idx)
                 break;
70ea1e69
         }
fce4450d
         if (j != tmp_mul - tmp_size)
             tmp_fields = 6;
70ea1e69
 
f8280ff4
         ff_put_v(bc, tmp_flags);
         ff_put_v(bc, tmp_fields);
c73fcc8d
         if (tmp_fields > 0) put_s(bc, tmp_pts);
         if (tmp_fields > 1) ff_put_v(bc, tmp_mul);
         if (tmp_fields > 2) ff_put_v(bc, tmp_stream);
         if (tmp_fields > 3) ff_put_v(bc, tmp_size);
         if (tmp_fields > 4) ff_put_v(bc, 0 /*tmp_res*/);
         if (tmp_fields > 5) ff_put_v(bc, j);
         if (tmp_fields > 6) ff_put_v(bc, tmp_match);
         if (tmp_fields > 7) ff_put_v(bc, tmp_head_idx);
a712d725
     }
fce4450d
     ff_put_v(bc, nut->header_count - 1);
     for (i = 1; i < nut->header_count; i++) {
f8280ff4
         ff_put_v(bc, nut->header_len[i]);
77eb5504
         avio_write(bc, nut->header[i], nut->header_len[i]);
70ea1e69
     }
97d5eb11
 }
70ea1e69
 
fce4450d
 static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
                               AVStream *st, int i)
 {
     NUTContext *nut       = avctx->priv_data;
59729451
     AVCodecContext *codec = st->codec;
1bd442c2
 
f8280ff4
     ff_put_v(bc, i);
fce4450d
     switch (codec->codec_type) {
c73fcc8d
     case AVMEDIA_TYPE_VIDEO:    ff_put_v(bc, 0); break;
     case AVMEDIA_TYPE_AUDIO:    ff_put_v(bc, 1); break;
f8280ff4
     case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
c73fcc8d
     default:                    ff_put_v(bc, 3); break;
0809b51e
     }
f8280ff4
     ff_put_v(bc, 4);
c73fcc8d
     if (codec->codec_tag) {
77eb5504
         avio_wl32(bc, codec->codec_tag);
fa586439
     } else {
         av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
ffd5f098
         return AVERROR(EINVAL);
fa586439
     }
0809b51e
 
f8280ff4
     ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
     ff_put_v(bc, nut->stream[i].msb_pts_shift);
     ff_put_v(bc, nut->stream[i].max_pts_distance);
     ff_put_v(bc, codec->has_b_frames);
77eb5504
     avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
0809b51e
 
f8280ff4
     ff_put_v(bc, codec->extradata_size);
77eb5504
     avio_write(bc, codec->extradata, codec->extradata_size);
0809b51e
 
fce4450d
     switch (codec->codec_type) {
72415b2a
     case AVMEDIA_TYPE_AUDIO:
f8280ff4
         ff_put_v(bc, codec->sample_rate);
         ff_put_v(bc, 1);
         ff_put_v(bc, codec->channels);
0809b51e
         break;
72415b2a
     case AVMEDIA_TYPE_VIDEO:
f8280ff4
         ff_put_v(bc, codec->width);
         ff_put_v(bc, codec->height);
0a5790d1
 
fce4450d
         if (st->sample_aspect_ratio.num <= 0 ||
             st->sample_aspect_ratio.den <= 0) {
f8280ff4
             ff_put_v(bc, 0);
             ff_put_v(bc, 0);
fce4450d
         } else {
f8280ff4
             ff_put_v(bc, st->sample_aspect_ratio.num);
             ff_put_v(bc, st->sample_aspect_ratio.den);
0a5790d1
         }
f8280ff4
         ff_put_v(bc, 0); /* csp type -- unknown */
0809b51e
         break;
     default:
         break;
     }
     return 0;
 }
 
fce4450d
 static int add_info(AVIOContext *bc, const char *type, const char *value)
 {
ead1939f
     put_str(bc, type);
     put_s(bc, -1);
     put_str(bc, value);
     return 1;
 }
 
fce4450d
 static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
 {
     AVFormatContext *s   = nut->avf;
d2d67e42
     AVDictionaryEntry *t = NULL;
ae628ec1
     AVIOContext *dyn_bc;
fce4450d
     uint8_t *dyn_buf = NULL;
     int count        = 0, dyn_size;
     int ret          = avio_open_dyn_buf(&dyn_bc);
     if (ret < 0)
899681cd
         return ret;
ead1939f
 
d2d67e42
     while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
43382b5f
         count += add_info(dyn_bc, t->key, t->value);
ead1939f
 
f8280ff4
     ff_put_v(bc, 0); //stream_if_plus1
     ff_put_v(bc, 0); //chapter_id
     ff_put_v(bc, 0); //timestamp_start
     ff_put_v(bc, 0); //length
ead1939f
 
f8280ff4
     ff_put_v(bc, count);
ead1939f
 
fce4450d
     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
77eb5504
     avio_write(bc, dyn_buf, dyn_size);
ead1939f
     av_free(dyn_buf);
899681cd
     return 0;
ead1939f
 }
 
c73fcc8d
 static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id) {
90c2295b
     AVFormatContext *s= nut->avf;
     AVStream* st = s->streams[stream_id];
ac456373
     AVDictionaryEntry *t = NULL;
ae628ec1
     AVIOContext *dyn_bc;
90c2295b
     uint8_t *dyn_buf=NULL;
     int count=0, dyn_size, i;
b92c5452
     int ret = avio_open_dyn_buf(&dyn_bc);
c73fcc8d
     if (ret < 0)
90c2295b
         return ret;
 
ac456373
     while ((t = av_dict_get(st->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
         count += add_info(dyn_bc, t->key, t->value);
90c2295b
     for (i=0; ff_nut_dispositions[i].flag; ++i) {
         if (st->disposition & ff_nut_dispositions[i].flag)
             count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
     }
e3fb5bc1
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
         uint8_t buf[256];
         snprintf(buf, sizeof(buf), "%d/%d", st->codec->time_base.den, st->codec->time_base.num);
         count += add_info(dyn_bc, "r_frame_rate", buf);
     }
6dc7d80d
     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
90c2295b
 
     if (count) {
f8280ff4
         ff_put_v(bc, stream_id + 1); //stream_id_plus1
         ff_put_v(bc, 0); //chapter_id
         ff_put_v(bc, 0); //timestamp_start
         ff_put_v(bc, 0); //length
90c2295b
 
f8280ff4
         ff_put_v(bc, count);
90c2295b
 
77eb5504
         avio_write(bc, dyn_buf, dyn_size);
90c2295b
     }
 
     av_free(dyn_buf);
     return count;
 }
 
073f8b10
 static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
 {
     AVIOContext *dyn_bc;
fce4450d
     uint8_t *dyn_buf     = NULL;
d2d67e42
     AVDictionaryEntry *t = NULL;
fce4450d
     AVChapter *ch        = nut->avf->chapters[id];
073f8b10
     int ret, dyn_size, count = 0;
 
b92c5452
     ret = avio_open_dyn_buf(&dyn_bc);
073f8b10
     if (ret < 0)
         return ret;
 
     ff_put_v(bc, 0);                                        // stream_id_plus1
     put_s(bc, id + 1);                                      // chapter_id
     put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
     ff_put_v(bc, ch->end - ch->start);                      // chapter_len
 
d2d67e42
     while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
073f8b10
         count += add_info(dyn_bc, t->key, t->value);
 
     ff_put_v(bc, count);
 
6dc7d80d
     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
073f8b10
     avio_write(bc, dyn_buf, dyn_size);
     av_freep(&dyn_buf);
     return 0;
 }
 
c73fcc8d
 static int write_index(NUTContext *nut, AVIOContext *bc) {
3a621c9d
     int i;
     Syncpoint dummy= { .pos= 0 };
     Syncpoint *next_node[2] = { NULL };
     int64_t startpos = avio_tell(bc);
     int64_t payload_size;
 
     put_tt(nut, nut->max_pts_tb, bc, nut->max_pts);
 
     ff_put_v(bc, nut->sp_count);
 
c73fcc8d
     for (i=0; i<nut->sp_count; i++) {
3a621c9d
         av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp, (void**)next_node);
         ff_put_v(bc, (next_node[1]->pos >> 4) - (dummy.pos>>4));
         dummy.pos = next_node[1]->pos;
     }
 
c73fcc8d
     for (i=0; i<nut->avf->nb_streams; i++) {
3a621c9d
         StreamContext *nus= &nut->stream[i];
         int64_t last_pts= -1;
         int j, k;
c73fcc8d
         for (j=0; j<nut->sp_count; j++) {
de2a2caf
             int flag;
3a621c9d
             int n = 0;
de2a2caf
 
             if (j && nus->keyframe_pts[j] == nus->keyframe_pts[j-1]) {
                 av_log(nut->avf, AV_LOG_WARNING, "Multiple keyframes with same PTS\n");
                 nus->keyframe_pts[j] = AV_NOPTS_VALUE;
             }
 
             flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
c73fcc8d
             for (; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
3a621c9d
                 n++;
 
             ff_put_v(bc, 1 + 2*flag + 4*n);
c73fcc8d
             for (k= j - n; k<=j && k<nut->sp_count; k++) {
                 if (nus->keyframe_pts[k] == AV_NOPTS_VALUE)
3a621c9d
                     continue;
                 av_assert0(nus->keyframe_pts[k] > last_pts);
                 ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
                 last_pts = nus->keyframe_pts[k];
             }
         }
     }
 
     payload_size = avio_tell(bc) - startpos + 8 + 4;
 
     avio_wb64(bc, 8 + payload_size + av_log2(payload_size) / 7 + 1 + 4*(payload_size > 4096));
 
     return 0;
 }
 
fce4450d
 static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
 {
da9e6c42
     NUTContext *nut = avctx->priv_data;
ae628ec1
     AVIOContext *dyn_bc;
899681cd
     int i, ret;
7e506494
 
03700d39
     ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
 
b92c5452
     ret = avio_open_dyn_buf(&dyn_bc);
fce4450d
     if (ret < 0)
899681cd
         return ret;
     write_mainheader(nut, dyn_bc);
     put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
7e506494
 
fce4450d
     for (i = 0; i < nut->avf->nb_streams; i++) {
b92c5452
         ret = avio_open_dyn_buf(&dyn_bc);
fce4450d
         if (ret < 0)
899681cd
             return ret;
fce4450d
         ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
         if (ret < 0)
fc0c4124
             return ret;
899681cd
         put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
7e506494
     }
ead1939f
 
b92c5452
     ret = avio_open_dyn_buf(&dyn_bc);
fce4450d
     if (ret < 0)
899681cd
         return ret;
     write_globalinfo(nut, dyn_bc);
     put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
14b3f996
 
90c2295b
     for (i = 0; i < nut->avf->nb_streams; i++) {
b92c5452
         ret = avio_open_dyn_buf(&dyn_bc);
fce4450d
         if (ret < 0)
90c2295b
             return ret;
         ret = write_streaminfo(nut, dyn_bc, i);
         if (ret < 0)
             return ret;
         if (ret > 0)
             put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
         else {
fce4450d
             uint8_t *buf;
6dc7d80d
             avio_close_dyn_buf(dyn_bc, &buf);
90c2295b
             av_free(buf);
         }
     }
 
073f8b10
     for (i = 0; i < nut->avf->nb_chapters; i++) {
b92c5452
         ret = avio_open_dyn_buf(&dyn_bc);
073f8b10
         if (ret < 0)
             return ret;
         ret = write_chapter(nut, dyn_bc, i);
         if (ret < 0) {
             uint8_t *buf;
6dc7d80d
             avio_close_dyn_buf(dyn_bc, &buf);
073f8b10
             av_freep(&buf);
             return ret;
         }
         put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
     }
 
fce4450d
     nut->last_syncpoint_pos = INT_MIN;
14b3f996
     nut->header_count++;
899681cd
     return 0;
7e506494
 }
 
fce4450d
 static int nut_write_header(AVFormatContext *s)
 {
97d5eb11
     NUTContext *nut = s->priv_data;
ae628ec1
     AVIOContext *bc = s->pb;
fc0c4124
     int i, j, ret;
97d5eb11
 
fce4450d
     nut->avf = s;
97d5eb11
 
6a70fead
     nut->stream   = av_calloc(s->nb_streams,  sizeof(*nut->stream ));
     nut->chapter  = av_calloc(s->nb_chapters, sizeof(*nut->chapter));
     nut->time_base= av_calloc(s->nb_streams +
                               s->nb_chapters, sizeof(*nut->time_base));
6266c515
     if (!nut->stream || !nut->chapter || !nut->time_base) {
76432655
         av_freep(&nut->stream);
         av_freep(&nut->chapter);
         av_freep(&nut->time_base);
         return AVERROR(ENOMEM);
     }
97d5eb11
 
fce4450d
     for (i = 0; i < s->nb_streams; i++) {
         AVStream *st = s->streams[i];
97d5eb11
         int ssize;
         AVRational time_base;
         ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
 
c73fcc8d
         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->sample_rate) {
             time_base = (AVRational) {1, st->codec->sample_rate};
4abc411b
         } else {
de707bc8
             time_base = ff_choose_timebase(s, st, 48000);
4eb0f5f6
         }
 
c3f9ebf7
         avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
97d5eb11
 
fce4450d
         for (j = 0; j < nut->time_base_count; j++)
             if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
97d5eb11
                 break;
             }
fce4450d
         nut->time_base[j]        = time_base;
         nut->stream[i].time_base = &nut->time_base[j];
         if (j == nut->time_base_count)
97d5eb11
             nut->time_base_count++;
 
fce4450d
         if (INT64_C(1000) * time_base.num >= time_base.den)
97d5eb11
             nut->stream[i].msb_pts_shift = 7;
         else
             nut->stream[i].msb_pts_shift = 14;
fce4450d
         nut->stream[i].max_pts_distance =
             FFMAX(time_base.den, time_base.num) / time_base.num;
97d5eb11
     }
 
073f8b10
     for (i = 0; i < s->nb_chapters; i++) {
         AVChapter *ch = s->chapters[i];
 
fce4450d
         for (j = 0; j < nut->time_base_count; j++)
073f8b10
             if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
                 break;
 
fce4450d
         nut->time_base[j]         = ch->time_base;
073f8b10
         nut->chapter[i].time_base = &nut->time_base[j];
fce4450d
         if (j == nut->time_base_count)
073f8b10
             nut->time_base_count++;
     }
 
82badd27
     nut->max_distance = MAX_DISTANCE;
a712d725
     build_elision_headers(s);
97d5eb11
     build_frame_code(s);
4a6d790a
     av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
97d5eb11
 
77eb5504
     avio_write(bc, ID_STRING, strlen(ID_STRING));
     avio_w8(bc, 0);
97d5eb11
 
fc0c4124
     if ((ret = write_headers(s, bc)) < 0)
         return ret;
dcc9bde0
 
5c4e2e87
     if (s->avoid_negative_ts < 0)
         s->avoid_negative_ts = 1;
 
b7f2fdde
     avio_flush(bc);
70ea1e69
 
     return 0;
 }
 
fce4450d
 static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc,
                             AVPacket *pkt)
 {
     int flags = 0;
 
     if (pkt->flags & AV_PKT_FLAG_KEY)
         flags |= FLAG_KEY;
     if (pkt->stream_index != fc->stream_id)
         flags |= FLAG_STREAM_ID;
     if (pkt->size / fc->size_mul)
         flags |= FLAG_SIZE_MSB;
     if (pkt->pts - nus->last_pts != fc->pts_delta)
         flags |= FLAG_CODED_PTS;
8113e838
     if (pkt->side_data_elems && nut->version > 3)
         flags |= FLAG_SM_DATA;
fce4450d
     if (pkt->size > 2 * nut->max_distance)
         flags |= FLAG_CHECKSUM;
     if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
         flags |= FLAG_CHECKSUM;
     if (pkt->size < nut->header_len[fc->header_idx] ||
         (pkt->size > 4096 && fc->header_idx)        ||
         memcmp(pkt->data, nut->header[fc->header_idx],
                nut->header_len[fc->header_idx]))
         flags |= FLAG_HEADER_IDX;
e1249ba9
 
d2062ff6
     return flags | (fc->flags & FLAG_CODED);
e1249ba9
 }
 
fce4450d
 static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
 {
a712d725
     int i;
fce4450d
     int best_i   = 0;
     int best_len = 0;
a712d725
 
fce4450d
     if (pkt->size > 4096)
a712d725
         return 0;
 
fce4450d
     for (i = 1; i < nut->header_count; i++)
         if (pkt->size >= nut->header_len[i]
             && nut->header_len[i] > best_len
             && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
             best_i   = i;
             best_len = nut->header_len[i];
a712d725
         }
     return best_i;
 }
 
8113e838
 static int write_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta)
 {
     AVStream *st = s->streams[pkt->stream_index];
     int ret, i, dyn_size;
     unsigned flags;
     AVIOContext *dyn_bc;
     int sm_data_count = 0;
     uint8_t tmp[256];
     uint8_t *dyn_buf;
 
     ret = avio_open_dyn_buf(&dyn_bc);
     if (ret < 0)
         return ret;
 
     for (i = 0; i<pkt->side_data_elems; i++) {
         const uint8_t *data = pkt->side_data[i].data;
         int size = pkt->side_data[i].size;
         const uint8_t *data_end = data + size;
 
         if (is_meta) {
             if (   pkt->side_data[i].type == AV_PKT_DATA_METADATA_UPDATE
                 || pkt->side_data[i].type == AV_PKT_DATA_STRINGS_METADATA) {
                 if (!size || data[size-1])
                     return AVERROR(EINVAL);
                 while (data < data_end) {
                     const uint8_t *key = data;
                     const uint8_t *val = data + strlen(key) + 1;
 
                     if(val >= data_end)
                         return AVERROR(EINVAL);
                     put_str(dyn_bc, key);
                     put_s(dyn_bc, -1);
                     put_str(dyn_bc, val);
                     data = val + strlen(val) + 1;
                     sm_data_count++;
                 }
             }
         } else {
             switch (pkt->side_data[i].type) {
             case AV_PKT_DATA_PALETTE:
             case AV_PKT_DATA_NEW_EXTRADATA:
             case AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL:
             default:
                 if (pkt->side_data[i].type == AV_PKT_DATA_PALETTE) {
                     put_str(dyn_bc, "Palette");
                 } else if(pkt->side_data[i].type == AV_PKT_DATA_NEW_EXTRADATA) {
                     put_str(dyn_bc, "Extradata");
                 } else if(pkt->side_data[i].type == AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL) {
                     snprintf(tmp, sizeof(tmp), "CodecSpecificSide%"PRId64"", AV_RB64(data));
                     put_str(dyn_bc, tmp);
                 } else {
                     snprintf(tmp, sizeof(tmp), "UserData%s-SD-%d",
                             (st->codec->flags & CODEC_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT,
                             pkt->side_data[i].type);
                     put_str(dyn_bc, tmp);
                 }
                 put_s(dyn_bc, -2);
                 put_str(dyn_bc, "bin");
                 ff_put_v(dyn_bc, pkt->side_data[i].size);
                 avio_write(dyn_bc, data, pkt->side_data[i].size);
                 sm_data_count++;
                 break;
             case AV_PKT_DATA_PARAM_CHANGE:
                 flags = bytestream_get_le32(&data);
                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
                     put_str(dyn_bc, "Channels");
                     put_s(dyn_bc, bytestream_get_le32(&data));
                     sm_data_count++;
                 }
                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
                     put_str(dyn_bc, "ChannelLayout");
                     put_s(dyn_bc, -2);
                     put_str(dyn_bc, "u64");
                     ff_put_v(bc, 8);
                     avio_write(dyn_bc, data, 8); data+=8;
                     sm_data_count++;
                 }
                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
                     put_str(dyn_bc, "SampleRate");
                     put_s(dyn_bc, bytestream_get_le32(&data));
                     sm_data_count++;
                 }
                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
                     put_str(dyn_bc, "Width");
                     put_s(dyn_bc, bytestream_get_le32(&data));
                     put_str(dyn_bc, "Height");
                     put_s(dyn_bc, bytestream_get_le32(&data));
                     sm_data_count+=2;
                 }
4b8c599e
                 break;
8113e838
             case AV_PKT_DATA_SKIP_SAMPLES:
                 if (AV_RL32(data)) {
                     put_str(dyn_bc, "SkipStart");
                     put_s(dyn_bc, (unsigned)AV_RL32(data));
                     sm_data_count++;
                 }
                 if (AV_RL32(data+4)) {
                     put_str(dyn_bc, "SkipEnd");
                     put_s(dyn_bc, (unsigned)AV_RL32(data+4));
                     sm_data_count++;
                 }
                 break;
             case AV_PKT_DATA_METADATA_UPDATE:
             case AV_PKT_DATA_STRINGS_METADATA:
                 // belongs into meta, not side data
                 break;
             }
         }
     }
 
     ff_put_v(bc, sm_data_count);
     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     avio_write(bc, dyn_buf, dyn_size);
     av_freep(&dyn_buf);
 
     return 0;
 }
 
fce4450d
 static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     NUTContext *nut    = s->priv_data;
     StreamContext *nus = &nut->stream[pkt->stream_index];
8113e838
     AVIOContext *bc    = s->pb, *dyn_bc, *sm_bc = NULL;
e1249ba9
     FrameCode *fc;
     int64_t coded_pts;
c73fcc8d
     int best_length, frame_code, flags, needed_flags, i, header_idx;
     int best_header_idx;
cc947f04
     int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
fce4450d
     int store_sp  = 0;
899681cd
     int ret;
8113e838
     int sm_size = 0;
     int data_size = pkt->size;
     uint8_t *sm_buf;
e1249ba9
 
b010d9b5
     if (pkt->pts < 0) {
07585ffa
         av_log(s, AV_LOG_ERROR,
                "Negative pts not supported stream %d, pts %"PRId64"\n",
                pkt->stream_index, pkt->pts);
b010d9b5
         return AVERROR(EINVAL);
     }
f53dd468
 
8113e838
     if (pkt->side_data_elems && nut->version > 3) {
         ret = avio_open_dyn_buf(&sm_bc);
         if (ret < 0)
             return ret;
         write_sm_data(s, sm_bc, pkt, 0);
         write_sm_data(s, sm_bc, pkt, 1);
         sm_size = avio_close_dyn_buf(sm_bc, &sm_buf);
         data_size += sm_size;
     }
 
fce4450d
     if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
da9e6c42
         write_headers(s, bc);
14b3f996
 
fce4450d
     if (key_frame && !(nus->last_flags & FLAG_KEY))
         store_sp = 1;
e1249ba9
 
8113e838
     if (data_size + 30 /*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
fce4450d
         store_sp = 1;
e1249ba9
 
93951943
 //FIXME: Ensure store_sp is 1 in the first place.
e1249ba9
 
fce4450d
     if (store_sp) {
         Syncpoint *sp, dummy = { .pos = INT64_MAX };
7c04134f
 
e1249ba9
         ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
fce4450d
         for (i = 0; i < s->nb_streams; i++) {
             AVStream *st   = s->streams[i];
4ddcc983
             int64_t dts_tb = av_rescale_rnd(pkt->dts,
                 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
                 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
                 AV_ROUND_DOWN);
fce4450d
             int index = av_index_search_timestamp(st, dts_tb,
                                                   AVSEEK_FLAG_BACKWARD);
             if (index >= 0)
                 dummy.pos = FFMIN(dummy.pos, st->index_entries[index].pos);
7c04134f
         }
fce4450d
         if (dummy.pos == INT64_MAX)
             dummy.pos = 0;
         sp = av_tree_find(nut->syncpoints, &dummy, (void *)ff_nut_sp_pos_cmp,
                           NULL);
e1249ba9
 
fce4450d
         nut->last_syncpoint_pos = avio_tell(bc);
         ret                     = avio_open_dyn_buf(&dyn_bc);
         if (ret < 0)
899681cd
             return ret;
073f8b10
         put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
fce4450d
         ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos) >> 4 : 0);
899681cd
         put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
7c04134f
 
55ae13e3
         if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
             return ret;
c2a134c6
 
c73fcc8d
         if ((1ll<<60) % nut->sp_count == 0)
             for (i=0; i<s->nb_streams; i++) {
c2a134c6
                 int j;
                 StreamContext *nus = &nut->stream[i];
f2afe961
                 av_reallocp_array(&nus->keyframe_pts, 2*nut->sp_count, sizeof(*nus->keyframe_pts));
c73fcc8d
                 if (!nus->keyframe_pts)
c2a134c6
                     return AVERROR(ENOMEM);
c73fcc8d
                 for (j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
c2a134c6
                     nus->keyframe_pts[j] = AV_NOPTS_VALUE;
         }
e1249ba9
     }
4a6d790a
     av_assert0(nus->last_pts != AV_NOPTS_VALUE);
e1249ba9
 
fce4450d
     coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
     if (ff_lsb2full(nus, coded_pts) != pkt->pts)
         coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
e1249ba9
 
fce4450d
     best_header_idx = find_best_header_idx(nut, pkt);
a712d725
 
fce4450d
     best_length = INT_MAX;
     frame_code  = -1;
     for (i = 0; i < 256; i++) {
         int length    = 0;
         FrameCode *fc = &nut->frame_code[i];
         int flags     = fc->flags;
e1249ba9
 
fce4450d
         if (flags & FLAG_INVALID)
e1249ba9
             continue;
fce4450d
         needed_flags = get_needed_flags(nut, nus, fc, pkt);
e1249ba9
 
fce4450d
         if (flags & FLAG_CODED) {
e1249ba9
             length++;
63dd9d0e
             flags = needed_flags;
e1249ba9
         }
 
fce4450d
         if ((flags & needed_flags) != needed_flags)
e1249ba9
             continue;
 
fce4450d
         if ((flags ^ needed_flags) & FLAG_KEY)
e1249ba9
             continue;
 
fce4450d
         if (flags & FLAG_STREAM_ID)
             length += ff_get_v_length(pkt->stream_index);
e1249ba9
 
8113e838
         if (data_size % fc->size_mul != fc->size_lsb)
e1249ba9
             continue;
fce4450d
         if (flags & FLAG_SIZE_MSB)
8113e838
             length += ff_get_v_length(data_size / fc->size_mul);
e1249ba9
 
fce4450d
         if (flags & FLAG_CHECKSUM)
             length += 4;
e1249ba9
 
fce4450d
         if (flags & FLAG_CODED_PTS)
f8280ff4
             length += ff_get_v_length(coded_pts);
e1249ba9
 
c73fcc8d
         if (   (flags & FLAG_CODED)
             && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx] + 1) {
a712d725
             flags |= FLAG_HEADER_IDX;
         }
 
fce4450d
         if (flags & FLAG_HEADER_IDX) {
a712d725
             length += 1 - nut->header_len[best_header_idx];
fce4450d
         } else {
a712d725
             length -= nut->header_len[fc->header_idx];
         }
 
fce4450d
         length *= 4;
         length += !(flags & FLAG_CODED_PTS);
         length += !(flags & FLAG_CHECKSUM);
e1249ba9
 
fce4450d
         if (length < best_length) {
             best_length = length;
             frame_code  = i;
e1249ba9
         }
     }
dd208614
     av_assert0(frame_code != -1);
fce4450d
     fc           = &nut->frame_code[frame_code];
     flags        = fc->flags;
     needed_flags = get_needed_flags(nut, nus, fc, pkt);
     header_idx   = fc->header_idx;
e1249ba9
 
4c4427a7
     ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
77eb5504
     avio_w8(bc, frame_code);
fce4450d
     if (flags & FLAG_CODED) {
         ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
e1249ba9
         flags = needed_flags;
     }
c73fcc8d
     if (flags & FLAG_STREAM_ID)  ff_put_v(bc, pkt->stream_index);
     if (flags & FLAG_CODED_PTS)  ff_put_v(bc, coded_pts);
8113e838
     if (flags & FLAG_SIZE_MSB )  ff_put_v(bc, data_size / fc->size_mul);
c73fcc8d
     if (flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx = best_header_idx);
e1249ba9
 
c73fcc8d
     if (flags & FLAG_CHECKSUM)   avio_wl32(bc, ffio_get_checksum(bc));
     else                         ffio_get_checksum(bc);
e1249ba9
 
8113e838
     if (flags & FLAG_SM_DATA) {
         avio_write(bc, sm_buf, sm_size);
         av_freep(&sm_buf);
     }
77eb5504
     avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
8113e838
 
fce4450d
     nus->last_flags = flags;
     nus->last_pts   = pkt->pts;
7c04134f
 
     //FIXME just store one per syncpoint
c73fcc8d
     if (flags & FLAG_KEY) {
7c04134f
         av_add_index_entry(
             s->streams[pkt->stream_index],
             nut->last_syncpoint_pos,
             pkt->pts,
             0,
             0,
             AVINDEX_KEYFRAME);
c73fcc8d
         if (nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
c2a134c6
             nus->keyframe_pts[nut->sp_count] = pkt->pts;
     }
7c04134f
 
c73fcc8d
     if (!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
b2a8ce4e
         nut->max_pts = pkt->pts;
         nut->max_pts_tb = nus->time_base;
     }
 
70ea1e69
     return 0;
 }
 
fce4450d
 static int nut_write_trailer(AVFormatContext *s)
 {
     NUTContext *nut = s->priv_data;
3a621c9d
     AVIOContext *bc = s->pb, *dyn_bc;
     int i, ret;
bd533e6c
 
fce4450d
     while (nut->header_count < 3)
da9e6c42
         write_headers(s, bc);
3a621c9d
 
     ret = avio_open_dyn_buf(&dyn_bc);
e39821a6
     if (ret >= 0 && nut->sp_count) {
3a621c9d
         write_index(nut, dyn_bc);
         put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
     }
 
4b83fc0f
     ff_nut_free_sp(nut);
c73fcc8d
     for (i=0; i<s->nb_streams; i++)
c2a134c6
         av_freep(&nut->stream[i].keyframe_pts);
 
27dbc47c
     av_freep(&nut->stream);
2cface71
     av_freep(&nut->chapter);
27dbc47c
     av_freep(&nut->time_base);
bd533e6c
 
     return 0;
 }
 
c6610a21
 AVOutputFormat ff_nut_muxer = {
dfc2c4d9
     .name           = "nut",
6774247a
     .long_name      = NULL_IF_CONFIG_SMALL("NUT"),
dfc2c4d9
     .mime_type      = "video/x-nut",
     .extensions     = "nut",
     .priv_data_size = sizeof(NUTContext),
36ef5369
     .audio_codec    = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
                       CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
     .video_codec    = AV_CODEC_ID_MPEG4,
5ee5dc4e
     .write_header   = nut_write_header,
     .write_packet   = nut_write_packet,
     .write_trailer  = nut_write_trailer,
20234a4b
     .flags          = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
1bd442c2
     .codec_tag      = ff_nut_codec_tags,
70ea1e69
 };