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

Generated by: LCOV version 1.13