LCOV - code coverage report
Current view: top level - libavformat - mpegenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 451 670 67.3 %
Date: 2018-05-20 11:54:08 Functions: 12 14 85.7 %

          Line data    Source code
       1             : /*
       2             :  * MPEG-1/2 muxer
       3             :  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
       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/attributes.h"
      25             : #include "libavutil/fifo.h"
      26             : #include "libavutil/log.h"
      27             : #include "libavutil/mathematics.h"
      28             : #include "libavutil/opt.h"
      29             : 
      30             : #include "libavcodec/put_bits.h"
      31             : 
      32             : #include "avformat.h"
      33             : #include "internal.h"
      34             : #include "mpeg.h"
      35             : 
      36             : #define MAX_PAYLOAD_SIZE 4096
      37             : 
      38             : typedef struct PacketDesc {
      39             :     int64_t pts;
      40             :     int64_t dts;
      41             :     int size;
      42             :     int unwritten_size;
      43             :     struct PacketDesc *next;
      44             : } PacketDesc;
      45             : 
      46             : typedef struct StreamInfo {
      47             :     AVFifoBuffer *fifo;
      48             :     uint8_t id;
      49             :     int max_buffer_size; /* in bytes */
      50             :     int buffer_index;
      51             :     PacketDesc *predecode_packet;
      52             :     PacketDesc *premux_packet;
      53             :     PacketDesc **next_packet;
      54             :     int packet_number;
      55             :     uint8_t lpcm_header[3];
      56             :     int lpcm_align;
      57             :     int bytes_to_iframe;
      58             :     int align_iframe;
      59             :     int64_t vobu_start_pts;
      60             : } StreamInfo;
      61             : 
      62             : typedef struct MpegMuxContext {
      63             :     const AVClass *class;
      64             :     int packet_size; /* required packet size */
      65             :     int packet_number;
      66             :     int pack_header_freq;     /* frequency (in packets^-1) at which we send pack headers */
      67             :     int system_header_freq;
      68             :     int system_header_size;
      69             :     int user_mux_rate; /* bitrate in units of bits/s */
      70             :     int mux_rate; /* bitrate in units of 50 bytes/s */
      71             :     /* stream info */
      72             :     int audio_bound;
      73             :     int video_bound;
      74             :     int is_mpeg2;
      75             :     int is_vcd;
      76             :     int is_svcd;
      77             :     int is_dvd;
      78             :     int64_t last_scr; /* current system clock */
      79             : 
      80             :     int64_t vcd_padding_bitrate_num;
      81             :     int64_t vcd_padding_bytes_written;
      82             : 
      83             :     int preload;
      84             : } MpegMuxContext;
      85             : 
      86             : extern AVOutputFormat ff_mpeg1vcd_muxer;
      87             : extern AVOutputFormat ff_mpeg2dvd_muxer;
      88             : extern AVOutputFormat ff_mpeg2svcd_muxer;
      89             : extern AVOutputFormat ff_mpeg2vob_muxer;
      90             : 
      91          91 : static int put_pack_header(AVFormatContext *ctx, uint8_t *buf,
      92             :                            int64_t timestamp)
      93             : {
      94          91 :     MpegMuxContext *s = ctx->priv_data;
      95             :     PutBitContext pb;
      96             : 
      97          91 :     init_put_bits(&pb, buf, 128);
      98             : 
      99          91 :     put_bits32(&pb, PACK_START_CODE);
     100          91 :     if (s->is_mpeg2)
     101           0 :         put_bits(&pb, 2, 0x1);
     102             :     else
     103          91 :         put_bits(&pb, 4, 0x2);
     104          91 :     put_bits(&pb,  3, (uint32_t)((timestamp >> 30) & 0x07));
     105          91 :     put_bits(&pb,  1, 1);
     106          91 :     put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
     107          91 :     put_bits(&pb,  1, 1);
     108          91 :     put_bits(&pb, 15, (uint32_t)((timestamp)       & 0x7fff));
     109          91 :     put_bits(&pb,  1, 1);
     110          91 :     if (s->is_mpeg2)
     111             :         /* clock extension */
     112           0 :         put_bits(&pb, 9, 0);
     113          91 :     put_bits(&pb, 1, 1);
     114          91 :     put_bits(&pb, 22, s->mux_rate);
     115          91 :     put_bits(&pb, 1, 1);
     116          91 :     if (s->is_mpeg2) {
     117           0 :         put_bits(&pb, 1, 1);
     118           0 :         put_bits(&pb, 5, 0x1f); /* reserved */
     119           0 :         put_bits(&pb, 3, 0); /* stuffing length */
     120             :     }
     121          91 :     flush_put_bits(&pb);
     122          91 :     return put_bits_ptr(&pb) - pb.buf;
     123             : }
     124             : 
     125           4 : static int put_system_header(AVFormatContext *ctx, uint8_t *buf,
     126             :                              int only_for_stream_id)
     127             : {
     128           4 :     MpegMuxContext *s = ctx->priv_data;
     129             :     int size, i, private_stream_coded, id;
     130             :     PutBitContext pb;
     131             : 
     132           4 :     init_put_bits(&pb, buf, 128);
     133             : 
     134           4 :     put_bits32(&pb, SYSTEM_HEADER_START_CODE);
     135           4 :     put_bits(&pb, 16, 0);
     136           4 :     put_bits(&pb, 1, 1);
     137             : 
     138             :     /* maximum bit rate of the multiplexed stream */
     139           4 :     put_bits(&pb, 22, s->mux_rate);
     140           4 :     put_bits(&pb, 1, 1); /* marker */
     141           4 :     if (s->is_vcd && only_for_stream_id == VIDEO_ID) {
     142             :         /* This header applies only to the video stream
     143             :          * (see VCD standard p. IV-7) */
     144           0 :         put_bits(&pb, 6, 0);
     145             :     } else
     146           4 :         put_bits(&pb, 6, s->audio_bound);
     147             : 
     148           4 :     if (s->is_vcd) {
     149             :         /* see VCD standard, p. IV-7 */
     150           0 :         put_bits(&pb, 1, 0);
     151           0 :         put_bits(&pb, 1, 1);
     152             :     } else {
     153           4 :         put_bits(&pb, 1, 0); /* variable bitrate */
     154           4 :         put_bits(&pb, 1, 0); /* nonconstrained bitstream */
     155             :     }
     156             : 
     157           4 :     if (s->is_vcd || s->is_dvd) {
     158             :         /* see VCD standard p IV-7 */
     159           0 :         put_bits(&pb, 1, 1); /* audio locked */
     160           0 :         put_bits(&pb, 1, 1); /* video locked */
     161             :     } else {
     162           4 :         put_bits(&pb, 1, 0); /* audio locked */
     163           4 :         put_bits(&pb, 1, 0); /* video locked */
     164             :     }
     165             : 
     166           4 :     put_bits(&pb, 1, 1); /* marker */
     167             : 
     168           4 :     if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
     169             :         /* This header applies only to the audio stream
     170             :          * (see VCD standard p. IV-7) */
     171           0 :         put_bits(&pb, 5, 0);
     172             :     } else
     173           4 :         put_bits(&pb, 5, s->video_bound);
     174             : 
     175           4 :     if (s->is_dvd) {
     176           0 :         put_bits(&pb, 1, 0);    /* packet_rate_restriction_flag */
     177           0 :         put_bits(&pb, 7, 0x7f); /* reserved byte */
     178             :     } else
     179           4 :         put_bits(&pb, 8, 0xff); /* reserved byte */
     180             : 
     181             :     /* DVD-Video Stream_bound entries
     182             :      * id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
     183             :      * id (0xB8) audio, maximum P-STD for any MPEG audio (0xC0 to 0xC7) streams. If there are none set to 4096 (32x128). (P-STD_buffer_bound_scale = 0)
     184             :      * id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
     185             :      * id (0xBF) private stream 2, NAV packs, set to 2x1024. */
     186           4 :     if (s->is_dvd) {
     187             : 
     188           0 :         int P_STD_max_video = 0;
     189           0 :         int P_STD_max_mpeg_audio = 0;
     190           0 :         int P_STD_max_mpeg_PS1 = 0;
     191             : 
     192           0 :         for (i = 0; i < ctx->nb_streams; i++) {
     193           0 :             StreamInfo *stream = ctx->streams[i]->priv_data;
     194             : 
     195           0 :             id = stream->id;
     196           0 :             if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
     197           0 :                 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
     198           0 :             } else if (id >= 0xc0 && id <= 0xc7 &&
     199           0 :                        stream->max_buffer_size > P_STD_max_mpeg_audio) {
     200           0 :                 P_STD_max_mpeg_audio = stream->max_buffer_size;
     201           0 :             } else if (id == 0xe0 &&
     202           0 :                        stream->max_buffer_size > P_STD_max_video) {
     203           0 :                 P_STD_max_video = stream->max_buffer_size;
     204             :             }
     205             :         }
     206             : 
     207             :         /* video */
     208           0 :         put_bits(&pb, 8, 0xb9); /* stream ID */
     209           0 :         put_bits(&pb, 2, 3);
     210           0 :         put_bits(&pb, 1, 1);
     211           0 :         put_bits(&pb, 13, P_STD_max_video / 1024);
     212             : 
     213             :         /* audio */
     214           0 :         if (P_STD_max_mpeg_audio == 0)
     215           0 :             P_STD_max_mpeg_audio = 4096;
     216           0 :         put_bits(&pb, 8, 0xb8); /* stream ID */
     217           0 :         put_bits(&pb, 2, 3);
     218           0 :         put_bits(&pb, 1, 0);
     219           0 :         put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
     220             : 
     221             :         /* private stream 1 */
     222           0 :         put_bits(&pb, 8, 0xbd); /* stream ID */
     223           0 :         put_bits(&pb, 2, 3);
     224           0 :         put_bits(&pb, 1, 0);
     225           0 :         put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
     226             : 
     227             :         /* private stream 2 */
     228           0 :         put_bits(&pb, 8, 0xbf); /* stream ID */
     229           0 :         put_bits(&pb, 2, 3);
     230           0 :         put_bits(&pb, 1, 1);
     231           0 :         put_bits(&pb, 13, 2);
     232             :     } else {
     233             :         /* audio stream info */
     234           4 :         private_stream_coded = 0;
     235          11 :         for (i = 0; i < ctx->nb_streams; i++) {
     236           7 :             StreamInfo *stream = ctx->streams[i]->priv_data;
     237             : 
     238             :             /* For VCDs, only include the stream info for the stream
     239             :              * that the pack which contains this system belongs to.
     240             :              * (see VCD standard p. IV-7) */
     241           7 :             if (!s->is_vcd || stream->id == only_for_stream_id ||
     242             :                 only_for_stream_id == 0) {
     243           7 :                 id = stream->id;
     244           7 :                 if (id < 0xc0) {
     245             :                     /* special case for private streams (AC-3 uses that) */
     246           1 :                     if (private_stream_coded)
     247           0 :                         continue;
     248           1 :                     private_stream_coded = 1;
     249           1 :                     id = 0xbd;
     250             :                 }
     251           7 :                 put_bits(&pb, 8, id);         /* stream ID */
     252           7 :                 put_bits(&pb, 2, 3);
     253           7 :                 if (id < 0xe0) {
     254             :                     /* audio */
     255           4 :                     put_bits(&pb, 1, 0);
     256           4 :                     put_bits(&pb, 13, stream->max_buffer_size / 128);
     257             :                 } else {
     258             :                     /* video */
     259           3 :                     put_bits(&pb, 1, 1);
     260           3 :                     put_bits(&pb, 13, stream->max_buffer_size / 1024);
     261             :                 }
     262             :             }
     263             :         }
     264             :     }
     265             : 
     266           4 :     flush_put_bits(&pb);
     267           4 :     size = put_bits_ptr(&pb) - pb.buf;
     268             :     /* patch packet size */
     269           4 :     AV_WB16(buf + 4, size - 6);
     270             : 
     271           4 :     return size;
     272             : }
     273             : 
     274           4 : static int get_system_header_size(AVFormatContext *ctx)
     275             : {
     276             :     int buf_index, i, private_stream_coded;
     277             :     StreamInfo *stream;
     278           4 :     MpegMuxContext *s = ctx->priv_data;
     279             : 
     280           4 :     if (s->is_dvd)
     281           0 :         return 18; // DVD-Video system headers are 18 bytes fixed length.
     282             : 
     283           4 :     buf_index = 12;
     284           4 :     private_stream_coded = 0;
     285          11 :     for (i = 0; i < ctx->nb_streams; i++) {
     286           7 :         stream = ctx->streams[i]->priv_data;
     287           7 :         if (stream->id < 0xc0) {
     288           1 :             if (private_stream_coded)
     289           0 :                 continue;
     290           1 :             private_stream_coded = 1;
     291             :         }
     292           7 :         buf_index += 3;
     293             :     }
     294           4 :     return buf_index;
     295             : }
     296             : 
     297           4 : static av_cold int mpeg_mux_init(AVFormatContext *ctx)
     298             : {
     299           4 :     MpegMuxContext *s = ctx->priv_data;
     300             :     int bitrate, i, mpa_id, mpv_id, h264_id, mps_id, ac3_id, dts_id, lpcm_id, j;
     301             :     AVStream *st;
     302             :     StreamInfo *stream;
     303             :     int audio_bitrate;
     304             :     int video_bitrate;
     305             : 
     306           4 :     s->packet_number = 0;
     307           4 :     s->is_vcd   =  (CONFIG_MPEG1VCD_MUXER  && ctx->oformat == &ff_mpeg1vcd_muxer);
     308           4 :     s->is_svcd  =  (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
     309          12 :     s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER  && ctx->oformat == &ff_mpeg2vob_muxer) ||
     310           8 :                    (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer) ||
     311           4 :                    (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
     312           4 :     s->is_dvd   =  (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer);
     313             : 
     314           4 :     if (ctx->packet_size) {
     315           0 :         if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
     316           0 :             av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
     317             :                    ctx->packet_size);
     318           0 :             goto fail;
     319             :         }
     320           0 :         s->packet_size = ctx->packet_size;
     321             :     } else
     322           4 :         s->packet_size = 2048;
     323           4 :     if (ctx->max_delay < 0)     /* Not set by the caller */
     324           0 :         ctx->max_delay = AV_TIME_BASE*7/10;
     325             : 
     326           4 :     s->vcd_padding_bytes_written = 0;
     327           4 :     s->vcd_padding_bitrate_num   = 0;
     328             : 
     329           4 :     s->audio_bound = 0;
     330           4 :     s->video_bound = 0;
     331             : 
     332           4 :     mpa_id  = AUDIO_ID;
     333           4 :     ac3_id  = AC3_ID;
     334           4 :     dts_id  = DTS_ID;
     335           4 :     mpv_id  = VIDEO_ID;
     336           4 :     h264_id = H264_ID;
     337           4 :     mps_id  = SUB_ID;
     338           4 :     lpcm_id = LPCM_ID;
     339             : 
     340          11 :     for (i = 0; i < ctx->nb_streams; i++) {
     341             :         AVCPBProperties *props;
     342             : 
     343           7 :         st     = ctx->streams[i];
     344           7 :         stream = av_mallocz(sizeof(StreamInfo));
     345           7 :         if (!stream)
     346           0 :             goto fail;
     347           7 :         st->priv_data = stream;
     348             : 
     349           7 :         avpriv_set_pts_info(st, 64, 1, 90000);
     350             : 
     351           7 :         switch (st->codecpar->codec_type) {
     352           4 :         case AVMEDIA_TYPE_AUDIO:
     353           8 :             if (!s->is_mpeg2 &&
     354           8 :                 (st->codecpar->codec_id == AV_CODEC_ID_AC3 ||
     355           8 :                  st->codecpar->codec_id == AV_CODEC_ID_DTS ||
     356           8 :                  st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ||
     357           4 :                  st->codecpar->codec_id == AV_CODEC_ID_PCM_DVD))
     358           1 :                  av_log(ctx, AV_LOG_WARNING,
     359             :                         "%s in MPEG-1 system streams is not widely supported, "
     360             :                         "consider using the vob or the dvd muxer "
     361             :                         "to force a MPEG-2 program stream.\n",
     362           1 :                         avcodec_get_name(st->codecpar->codec_id));
     363           4 :             if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
     364           0 :                 stream->id = ac3_id++;
     365           4 :             } else if (st->codecpar->codec_id == AV_CODEC_ID_DTS) {
     366           0 :                 stream->id = dts_id++;
     367           8 :             } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ||
     368           4 :                        st->codecpar->codec_id == AV_CODEC_ID_PCM_DVD) {
     369           1 :                 if (st->codecpar->bits_per_coded_sample != 16) {
     370           0 :                     av_log(ctx, AV_LOG_ERROR, "Only 16 bit LPCM streams can be muxed.\n");
     371           0 :                     goto fail;
     372             :                 }
     373           1 :                 stream->id = lpcm_id++;
     374           3 :                 for (j = 0; j < 4; j++) {
     375           3 :                     if (lpcm_freq_tab[j] == st->codecpar->sample_rate)
     376           1 :                         break;
     377             :                 }
     378           1 :                 if (j == 4) {
     379             :                     int sr;
     380           0 :                     av_log(ctx, AV_LOG_ERROR, "Invalid sampling rate for PCM stream.\n");
     381           0 :                     av_log(ctx, AV_LOG_INFO, "Allowed sampling rates:");
     382           0 :                     for (sr = 0; sr < 4; sr++)
     383           0 :                          av_log(ctx, AV_LOG_INFO, " %d", lpcm_freq_tab[sr]);
     384           0 :                     av_log(ctx, AV_LOG_INFO, "\n");
     385           0 :                     goto fail;
     386             :                 }
     387           1 :                 if (st->codecpar->channels > 8) {
     388           0 :                     av_log(ctx, AV_LOG_ERROR, "At most 8 channels allowed for LPCM streams.\n");
     389           0 :                     goto fail;
     390             :                 }
     391           1 :                 stream->lpcm_header[0] = 0x0c;
     392           1 :                 stream->lpcm_header[1] = (st->codecpar->channels - 1) | (j << 4);
     393           1 :                 stream->lpcm_header[2] = 0x80;
     394           1 :                 stream->lpcm_align     = st->codecpar->channels * 2;
     395             :             } else {
     396           3 :                 stream->id = mpa_id++;
     397             :             }
     398             : 
     399             :             /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
     400             :              * Right now it is also used for everything else. */
     401           4 :             stream->max_buffer_size = 4 * 1024;
     402           4 :             s->audio_bound++;
     403           4 :             break;
     404           3 :         case AVMEDIA_TYPE_VIDEO:
     405           3 :             if (st->codecpar->codec_id == AV_CODEC_ID_H264)
     406           0 :                 stream->id = h264_id++;
     407             :             else
     408           3 :                 stream->id = mpv_id++;
     409             : 
     410           3 :             props = (AVCPBProperties*)av_stream_get_side_data(st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
     411           3 :             if (props && props->buffer_size)
     412           0 :                 stream->max_buffer_size = 6 * 1024 + props->buffer_size / 8;
     413             :             else {
     414           3 :                 av_log(ctx, AV_LOG_WARNING,
     415             :                        "VBV buffer size not set, using default size of 230KB\n"
     416             :                        "If you want the mpeg file to be compliant to some specification\n"
     417             :                        "Like DVD, VCD or others, make sure you set the correct buffer size\n");
     418             :                 // FIXME: this is probably too small as default
     419           3 :                 stream->max_buffer_size = 230 * 1024;
     420             :             }
     421           3 :             if (stream->max_buffer_size > 1024 * 8191) {
     422           0 :                 av_log(ctx, AV_LOG_WARNING, "buffer size %d, too large\n", stream->max_buffer_size);
     423           0 :                 stream->max_buffer_size = 1024 * 8191;
     424             :             }
     425           3 :             s->video_bound++;
     426           3 :             break;
     427           0 :         case AVMEDIA_TYPE_SUBTITLE:
     428           0 :             stream->id              = mps_id++;
     429           0 :             stream->max_buffer_size = 16 * 1024;
     430           0 :             break;
     431           0 :         default:
     432           0 :             av_log(ctx, AV_LOG_ERROR, "Invalid media type %s for output stream #%d\n",
     433           0 :                    av_get_media_type_string(st->codecpar->codec_type), i);
     434           0 :             return AVERROR(EINVAL);
     435             :         }
     436           7 :         stream->fifo = av_fifo_alloc(16);
     437           7 :         if (!stream->fifo)
     438           0 :             goto fail;
     439             :     }
     440           4 :     bitrate       = 0;
     441           4 :     audio_bitrate = 0;
     442           4 :     video_bitrate = 0;
     443          11 :     for (i = 0; i < ctx->nb_streams; i++) {
     444             :         AVCPBProperties *props;
     445             :         int codec_rate;
     446           7 :         st     = ctx->streams[i];
     447           7 :         stream = (StreamInfo *)st->priv_data;
     448             : 
     449           7 :         props = (AVCPBProperties*)av_stream_get_side_data(st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
     450           7 :         if (props)
     451           3 :             codec_rate = props->max_bitrate;
     452             :         else
     453           4 :             codec_rate = st->codecpar->bit_rate;
     454             : 
     455           7 :         if (!codec_rate)
     456           3 :             codec_rate = (1 << 21) * 8 * 50 / ctx->nb_streams;
     457             : 
     458           7 :         bitrate += codec_rate;
     459             : 
     460           7 :         if ((stream->id & 0xe0) == AUDIO_ID)
     461           3 :             audio_bitrate += codec_rate;
     462           4 :         else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
     463           3 :             video_bitrate += codec_rate;
     464             :     }
     465             : 
     466           4 :     if (s->user_mux_rate) {
     467           0 :         s->mux_rate = (s->user_mux_rate + (8 * 50) - 1) / (8 * 50);
     468             :     } else {
     469             :         /* we increase slightly the bitrate to take into account the
     470             :          * headers. XXX: compute it exactly */
     471           4 :         bitrate    += bitrate / 20;
     472           4 :         bitrate    += 10000;
     473           4 :         s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
     474           4 :         if (s->mux_rate >= (1<<22)) {
     475           0 :             av_log(ctx, AV_LOG_WARNING, "mux rate %d is too large\n", s->mux_rate);
     476           0 :             s->mux_rate = (1<<22) - 1;
     477             :         }
     478             :     }
     479             : 
     480           4 :     if (s->is_vcd) {
     481             :         int64_t overhead_rate;
     482             : 
     483             :         /* The VCD standard mandates that the mux_rate field is 3528
     484             :          * (see standard p. IV-6).
     485             :          * The value is actually "wrong", i.e. if you calculate
     486             :          * it using the normal formula and the 75 sectors per second transfer
     487             :          * rate you get a different value because the real pack size is 2324,
     488             :          * not 2352. But the standard explicitly specifies that the mux_rate
     489             :          * field in the header must have this value. */
     490             :         // s->mux_rate = 2352 * 75 / 50;    /* = 3528 */
     491             : 
     492             :         /* The VCD standard states that the muxed stream must be
     493             :          * exactly 75 packs / second (the data rate of a single speed cdrom).
     494             :          * Since the video bitrate (probably 1150000 bits/sec) will be below
     495             :          * the theoretical maximum we have to add some padding packets
     496             :          * to make up for the lower data rate.
     497             :          * (cf. VCD standard p. IV-6 ) */
     498             : 
     499             :         /* Add the header overhead to the data rate.
     500             :          * 2279 data bytes per audio pack, 2294 data bytes per video pack */
     501           0 :         overhead_rate  = audio_bitrate * 2294LL * (2324 - 2279);
     502           0 :         overhead_rate += video_bitrate * 2279LL * (2324 - 2294);
     503             : 
     504             :         /* Add padding so that the full bitrate is 2324*75 bytes/sec */
     505           0 :         s->vcd_padding_bitrate_num = (2324LL * 75 * 8 - bitrate) * 2279 * 2294 - overhead_rate;
     506             : #define VCD_PADDING_BITRATE_DEN (2279 * 2294)
     507             :     }
     508             : 
     509           4 :     if (s->is_vcd || s->is_mpeg2)
     510             :         /* every packet */
     511           0 :         s->pack_header_freq = 1;
     512             :     else
     513             :         /* every 2 seconds */
     514           4 :         s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
     515             : 
     516             :     /* the above seems to make pack_header_freq zero sometimes */
     517           4 :     if (s->pack_header_freq == 0)
     518           0 :         s->pack_header_freq = 1;
     519             : 
     520           4 :     if (s->is_mpeg2)
     521             :         /* every 200 packets. Need to look at the spec.  */
     522           0 :         s->system_header_freq = s->pack_header_freq * 40;
     523           4 :     else if (s->is_vcd)
     524             :         /* the standard mandates that there are only two system headers
     525             :          * in the whole file: one in the first packet of each stream.
     526             :          * (see standard p. IV-7 and IV-8) */
     527           0 :         s->system_header_freq = 0x7fffffff;
     528             :     else
     529           4 :         s->system_header_freq = s->pack_header_freq * 5;
     530             : 
     531          11 :     for (i = 0; i < ctx->nb_streams; i++) {
     532           7 :         stream                = ctx->streams[i]->priv_data;
     533           7 :         stream->packet_number = 0;
     534             :     }
     535           4 :     s->system_header_size = get_system_header_size(ctx);
     536           4 :     s->last_scr           = AV_NOPTS_VALUE;
     537           4 :     return 0;
     538             : 
     539           0 : fail:
     540           0 :     for (i = 0; i < ctx->nb_streams; i++)
     541           0 :         av_freep(&ctx->streams[i]->priv_data);
     542           0 :     return AVERROR(ENOMEM);
     543             : }
     544             : 
     545         212 : static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
     546             : {
     547         212 :     avio_w8(pb, (id << 4) |  (((timestamp >> 30) & 0x07)   << 1) | 1);
     548         212 :     avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
     549         212 :     avio_wb16(pb, (uint16_t)((((timestamp)       & 0x7fff) << 1) | 1));
     550         212 : }
     551             : 
     552             : /* return the number of padding bytes that should be inserted into
     553             :  * the multiplexed stream. */
     554           0 : static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
     555             : {
     556           0 :     MpegMuxContext *s = ctx->priv_data;
     557           0 :     int pad_bytes = 0;
     558             : 
     559           0 :     if (s->vcd_padding_bitrate_num > 0 && pts != AV_NOPTS_VALUE) {
     560             :         int64_t full_pad_bytes;
     561             : 
     562             :         // FIXME: this is wrong
     563           0 :         full_pad_bytes =
     564           0 :             av_rescale(s->vcd_padding_bitrate_num, pts, 90000LL * 8 * VCD_PADDING_BITRATE_DEN);
     565           0 :         pad_bytes = (int)(full_pad_bytes - s->vcd_padding_bytes_written);
     566             : 
     567           0 :         if (pad_bytes < 0)
     568             :             /* might happen if we have already padded to a later timestamp. This
     569             :              * can occur if another stream has already advanced further. */
     570           0 :             pad_bytes = 0;
     571             :     }
     572             : 
     573           0 :     return pad_bytes;
     574             : }
     575             : 
     576             : /* Write an MPEG padding packet header. */
     577           7 : static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,
     578             :                                int packet_bytes)
     579             : {
     580           7 :     MpegMuxContext *s = ctx->priv_data;
     581             :     int i;
     582             : 
     583           7 :     avio_wb32(pb, PADDING_STREAM);
     584           7 :     avio_wb16(pb, packet_bytes - 6);
     585           7 :     if (!s->is_mpeg2) {
     586           7 :         avio_w8(pb, 0x0f);
     587           7 :         packet_bytes -= 7;
     588             :     } else
     589           0 :         packet_bytes -= 6;
     590             : 
     591       10289 :     for (i = 0; i < packet_bytes; i++)
     592       10282 :         avio_w8(pb, 0xff);
     593           7 : }
     594             : 
     595         598 : static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len)
     596             : {
     597         598 :     int nb_frames        = 0;
     598         598 :     PacketDesc *pkt_desc = stream->premux_packet;
     599             : 
     600        1985 :     while (len > 0) {
     601         789 :         if (pkt_desc->size == pkt_desc->unwritten_size)
     602         241 :             nb_frames++;
     603         789 :         len     -= pkt_desc->unwritten_size;
     604         789 :         pkt_desc = pkt_desc->next;
     605             :     }
     606             : 
     607         598 :     return nb_frames;
     608             : }
     609             : 
     610             : /* flush the packet on stream stream_index */
     611         598 : static int flush_packet(AVFormatContext *ctx, int stream_index,
     612             :                         int64_t pts, int64_t dts, int64_t scr, int trailer_size)
     613             : {
     614         598 :     MpegMuxContext *s  = ctx->priv_data;
     615         598 :     StreamInfo *stream = ctx->streams[stream_index]->priv_data;
     616             :     uint8_t *buf_ptr;
     617             :     int size, payload_size, startcode, id, stuffing_size, i, header_len;
     618             :     int packet_size;
     619             :     uint8_t buffer[128];
     620         598 :     int zero_trail_bytes = 0;
     621         598 :     int pad_packet_bytes = 0;
     622             :     int pes_flags;
     623             :     /* "general" pack without data specific to one stream? */
     624         598 :     int general_pack = 0;
     625             :     int nb_frames;
     626             : 
     627         598 :     id = stream->id;
     628             : 
     629         598 :     av_log(ctx, AV_LOG_TRACE, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
     630             : 
     631         598 :     buf_ptr = buffer;
     632             : 
     633         598 :     if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
     634             :         /* output pack and systems header if needed */
     635          91 :         size        = put_pack_header(ctx, buf_ptr, scr);
     636          91 :         buf_ptr    += size;
     637          91 :         s->last_scr = scr;
     638             : 
     639          91 :         if (s->is_vcd) {
     640             :             /* there is exactly one system header for each stream in a VCD MPEG,
     641             :              * One in the very first video packet and one in the very first
     642             :              * audio packet (see VCD standard p. IV-7 and IV-8). */
     643             : 
     644           0 :             if (stream->packet_number == 0) {
     645           0 :                 size     = put_system_header(ctx, buf_ptr, id);
     646           0 :                 buf_ptr += size;
     647             :             }
     648          91 :         } else if (s->is_dvd) {
     649           0 :             if (stream->align_iframe || s->packet_number == 0) {
     650           0 :                 int PES_bytes_to_fill = s->packet_size - size - 10;
     651             : 
     652           0 :                 if (pts != AV_NOPTS_VALUE) {
     653           0 :                     if (dts != pts)
     654           0 :                         PES_bytes_to_fill -= 5 + 5;
     655             :                     else
     656           0 :                         PES_bytes_to_fill -= 5;
     657             :                 }
     658             : 
     659           0 :                 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
     660           0 :                     size     = put_system_header(ctx, buf_ptr, 0);
     661           0 :                     buf_ptr += size;
     662           0 :                     size     = buf_ptr - buffer;
     663           0 :                     avio_write(ctx->pb, buffer, size);
     664             : 
     665           0 :                     avio_wb32(ctx->pb, PRIVATE_STREAM_2);
     666           0 :                     avio_wb16(ctx->pb, 0x03d4);     // length
     667           0 :                     avio_w8(ctx->pb, 0x00);         // substream ID, 00=PCI
     668           0 :                     for (i = 0; i < 979; i++)
     669           0 :                         avio_w8(ctx->pb, 0x00);
     670             : 
     671           0 :                     avio_wb32(ctx->pb, PRIVATE_STREAM_2);
     672           0 :                     avio_wb16(ctx->pb, 0x03fa);     // length
     673           0 :                     avio_w8(ctx->pb, 0x01);         // substream ID, 01=DSI
     674           0 :                     for (i = 0; i < 1017; i++)
     675           0 :                         avio_w8(ctx->pb, 0x00);
     676             : 
     677           0 :                     memset(buffer, 0, 128);
     678           0 :                     buf_ptr = buffer;
     679           0 :                     s->packet_number++;
     680           0 :                     stream->align_iframe = 0;
     681             :                     // FIXME: rounding and first few bytes of each packet
     682           0 :                     scr        += s->packet_size * 90000LL /
     683           0 :                                   (s->mux_rate * 50LL);
     684           0 :                     size        = put_pack_header(ctx, buf_ptr, scr);
     685           0 :                     s->last_scr = scr;
     686           0 :                     buf_ptr    += size;
     687             :                     /* GOP Start */
     688           0 :                 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
     689           0 :                     pad_packet_bytes = PES_bytes_to_fill -
     690           0 :                                        stream->bytes_to_iframe;
     691             :                 }
     692             :             }
     693             :         } else {
     694          91 :             if ((s->packet_number % s->system_header_freq) == 0) {
     695           4 :                 size     = put_system_header(ctx, buf_ptr, 0);
     696           4 :                 buf_ptr += size;
     697             :             }
     698             :         }
     699             :     }
     700         598 :     size = buf_ptr - buffer;
     701         598 :     avio_write(ctx->pb, buffer, size);
     702             : 
     703         598 :     packet_size = s->packet_size - size;
     704             : 
     705         598 :     if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
     706             :         /* The VCD standard demands that 20 zero bytes follow
     707             :          * each audio pack (see standard p. IV-8). */
     708           0 :         zero_trail_bytes += 20;
     709             : 
     710        1196 :     if ((s->is_vcd && stream->packet_number == 0) ||
     711         598 :         (s->is_svcd && s->packet_number == 0)) {
     712             :         /* for VCD the first pack of each stream contains only the pack header,
     713             :          * the system header and lots of padding (see VCD standard p. IV-6).
     714             :          * In the case of an audio pack, 20 zero bytes are also added at
     715             :          * the end. */
     716             :         /* For SVCD we fill the very first pack to increase compatibility with
     717             :          * some DVD players. Not mandated by the standard. */
     718           0 :         if (s->is_svcd)
     719             :             /* the system header refers to both streams and no stream data */
     720           0 :             general_pack = 1;
     721           0 :         pad_packet_bytes = packet_size - zero_trail_bytes;
     722             :     }
     723             : 
     724         598 :     packet_size -= pad_packet_bytes + zero_trail_bytes;
     725             : 
     726         598 :     if (packet_size > 0) {
     727             :         /* packet header size */
     728         598 :         packet_size -= 6;
     729             : 
     730             :         /* packet header */
     731         598 :         if (s->is_mpeg2) {
     732           0 :             header_len = 3;
     733           0 :             if (stream->packet_number == 0)
     734           0 :                 header_len += 3; /* PES extension */
     735           0 :             header_len += 1; /* obligatory stuffing byte */
     736             :         } else {
     737         598 :             header_len = 0;
     738             :         }
     739         598 :         if (pts != AV_NOPTS_VALUE) {
     740         492 :             if (dts != pts)
     741         436 :                 header_len += 5 + 5;
     742             :             else
     743          56 :                 header_len += 5;
     744             :         } else {
     745         106 :             if (!s->is_mpeg2)
     746         106 :                 header_len++;
     747             :         }
     748             : 
     749         598 :         payload_size = packet_size - header_len;
     750         598 :         if (id < 0xc0) {
     751          44 :             startcode     = PRIVATE_STREAM_1;
     752          44 :             payload_size -= 1;
     753          44 :             if (id >= 0x40) {
     754          44 :                 payload_size -= 3;
     755          44 :                 if (id >= 0xa0)
     756          44 :                     payload_size -= 3;
     757             :             }
     758             :         } else {
     759         554 :             startcode = 0x100 + id;
     760             :         }
     761             : 
     762         598 :         stuffing_size = payload_size - av_fifo_size(stream->fifo);
     763             : 
     764             :         // first byte does not fit -> reset pts/dts + stuffing
     765         598 :         if (payload_size <= trailer_size && pts != AV_NOPTS_VALUE) {
     766         358 :             int timestamp_len = 0;
     767         358 :             if (dts != pts)
     768         358 :                 timestamp_len += 5;
     769         358 :             if (pts != AV_NOPTS_VALUE)
     770         358 :                 timestamp_len += s->is_mpeg2 ? 5 : 4;
     771         358 :             pts         =
     772         358 :             dts         = AV_NOPTS_VALUE;
     773         358 :             header_len -= timestamp_len;
     774         358 :             if (s->is_dvd && stream->align_iframe) {
     775           0 :                 pad_packet_bytes += timestamp_len;
     776           0 :                 packet_size      -= timestamp_len;
     777             :             } else {
     778         358 :                 payload_size += timestamp_len;
     779             :             }
     780         358 :             stuffing_size += timestamp_len;
     781         358 :             if (payload_size > trailer_size)
     782           0 :                 stuffing_size += payload_size - trailer_size;
     783             :         }
     784             : 
     785             :         // can't use padding, so use stuffing
     786         598 :         if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) {
     787           0 :             packet_size  += pad_packet_bytes;
     788           0 :             payload_size += pad_packet_bytes; // undo the previous adjustment
     789           0 :             if (stuffing_size < 0)
     790           0 :                 stuffing_size = pad_packet_bytes;
     791             :             else
     792           0 :                 stuffing_size += pad_packet_bytes;
     793           0 :             pad_packet_bytes = 0;
     794             :         }
     795             : 
     796         598 :         if (stuffing_size < 0)
     797         591 :             stuffing_size = 0;
     798             : 
     799         598 :         if (startcode == PRIVATE_STREAM_1 && id >= 0xa0) {
     800          44 :             if (payload_size < av_fifo_size(stream->fifo))
     801          43 :                 stuffing_size += payload_size % stream->lpcm_align;
     802             :         }
     803             : 
     804         598 :         if (stuffing_size > 16) {   /* <=16 for MPEG-1, <=32 for MPEG-2 */
     805           7 :             pad_packet_bytes += stuffing_size;
     806           7 :             packet_size      -= stuffing_size;
     807           7 :             payload_size     -= stuffing_size;
     808           7 :             stuffing_size     = 0;
     809             :         }
     810             : 
     811         598 :         nb_frames = get_nb_frames(ctx, stream, payload_size - stuffing_size);
     812             : 
     813         598 :         avio_wb32(ctx->pb, startcode);
     814             : 
     815         598 :         avio_wb16(ctx->pb, packet_size);
     816             : 
     817         598 :         if (!s->is_mpeg2)
     818         599 :             for (i = 0; i < stuffing_size; i++)
     819           1 :                 avio_w8(ctx->pb, 0xff);
     820             : 
     821         598 :         if (s->is_mpeg2) {
     822           0 :             avio_w8(ctx->pb, 0x80); /* mpeg2 id */
     823             : 
     824           0 :             pes_flags = 0;
     825             : 
     826           0 :             if (pts != AV_NOPTS_VALUE) {
     827           0 :                 pes_flags |= 0x80;
     828           0 :                 if (dts != pts)
     829           0 :                     pes_flags |= 0x40;
     830             :             }
     831             : 
     832             :             /* Both the MPEG-2 and the SVCD standards demand that the
     833             :              * P-STD_buffer_size field be included in the first packet of
     834             :              * every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
     835             :              * and MPEG-2 standard 2.7.7) */
     836           0 :             if (stream->packet_number == 0)
     837           0 :                 pes_flags |= 0x01;
     838             : 
     839           0 :             avio_w8(ctx->pb, pes_flags); /* flags */
     840           0 :             avio_w8(ctx->pb, header_len - 3 + stuffing_size);
     841             : 
     842           0 :             if (pes_flags & 0x80)  /* write pts */
     843           0 :                 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
     844           0 :             if (pes_flags & 0x40)  /* write dts */
     845           0 :                 put_timestamp(ctx->pb, 0x01, dts);
     846             : 
     847           0 :             if (pes_flags & 0x01) {  /* write pes extension */
     848           0 :                 avio_w8(ctx->pb, 0x10); /* flags */
     849             : 
     850             :                 /* P-STD buffer info */
     851           0 :                 if ((id & 0xe0) == AUDIO_ID)
     852           0 :                     avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size / 128);
     853             :                 else
     854           0 :                     avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size / 1024);
     855             :             }
     856             :         } else {
     857         598 :             if (pts != AV_NOPTS_VALUE) {
     858         134 :                 if (dts != pts) {
     859          78 :                     put_timestamp(ctx->pb, 0x03, pts);
     860          78 :                     put_timestamp(ctx->pb, 0x01, dts);
     861             :                 } else {
     862          56 :                     put_timestamp(ctx->pb, 0x02, pts);
     863             :                 }
     864             :             } else {
     865         464 :                 avio_w8(ctx->pb, 0x0f);
     866             :             }
     867             :         }
     868             : 
     869         598 :         if (s->is_mpeg2) {
     870             :             /* special stuffing byte that is always written
     871             :              * to prevent accidental generation of start codes. */
     872           0 :             avio_w8(ctx->pb, 0xff);
     873             : 
     874           0 :             for (i = 0; i < stuffing_size; i++)
     875           0 :                 avio_w8(ctx->pb, 0xff);
     876             :         }
     877             : 
     878         598 :         if (startcode == PRIVATE_STREAM_1) {
     879          44 :             avio_w8(ctx->pb, id);
     880          44 :             if (id >= 0xa0) {
     881             :                 /* LPCM (XXX: check nb_frames) */
     882          44 :                 avio_w8(ctx->pb, 7);
     883          44 :                 avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
     884          44 :                 avio_w8(ctx->pb, stream->lpcm_header[0]);
     885          44 :                 avio_w8(ctx->pb, stream->lpcm_header[1]);
     886          44 :                 avio_w8(ctx->pb, stream->lpcm_header[2]);
     887           0 :             } else if (id >= 0x40) {
     888             :                 /* AC-3 */
     889           0 :                 avio_w8(ctx->pb, nb_frames);
     890           0 :                 avio_wb16(ctx->pb, trailer_size + 1);
     891             :             }
     892             :         }
     893             : 
     894             :         /* output data */
     895         598 :         av_assert0(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
     896         598 :         av_fifo_generic_read(stream->fifo, ctx->pb,
     897             :                              payload_size - stuffing_size,
     898             :                              (void (*)(void*, void*, int))avio_write);
     899         598 :         stream->bytes_to_iframe -= payload_size - stuffing_size;
     900             :     } else {
     901           0 :         payload_size  =
     902           0 :         stuffing_size = 0;
     903             :     }
     904             : 
     905         598 :     if (pad_packet_bytes > 0)
     906           7 :         put_padding_packet(ctx, ctx->pb, pad_packet_bytes);
     907             : 
     908         598 :     for (i = 0; i < zero_trail_bytes; i++)
     909           0 :         avio_w8(ctx->pb, 0x00);
     910             : 
     911         598 :     avio_flush(ctx->pb);
     912             : 
     913         598 :     s->packet_number++;
     914             : 
     915             :     /* only increase the stream packet number if this pack actually contains
     916             :      * something that is specific to this stream! I.e. a dedicated header
     917             :      * or some data. */
     918         598 :     if (!general_pack)
     919         598 :         stream->packet_number++;
     920             : 
     921         598 :     return payload_size - stuffing_size;
     922             : }
     923             : 
     924           0 : static void put_vcd_padding_sector(AVFormatContext *ctx)
     925             : {
     926             :     /* There are two ways to do this padding: writing a sector/pack
     927             :      * of 0 values, or writing an MPEG padding pack. Both seem to
     928             :      * work with most decoders, BUT the VCD standard only allows a 0-sector
     929             :      * (see standard p. IV-4, IV-5).
     930             :      * So a 0-sector it is... */
     931             : 
     932           0 :     MpegMuxContext *s = ctx->priv_data;
     933             :     int i;
     934             : 
     935           0 :     for (i = 0; i < s->packet_size; i++)
     936           0 :         avio_w8(ctx->pb, 0);
     937             : 
     938           0 :     s->vcd_padding_bytes_written += s->packet_size;
     939             : 
     940           0 :     avio_flush(ctx->pb);
     941             : 
     942             :     /* increasing the packet number is correct. The SCR of the following packs
     943             :      * is calculated from the packet_number and it has to include the padding
     944             :      * sector (it represents the sector index, not the MPEG pack index)
     945             :      * (see VCD standard p. IV-6) */
     946           0 :     s->packet_number++;
     947           0 : }
     948             : 
     949         839 : static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr)
     950             : {
     951             :     int i;
     952             : 
     953        2429 :     for (i = 0; i < ctx->nb_streams; i++) {
     954        1590 :         AVStream *st = ctx->streams[i];
     955        1590 :         StreamInfo *stream = st->priv_data;
     956             :         PacketDesc *pkt_desc;
     957             : 
     958        5237 :         while ((pkt_desc = stream->predecode_packet) &&
     959        1816 :                scr > pkt_desc->dts) { // FIXME: > vs >=
     960         482 :             if (stream->buffer_index < pkt_desc->size ||
     961         241 :                 stream->predecode_packet == stream->premux_packet) {
     962           0 :                 av_log(ctx, AV_LOG_ERROR,
     963             :                        "buffer underflow st=%d bufi=%d size=%d\n",
     964           0 :                        i, stream->buffer_index, pkt_desc->size);
     965           0 :                 break;
     966             :             }
     967         241 :             stream->buffer_index    -= pkt_desc->size;
     968         241 :             stream->predecode_packet = pkt_desc->next;
     969         241 :             av_freep(&pkt_desc);
     970             :         }
     971             :     }
     972             : 
     973         839 :     return 0;
     974             : }
     975             : 
     976         843 : static int output_packet(AVFormatContext *ctx, int flush)
     977             : {
     978         843 :     MpegMuxContext *s = ctx->priv_data;
     979             :     AVStream *st;
     980             :     StreamInfo *stream;
     981         843 :     int i, avail_space = 0, es_size, trailer_size;
     982         843 :     int best_i = -1;
     983         843 :     int best_score = INT_MIN;
     984         843 :     int ignore_constraints = 0;
     985         843 :     int ignore_delay = 0;
     986         843 :     int64_t scr = s->last_scr;
     987             :     PacketDesc *timestamp_packet;
     988         843 :     const int64_t max_delay = av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
     989             : 
     990        1084 : retry:
     991        2847 :     for (i = 0; i < ctx->nb_streams; i++) {
     992        2004 :         AVStream *st = ctx->streams[i];
     993        2004 :         StreamInfo *stream = st->priv_data;
     994        2004 :         const int avail_data = av_fifo_size(stream->fifo);
     995        2004 :         const int space = stream->max_buffer_size - stream->buffer_index;
     996        2004 :         int rel_space = 1024LL * space / stream->max_buffer_size;
     997        2004 :         PacketDesc *next_pkt = stream->premux_packet;
     998             : 
     999             :         /* for subtitle, a single PES packet must be generated,
    1000             :          * so we flush after every single subtitle packet */
    1001        2004 :         if (s->packet_size > avail_data && !flush
    1002         241 :             && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
    1003         241 :             return 0;
    1004        1763 :         if (avail_data == 0)
    1005         187 :             continue;
    1006        1576 :         av_assert0(avail_data > 0);
    1007             : 
    1008        1576 :         if (space < s->packet_size && !ignore_constraints)
    1009         587 :             continue;
    1010             : 
    1011         989 :         if (next_pkt && next_pkt->dts - scr > max_delay && !ignore_delay)
    1012         152 :             continue;
    1013         837 :         if (   stream->predecode_packet
    1014         837 :             && stream->predecode_packet->size > stream->buffer_index)
    1015         150 :             rel_space += 1<<28;
    1016         837 :         if (rel_space > best_score) {
    1017         763 :             best_score  = rel_space;
    1018         763 :             best_i      = i;
    1019         763 :             avail_space = space;
    1020             :         }
    1021             :     }
    1022             : 
    1023         843 :     if (best_i < 0) {
    1024         245 :         int64_t best_dts = INT64_MAX;
    1025         245 :         int has_premux = 0;
    1026             : 
    1027         690 :         for (i = 0; i < ctx->nb_streams; i++) {
    1028         445 :             AVStream *st = ctx->streams[i];
    1029         445 :             StreamInfo *stream = st->priv_data;
    1030         445 :             PacketDesc *pkt_desc = stream->predecode_packet;
    1031         445 :             if (pkt_desc && pkt_desc->dts < best_dts)
    1032         350 :                 best_dts = pkt_desc->dts;
    1033         445 :             has_premux |= !!stream->premux_packet;
    1034             :         }
    1035             : 
    1036         245 :         if (best_dts < INT64_MAX) {
    1037         241 :             av_log(ctx, AV_LOG_TRACE, "bumping scr, scr:%f, dts:%f\n",
    1038             :                     scr / 90000.0, best_dts / 90000.0);
    1039             : 
    1040         241 :             if (scr >= best_dts + 1 && !ignore_constraints) {
    1041           0 :                 av_log(ctx, AV_LOG_ERROR,
    1042             :                     "packet too large, ignoring buffer limits to mux it\n");
    1043           0 :                 ignore_constraints = 1;
    1044             :             }
    1045         241 :             scr = FFMAX(best_dts + 1, scr);
    1046         241 :             if (remove_decoded_packets(ctx, scr) < 0)
    1047           0 :                 return -1;
    1048           4 :         } else if (has_premux && flush) {
    1049           0 :             av_log(ctx, AV_LOG_ERROR,
    1050             :                   "delay too large, ignoring ...\n");
    1051           0 :             ignore_delay = 1;
    1052           0 :             ignore_constraints = 1;
    1053             :         } else
    1054           4 :             return 0;
    1055             : 
    1056         241 :         goto retry;
    1057             :     }
    1058             : 
    1059         598 :     av_assert0(best_i >= 0);
    1060             : 
    1061         598 :     st     = ctx->streams[best_i];
    1062         598 :     stream = st->priv_data;
    1063             : 
    1064         598 :     av_assert0(av_fifo_size(stream->fifo) > 0);
    1065             : 
    1066         598 :     av_assert0(avail_space >= s->packet_size || ignore_constraints);
    1067             : 
    1068         598 :     timestamp_packet = stream->premux_packet;
    1069         598 :     if (timestamp_packet->unwritten_size == timestamp_packet->size) {
    1070          50 :         trailer_size = 0;
    1071             :     } else {
    1072         548 :         trailer_size     = timestamp_packet->unwritten_size;
    1073         548 :         timestamp_packet = timestamp_packet->next;
    1074             :     }
    1075             : 
    1076         598 :     if (timestamp_packet) {
    1077        1476 :         av_log(ctx, AV_LOG_TRACE, "dts:%f pts:%f scr:%f stream:%d\n",
    1078         492 :                 timestamp_packet->dts / 90000.0,
    1079         492 :                 timestamp_packet->pts / 90000.0,
    1080             :                 scr / 90000.0, best_i);
    1081         492 :         es_size = flush_packet(ctx, best_i, timestamp_packet->pts,
    1082             :                                timestamp_packet->dts, scr, trailer_size);
    1083             :     } else {
    1084         106 :         av_assert0(av_fifo_size(stream->fifo) == trailer_size);
    1085         106 :         es_size = flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr,
    1086             :                                trailer_size);
    1087             :     }
    1088             : 
    1089         598 :     if (s->is_vcd) {
    1090             :         /* Write one or more padding sectors, if necessary, to reach
    1091             :          * the constant overall bitrate. */
    1092             :         int vcd_pad_bytes;
    1093             : 
    1094             :         // FIXME: pts cannot be correct here
    1095           0 :         while ((vcd_pad_bytes = get_vcd_padding_size(ctx, stream->premux_packet->pts)) >= s->packet_size) {
    1096           0 :             put_vcd_padding_sector(ctx);
    1097             :             // FIXME: rounding and first few bytes of each packet
    1098           0 :             s->last_scr += s->packet_size * 90000LL / (s->mux_rate * 50LL);
    1099             :         }
    1100             :     }
    1101             : 
    1102         598 :     stream->buffer_index += es_size;
    1103             :     // FIXME: rounding and first few bytes of each packet
    1104         598 :     s->last_scr          += s->packet_size * 90000LL / (s->mux_rate * 50LL);
    1105             : 
    1106        2269 :     while (stream->premux_packet &&
    1107         832 :            stream->premux_packet->unwritten_size <= es_size) {
    1108         241 :         es_size              -= stream->premux_packet->unwritten_size;
    1109         241 :         stream->premux_packet = stream->premux_packet->next;
    1110             :     }
    1111         598 :     if (es_size) {
    1112         548 :         av_assert0(stream->premux_packet);
    1113         548 :         stream->premux_packet->unwritten_size -= es_size;
    1114             :     }
    1115             : 
    1116         598 :     if (remove_decoded_packets(ctx, s->last_scr) < 0)
    1117           0 :         return -1;
    1118             : 
    1119         598 :     return 1;
    1120             : }
    1121             : 
    1122         241 : static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
    1123             : {
    1124         241 :     int stream_index = pkt->stream_index;
    1125         241 :     int size         = pkt->size;
    1126         241 :     uint8_t *buf     = pkt->data;
    1127         241 :     MpegMuxContext *s = ctx->priv_data;
    1128         241 :     AVStream *st      = ctx->streams[stream_index];
    1129         241 :     StreamInfo *stream = st->priv_data;
    1130             :     int64_t pts, dts;
    1131             :     PacketDesc *pkt_desc;
    1132             :     int preload;
    1133         321 :     const int is_iframe = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
    1134          80 :                           (pkt->flags & AV_PKT_FLAG_KEY);
    1135             : 
    1136         241 :     preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
    1137             : 
    1138         241 :     pts = pkt->pts;
    1139         241 :     dts = pkt->dts;
    1140             : 
    1141         241 :     if (s->last_scr == AV_NOPTS_VALUE) {
    1142           4 :         if (dts == AV_NOPTS_VALUE || (dts < preload && ctx->avoid_negative_ts) || s->is_dvd) {
    1143           4 :             if (dts != AV_NOPTS_VALUE)
    1144           4 :                 s->preload += av_rescale(-dts, AV_TIME_BASE, 90000);
    1145           4 :             s->last_scr = 0;
    1146             :         } else {
    1147           0 :             s->last_scr = dts - preload;
    1148           0 :             s->preload = 0;
    1149             :         }
    1150           4 :         preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
    1151           4 :         av_log(ctx, AV_LOG_DEBUG, "First SCR: %"PRId64" First DTS: %"PRId64"\n", s->last_scr, dts + preload);
    1152             :     }
    1153             : 
    1154         241 :     if (dts != AV_NOPTS_VALUE) dts += preload;
    1155         241 :     if (pts != AV_NOPTS_VALUE) pts += preload;
    1156             : 
    1157         241 :     av_log(ctx, AV_LOG_TRACE, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n",
    1158             :             dts / 90000.0, pts / 90000.0, pkt->flags,
    1159             :             pkt->stream_index, pts != AV_NOPTS_VALUE);
    1160         241 :     if (!stream->premux_packet)
    1161           7 :         stream->next_packet = &stream->premux_packet;
    1162         241 :     *stream->next_packet     =
    1163             :     pkt_desc                 = av_mallocz(sizeof(PacketDesc));
    1164         241 :     if (!pkt_desc)
    1165           0 :         return AVERROR(ENOMEM);
    1166         241 :     pkt_desc->pts            = pts;
    1167         241 :     pkt_desc->dts            = dts;
    1168             : 
    1169         241 :     if (st->codecpar->codec_id == AV_CODEC_ID_PCM_DVD) {
    1170          44 :         if (size < 3) {
    1171           0 :             av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n", size);
    1172           0 :             return AVERROR(EINVAL);
    1173             :         }
    1174             : 
    1175             :         /* Skip first 3 bytes of packet data, which comprise PCM header
    1176             :            and will be written fresh by this muxer. */
    1177          44 :         buf += 3;
    1178          44 :         size -= 3;
    1179             :     }
    1180             : 
    1181         241 :     pkt_desc->unwritten_size =
    1182         241 :     pkt_desc->size           = size;
    1183         241 :     if (!stream->predecode_packet)
    1184           7 :         stream->predecode_packet = pkt_desc;
    1185         241 :     stream->next_packet = &pkt_desc->next;
    1186             : 
    1187         241 :     if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
    1188           0 :         return -1;
    1189             : 
    1190         241 :     if (s->is_dvd) {
    1191             :         // min VOBU length 0.4 seconds (mpucoder)
    1192           0 :         if (is_iframe &&
    1193           0 :             (s->packet_number == 0 ||
    1194           0 :              (pts - stream->vobu_start_pts >= 36000))) {
    1195           0 :             stream->bytes_to_iframe = av_fifo_size(stream->fifo);
    1196           0 :             stream->align_iframe    = 1;
    1197           0 :             stream->vobu_start_pts  = pts;
    1198             :         }
    1199             :     }
    1200             : 
    1201         241 :     av_fifo_generic_write(stream->fifo, buf, size, NULL);
    1202             : 
    1203         588 :     for (;;) {
    1204         829 :         int ret = output_packet(ctx, 0);
    1205         829 :         if (ret <= 0)
    1206         241 :             return ret;
    1207             :     }
    1208             : }
    1209             : 
    1210          14 : static int mpeg_mux_end(AVFormatContext *ctx)
    1211             : {
    1212             :     StreamInfo *stream;
    1213             :     int i;
    1214             : 
    1215          10 :     for (;;) {
    1216          14 :         int ret = output_packet(ctx, 1);
    1217          14 :         if (ret < 0)
    1218           0 :             return ret;
    1219          14 :         else if (ret == 0)
    1220           4 :             break;
    1221             :     }
    1222             : 
    1223             :     /* End header according to MPEG-1 systems standard. We do not write
    1224             :      * it as it is usually not needed by decoders and because it
    1225             :      * complicates MPEG stream concatenation. */
    1226             :     // avio_wb32(ctx->pb, ISO_11172_END_CODE);
    1227             :     // avio_flush(ctx->pb);
    1228             : 
    1229          11 :     for (i = 0; i < ctx->nb_streams; i++) {
    1230           7 :         stream = ctx->streams[i]->priv_data;
    1231             : 
    1232           7 :         av_assert0(av_fifo_size(stream->fifo) == 0);
    1233           7 :         av_fifo_freep(&stream->fifo);
    1234             :     }
    1235           4 :     return 0;
    1236             : }
    1237             : 
    1238             : #define OFFSET(x) offsetof(MpegMuxContext, x)
    1239             : #define E AV_OPT_FLAG_ENCODING_PARAM
    1240             : static const AVOption options[] = {
    1241             :     { "muxrate", NULL,                                          OFFSET(user_mux_rate), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, ((1<<22) - 1) * (8 * 50), E },
    1242             :     { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload),  AV_OPT_TYPE_INT, { .i64 = 500000 }, 0, INT_MAX, E },
    1243             :     { NULL },
    1244             : };
    1245             : 
    1246             : #define MPEGENC_CLASS(flavor)                   \
    1247             : static const AVClass flavor ## _class = {       \
    1248             :     .class_name = #flavor " muxer",             \
    1249             :     .item_name  = av_default_item_name,         \
    1250             :     .version    = LIBAVUTIL_VERSION_INT,        \
    1251             :     .option     = options,                      \
    1252             : };
    1253             : 
    1254             : #if CONFIG_MPEG1SYSTEM_MUXER
    1255             : MPEGENC_CLASS(mpeg)
    1256             : AVOutputFormat ff_mpeg1system_muxer = {
    1257             :     .name              = "mpeg",
    1258             :     .long_name         = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream"),
    1259             :     .mime_type         = "video/mpeg",
    1260             :     .extensions        = "mpg,mpeg",
    1261             :     .priv_data_size    = sizeof(MpegMuxContext),
    1262             :     .audio_codec       = AV_CODEC_ID_MP2,
    1263             :     .video_codec       = AV_CODEC_ID_MPEG1VIDEO,
    1264             :     .write_header      = mpeg_mux_init,
    1265             :     .write_packet      = mpeg_mux_write_packet,
    1266             :     .write_trailer     = mpeg_mux_end,
    1267             :     .priv_class        = &mpeg_class,
    1268             : };
    1269             : #endif
    1270             : 
    1271             : #if CONFIG_MPEG1VCD_MUXER
    1272             : MPEGENC_CLASS(vcd)
    1273             : AVOutputFormat ff_mpeg1vcd_muxer = {
    1274             :     .name              = "vcd",
    1275             :     .long_name         = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream (VCD)"),
    1276             :     .mime_type         = "video/mpeg",
    1277             :     .priv_data_size    = sizeof(MpegMuxContext),
    1278             :     .audio_codec       = AV_CODEC_ID_MP2,
    1279             :     .video_codec       = AV_CODEC_ID_MPEG1VIDEO,
    1280             :     .write_header      = mpeg_mux_init,
    1281             :     .write_packet      = mpeg_mux_write_packet,
    1282             :     .write_trailer     = mpeg_mux_end,
    1283             :     .priv_class        = &vcd_class,
    1284             : };
    1285             : #endif
    1286             : 
    1287             : #if CONFIG_MPEG2VOB_MUXER
    1288             : MPEGENC_CLASS(vob)
    1289             : AVOutputFormat ff_mpeg2vob_muxer = {
    1290             :     .name              = "vob",
    1291             :     .long_name         = NULL_IF_CONFIG_SMALL("MPEG-2 PS (VOB)"),
    1292             :     .mime_type         = "video/mpeg",
    1293             :     .extensions        = "vob",
    1294             :     .priv_data_size    = sizeof(MpegMuxContext),
    1295             :     .audio_codec       = AV_CODEC_ID_MP2,
    1296             :     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
    1297             :     .write_header      = mpeg_mux_init,
    1298             :     .write_packet      = mpeg_mux_write_packet,
    1299             :     .write_trailer     = mpeg_mux_end,
    1300             :     .priv_class        = &vob_class,
    1301             : };
    1302             : #endif
    1303             : 
    1304             : /* Same as mpeg2vob_mux except that the pack size is 2324 */
    1305             : #if CONFIG_MPEG2SVCD_MUXER
    1306             : MPEGENC_CLASS(svcd)
    1307             : AVOutputFormat ff_mpeg2svcd_muxer = {
    1308             :     .name              = "svcd",
    1309             :     .long_name         = NULL_IF_CONFIG_SMALL("MPEG-2 PS (SVCD)"),
    1310             :     .mime_type         = "video/mpeg",
    1311             :     .extensions        = "vob",
    1312             :     .priv_data_size    = sizeof(MpegMuxContext),
    1313             :     .audio_codec       = AV_CODEC_ID_MP2,
    1314             :     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
    1315             :     .write_header      = mpeg_mux_init,
    1316             :     .write_packet      = mpeg_mux_write_packet,
    1317             :     .write_trailer     = mpeg_mux_end,
    1318             :     .priv_class        = &svcd_class,
    1319             : };
    1320             : #endif
    1321             : 
    1322             : /*  Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
    1323             : #if CONFIG_MPEG2DVD_MUXER
    1324             : MPEGENC_CLASS(dvd)
    1325             : AVOutputFormat ff_mpeg2dvd_muxer = {
    1326             :     .name              = "dvd",
    1327             :     .long_name         = NULL_IF_CONFIG_SMALL("MPEG-2 PS (DVD VOB)"),
    1328             :     .mime_type         = "video/mpeg",
    1329             :     .extensions        = "dvd",
    1330             :     .priv_data_size    = sizeof(MpegMuxContext),
    1331             :     .audio_codec       = AV_CODEC_ID_MP2,
    1332             :     .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
    1333             :     .write_header      = mpeg_mux_init,
    1334             :     .write_packet      = mpeg_mux_write_packet,
    1335             :     .write_trailer     = mpeg_mux_end,
    1336             :     .priv_class        = &dvd_class,
    1337             : };
    1338             : #endif

Generated by: LCOV version 1.13