LCOV - code coverage report
Current view: top level - libavformat - nutenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 573 776 73.8 %
Date: 2017-12-10 21:22:29 Functions: 21 23 91.3 %

          Line data    Source code
       1             : /*
       2             :  * nut muxer
       3             :  * Copyright (c) 2004-2007 Michael Niedermayer
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       7             :  * FFmpeg is free software; you can redistribute it and/or
       8             :  * modify it under the terms of the GNU Lesser General Public
       9             :  * License as published by the Free Software Foundation; either
      10             :  * version 2.1 of the License, or (at your option) any later version.
      11             :  *
      12             :  * FFmpeg is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15             :  * Lesser General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU Lesser General Public
      18             :  * License along with FFmpeg; if not, write to the Free Software
      19             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      20             :  */
      21             : 
      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/avassert.h"
      29             : #include "libavutil/time.h"
      30             : #include "libavutil/opt.h"
      31             : #include "libavcodec/bytestream.h"
      32             : #include "libavcodec/mpegaudiodata.h"
      33             : #include "nut.h"
      34             : #include "internal.h"
      35             : #include "avio_internal.h"
      36             : #include "riff.h"
      37             : 
      38        2981 : static int find_expected_header(AVCodecParameters *p, int size, int key_frame,
      39             :                                 uint8_t out[64])
      40             : {
      41        2981 :     int sample_rate = p->sample_rate;
      42             : 
      43        2981 :     if (size > 4096)
      44           0 :         return 0;
      45             : 
      46        2981 :     AV_WB24(out, 1);
      47             : 
      48        2981 :     if (p->codec_id == AV_CODEC_ID_MPEG4) {
      49           0 :         if (key_frame) {
      50           0 :             return 3;
      51             :         } else {
      52           0 :             out[3] = 0xB6;
      53           0 :             return 4;
      54             :         }
      55        5962 :     } else if (p->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
      56        2981 :                p->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
      57           0 :         return 3;
      58        2981 :     } else if (p->codec_id == AV_CODEC_ID_H264) {
      59           0 :         return 3;
      60        5962 :     } else if (p->codec_id == AV_CODEC_ID_MP3 ||
      61        2981 :                p->codec_id == AV_CODEC_ID_MP2) {
      62             :         int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
      63         126 :         int layer           = p->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
      64         126 :         unsigned int header = 0xFFF00000;
      65             : 
      66         126 :         lsf           = sample_rate < (24000 + 32000) / 2;
      67         126 :         mpeg25        = sample_rate < (12000 + 16000) / 2;
      68         126 :         sample_rate <<= lsf + mpeg25;
      69         126 :         if      (sample_rate < (32000 + 44100) / 2) sample_rate_index = 2;
      70         126 :         else if (sample_rate < (44100 + 48000) / 2) sample_rate_index = 0;
      71           0 :         else                                        sample_rate_index = 1;
      72             : 
      73         126 :         sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
      74             : 
      75        3568 :         for (bitrate_index = 2; bitrate_index < 30; bitrate_index++) {
      76        3446 :             frame_size =
      77        3446 :                 avpriv_mpa_bitrate_tab[lsf][layer - 1][bitrate_index >> 1];
      78        6892 :             frame_size = (frame_size * 144000) / (sample_rate << lsf) +
      79        3446 :                 (bitrate_index & 1);
      80             : 
      81        3446 :             if (frame_size == size)
      82           4 :                 break;
      83             :         }
      84             : 
      85         126 :         header |= (!lsf) << 19;
      86         126 :         header |= (4 - layer) << 17;
      87         126 :         header |= 1 << 16; //no crc
      88         126 :         AV_WB32(out, header);
      89         126 :         if (size <= 0)
      90         122 :             return 2;  //we guess there is no crc, if there is one the user clearly does not care about overhead
      91           4 :         if (bitrate_index == 30)
      92           0 :             return -1;  //something is wrong ...
      93             : 
      94           4 :         header |= (bitrate_index >> 1) << 12;
      95           4 :         header |= sample_rate_index << 10;
      96           4 :         header |= (bitrate_index & 1) << 9;
      97             : 
      98           4 :         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
     101             :     }
     102        2855 :     return 0;
     103             : }
     104             : 
     105        2981 : static int find_header_idx(AVFormatContext *s, AVCodecParameters *p, int size,
     106             :                            int frame_type)
     107             : {
     108        2981 :     NUTContext *nut = s->priv_data;
     109             :     uint8_t out[64];
     110             :     int i;
     111        2981 :     int len = find_expected_header(p, size, frame_type, out);
     112             : 
     113       20741 :     for (i = 1; i < nut->header_count; i++) {
     114       17886 :         if (len == nut->header_len[i] && !memcmp(out, nut->header[i], len)) {
     115         126 :             return i;
     116             :         }
     117             :     }
     118             : 
     119        2855 :     return 0;
     120             : }
     121             : 
     122        1770 : static void build_elision_headers(AVFormatContext *s)
     123             : {
     124        1770 :     NUTContext *nut = s->priv_data;
     125             :     int i;
     126             :     //FIXME this is lame
     127             :     //FIXME write a 2pass mode to find the maximal headers
     128             :     static const uint8_t headers[][5] = {
     129             :         { 3, 0x00, 0x00, 0x01 },
     130             :         { 4, 0x00, 0x00, 0x01, 0xB6},
     131             :         { 2, 0xFF, 0xFA }, //mp3+crc
     132             :         { 2, 0xFF, 0xFB }, //mp3
     133             :         { 2, 0xFF, 0xFC }, //mp2+crc
     134             :         { 2, 0xFF, 0xFD }, //mp2
     135             :     };
     136             : 
     137        1770 :     nut->header_count = 7;
     138       12390 :     for (i = 1; i < nut->header_count; i++) {
     139       10620 :         nut->header_len[i] = headers[i - 1][0];
     140       10620 :         nut->header[i]     = &headers[i - 1][1];
     141             :     }
     142        1770 : }
     143             : 
     144        1770 : static void build_frame_code(AVFormatContext *s)
     145             : {
     146        1770 :     NUTContext *nut = s->priv_data;
     147             :     int key_frame, index, pred, stream_id;
     148        1770 :     int start = 1;
     149        1770 :     int end   = 254;
     150        1770 :     int keyframe_0_esc = s->nb_streams > 2;
     151             :     int pred_table[10];
     152             :     FrameCode *ft;
     153             : 
     154        1770 :     ft            = &nut->frame_code[start];
     155        1770 :     ft->flags     = FLAG_CODED;
     156        1770 :     ft->size_mul  = 1;
     157        1770 :     ft->pts_delta = 1;
     158        1770 :     start++;
     159             : 
     160        1770 :     if (keyframe_0_esc) {
     161             :         /* keyframe = 0 escape */
     162           1 :         FrameCode *ft = &nut->frame_code[start];
     163           1 :         ft->flags    = FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
     164           1 :         ft->size_mul = 1;
     165           1 :         start++;
     166             :     }
     167             : 
     168        3543 :     for (stream_id = 0; stream_id < s->nb_streams; stream_id++) {
     169        1773 :         int start2 = start + (end - start) * stream_id       / s->nb_streams;
     170        1773 :         int end2   = start + (end - start) * (stream_id + 1) / s->nb_streams;
     171        1773 :         AVCodecParameters *par        = s->streams[stream_id]->codecpar;
     172        1773 :         int is_audio                  = par->codec_type == AVMEDIA_TYPE_AUDIO;
     173        1773 :         int intra_only        = /*codec->intra_only || */ is_audio;
     174             :         int pred_count;
     175        1773 :         int frame_size = 0;
     176             : 
     177        1773 :         if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
     178          13 :             frame_size = av_get_audio_frame_duration2(par, 0);
     179          13 :             if (par->codec_id == AV_CODEC_ID_VORBIS && !frame_size)
     180           0 :                 frame_size = 64;
     181             :         } else {
     182        1760 :             AVRational f = av_div_q(av_inv_q(s->streams[stream_id]->avg_frame_rate), *nut->stream[stream_id].time_base);
     183        1760 :             if (f.den == 1 && f.num>0)
     184        1760 :                 frame_size = f.num;
     185             :         }
     186        1773 :         if (!frame_size)
     187          12 :             frame_size = 1;
     188             : 
     189        5319 :         for (key_frame = 0; key_frame < 2; key_frame++) {
     190        3546 :             if (!intra_only || !keyframe_0_esc || key_frame != 0) {
     191        3545 :                 FrameCode *ft = &nut->frame_code[start2];
     192        3545 :                 ft->flags     = FLAG_KEY * key_frame;
     193        3545 :                 ft->flags    |= FLAG_SIZE_MSB | FLAG_CODED_PTS;
     194        3545 :                 ft->stream_id = stream_id;
     195        3545 :                 ft->size_mul  = 1;
     196        3545 :                 if (is_audio)
     197          25 :                     ft->header_idx = find_header_idx(s, par, -1, key_frame);
     198        3545 :                 start2++;
     199             :             }
     200             :         }
     201             : 
     202        1773 :         key_frame = intra_only;
     203             : #if 1
     204        1773 :         if (is_audio) {
     205             :             int frame_bytes;
     206             :             int pts;
     207             : 
     208          13 :             if (par->block_align > 0) {
     209          12 :                 frame_bytes = par->block_align;
     210             :             } else {
     211           1 :                 int frame_size = av_get_audio_frame_duration2(par, 0);
     212           1 :                 frame_bytes = frame_size * (int64_t)par->bit_rate / (8 * par->sample_rate);
     213             :             }
     214             : 
     215          39 :             for (pts = 0; pts < 2; pts++) {
     216          78 :                 for (pred = 0; pred < 2; pred++) {
     217          52 :                     FrameCode *ft  = &nut->frame_code[start2];
     218          52 :                     ft->flags      = FLAG_KEY * key_frame;
     219          52 :                     ft->stream_id  = stream_id;
     220          52 :                     ft->size_mul   = frame_bytes + 2;
     221          52 :                     ft->size_lsb   = frame_bytes + pred;
     222          52 :                     ft->pts_delta  = pts * frame_size;
     223          52 :                     ft->header_idx = find_header_idx(s, par, frame_bytes + pred, key_frame);
     224          52 :                     start2++;
     225             :                 }
     226             :             }
     227             :         } else {
     228        1760 :             FrameCode *ft = &nut->frame_code[start2];
     229        1760 :             ft->flags     = FLAG_KEY | FLAG_SIZE_MSB;
     230        1760 :             ft->stream_id = stream_id;
     231        1760 :             ft->size_mul  = 1;
     232        1760 :             ft->pts_delta = frame_size;
     233        1760 :             start2++;
     234             :         }
     235             : #endif
     236             : 
     237        1773 :         if (par->video_delay) {
     238           0 :             pred_count    = 5;
     239           0 :             pred_table[0] = -2;
     240           0 :             pred_table[1] = -1;
     241           0 :             pred_table[2] = 1;
     242           0 :             pred_table[3] = 3;
     243           0 :             pred_table[4] = 4;
     244        1773 :         } else if (par->codec_id == AV_CODEC_ID_VORBIS) {
     245           0 :             pred_count    = 3;
     246           0 :             pred_table[0] = 2;
     247           0 :             pred_table[1] = 9;
     248           0 :             pred_table[2] = 16;
     249             :         } else {
     250        1773 :             pred_count    = 1;
     251        1773 :             pred_table[0] = 1;
     252             :         }
     253             : 
     254        3546 :         for (pred = 0; pred < pred_count; pred++) {
     255        1773 :             int start3 = start2 + (end2 - start2) * pred / pred_count;
     256        1773 :             int end3   = start2 + (end2 - start2) * (pred + 1) / pred_count;
     257             : 
     258        1773 :             pred_table[pred] *= frame_size;
     259             : 
     260      442455 :             for (index = start3; index < end3; index++) {
     261      440682 :                 FrameCode *ft = &nut->frame_code[index];
     262      440682 :                 ft->flags     = FLAG_KEY * key_frame;
     263      440682 :                 ft->flags    |= FLAG_SIZE_MSB;
     264      440682 :                 ft->stream_id = stream_id;
     265             : //FIXME use single byte size and pred from last
     266      440682 :                 ft->size_mul  = end3 - start3;
     267      440682 :                 ft->size_lsb  = index - start3;
     268      440682 :                 ft->pts_delta = pred_table[pred];
     269      440682 :                 if (is_audio)
     270        2904 :                     ft->header_idx = find_header_idx(s, par, -1, key_frame);
     271             :             }
     272             :         }
     273             :     }
     274        1770 :     memmove(&nut->frame_code['N' + 1], &nut->frame_code['N'], sizeof(FrameCode) * (255 - 'N'));
     275        1770 :     nut->frame_code[0].flags       =
     276        1770 :         nut->frame_code[255].flags =
     277        1770 :         nut->frame_code['N'].flags = FLAG_INVALID;
     278        1770 : }
     279             : 
     280        5245 : static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val)
     281             : {
     282        5245 :     val *= nut->time_base_count;
     283        5245 :     val += time_base - nut->time_base;
     284        5245 :     ff_put_v(bc, val);
     285        5245 : }
     286             : /**
     287             :  * Store a string as vb.
     288             :  */
     289        7080 : static void put_str(AVIOContext *bc, const char *string)
     290             : {
     291        7080 :     size_t len = strlen(string);
     292             : 
     293        7080 :     ff_put_v(bc, len);
     294        7080 :     avio_write(bc, string, len);
     295        7080 : }
     296             : 
     297       14182 : static void put_s(AVIOContext *bc, int64_t val)
     298             : {
     299       14182 :     ff_put_v(bc, 2 * FFABS(val) - (val > 0));
     300       14182 : }
     301             : 
     302             : //FIXME remove calculate_checksum
     303       12331 : static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc,
     304             :                        int calculate_checksum, uint64_t startcode)
     305             : {
     306       12331 :     uint8_t *dyn_buf = NULL;
     307       12331 :     int dyn_size     = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     308       12331 :     int forw_ptr     = dyn_size + 4 * calculate_checksum;
     309             : 
     310       12331 :     if (forw_ptr > 4096)
     311           0 :         ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
     312       12331 :     avio_wb64(bc, startcode);
     313       12331 :     ff_put_v(bc, forw_ptr);
     314       12331 :     if (forw_ptr > 4096)
     315           0 :         avio_wl32(bc, ffio_get_checksum(bc));
     316             : 
     317       12331 :     if (calculate_checksum)
     318       12331 :         ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
     319       12331 :     avio_write(bc, dyn_buf, dyn_size);
     320       12331 :     if (calculate_checksum)
     321       12331 :         avio_wl32(bc, ffio_get_checksum(bc));
     322             : 
     323       12331 :     av_free(dyn_buf);
     324       12331 : }
     325             : 
     326        1770 : static void write_mainheader(NUTContext *nut, AVIOContext *bc)
     327             : {
     328             :     int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,
     329             :         tmp_head_idx;
     330             :     int64_t tmp_match;
     331             : 
     332        1770 :     ff_put_v(bc, nut->version);
     333        1770 :     if (nut->version > 3)
     334           0 :         ff_put_v(bc, nut->minor_version = 1);
     335        1770 :     ff_put_v(bc, nut->avf->nb_streams);
     336        1770 :     ff_put_v(bc, nut->max_distance);
     337        1770 :     ff_put_v(bc, nut->time_base_count);
     338             : 
     339        3542 :     for (i = 0; i < nut->time_base_count; i++) {
     340        1772 :         ff_put_v(bc, nut->time_base[i].num);
     341        1772 :         ff_put_v(bc, nut->time_base[i].den);
     342             :     }
     343             : 
     344        1770 :     tmp_pts      = 0;
     345        1770 :     tmp_mul      = 1;
     346        1770 :     tmp_stream   = 0;
     347        1770 :     tmp_match    = 1 - (1LL << 62);
     348        1770 :     tmp_head_idx = 0;
     349       15955 :     for (i = 0; i < 256; ) {
     350       12415 :         tmp_fields = 0;
     351       12415 :         tmp_size   = 0;
     352             : //        tmp_res=0;
     353       12415 :         if (tmp_pts      != nut->frame_code[i].pts_delta ) tmp_fields = 1;
     354       12415 :         if (tmp_mul      != nut->frame_code[i].size_mul  ) tmp_fields = 2;
     355       12415 :         if (tmp_stream   != nut->frame_code[i].stream_id ) tmp_fields = 3;
     356       12415 :         if (tmp_size     != nut->frame_code[i].size_lsb  ) tmp_fields = 4;
     357             : //        if (tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;
     358       12415 :         if (tmp_head_idx != nut->frame_code[i].header_idx) tmp_fields = 8;
     359             : 
     360       12415 :         tmp_pts    = nut->frame_code[i].pts_delta;
     361       12415 :         tmp_flags  = nut->frame_code[i].flags;
     362       12415 :         tmp_stream = nut->frame_code[i].stream_id;
     363       12415 :         tmp_mul    = nut->frame_code[i].size_mul;
     364       12415 :         tmp_size   = nut->frame_code[i].size_lsb;
     365             : //        tmp_res   = nut->frame_code[i].res;
     366       12415 :         tmp_head_idx = nut->frame_code[i].header_idx;
     367             : 
     368      465535 :         for (j = 0; i < 256; j++, i++) {
     369      463765 :             if (i == 'N') {
     370        1770 :                 j--;
     371        1770 :                 continue;
     372             :             }
     373      916904 :             if (nut->frame_code[i].pts_delta  != tmp_pts      ||
     374      906259 :                 nut->frame_code[i].flags      != tmp_flags    ||
     375      902700 :                 nut->frame_code[i].stream_id  != tmp_stream   ||
     376      902700 :                 nut->frame_code[i].size_mul   != tmp_mul      ||
     377      902700 :                 nut->frame_code[i].size_lsb   != tmp_size + j ||
     378             : //              nut->frame_code[i].res        != tmp_res      ||
     379      451350 :                 nut->frame_code[i].header_idx != tmp_head_idx)
     380             :                 break;
     381             :         }
     382       12415 :         if (j != tmp_mul - tmp_size)
     383        3540 :             tmp_fields = 6;
     384             : 
     385       12415 :         ff_put_v(bc, tmp_flags);
     386       12415 :         ff_put_v(bc, tmp_fields);
     387       12415 :         if (tmp_fields > 0) put_s(bc, tmp_pts);
     388       12415 :         if (tmp_fields > 1) ff_put_v(bc, tmp_mul);
     389       12415 :         if (tmp_fields > 2) ff_put_v(bc, tmp_stream);
     390       12415 :         if (tmp_fields > 3) ff_put_v(bc, tmp_size);
     391       12415 :         if (tmp_fields > 4) ff_put_v(bc, 0 /*tmp_res*/);
     392       12415 :         if (tmp_fields > 5) ff_put_v(bc, j);
     393       12415 :         if (tmp_fields > 6) ff_put_v(bc, tmp_match);
     394       12415 :         if (tmp_fields > 7) ff_put_v(bc, tmp_head_idx);
     395             :     }
     396        1770 :     ff_put_v(bc, nut->header_count - 1);
     397       12390 :     for (i = 1; i < nut->header_count; i++) {
     398       10620 :         ff_put_v(bc, nut->header_len[i]);
     399       10620 :         avio_write(bc, nut->header[i], nut->header_len[i]);
     400             :     }
     401             :     // flags had been effectively introduced in version 4
     402        1770 :     if (nut->version > 3)
     403           0 :         ff_put_v(bc, nut->flags);
     404        1770 : }
     405             : 
     406        1773 : static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc,
     407             :                               AVStream *st, int i)
     408             : {
     409        1773 :     NUTContext *nut       = avctx->priv_data;
     410        1773 :     AVCodecParameters *par = st->codecpar;
     411             : 
     412        1773 :     ff_put_v(bc, i);
     413        1773 :     switch (par->codec_type) {
     414        1760 :     case AVMEDIA_TYPE_VIDEO:    ff_put_v(bc, 0); break;
     415          13 :     case AVMEDIA_TYPE_AUDIO:    ff_put_v(bc, 1); break;
     416           0 :     case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
     417           0 :     default:                    ff_put_v(bc, 3); break;
     418             :     }
     419        1773 :     ff_put_v(bc, 4);
     420             : 
     421        1773 :     if (par->codec_tag) {
     422        1773 :         avio_wl32(bc, par->codec_tag);
     423             :     } else {
     424           0 :         av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
     425           0 :         return AVERROR(EINVAL);
     426             :     }
     427             : 
     428        1773 :     ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
     429        1773 :     ff_put_v(bc, nut->stream[i].msb_pts_shift);
     430        1773 :     ff_put_v(bc, nut->stream[i].max_pts_distance);
     431        1773 :     ff_put_v(bc, par->video_delay);
     432        1773 :     avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
     433             : 
     434        1773 :     ff_put_v(bc, par->extradata_size);
     435        1773 :     avio_write(bc, par->extradata, par->extradata_size);
     436             : 
     437        1773 :     switch (par->codec_type) {
     438          13 :     case AVMEDIA_TYPE_AUDIO:
     439          13 :         ff_put_v(bc, par->sample_rate);
     440          13 :         ff_put_v(bc, 1);
     441          13 :         ff_put_v(bc, par->channels);
     442          13 :         break;
     443        1760 :     case AVMEDIA_TYPE_VIDEO:
     444        1760 :         ff_put_v(bc, par->width);
     445        1760 :         ff_put_v(bc, par->height);
     446             : 
     447        1764 :         if (st->sample_aspect_ratio.num <= 0 ||
     448           4 :             st->sample_aspect_ratio.den <= 0) {
     449        1756 :             ff_put_v(bc, 0);
     450        1756 :             ff_put_v(bc, 0);
     451             :         } else {
     452           4 :             ff_put_v(bc, st->sample_aspect_ratio.num);
     453           4 :             ff_put_v(bc, st->sample_aspect_ratio.den);
     454             :         }
     455        1760 :         ff_put_v(bc, 0); /* csp type -- unknown */
     456        1760 :         break;
     457           0 :     default:
     458           0 :         break;
     459             :     }
     460        1773 :     return 0;
     461             : }
     462             : 
     463        3540 : static int add_info(AVIOContext *bc, const char *type, const char *value)
     464             : {
     465        3540 :     put_str(bc, type);
     466        3540 :     put_s(bc, -1);
     467        3540 :     put_str(bc, value);
     468        3540 :     return 1;
     469             : }
     470             : 
     471        1770 : static int write_globalinfo(NUTContext *nut, AVIOContext *bc)
     472             : {
     473        1770 :     AVFormatContext *s   = nut->avf;
     474        1770 :     AVDictionaryEntry *t = NULL;
     475             :     AVIOContext *dyn_bc;
     476        1770 :     uint8_t *dyn_buf = NULL;
     477        1770 :     int count        = 0, dyn_size;
     478        1770 :     int ret          = avio_open_dyn_buf(&dyn_bc);
     479        1770 :     if (ret < 0)
     480           0 :         return ret;
     481             : 
     482        1770 :     ff_standardize_creation_time(s);
     483        3544 :     while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
     484           4 :         count += add_info(dyn_bc, t->key, t->value);
     485             : 
     486        1770 :     ff_put_v(bc, 0); //stream_if_plus1
     487        1770 :     ff_put_v(bc, 0); //chapter_id
     488        1770 :     ff_put_v(bc, 0); //timestamp_start
     489        1770 :     ff_put_v(bc, 0); //length
     490             : 
     491        1770 :     ff_put_v(bc, count);
     492             : 
     493        1770 :     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     494        1770 :     avio_write(bc, dyn_buf, dyn_size);
     495        1770 :     av_free(dyn_buf);
     496        1770 :     return 0;
     497             : }
     498             : 
     499        1773 : static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id) {
     500        1773 :     AVFormatContext *s= nut->avf;
     501        1773 :     AVStream* st = s->streams[stream_id];
     502        1773 :     AVDictionaryEntry *t = NULL;
     503             :     AVIOContext *dyn_bc;
     504        1773 :     uint8_t *dyn_buf=NULL;
     505        1773 :     int count=0, dyn_size, i;
     506        1773 :     int ret = avio_open_dyn_buf(&dyn_bc);
     507        1773 :     if (ret < 0)
     508           0 :         return ret;
     509             : 
     510        5322 :     while ((t = av_dict_get(st->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
     511        1776 :         count += add_info(dyn_bc, t->key, t->value);
     512       12411 :     for (i=0; ff_nut_dispositions[i].flag; ++i) {
     513       10638 :         if (st->disposition & ff_nut_dispositions[i].flag)
     514           0 :             count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
     515             :     }
     516        1773 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
     517             :         uint8_t buf[256];
     518        1760 :         if (st->r_frame_rate.num>0 && st->r_frame_rate.den>0)
     519           0 :             snprintf(buf, sizeof(buf), "%d/%d", st->r_frame_rate.num, st->r_frame_rate.den);
     520             :         else
     521        1760 :             snprintf(buf, sizeof(buf), "%d/%d", st->avg_frame_rate.num, st->avg_frame_rate.den);
     522        1760 :         count += add_info(dyn_bc, "r_frame_rate", buf);
     523             :     }
     524        1773 :     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     525             : 
     526        1773 :     if (count) {
     527        1773 :         ff_put_v(bc, stream_id + 1); //stream_id_plus1
     528        1773 :         ff_put_v(bc, 0); //chapter_id
     529        1773 :         ff_put_v(bc, 0); //timestamp_start
     530        1773 :         ff_put_v(bc, 0); //length
     531             : 
     532        1773 :         ff_put_v(bc, count);
     533             : 
     534        1773 :         avio_write(bc, dyn_buf, dyn_size);
     535             :     }
     536             : 
     537        1773 :     av_free(dyn_buf);
     538        1773 :     return count;
     539             : }
     540             : 
     541           0 : static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
     542             : {
     543             :     AVIOContext *dyn_bc;
     544           0 :     uint8_t *dyn_buf     = NULL;
     545           0 :     AVDictionaryEntry *t = NULL;
     546           0 :     AVChapter *ch        = nut->avf->chapters[id];
     547           0 :     int ret, dyn_size, count = 0;
     548             : 
     549           0 :     ret = avio_open_dyn_buf(&dyn_bc);
     550           0 :     if (ret < 0)
     551           0 :         return ret;
     552             : 
     553           0 :     ff_put_v(bc, 0);                                        // stream_id_plus1
     554           0 :     put_s(bc, id + 1);                                      // chapter_id
     555           0 :     put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
     556           0 :     ff_put_v(bc, ch->end - ch->start);                      // chapter_len
     557             : 
     558           0 :     while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
     559           0 :         count += add_info(dyn_bc, t->key, t->value);
     560             : 
     561           0 :     ff_put_v(bc, count);
     562             : 
     563           0 :     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     564           0 :     avio_write(bc, dyn_buf, dyn_size);
     565           0 :     av_freep(&dyn_buf);
     566           0 :     return 0;
     567             : }
     568             : 
     569        1770 : static int write_index(NUTContext *nut, AVIOContext *bc) {
     570             :     int i;
     571        1770 :     Syncpoint dummy= { .pos= 0 };
     572        1770 :     Syncpoint *next_node[2] = { NULL };
     573        1770 :     int64_t startpos = avio_tell(bc);
     574             :     int64_t payload_size;
     575             : 
     576        1770 :     put_tt(nut, nut->max_pts_tb, bc, nut->max_pts);
     577             : 
     578        1770 :     ff_put_v(bc, nut->sp_count);
     579             : 
     580        5245 :     for (i=0; i<nut->sp_count; i++) {
     581        3475 :         av_tree_find(nut->syncpoints, &dummy, ff_nut_sp_pos_cmp, (void**)next_node);
     582        3475 :         ff_put_v(bc, (next_node[1]->pos >> 4) - (dummy.pos>>4));
     583        3475 :         dummy.pos = next_node[1]->pos;
     584             :     }
     585             : 
     586        3543 :     for (i=0; i<nut->avf->nb_streams; i++) {
     587        1773 :         StreamContext *nus= &nut->stream[i];
     588        1773 :         int64_t last_pts= -1;
     589             :         int j, k;
     590        3754 :         for (j=0; j<nut->sp_count; j++) {
     591             :             int flag;
     592        1981 :             int n = 0;
     593             : 
     594        1981 :             if (j && nus->keyframe_pts[j] == nus->keyframe_pts[j-1]) {
     595           0 :                 av_log(nut->avf, AV_LOG_WARNING, "Multiple keyframes with same PTS\n");
     596           0 :                 nus->keyframe_pts[j] = AV_NOPTS_VALUE;
     597             :             }
     598             : 
     599        1981 :             flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
     600        3704 :             for (; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
     601        1723 :                 n++;
     602             : 
     603        1981 :             ff_put_v(bc, 1 + 2*flag + 4*n);
     604        5490 :             for (k= j - n; k<=j && k<nut->sp_count; k++) {
     605        3509 :                 if (nus->keyframe_pts[k] == AV_NOPTS_VALUE)
     606        1799 :                     continue;
     607        1710 :                 av_assert0(nus->keyframe_pts[k] > last_pts);
     608        1710 :                 ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
     609        1710 :                 last_pts = nus->keyframe_pts[k];
     610             :             }
     611             :         }
     612             :     }
     613             : 
     614        1770 :     payload_size = avio_tell(bc) - startpos + 8 + 4;
     615             : 
     616        1770 :     avio_wb64(bc, 8 + payload_size + av_log2(payload_size) / 7 + 1 + 4*(payload_size > 4096));
     617             : 
     618        1770 :     return 0;
     619             : }
     620             : 
     621        1770 : static int write_headers(AVFormatContext *avctx, AVIOContext *bc)
     622             : {
     623        1770 :     NUTContext *nut = avctx->priv_data;
     624             :     AVIOContext *dyn_bc;
     625             :     int i, ret;
     626             : 
     627        1770 :     ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
     628             : 
     629        1770 :     ret = avio_open_dyn_buf(&dyn_bc);
     630        1770 :     if (ret < 0)
     631           0 :         return ret;
     632        1770 :     write_mainheader(nut, dyn_bc);
     633        1770 :     put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
     634             : 
     635        3543 :     for (i = 0; i < nut->avf->nb_streams; i++) {
     636        1773 :         ret = avio_open_dyn_buf(&dyn_bc);
     637        1773 :         if (ret < 0)
     638           0 :             return ret;
     639        1773 :         ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i);
     640        1773 :         if (ret < 0)
     641           0 :             return ret;
     642        1773 :         put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
     643             :     }
     644             : 
     645        1770 :     ret = avio_open_dyn_buf(&dyn_bc);
     646        1770 :     if (ret < 0)
     647           0 :         return ret;
     648        1770 :     write_globalinfo(nut, dyn_bc);
     649        1770 :     put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
     650             : 
     651        3543 :     for (i = 0; i < nut->avf->nb_streams; i++) {
     652        1773 :         ret = avio_open_dyn_buf(&dyn_bc);
     653        1773 :         if (ret < 0)
     654           0 :             return ret;
     655        1773 :         ret = write_streaminfo(nut, dyn_bc, i);
     656        1773 :         if (ret < 0)
     657           0 :             return ret;
     658        1773 :         if (ret > 0)
     659        1773 :             put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
     660             :         else
     661           0 :             ffio_free_dyn_buf(&dyn_bc);
     662             :     }
     663             : 
     664        1770 :     for (i = 0; i < nut->avf->nb_chapters; i++) {
     665           0 :         ret = avio_open_dyn_buf(&dyn_bc);
     666           0 :         if (ret < 0)
     667           0 :             return ret;
     668           0 :         ret = write_chapter(nut, dyn_bc, i);
     669           0 :         if (ret < 0) {
     670           0 :             ffio_free_dyn_buf(&dyn_bc);
     671           0 :             return ret;
     672             :         }
     673           0 :         put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
     674             :     }
     675             : 
     676        1770 :     nut->last_syncpoint_pos = INT_MIN;
     677        1770 :     nut->header_count++;
     678        1770 :     return 0;
     679             : }
     680             : 
     681        1770 : static int nut_write_header(AVFormatContext *s)
     682             : {
     683        1770 :     NUTContext *nut = s->priv_data;
     684        1770 :     AVIOContext *bc = s->pb;
     685             :     int i, j, ret;
     686             : 
     687        1770 :     nut->avf = s;
     688             : 
     689        1770 :     nut->version = FFMAX(NUT_STABLE_VERSION, 3 + !!nut->flags);
     690        1770 :     if (nut->version > 3 && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
     691           0 :         av_log(s, AV_LOG_ERROR,
     692             :                "The additional syncpoint modes require version %d, "
     693             :                "that is currently not finalized, "
     694             :                "please set -f_strict experimental in order to enable it.\n",
     695             :                nut->version);
     696           0 :         return AVERROR_EXPERIMENTAL;
     697             :     }
     698             : 
     699        1770 :     nut->stream   = av_calloc(s->nb_streams,  sizeof(*nut->stream ));
     700        1770 :     nut->chapter  = av_calloc(s->nb_chapters, sizeof(*nut->chapter));
     701        3540 :     nut->time_base= av_calloc(s->nb_streams +
     702        1770 :                               s->nb_chapters, sizeof(*nut->time_base));
     703        1770 :     if (!nut->stream || !nut->chapter || !nut->time_base) {
     704           0 :         av_freep(&nut->stream);
     705           0 :         av_freep(&nut->chapter);
     706           0 :         av_freep(&nut->time_base);
     707           0 :         return AVERROR(ENOMEM);
     708             :     }
     709             : 
     710        3543 :     for (i = 0; i < s->nb_streams; i++) {
     711        1773 :         AVStream *st = s->streams[i];
     712             :         int ssize;
     713             :         AVRational time_base;
     714        1773 :         ff_parse_specific_params(st, &time_base.den, &ssize, &time_base.num);
     715             : 
     716        1773 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate) {
     717          13 :             time_base = (AVRational) {1, st->codecpar->sample_rate};
     718             :         } else {
     719        1760 :             time_base = ff_choose_timebase(s, st, 48000);
     720             :         }
     721             : 
     722        1773 :         avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
     723             : 
     724        1776 :         for (j = 0; j < nut->time_base_count; j++)
     725           4 :             if (!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))) {
     726           1 :                 break;
     727             :             }
     728        1773 :         nut->time_base[j]        = time_base;
     729        1773 :         nut->stream[i].time_base = &nut->time_base[j];
     730        1773 :         if (j == nut->time_base_count)
     731        1772 :             nut->time_base_count++;
     732             : 
     733        1773 :         if (INT64_C(1000) * time_base.num >= time_base.den)
     734           0 :             nut->stream[i].msb_pts_shift = 7;
     735             :         else
     736        1773 :             nut->stream[i].msb_pts_shift = 14;
     737        3546 :         nut->stream[i].max_pts_distance =
     738        3546 :             FFMAX(time_base.den, time_base.num) / time_base.num;
     739             :     }
     740             : 
     741        1770 :     for (i = 0; i < s->nb_chapters; i++) {
     742           0 :         AVChapter *ch = s->chapters[i];
     743             : 
     744           0 :         for (j = 0; j < nut->time_base_count; j++)
     745           0 :             if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
     746           0 :                 break;
     747             : 
     748           0 :         nut->time_base[j]         = ch->time_base;
     749           0 :         nut->chapter[i].time_base = &nut->time_base[j];
     750           0 :         if (j == nut->time_base_count)
     751           0 :             nut->time_base_count++;
     752             :     }
     753             : 
     754        1770 :     nut->max_distance = MAX_DISTANCE;
     755        1770 :     build_elision_headers(s);
     756        1770 :     build_frame_code(s);
     757        1770 :     av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
     758             : 
     759        1770 :     avio_write(bc, ID_STRING, strlen(ID_STRING));
     760        1770 :     avio_w8(bc, 0);
     761             : 
     762        1770 :     if ((ret = write_headers(s, bc)) < 0)
     763           0 :         return ret;
     764             : 
     765        1770 :     if (s->avoid_negative_ts < 0)
     766        1770 :         s->avoid_negative_ts = 1;
     767             : 
     768        1770 :     avio_flush(bc);
     769             : 
     770        1770 :     return 0;
     771             : }
     772             : 
     773     1524254 : static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc,
     774             :                             AVPacket *pkt)
     775             : {
     776     1524254 :     int flags = 0;
     777             : 
     778     1524254 :     if (pkt->flags & AV_PKT_FLAG_KEY)
     779     1518666 :         flags |= FLAG_KEY;
     780     1524254 :     if (pkt->stream_index != fc->stream_id)
     781       10467 :         flags |= FLAG_STREAM_ID;
     782     1524254 :     if (pkt->size / fc->size_mul)
     783     1524069 :         flags |= FLAG_SIZE_MSB;
     784     1524254 :     if (pkt->pts - nus->last_pts != fc->pts_delta)
     785     1459442 :         flags |= FLAG_CODED_PTS;
     786     1524254 :     if (pkt->side_data_elems && nut->version > 3)
     787           0 :         flags |= FLAG_SM_DATA;
     788     1524254 :     if (pkt->size > 2 * nut->max_distance)
     789      675640 :         flags |= FLAG_CHECKSUM;
     790     1524254 :     if (FFABS(pkt->pts - nus->last_pts) > nus->max_pts_distance)
     791           0 :         flags |= FLAG_CHECKSUM;
     792     3048508 :     if (pkt->size < nut->header_len[fc->header_idx] ||
     793     4176420 :         (pkt->size > 4096 && fc->header_idx)        ||
     794     1521104 :         memcmp(pkt->data, nut->header[fc->header_idx],
     795     1521104 :                nut->header_len[fc->header_idx]))
     796        3150 :         flags |= FLAG_HEADER_IDX;
     797             : 
     798     1524254 :     return flags | (fc->flags & FLAG_CODED);
     799             : }
     800             : 
     801        6001 : static int find_best_header_idx(NUTContext *nut, AVPacket *pkt)
     802             : {
     803             :     int i;
     804        6001 :     int best_i   = 0;
     805        6001 :     int best_len = 0;
     806             : 
     807        6001 :     if (pkt->size > 4096)
     808        4453 :         return 0;
     809             : 
     810       12384 :     for (i = 1; i < nut->header_count; i++)
     811       10836 :         if (pkt->size >= nut->header_len[i]
     812       10836 :             && nut->header_len[i] > best_len
     813        9288 :             && !memcmp(pkt->data, nut->header[i], nut->header_len[i])) {
     814          39 :             best_i   = i;
     815          39 :             best_len = nut->header_len[i];
     816             :         }
     817        1548 :     return best_i;
     818             : }
     819             : 
     820           0 : static int write_sm_data(AVFormatContext *s, AVIOContext *bc, AVPacket *pkt, int is_meta)
     821             : {
     822             :     int ret, i, dyn_size;
     823             :     unsigned flags;
     824             :     AVIOContext *dyn_bc;
     825           0 :     int sm_data_count = 0;
     826             :     uint8_t tmp[256];
     827             :     uint8_t *dyn_buf;
     828             : 
     829           0 :     ret = avio_open_dyn_buf(&dyn_bc);
     830           0 :     if (ret < 0)
     831           0 :         return ret;
     832             : 
     833           0 :     for (i = 0; i<pkt->side_data_elems; i++) {
     834           0 :         const uint8_t *data = pkt->side_data[i].data;
     835           0 :         int size = pkt->side_data[i].size;
     836           0 :         const uint8_t *data_end = data + size;
     837             : 
     838           0 :         if (is_meta) {
     839           0 :             if (   pkt->side_data[i].type == AV_PKT_DATA_METADATA_UPDATE
     840           0 :                 || pkt->side_data[i].type == AV_PKT_DATA_STRINGS_METADATA) {
     841           0 :                 if (!size || data[size-1]) {
     842           0 :                     ret = AVERROR(EINVAL);
     843           0 :                     goto fail;
     844             :                 }
     845           0 :                 while (data < data_end) {
     846           0 :                     const uint8_t *key = data;
     847           0 :                     const uint8_t *val = data + strlen(key) + 1;
     848             : 
     849           0 :                     if(val >= data_end) {
     850           0 :                         ret = AVERROR(EINVAL);
     851           0 :                         goto fail;
     852             :                     }
     853           0 :                     put_str(dyn_bc, key);
     854           0 :                     put_s(dyn_bc, -1);
     855           0 :                     put_str(dyn_bc, val);
     856           0 :                     data = val + strlen(val) + 1;
     857           0 :                     sm_data_count++;
     858             :                 }
     859             :             }
     860             :         } else {
     861           0 :             switch (pkt->side_data[i].type) {
     862           0 :             case AV_PKT_DATA_PALETTE:
     863             :             case AV_PKT_DATA_NEW_EXTRADATA:
     864             :             case AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL:
     865             :             default:
     866           0 :                 if (pkt->side_data[i].type == AV_PKT_DATA_PALETTE) {
     867           0 :                     put_str(dyn_bc, "Palette");
     868           0 :                 } else if(pkt->side_data[i].type == AV_PKT_DATA_NEW_EXTRADATA) {
     869           0 :                     put_str(dyn_bc, "Extradata");
     870           0 :                 } else if(pkt->side_data[i].type == AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL) {
     871           0 :                     snprintf(tmp, sizeof(tmp), "CodecSpecificSide%"PRId64"", AV_RB64(data));
     872           0 :                     put_str(dyn_bc, tmp);
     873             :                 } else {
     874           0 :                     snprintf(tmp, sizeof(tmp), "UserData%s-SD-%d",
     875           0 :                             (s->flags & AVFMT_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT,
     876           0 :                             pkt->side_data[i].type);
     877           0 :                     put_str(dyn_bc, tmp);
     878             :                 }
     879           0 :                 put_s(dyn_bc, -2);
     880           0 :                 put_str(dyn_bc, "bin");
     881           0 :                 ff_put_v(dyn_bc, pkt->side_data[i].size);
     882           0 :                 avio_write(dyn_bc, data, pkt->side_data[i].size);
     883           0 :                 sm_data_count++;
     884           0 :                 break;
     885           0 :             case AV_PKT_DATA_PARAM_CHANGE:
     886           0 :                 flags = bytestream_get_le32(&data);
     887           0 :                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
     888           0 :                     put_str(dyn_bc, "Channels");
     889           0 :                     put_s(dyn_bc, bytestream_get_le32(&data));
     890           0 :                     sm_data_count++;
     891             :                 }
     892           0 :                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
     893           0 :                     put_str(dyn_bc, "ChannelLayout");
     894           0 :                     put_s(dyn_bc, -2);
     895           0 :                     put_str(dyn_bc, "u64");
     896           0 :                     ff_put_v(bc, 8);
     897           0 :                     avio_write(dyn_bc, data, 8); data+=8;
     898           0 :                     sm_data_count++;
     899             :                 }
     900           0 :                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
     901           0 :                     put_str(dyn_bc, "SampleRate");
     902           0 :                     put_s(dyn_bc, bytestream_get_le32(&data));
     903           0 :                     sm_data_count++;
     904             :                 }
     905           0 :                 if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
     906           0 :                     put_str(dyn_bc, "Width");
     907           0 :                     put_s(dyn_bc, bytestream_get_le32(&data));
     908           0 :                     put_str(dyn_bc, "Height");
     909           0 :                     put_s(dyn_bc, bytestream_get_le32(&data));
     910           0 :                     sm_data_count+=2;
     911             :                 }
     912           0 :                 break;
     913           0 :             case AV_PKT_DATA_SKIP_SAMPLES:
     914           0 :                 if (AV_RL32(data)) {
     915           0 :                     put_str(dyn_bc, "SkipStart");
     916           0 :                     put_s(dyn_bc, (unsigned)AV_RL32(data));
     917           0 :                     sm_data_count++;
     918             :                 }
     919           0 :                 if (AV_RL32(data+4)) {
     920           0 :                     put_str(dyn_bc, "SkipEnd");
     921           0 :                     put_s(dyn_bc, (unsigned)AV_RL32(data+4));
     922           0 :                     sm_data_count++;
     923             :                 }
     924           0 :                 break;
     925           0 :             case AV_PKT_DATA_METADATA_UPDATE:
     926             :             case AV_PKT_DATA_STRINGS_METADATA:
     927             :             case AV_PKT_DATA_QUALITY_STATS:
     928             :                 // belongs into meta, not side data
     929           0 :                 break;
     930             :             }
     931             :         }
     932             :     }
     933             : 
     934           0 : fail:
     935           0 :     ff_put_v(bc, sm_data_count);
     936           0 :     dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
     937           0 :     avio_write(bc, dyn_buf, dyn_size);
     938           0 :     av_freep(&dyn_buf);
     939             : 
     940           0 :     return ret;
     941             : }
     942             : 
     943        6001 : static int nut_write_packet(AVFormatContext *s, AVPacket *pkt)
     944             : {
     945        6001 :     NUTContext *nut    = s->priv_data;
     946        6001 :     StreamContext *nus = &nut->stream[pkt->stream_index];
     947        6001 :     AVIOContext *bc    = s->pb, *dyn_bc, *sm_bc = NULL;
     948             :     FrameCode *fc;
     949             :     int64_t coded_pts;
     950             :     int best_length, frame_code, flags, needed_flags, i, header_idx;
     951             :     int best_header_idx;
     952        6001 :     int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
     953        6001 :     int store_sp  = 0;
     954        6001 :     int ret = 0;
     955        6001 :     int sm_size = 0;
     956        6001 :     int data_size = pkt->size;
     957        6001 :     uint8_t *sm_buf = NULL;
     958             : 
     959        6001 :     if (pkt->pts < 0) {
     960           0 :         av_log(s, AV_LOG_ERROR,
     961             :                "Negative pts not supported stream %d, pts %"PRId64"\n",
     962             :                pkt->stream_index, pkt->pts);
     963           0 :         if (pkt->pts == AV_NOPTS_VALUE)
     964           0 :             av_log(s, AV_LOG_ERROR, "Try to enable the genpts flag\n");
     965           0 :         return AVERROR(EINVAL);
     966             :     }
     967             : 
     968        6001 :     if (pkt->side_data_elems && nut->version > 3) {
     969           0 :         ret = avio_open_dyn_buf(&sm_bc);
     970           0 :         if (ret < 0)
     971           0 :             return ret;
     972           0 :         ret = write_sm_data(s, sm_bc, pkt, 0);
     973           0 :         if (ret >= 0)
     974           0 :             ret = write_sm_data(s, sm_bc, pkt, 1);
     975           0 :         sm_size = avio_close_dyn_buf(sm_bc, &sm_buf);
     976           0 :         if (ret < 0)
     977           0 :             goto fail;
     978           0 :         data_size += sm_size;
     979             :     }
     980             : 
     981        6001 :     if (1LL << (20 + 3 * nut->header_count) <= avio_tell(bc))
     982           0 :         write_headers(s, bc);
     983             : 
     984        6001 :     if (key_frame && !(nus->last_flags & FLAG_KEY))
     985        1775 :         store_sp = 1;
     986             : 
     987        6001 :     if (data_size + 30 /*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
     988        3474 :         store_sp = 1;
     989             : 
     990             : //FIXME: Ensure store_sp is 1 in the first place.
     991             : 
     992        9476 :     if (store_sp &&
     993        3475 :         (!(nut->flags & NUT_PIPE) || nut->last_syncpoint_pos == INT_MIN)) {
     994        3475 :         int64_t sp_pos = INT64_MAX;
     995             : 
     996        3475 :         ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
     997        6984 :         for (i = 0; i < s->nb_streams; i++) {
     998        3509 :             AVStream *st   = s->streams[i];
     999        7018 :             int64_t dts_tb = av_rescale_rnd(pkt->dts,
    1000        3509 :                 nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
    1001        3509 :                 nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
    1002             :                 AV_ROUND_DOWN);
    1003        3509 :             int index = av_index_search_timestamp(st, dts_tb,
    1004             :                                                   AVSEEK_FLAG_BACKWARD);
    1005        3509 :             if (index >= 0) {
    1006        1732 :                 sp_pos = FFMIN(sp_pos, st->index_entries[index].pos);
    1007        1732 :                 if (!nut->write_index && 2*index > st->nb_index_entries) {
    1008           0 :                     memmove(st->index_entries,
    1009           0 :                             st->index_entries + index,
    1010           0 :                             sizeof(*st->index_entries) * (st->nb_index_entries - index));
    1011           0 :                     st->nb_index_entries -=  index;
    1012             :                 }
    1013             :             }
    1014             :         }
    1015             : 
    1016        3475 :         nut->last_syncpoint_pos = avio_tell(bc);
    1017        3475 :         ret                     = avio_open_dyn_buf(&dyn_bc);
    1018        3475 :         if (ret < 0)
    1019           0 :             goto fail;
    1020        3475 :         put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
    1021        3475 :         ff_put_v(dyn_bc, sp_pos != INT64_MAX ? (nut->last_syncpoint_pos - sp_pos) >> 4 : 0);
    1022             : 
    1023        3475 :         if (nut->flags & NUT_BROADCAST) {
    1024           0 :             put_tt(nut, nus->time_base, dyn_bc,
    1025           0 :                    av_rescale_q(av_gettime(), AV_TIME_BASE_Q, *nus->time_base));
    1026             :         }
    1027        3475 :         put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
    1028             : 
    1029        3475 :         if (nut->write_index) {
    1030        3475 :         if ((ret = ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0 /*unused*/, pkt->dts)) < 0)
    1031           0 :             goto fail;
    1032             : 
    1033        3475 :         if ((1ll<<60) % nut->sp_count == 0)
    1034        4488 :             for (i=0; i<s->nb_streams; i++) {
    1035             :                 int j;
    1036        2250 :                 StreamContext *nus = &nut->stream[i];
    1037        2250 :                 av_reallocp_array(&nus->keyframe_pts, 2*nut->sp_count, sizeof(*nus->keyframe_pts));
    1038        2250 :                 if (!nus->keyframe_pts) {
    1039           0 :                     ret = AVERROR(ENOMEM);
    1040           0 :                     goto fail;
    1041             :                 }
    1042        8280 :                 for (j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
    1043        6030 :                     nus->keyframe_pts[j] = AV_NOPTS_VALUE;
    1044             :         }
    1045             :         }
    1046             :     }
    1047        6001 :     av_assert0(nus->last_pts != AV_NOPTS_VALUE);
    1048             : 
    1049        6001 :     coded_pts = pkt->pts & ((1 << nus->msb_pts_shift) - 1);
    1050        6001 :     if (ff_lsb2full(nus, coded_pts) != pkt->pts)
    1051           0 :         coded_pts = pkt->pts + (1 << nus->msb_pts_shift);
    1052             : 
    1053        6001 :     best_header_idx = find_best_header_idx(nut, pkt);
    1054             : 
    1055        6001 :     best_length = INT_MAX;
    1056        6001 :     frame_code  = -1;
    1057     1542257 :     for (i = 0; i < 256; i++) {
    1058     1536256 :         int length    = 0;
    1059     1536256 :         FrameCode *fc = &nut->frame_code[i];
    1060     1536256 :         int flags     = fc->flags;
    1061             : 
    1062     1536256 :         if (flags & FLAG_INVALID)
    1063       18003 :             continue;
    1064     1518253 :         needed_flags = get_needed_flags(nut, nus, fc, pkt);
    1065             : 
    1066     1518253 :         if (flags & FLAG_CODED) {
    1067        6001 :             length++;
    1068        6001 :             flags = needed_flags;
    1069             :         }
    1070             : 
    1071     1518253 :         if ((flags & needed_flags) != needed_flags)
    1072     1503653 :             continue;
    1073             : 
    1074       14600 :         if ((flags ^ needed_flags) & FLAG_KEY)
    1075          36 :             continue;
    1076             : 
    1077       14564 :         if (flags & FLAG_STREAM_ID)
    1078          47 :             length += ff_get_v_length(pkt->stream_index);
    1079             : 
    1080       14564 :         if (data_size % fc->size_mul != fc->size_lsb)
    1081        4950 :             continue;
    1082        9614 :         if (flags & FLAG_SIZE_MSB)
    1083        9585 :             length += ff_get_v_length(data_size / fc->size_mul);
    1084             : 
    1085        9614 :         if (flags & FLAG_CHECKSUM)
    1086        2660 :             length += 4;
    1087             : 
    1088        9614 :         if (flags & FLAG_CODED_PTS)
    1089        9342 :             length += ff_get_v_length(coded_pts);
    1090             : 
    1091        9614 :         if (   (flags & FLAG_CODED)
    1092        6001 :             && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx] + 1) {
    1093          39 :             flags |= FLAG_HEADER_IDX;
    1094             :         }
    1095             : 
    1096        9614 :         if (flags & FLAG_HEADER_IDX) {
    1097          39 :             length += 1 - nut->header_len[best_header_idx];
    1098             :         } else {
    1099        9575 :             length -= nut->header_len[fc->header_idx];
    1100             :         }
    1101             : 
    1102        9614 :         length *= 4;
    1103        9614 :         length += !(flags & FLAG_CODED_PTS);
    1104        9614 :         length += !(flags & FLAG_CHECKSUM);
    1105             : 
    1106        9614 :         if (length < best_length) {
    1107        9587 :             best_length = length;
    1108        9587 :             frame_code  = i;
    1109             :         }
    1110             :     }
    1111        6001 :     av_assert0(frame_code != -1);
    1112             : 
    1113        6001 :     fc           = &nut->frame_code[frame_code];
    1114        6001 :     flags        = fc->flags;
    1115        6001 :     needed_flags = get_needed_flags(nut, nus, fc, pkt);
    1116        6001 :     header_idx   = fc->header_idx;
    1117             : 
    1118        6001 :     ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
    1119        6001 :     avio_w8(bc, frame_code);
    1120        6001 :     if (flags & FLAG_CODED) {
    1121        2660 :         ff_put_v(bc, (flags ^ needed_flags) & ~(FLAG_CODED));
    1122        2660 :         flags = needed_flags;
    1123             :     }
    1124        6001 :     if (flags & FLAG_STREAM_ID)  ff_put_v(bc, pkt->stream_index);
    1125        6001 :     if (flags & FLAG_CODED_PTS)  ff_put_v(bc, coded_pts);
    1126        6001 :     if (flags & FLAG_SIZE_MSB )  ff_put_v(bc, data_size / fc->size_mul);
    1127        6001 :     if (flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx = best_header_idx);
    1128             : 
    1129        6001 :     if (flags & FLAG_CHECKSUM)   avio_wl32(bc, ffio_get_checksum(bc));
    1130        3341 :     else                         ffio_get_checksum(bc);
    1131             : 
    1132        6001 :     if (flags & FLAG_SM_DATA) {
    1133           0 :         avio_write(bc, sm_buf, sm_size);
    1134             :     }
    1135        6001 :     avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
    1136             : 
    1137        6001 :     nus->last_flags = flags;
    1138        6001 :     nus->last_pts   = pkt->pts;
    1139             : 
    1140             :     //FIXME just store one per syncpoint
    1141        6001 :     if (flags & FLAG_KEY && !(nut->flags & NUT_PIPE)) {
    1142       11958 :         av_add_index_entry(
    1143        5979 :             s->streams[pkt->stream_index],
    1144             :             nut->last_syncpoint_pos,
    1145             :             pkt->pts,
    1146             :             0,
    1147             :             0,
    1148             :             AVINDEX_KEYFRAME);
    1149        5979 :         if (nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
    1150        3481 :             nus->keyframe_pts[nut->sp_count] = pkt->pts;
    1151             :     }
    1152             : 
    1153        6001 :     if (!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
    1154        5996 :         nut->max_pts = pkt->pts;
    1155        5996 :         nut->max_pts_tb = nus->time_base;
    1156             :     }
    1157             : 
    1158        6006 : fail:
    1159        6001 :     av_freep(&sm_buf);
    1160             : 
    1161        6001 :     return ret;
    1162             : }
    1163             : 
    1164        1770 : static int nut_write_trailer(AVFormatContext *s)
    1165             : {
    1166        1770 :     NUTContext *nut = s->priv_data;
    1167        1770 :     AVIOContext *bc = s->pb, *dyn_bc;
    1168             :     int ret;
    1169             : 
    1170        3540 :     while (nut->header_count < 3)
    1171           0 :         write_headers(s, bc);
    1172             : 
    1173        1770 :     ret = avio_open_dyn_buf(&dyn_bc);
    1174        1770 :     if (ret >= 0 && nut->sp_count) {
    1175             :         av_assert1(nut->write_index);
    1176        1770 :         write_index(nut, dyn_bc);
    1177        1770 :         put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
    1178             :     }
    1179             : 
    1180        1770 :     return 0;
    1181             : }
    1182             : 
    1183        1770 : static void nut_write_deinit(AVFormatContext *s)
    1184             : {
    1185        1770 :     NUTContext *nut = s->priv_data;
    1186             :     int i;
    1187             : 
    1188        1770 :     ff_nut_free_sp(nut);
    1189        1770 :     if (nut->stream)
    1190        3543 :         for (i=0; i<s->nb_streams; i++)
    1191        1773 :             av_freep(&nut->stream[i].keyframe_pts);
    1192             : 
    1193        1770 :     av_freep(&nut->stream);
    1194        1770 :     av_freep(&nut->chapter);
    1195        1770 :     av_freep(&nut->time_base);
    1196        1770 : }
    1197             : 
    1198             : #define OFFSET(x) offsetof(NUTContext, x)
    1199             : #define E AV_OPT_FLAG_ENCODING_PARAM
    1200             : static const AVOption options[] = {
    1201             :     { "syncpoints",  "NUT syncpoint behaviour",                         OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0},             INT_MIN, INT_MAX, E, "syncpoints" },
    1202             :     { "default",     "",                                                0,             AV_OPT_TYPE_CONST, {.i64 = 0},             INT_MIN, INT_MAX, E, "syncpoints" },
    1203             :     { "none",        "Disable syncpoints, low overhead and unseekable", 0,             AV_OPT_TYPE_CONST, {.i64 = NUT_PIPE},      INT_MIN, INT_MAX, E, "syncpoints" },
    1204             :     { "timestamped", "Extend syncpoints with a wallclock timestamp",    0,             AV_OPT_TYPE_CONST, {.i64 = NUT_BROADCAST}, INT_MIN, INT_MAX, E, "syncpoints" },
    1205             :     { "write_index", "Write index",                               OFFSET(write_index), AV_OPT_TYPE_BOOL,  {.i64 = 1},                   0,       1, E, },
    1206             :     { NULL },
    1207             : };
    1208             : 
    1209             : static const AVClass class = {
    1210             :     .class_name = "nutenc",
    1211             :     .item_name  = av_default_item_name,
    1212             :     .option     = options,
    1213             :     .version    = LIBAVUTIL_VERSION_INT,
    1214             : };
    1215             : 
    1216             : AVOutputFormat ff_nut_muxer = {
    1217             :     .name           = "nut",
    1218             :     .long_name      = NULL_IF_CONFIG_SMALL("NUT"),
    1219             :     .mime_type      = "video/x-nut",
    1220             :     .extensions     = "nut",
    1221             :     .priv_data_size = sizeof(NUTContext),
    1222             :     .audio_codec    = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
    1223             :                       CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
    1224             :     .video_codec    = AV_CODEC_ID_MPEG4,
    1225             :     .write_header   = nut_write_header,
    1226             :     .write_packet   = nut_write_packet,
    1227             :     .write_trailer  = nut_write_trailer,
    1228             :     .deinit         = nut_write_deinit,
    1229             :     .flags          = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
    1230             :     .codec_tag      = ff_nut_codec_tags,
    1231             :     .priv_class     = &class,
    1232             : };

Generated by: LCOV version 1.13