mpegenc.c 47.2 KB
Newer Older
1
/*
2
 * MPEG-1/2 muxer
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

22 23
#include <stdint.h>

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 35 36 37 38 39 40 41 42 43 44 45
#include "mpeg.h"

#define MAX_PAYLOAD_SIZE 4096

typedef struct PacketDesc {
    int64_t pts;
    int64_t dts;
    int size;
    int unwritten_size;
    struct PacketDesc *next;
} PacketDesc;

46
typedef struct StreamInfo {
47
    AVFifoBuffer *fifo;
48 49 50 51 52 53 54 55 56 57 58 59 60 61
    uint8_t id;
    int max_buffer_size; /* in bytes */
    int buffer_index;
    PacketDesc *predecode_packet;
    PacketDesc *premux_packet;
    PacketDesc **next_packet;
    int packet_number;
    uint8_t lpcm_header[3];
    int lpcm_align;
    int bytes_to_iframe;
    int align_iframe;
    int64_t vobu_start_pts;
} StreamInfo;

62
typedef struct MpegMuxContext {
63
    const AVClass *class;
64 65 66 67 68
    int packet_size; /* required packet size */
    int packet_number;
    int pack_header_freq;     /* frequency (in packets^-1) at which we send pack headers */
    int system_header_freq;
    int system_header_size;
69
    int user_mux_rate; /* bitrate in units of bits/s */
70 71 72 73 74 75 76 77 78 79
    int mux_rate; /* bitrate in units of 50 bytes/s */
    /* stream info */
    int audio_bound;
    int video_bound;
    int is_mpeg2;
    int is_vcd;
    int is_svcd;
    int is_dvd;
    int64_t last_scr; /* current system clock */

80
    int64_t vcd_padding_bitrate_num;
81 82
    int64_t vcd_padding_bytes_written;

83
    int preload;
84 85
} MpegMuxContext;

86 87 88 89
extern AVOutputFormat ff_mpeg1vcd_muxer;
extern AVOutputFormat ff_mpeg2dvd_muxer;
extern AVOutputFormat ff_mpeg2svcd_muxer;
extern AVOutputFormat ff_mpeg2vob_muxer;
90

91 92
static int put_pack_header(AVFormatContext *ctx, uint8_t *buf,
                           int64_t timestamp)
93 94 95 96 97 98
{
    MpegMuxContext *s = ctx->priv_data;
    PutBitContext pb;

    init_put_bits(&pb, buf, 128);

99
    put_bits32(&pb, PACK_START_CODE);
100
    if (s->is_mpeg2)
101
        put_bits(&pb, 2, 0x1);
102
    else
103
        put_bits(&pb, 4, 0x2);
104 105
    put_bits(&pb,  3, (uint32_t)((timestamp >> 30) & 0x07));
    put_bits(&pb,  1, 1);
106
    put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
107 108 109 110
    put_bits(&pb,  1, 1);
    put_bits(&pb, 15, (uint32_t)((timestamp)       & 0x7fff));
    put_bits(&pb,  1, 1);
    if (s->is_mpeg2)
111 112 113 114 115 116 117 118 119 120 121
        /* clock extension */
        put_bits(&pb, 9, 0);
    put_bits(&pb, 1, 1);
    put_bits(&pb, 22, s->mux_rate);
    put_bits(&pb, 1, 1);
    if (s->is_mpeg2) {
        put_bits(&pb, 1, 1);
        put_bits(&pb, 5, 0x1f); /* reserved */
        put_bits(&pb, 3, 0); /* stuffing length */
    }
    flush_put_bits(&pb);
122
    return put_bits_ptr(&pb) - pb.buf;
123 124
}

125 126
static int put_system_header(AVFormatContext *ctx, uint8_t *buf,
                             int only_for_stream_id)
127 128 129 130 131 132 133
{
    MpegMuxContext *s = ctx->priv_data;
    int size, i, private_stream_coded, id;
    PutBitContext pb;

    init_put_bits(&pb, buf, 128);

134
    put_bits32(&pb, SYSTEM_HEADER_START_CODE);
135 136 137
    put_bits(&pb, 16, 0);
    put_bits(&pb, 1, 1);

138 139
    /* maximum bit rate of the multiplexed stream */
    put_bits(&pb, 22, s->mux_rate);
140
    put_bits(&pb, 1, 1); /* marker */
141 142 143
    if (s->is_vcd && only_for_stream_id == VIDEO_ID) {
        /* This header applies only to the video stream
         * (see VCD standard p. IV-7) */
144 145 146 147 148
        put_bits(&pb, 6, 0);
    } else
        put_bits(&pb, 6, s->audio_bound);

    if (s->is_vcd) {
149
        /* see VCD standard, p. IV-7 */
150 151 152
        put_bits(&pb, 1, 0);
        put_bits(&pb, 1, 1);
    } else {
153
        put_bits(&pb, 1, 0); /* variable bitrate */
154
        put_bits(&pb, 1, 0); /* nonconstrained bitstream */
155 156 157 158 159 160 161 162 163 164 165 166 167
    }

    if (s->is_vcd || s->is_dvd) {
        /* see VCD standard p IV-7 */
        put_bits(&pb, 1, 1); /* audio locked */
        put_bits(&pb, 1, 1); /* video locked */
    } else {
        put_bits(&pb, 1, 0); /* audio locked */
        put_bits(&pb, 1, 0); /* video locked */
    }

    put_bits(&pb, 1, 1); /* marker */

168
    if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
169 170
        /* This header applies only to the audio stream
         * (see VCD standard p. IV-7) */
171 172 173 174 175 176 177 178 179 180 181
        put_bits(&pb, 5, 0);
    } else
        put_bits(&pb, 5, s->video_bound);

    if (s->is_dvd) {
        put_bits(&pb, 1, 0);    /* packet_rate_restriction_flag */
        put_bits(&pb, 7, 0x7f); /* reserved byte */
    } else
        put_bits(&pb, 8, 0xff); /* reserved byte */

    /* DVD-Video Stream_bound entries
182 183 184 185
     * id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
     * 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)
     * id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
     * id (0xBF) private stream 2, NAV packs, set to 2x1024. */
186 187 188 189 190 191
    if (s->is_dvd) {

        int P_STD_max_video = 0;
        int P_STD_max_mpeg_audio = 0;
        int P_STD_max_mpeg_PS1 = 0;

192
        for (i = 0; i < ctx->nb_streams; i++) {
193 194 195 196 197
            StreamInfo *stream = ctx->streams[i]->priv_data;

            id = stream->id;
            if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
                P_STD_max_mpeg_PS1 = stream->max_buffer_size;
198 199
            } else if (id >= 0xc0 && id <= 0xc7 &&
                       stream->max_buffer_size > P_STD_max_mpeg_audio) {
200
                P_STD_max_mpeg_audio = stream->max_buffer_size;
201 202
            } else if (id == 0xe0 &&
                       stream->max_buffer_size > P_STD_max_video) {
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
                P_STD_max_video = stream->max_buffer_size;
            }
        }

        /* video */
        put_bits(&pb, 8, 0xb9); /* stream ID */
        put_bits(&pb, 2, 3);
        put_bits(&pb, 1, 1);
        put_bits(&pb, 13, P_STD_max_video / 1024);

        /* audio */
        if (P_STD_max_mpeg_audio == 0)
            P_STD_max_mpeg_audio = 4096;
        put_bits(&pb, 8, 0xb8); /* stream ID */
        put_bits(&pb, 2, 3);
        put_bits(&pb, 1, 0);
        put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);

        /* private stream 1 */
        put_bits(&pb, 8, 0xbd); /* stream ID */
        put_bits(&pb, 2, 3);
        put_bits(&pb, 1, 0);
        put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);

        /* private stream 2 */
        put_bits(&pb, 8, 0xbf); /* stream ID */
        put_bits(&pb, 2, 3);
        put_bits(&pb, 1, 1);
        put_bits(&pb, 13, 2);
232
    } else {
233 234
        /* audio stream info */
        private_stream_coded = 0;
235
        for (i = 0; i < ctx->nb_streams; i++) {
236 237 238
            StreamInfo *stream = ctx->streams[i]->priv_data;

            /* For VCDs, only include the stream info for the stream
239 240 241 242
             * that the pack which contains this system belongs to.
             * (see VCD standard p. IV-7) */
            if (!s->is_vcd || stream->id == only_for_stream_id ||
                only_for_stream_id == 0) {
243 244
                id = stream->id;
                if (id < 0xc0) {
245
                    /* special case for private streams (AC-3 uses that) */
246 247 248 249 250
                    if (private_stream_coded)
                        continue;
                    private_stream_coded = 1;
                    id = 0xbd;
                }
251
                put_bits(&pb, 8, id);         /* stream ID */
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                put_bits(&pb, 2, 3);
                if (id < 0xe0) {
                    /* audio */
                    put_bits(&pb, 1, 0);
                    put_bits(&pb, 13, stream->max_buffer_size / 128);
                } else {
                    /* video */
                    put_bits(&pb, 1, 1);
                    put_bits(&pb, 13, stream->max_buffer_size / 1024);
                }
            }
        }
    }

    flush_put_bits(&pb);
267
    size = put_bits_ptr(&pb) - pb.buf;
268
    /* patch packet size */
269
    AV_WB16(buf + 4, size - 6);
270 271 272 273 274 275 276 277 278 279 280

    return size;
}

static int get_system_header_size(AVFormatContext *ctx)
{
    int buf_index, i, private_stream_coded;
    StreamInfo *stream;
    MpegMuxContext *s = ctx->priv_data;

    if (s->is_dvd)
281
        return 18; // DVD-Video system headers are 18 bytes fixed length.
282 283 284

    buf_index = 12;
    private_stream_coded = 0;
285
    for (i = 0; i < ctx->nb_streams; i++) {
286 287 288 289 290 291 292 293 294 295 296
        stream = ctx->streams[i]->priv_data;
        if (stream->id < 0xc0) {
            if (private_stream_coded)
                continue;
            private_stream_coded = 1;
        }
        buf_index += 3;
    }
    return buf_index;
}

297
static av_cold int mpeg_mux_init(AVFormatContext *ctx)
298 299
{
    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 302 303 304 305 306
    AVStream *st;
    StreamInfo *stream;
    int audio_bitrate;
    int video_bitrate;

    s->packet_number = 0;
307 308
    s->is_vcd   =  (CONFIG_MPEG1VCD_MUXER  && ctx->oformat == &ff_mpeg1vcd_muxer);
    s->is_svcd  =  (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
309 310 311
    s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER  && ctx->oformat == &ff_mpeg2vob_muxer) ||
                   (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer) ||
                   (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
312
    s->is_dvd   =  (CONFIG_MPEG2DVD_MUXER  && ctx->oformat == &ff_mpeg2dvd_muxer);
313

314
    if (ctx->packet_size) {
315 316 317 318 319
        if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
            av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
                   ctx->packet_size);
            goto fail;
        }
320
        s->packet_size = ctx->packet_size;
321
    } else
322
        s->packet_size = 2048;
323
    if (ctx->max_delay < 0)     /* Not set by the caller */
324
        ctx->max_delay = AV_TIME_BASE*7/10;
325 326

    s->vcd_padding_bytes_written = 0;
327
    s->vcd_padding_bitrate_num   = 0;
328 329 330

    s->audio_bound = 0;
    s->video_bound = 0;
331 332 333 334 335

    mpa_id  = AUDIO_ID;
    ac3_id  = AC3_ID;
    dts_id  = DTS_ID;
    mpv_id  = VIDEO_ID;
336
    h264_id = H264_ID;
337
    mps_id  = SUB_ID;
338
    lpcm_id = LPCM_ID;
339 340

    for (i = 0; i < ctx->nb_streams; i++) {
341 342
        AVCPBProperties *props;

343
        st     = ctx->streams[i];
344 345 346 347 348
        stream = av_mallocz(sizeof(StreamInfo));
        if (!stream)
            goto fail;
        st->priv_data = stream;

349
        avpriv_set_pts_info(st, 64, 1, 90000);
350

351
        switch (st->codecpar->codec_type) {
352
        case AVMEDIA_TYPE_AUDIO:
353
            if (!s->is_mpeg2 &&
354 355
                (st->codecpar->codec_id == AV_CODEC_ID_AC3 ||
                 st->codecpar->codec_id == AV_CODEC_ID_DTS ||
356 357
                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ||
                 st->codecpar->codec_id == AV_CODEC_ID_PCM_DVD))
358 359 360 361
                 av_log(ctx, AV_LOG_WARNING,
                        "%s in MPEG-1 system streams is not widely supported, "
                        "consider using the vob or the dvd muxer "
                        "to force a MPEG-2 program stream.\n",
362
                        avcodec_get_name(st->codecpar->codec_id));
363
            if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
364
                stream->id = ac3_id++;
365
            } else if (st->codecpar->codec_id == AV_CODEC_ID_DTS) {
366
                stream->id = dts_id++;
367
            } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) {
368
                stream->id = lpcm_id++;
369
                for (j = 0; j < 4; j++) {
370
                    if (lpcm_freq_tab[j] == st->codecpar->sample_rate)
371 372
                        break;
                }
373 374 375 376 377 378 379
                if (j == 4) {
                    int sr;
                    av_log(ctx, AV_LOG_ERROR, "Invalid sampling rate for PCM stream.\n");
                    av_log(ctx, AV_LOG_INFO, "Allowed sampling rates:");
                    for (sr = 0; sr < 4; sr++)
                         av_log(ctx, AV_LOG_INFO, " %d", lpcm_freq_tab[sr]);
                    av_log(ctx, AV_LOG_INFO, "\n");
380
                    goto fail;
381 382 383 384 385
                }
                if (st->codecpar->channels > 8) {
                    av_log(ctx, AV_LOG_ERROR, "At most 8 channels allowed for LPCM streams.\n");
                    goto fail;
                }
386
                stream->lpcm_header[0] = 0x0c;
387
                stream->lpcm_header[1] = (st->codecpar->channels - 1) | (j << 4);
388
                stream->lpcm_header[2] = 0x80;
389
                stream->lpcm_align     = st->codecpar->channels * 2;
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
            } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_DVD) {
                int freq;

                switch (st->codecpar->sample_rate) {
                case 48000: freq = 0; break;
                case 96000: freq = 1; break;
                case 44100: freq = 2; break;
                case 32000: freq = 3; break;
                default:
                    av_log(ctx, AV_LOG_ERROR, "Unsupported sample rate.\n");
                    return AVERROR(EINVAL);
                }

                stream->lpcm_header[0] = 0x0c;
                stream->lpcm_header[1] = (freq << 4) |
                                         (((st->codecpar->bits_per_coded_sample - 16) / 4) << 6) |
                                         st->codecpar->channels - 1;
                stream->lpcm_header[2] = 0x80;
                stream->id = lpcm_id++;
                stream->lpcm_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8;
410 411 412 413 414 415 416 417 418 419
            } else if (st->codecpar->codec_id == AV_CODEC_ID_MLP ||
                       st->codecpar->codec_id == AV_CODEC_ID_TRUEHD) {
                       av_log(ctx, AV_LOG_ERROR, "Support for muxing audio codec %s not implemented.\n",
                              avcodec_get_name(st->codecpar->codec_id));
                       return AVERROR_PATCHWELCOME;
            } else if (st->codecpar->codec_id != AV_CODEC_ID_MP1 &&
                       st->codecpar->codec_id != AV_CODEC_ID_MP2 &&
                       st->codecpar->codec_id != AV_CODEC_ID_MP3) {
                       av_log(ctx, AV_LOG_ERROR, "Unsupported audio codec. Must be one of mp1, mp2, mp3, 16-bit pcm_dvd, pcm_s16be, ac3 or dts.\n");
                       goto fail;
420 421 422 423 424
            } else {
                stream->id = mpa_id++;
            }

            /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
425
             * Right now it is also used for everything else. */
426 427 428
            stream->max_buffer_size = 4 * 1024;
            s->audio_bound++;
            break;
429
        case AVMEDIA_TYPE_VIDEO:
430
            if (st->codecpar->codec_id == AV_CODEC_ID_H264)
431 432 433
                stream->id = h264_id++;
            else
                stream->id = mpv_id++;
434 435 436 437

            props = (AVCPBProperties*)av_stream_get_side_data(st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
            if (props && props->buffer_size)
                stream->max_buffer_size = 6 * 1024 + props->buffer_size / 8;
438
            else {
439
                av_log(ctx, AV_LOG_WARNING,
440
                       "VBV buffer size not set, using default size of 230KB\n"
441 442
                       "If you want the mpeg file to be compliant to some specification\n"
                       "Like DVD, VCD or others, make sure you set the correct buffer size\n");
443 444
                // FIXME: this is probably too small as default
                stream->max_buffer_size = 230 * 1024;
445
            }
446 447 448 449
            if (stream->max_buffer_size > 1024 * 8191) {
                av_log(ctx, AV_LOG_WARNING, "buffer size %d, too large\n", stream->max_buffer_size);
                stream->max_buffer_size = 1024 * 8191;
            }
450 451
            s->video_bound++;
            break;
452
        case AVMEDIA_TYPE_SUBTITLE:
453
            stream->id              = mps_id++;
454 455 456
            stream->max_buffer_size = 16 * 1024;
            break;
        default:
457
            av_log(ctx, AV_LOG_ERROR, "Invalid media type %s for output stream #%d\n",
458
                   av_get_media_type_string(st->codecpar->codec_type), i);
459
            return AVERROR(EINVAL);
460
        }
461
        stream->fifo = av_fifo_alloc(16);
462 463
        if (!stream->fifo)
            goto fail;
464
    }
465
    bitrate       = 0;
466 467
    audio_bitrate = 0;
    video_bitrate = 0;
468
    for (i = 0; i < ctx->nb_streams; i++) {
469
        AVCPBProperties *props;
470
        int codec_rate;
471 472
        st     = ctx->streams[i];
        stream = (StreamInfo *)st->priv_data;
473

474 475 476
        props = (AVCPBProperties*)av_stream_get_side_data(st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
        if (props)
            codec_rate = props->max_bitrate;
477
        else
478
            codec_rate = st->codecpar->bit_rate;
479

480 481
        if (!codec_rate)
            codec_rate = (1 << 21) * 8 * 50 / ctx->nb_streams;
482 483 484

        bitrate += codec_rate;

485
        if ((stream->id & 0xe0) == AUDIO_ID)
486
            audio_bitrate += codec_rate;
487
        else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
488 489 490
            video_bitrate += codec_rate;
    }

491 492 493
    if (s->user_mux_rate) {
        s->mux_rate = (s->user_mux_rate + (8 * 50) - 1) / (8 * 50);
    } else {
494
        /* we increase slightly the bitrate to take into account the
495 496 497
         * headers. XXX: compute it exactly */
        bitrate    += bitrate / 20;
        bitrate    += 10000;
498
        s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
499 500 501 502
        if (s->mux_rate >= (1<<22)) {
            av_log(ctx, AV_LOG_WARNING, "mux rate %d is too large\n", s->mux_rate);
            s->mux_rate = (1<<22) - 1;
        }
503 504 505
    }

    if (s->is_vcd) {
506
        int64_t overhead_rate;
507 508

        /* The VCD standard mandates that the mux_rate field is 3528
509 510 511 512 513 514 515
         * (see standard p. IV-6).
         * The value is actually "wrong", i.e. if you calculate
         * it using the normal formula and the 75 sectors per second transfer
         * rate you get a different value because the real pack size is 2324,
         * not 2352. But the standard explicitly specifies that the mux_rate
         * field in the header must have this value. */
        // s->mux_rate = 2352 * 75 / 50;    /* = 3528 */
516 517

        /* The VCD standard states that the muxed stream must be
518 519 520 521 522
         * exactly 75 packs / second (the data rate of a single speed cdrom).
         * Since the video bitrate (probably 1150000 bits/sec) will be below
         * the theoretical maximum we have to add some padding packets
         * to make up for the lower data rate.
         * (cf. VCD standard p. IV-6 ) */
523 524

        /* Add the header overhead to the data rate.
525
         * 2279 data bytes per audio pack, 2294 data bytes per video pack */
526 527
        overhead_rate  = audio_bitrate * 2294LL * (2324 - 2279);
        overhead_rate += video_bitrate * 2279LL * (2324 - 2294);
528 529

        /* Add padding so that the full bitrate is 2324*75 bytes/sec */
530 531
        s->vcd_padding_bitrate_num = (2324LL * 75 * 8 - bitrate) * 2279 * 2294 - overhead_rate;
#define VCD_PADDING_BITRATE_DEN (2279 * 2294)
532 533 534 535 536 537 538 539 540 541 542
    }

    if (s->is_vcd || s->is_mpeg2)
        /* every packet */
        s->pack_header_freq = 1;
    else
        /* every 2 seconds */
        s->pack_header_freq = 2 * bitrate / s->packet_size / 8;

    /* the above seems to make pack_header_freq zero sometimes */
    if (s->pack_header_freq == 0)
543
        s->pack_header_freq = 1;
544 545 546 547 548 549

    if (s->is_mpeg2)
        /* every 200 packets. Need to look at the spec.  */
        s->system_header_freq = s->pack_header_freq * 40;
    else if (s->is_vcd)
        /* the standard mandates that there are only two system headers
550 551
         * in the whole file: one in the first packet of each stream.
         * (see standard p. IV-7 and IV-8) */
552 553 554 555
        s->system_header_freq = 0x7fffffff;
    else
        s->system_header_freq = s->pack_header_freq * 5;

556 557
    for (i = 0; i < ctx->nb_streams; i++) {
        stream                = ctx->streams[i]->priv_data;
558 559 560
        stream->packet_number = 0;
    }
    s->system_header_size = get_system_header_size(ctx);
561
    s->last_scr           = AV_NOPTS_VALUE;
562
    return 0;
563 564 565

fail:
    for (i = 0; i < ctx->nb_streams; i++)
566
        av_freep(&ctx->streams[i]->priv_data);
567 568 569
    return AVERROR(ENOMEM);
}

570
static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
571
{
572
    avio_w8(pb, (id << 4) |  (((timestamp >> 30) & 0x07)   << 1) | 1);
573
    avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
574
    avio_wb16(pb, (uint16_t)((((timestamp)       & 0x7fff) << 1) | 1));
575 576 577
}

/* return the number of padding bytes that should be inserted into
578
 * the multiplexed stream. */
579 580 581 582 583
static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
{
    MpegMuxContext *s = ctx->priv_data;
    int pad_bytes = 0;

584
    if (s->vcd_padding_bitrate_num > 0 && pts != AV_NOPTS_VALUE) {
585 586
        int64_t full_pad_bytes;

587 588
        // FIXME: this is wrong
        full_pad_bytes =
589
            av_rescale(s->vcd_padding_bitrate_num, pts, 90000LL * 8 * VCD_PADDING_BITRATE_DEN);
590
        pad_bytes = (int)(full_pad_bytes - s->vcd_padding_bytes_written);
591

592
        if (pad_bytes < 0)
593
            /* might happen if we have already padded to a later timestamp. This
594 595
             * can occur if another stream has already advanced further. */
            pad_bytes = 0;
596 597 598 599 600 601
    }

    return pad_bytes;
}

/* Write an MPEG padding packet header. */
602 603
static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,
                               int packet_bytes)
604 605 606 607
{
    MpegMuxContext *s = ctx->priv_data;
    int i;

608 609
    avio_wb32(pb, PADDING_STREAM);
    avio_wb16(pb, packet_bytes - 6);
610
    if (!s->is_mpeg2) {
611
        avio_w8(pb, 0x0f);
612 613 614 615
        packet_bytes -= 7;
    } else
        packet_bytes -= 6;

616
    for (i = 0; i < packet_bytes; i++)
617
        avio_w8(pb, 0xff);
618 619
}

620 621 622 623
static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len)
{
    int nb_frames        = 0;
    PacketDesc *pkt_desc = stream->premux_packet;
624

625 626
    while (len > 0) {
        if (pkt_desc->size == pkt_desc->unwritten_size)
627
            nb_frames++;
628 629
        len     -= pkt_desc->unwritten_size;
        pkt_desc = pkt_desc->next;
630 631 632 633 634 635 636
    }

    return nb_frames;
}

/* flush the packet on stream stream_index */
static int flush_packet(AVFormatContext *ctx, int stream_index,
637
                        int64_t pts, int64_t dts, int64_t scr, int trailer_size)
638
{
639
    MpegMuxContext *s  = ctx->priv_data;
640 641 642 643 644 645 646 647
    StreamInfo *stream = ctx->streams[stream_index]->priv_data;
    uint8_t *buf_ptr;
    int size, payload_size, startcode, id, stuffing_size, i, header_len;
    int packet_size;
    uint8_t buffer[128];
    int zero_trail_bytes = 0;
    int pad_packet_bytes = 0;
    int pes_flags;
648 649
    /* "general" pack without data specific to one stream? */
    int general_pack = 0;
650 651 652 653
    int nb_frames;

    id = stream->id;

654
    av_log(ctx, AV_LOG_TRACE, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
655 656 657 658 659

    buf_ptr = buffer;

    if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
        /* output pack and systems header if needed */
660 661 662
        size        = put_pack_header(ctx, buf_ptr, scr);
        buf_ptr    += size;
        s->last_scr = scr;
663 664 665

        if (s->is_vcd) {
            /* there is exactly one system header for each stream in a VCD MPEG,
666 667
             * One in the very first video packet and one in the very first
             * audio packet (see VCD standard p. IV-7 and IV-8). */
668

669 670
            if (stream->packet_number == 0) {
                size     = put_system_header(ctx, buf_ptr, id);
671 672 673
                buf_ptr += size;
            }
        } else if (s->is_dvd) {
674
            if (stream->align_iframe || s->packet_number == 0) {
675 676 677 678 679 680 681 682 683 684
                int PES_bytes_to_fill = s->packet_size - size - 10;

                if (pts != AV_NOPTS_VALUE) {
                    if (dts != pts)
                        PES_bytes_to_fill -= 5 + 5;
                    else
                        PES_bytes_to_fill -= 5;
                }

                if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
685
                    size     = put_system_header(ctx, buf_ptr, 0);
686
                    buf_ptr += size;
687
                    size     = buf_ptr - buffer;
688
                    avio_write(ctx->pb, buffer, size);
689

690
                    avio_wb32(ctx->pb, PRIVATE_STREAM_2);
691 692
                    avio_wb16(ctx->pb, 0x03d4);     // length
                    avio_w8(ctx->pb, 0x00);         // substream ID, 00=PCI
693
                    for (i = 0; i < 979; i++)
694
                        avio_w8(ctx->pb, 0x00);
695

696
                    avio_wb32(ctx->pb, PRIVATE_STREAM_2);
697 698
                    avio_wb16(ctx->pb, 0x03fa);     // length
                    avio_w8(ctx->pb, 0x01);         // substream ID, 01=DSI
699
                    for (i = 0; i < 1017; i++)
700
                        avio_w8(ctx->pb, 0x00);
701 702 703 704 705

                    memset(buffer, 0, 128);
                    buf_ptr = buffer;
                    s->packet_number++;
                    stream->align_iframe = 0;
706 707 708 709 710 711
                    // FIXME: rounding and first few bytes of each packet
                    scr        += s->packet_size * 90000LL /
                                  (s->mux_rate * 50LL);
                    size        = put_pack_header(ctx, buf_ptr, scr);
                    s->last_scr = scr;
                    buf_ptr    += size;
712 713
                    /* GOP Start */
                } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
714 715
                    pad_packet_bytes = PES_bytes_to_fill -
                                       stream->bytes_to_iframe;
716 717 718 719
                }
            }
        } else {
            if ((s->packet_number % s->system_header_freq) == 0) {
720
                size     = put_system_header(ctx, buf_ptr, 0);
721 722 723 724 725
                buf_ptr += size;
            }
        }
    }
    size = buf_ptr - buffer;
726
    avio_write(ctx->pb, buffer, size);
727 728 729

    packet_size = s->packet_size - size;

730
    if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
731
        /* The VCD standard demands that 20 zero bytes follow
732
         * each audio pack (see standard p. IV-8). */
733 734
        zero_trail_bytes += 20;

735 736
    if ((s->is_vcd && stream->packet_number == 0) ||
        (s->is_svcd && s->packet_number == 0)) {
737
        /* for VCD the first pack of each stream contains only the pack header,
738 739 740
         * the system header and lots of padding (see VCD standard p. IV-6).
         * In the case of an audio pack, 20 zero bytes are also added at
         * the end. */
741
        /* For SVCD we fill the very first pack to increase compatibility with
742
         * some DVD players. Not mandated by the standard. */
743
        if (s->is_svcd)
744 745
            /* the system header refers to both streams and no stream data */
            general_pack = 1;
746 747 748 749 750 751 752 753 754 755 756 757
        pad_packet_bytes = packet_size - zero_trail_bytes;
    }

    packet_size -= pad_packet_bytes + zero_trail_bytes;

    if (packet_size > 0) {
        /* packet header size */
        packet_size -= 6;

        /* packet header */
        if (s->is_mpeg2) {
            header_len = 3;
758
            if (stream->packet_number == 0)
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
                header_len += 3; /* PES extension */
            header_len += 1; /* obligatory stuffing byte */
        } else {
            header_len = 0;
        }
        if (pts != AV_NOPTS_VALUE) {
            if (dts != pts)
                header_len += 5 + 5;
            else
                header_len += 5;
        } else {
            if (!s->is_mpeg2)
                header_len++;
        }

        payload_size = packet_size - header_len;
        if (id < 0xc0) {
776
            startcode     = PRIVATE_STREAM_1;
777 778 779 780 781 782 783 784 785 786
            payload_size -= 1;
            if (id >= 0x40) {
                payload_size -= 3;
                if (id >= 0xa0)
                    payload_size -= 3;
            }
        } else {
            startcode = 0x100 + id;
        }

787
        stuffing_size = payload_size - av_fifo_size(stream->fifo);
788 789

        // first byte does not fit -> reset pts/dts + stuffing
790 791 792
        if (payload_size <= trailer_size && pts != AV_NOPTS_VALUE) {
            int timestamp_len = 0;
            if (dts != pts)
793
                timestamp_len += 5;
794
            if (pts != AV_NOPTS_VALUE)
795
                timestamp_len += s->is_mpeg2 ? 5 : 4;
796 797
            pts         =
            dts         = AV_NOPTS_VALUE;
798 799 800
            header_len -= timestamp_len;
            if (s->is_dvd && stream->align_iframe) {
                pad_packet_bytes += timestamp_len;
801
                packet_size      -= timestamp_len;
802 803 804 805
            } else {
                payload_size += timestamp_len;
            }
            stuffing_size += timestamp_len;
806
            if (payload_size > trailer_size)
807 808 809
                stuffing_size += payload_size - trailer_size;
        }

810 811 812
        // can't use padding, so use stuffing
        if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) {
            packet_size  += pad_packet_bytes;
813
            payload_size += pad_packet_bytes; // undo the previous adjustment
814 815 816
            if (stuffing_size < 0)
                stuffing_size = pad_packet_bytes;
            else
817 818 819 820 821 822
                stuffing_size += pad_packet_bytes;
            pad_packet_bytes = 0;
        }

        if (stuffing_size < 0)
            stuffing_size = 0;
823 824 825 826 827 828

        if (startcode == PRIVATE_STREAM_1 && id >= 0xa0) {
            if (payload_size < av_fifo_size(stream->fifo))
                stuffing_size += payload_size % stream->lpcm_align;
        }

829
        if (stuffing_size > 16) {   /* <=16 for MPEG-1, <=32 for MPEG-2 */
830
            pad_packet_bytes += stuffing_size;
Michael Niedermayer's avatar
Michael Niedermayer committed
831 832
            packet_size      -= stuffing_size;
            payload_size     -= stuffing_size;
833
            stuffing_size     = 0;
834 835
        }

836
        nb_frames = get_nb_frames(ctx, stream, payload_size - stuffing_size);
837

838
        avio_wb32(ctx->pb, startcode);
839

840
        avio_wb16(ctx->pb, packet_size);
841 842

        if (!s->is_mpeg2)
843
            for (i = 0; i < stuffing_size; i++)
844
                avio_w8(ctx->pb, 0xff);
845 846

        if (s->is_mpeg2) {
847
            avio_w8(ctx->pb, 0x80); /* mpeg2 id */
848

849
            pes_flags = 0;
850 851 852 853 854 855 856 857

            if (pts != AV_NOPTS_VALUE) {
                pes_flags |= 0x80;
                if (dts != pts)
                    pes_flags |= 0x40;
            }

            /* Both the MPEG-2 and the SVCD standards demand that the
858 859 860
             * P-STD_buffer_size field be included in the first packet of
             * every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
             * and MPEG-2 standard 2.7.7) */
861 862 863
            if (stream->packet_number == 0)
                pes_flags |= 0x01;

864 865
            avio_w8(ctx->pb, pes_flags); /* flags */
            avio_w8(ctx->pb, header_len - 3 + stuffing_size);
866

867
            if (pes_flags & 0x80)  /* write pts */
868
                put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
869
            if (pes_flags & 0x40)  /* write dts */
870
                put_timestamp(ctx->pb, 0x01, dts);
871

872
            if (pes_flags & 0x01) {  /* write pes extension */
873
                avio_w8(ctx->pb, 0x10); /* flags */
874 875

                /* P-STD buffer info */
876
                if ((id & 0xe0) == AUDIO_ID)
877
                    avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size / 128);
878
                else
879
                    avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size / 1024);
880 881 882 883
            }
        } else {
            if (pts != AV_NOPTS_VALUE) {
                if (dts != pts) {
884 885
                    put_timestamp(ctx->pb, 0x03, pts);
                    put_timestamp(ctx->pb, 0x01, dts);
886
                } else {
887
                    put_timestamp(ctx->pb, 0x02, pts);
888 889
                }
            } else {
890
                avio_w8(ctx->pb, 0x0f);
891 892 893 894 895
            }
        }

        if (s->is_mpeg2) {
            /* special stuffing byte that is always written
896
             * to prevent accidental generation of start codes. */
897
            avio_w8(ctx->pb, 0xff);
898

899
            for (i = 0; i < stuffing_size; i++)
900
                avio_w8(ctx->pb, 0xff);
901 902 903
        }

        if (startcode == PRIVATE_STREAM_1) {
904
            avio_w8(ctx->pb, id);
905 906
            if (id >= 0xa0) {
                /* LPCM (XXX: check nb_frames) */
907 908 909 910 911
                avio_w8(ctx->pb, 7);
                avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
                avio_w8(ctx->pb, stream->lpcm_header[0]);
                avio_w8(ctx->pb, stream->lpcm_header[1]);
                avio_w8(ctx->pb, stream->lpcm_header[2]);
912
            } else if (id >= 0x40) {
913
                /* AC-3 */
914
                avio_w8(ctx->pb, nb_frames);
915
                avio_wb16(ctx->pb, trailer_size + 1);
916 917 918 919
            }
        }

        /* output data */
920
        av_assert0(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
921
        av_fifo_generic_read(stream->fifo, ctx->pb,
922 923
                             payload_size - stuffing_size,
                             (void (*)(void*, void*, int))avio_write);
924
        stream->bytes_to_iframe -= payload_size - stuffing_size;
925 926 927
    } else {
        payload_size  =
        stuffing_size = 0;
928 929 930
    }

    if (pad_packet_bytes > 0)
931
        put_padding_packet(ctx, ctx->pb, pad_packet_bytes);
932

933
    for (i = 0; i < zero_trail_bytes; i++)
934
        avio_w8(ctx->pb, 0x00);
935

936
    avio_flush(ctx->pb);
937 938 939 940

    s->packet_number++;

    /* only increase the stream packet number if this pack actually contains
941 942
     * something that is specific to this stream! I.e. a dedicated header
     * or some data. */
943 944 945 946 947 948 949 950 951
    if (!general_pack)
        stream->packet_number++;

    return payload_size - stuffing_size;
}

static void put_vcd_padding_sector(AVFormatContext *ctx)
{
    /* There are two ways to do this padding: writing a sector/pack
952 953 954 955
     * of 0 values, or writing an MPEG padding pack. Both seem to
     * work with most decoders, BUT the VCD standard only allows a 0-sector
     * (see standard p. IV-4, IV-5).
     * So a 0-sector it is... */
956 957 958 959

    MpegMuxContext *s = ctx->priv_data;
    int i;

960
    for (i = 0; i < s->packet_size; i++)
961
        avio_w8(ctx->pb, 0);
962 963 964

    s->vcd_padding_bytes_written += s->packet_size;

965
    avio_flush(ctx->pb);
966 967

    /* increasing the packet number is correct. The SCR of the following packs
968 969 970
     * is calculated from the packet_number and it has to include the padding
     * sector (it represents the sector index, not the MPEG pack index)
     * (see VCD standard p. IV-6) */
971 972 973
    s->packet_number++;
}

974 975
static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr)
{
976 977
    int i;

978
    for (i = 0; i < ctx->nb_streams; i++) {
979 980 981 982
        AVStream *st = ctx->streams[i];
        StreamInfo *stream = st->priv_data;
        PacketDesc *pkt_desc;

983 984 985 986
        while ((pkt_desc = stream->predecode_packet) &&
               scr > pkt_desc->dts) { // FIXME: > vs >=
            if (stream->buffer_index < pkt_desc->size ||
                stream->predecode_packet == stream->premux_packet) {
987
                av_log(ctx, AV_LOG_ERROR,
988
                       "buffer underflow st=%d bufi=%d size=%d\n",
989 990 991
                       i, stream->buffer_index, pkt_desc->size);
                break;
            }
992 993
            stream->buffer_index    -= pkt_desc->size;
            stream->predecode_packet = pkt_desc->next;
994 995 996 997 998 999 1000
            av_freep(&pkt_desc);
        }
    }

    return 0;
}

1001 1002
static int output_packet(AVFormatContext *ctx, int flush)
{
1003 1004 1005
    MpegMuxContext *s = ctx->priv_data;
    AVStream *st;
    StreamInfo *stream;
1006 1007 1008 1009
    int i, avail_space = 0, es_size, trailer_size;
    int best_i = -1;
    int best_score = INT_MIN;
    int ignore_constraints = 0;
1010
    int ignore_delay = 0;
1011
    int64_t scr = s->last_scr;
1012
    PacketDesc *timestamp_packet;
1013
    const int64_t max_delay = av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1014 1015

retry:
1016
    for (i = 0; i < ctx->nb_streams; i++) {
1017 1018
        AVStream *st = ctx->streams[i];
        StreamInfo *stream = st->priv_data;
1019 1020
        const int avail_data = av_fifo_size(stream->fifo);
        const int space = stream->max_buffer_size - stream->buffer_index;
1021
        int rel_space = 1024LL * space / stream->max_buffer_size;
1022
        PacketDesc *next_pkt = stream->premux_packet;
1023 1024

        /* for subtitle, a single PES packet must be generated,
1025 1026
         * so we flush after every single subtitle packet */
        if (s->packet_size > avail_data && !flush
1027
            && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
1028
            return 0;
1029
        if (avail_data == 0)
1030
            continue;
1031
        av_assert0(avail_data > 0);
1032

1033
        if (space < s->packet_size && !ignore_constraints)
1034 1035
            continue;

1036
        if (next_pkt && next_pkt->dts - scr > max_delay && !ignore_delay)
1037
            continue;
1038 1039 1040
        if (   stream->predecode_packet
            && stream->predecode_packet->size > stream->buffer_index)
            rel_space += 1<<28;
1041 1042 1043 1044
        if (rel_space > best_score) {
            best_score  = rel_space;
            best_i      = i;
            avail_space = space;
1045 1046 1047
        }
    }

1048 1049
    if (best_i < 0) {
        int64_t best_dts = INT64_MAX;
1050
        int has_premux = 0;
1051

1052
        for (i = 0; i < ctx->nb_streams; i++) {
1053 1054
            AVStream *st = ctx->streams[i];
            StreamInfo *stream = st->priv_data;
1055 1056 1057
            PacketDesc *pkt_desc = stream->predecode_packet;
            if (pkt_desc && pkt_desc->dts < best_dts)
                best_dts = pkt_desc->dts;
1058
            has_premux |= !!stream->premux_packet;
1059 1060
        }

1061
        if (best_dts < INT64_MAX) {
1062
            av_log(ctx, AV_LOG_TRACE, "bumping scr, scr:%f, dts:%f\n",
1063
                    scr / 90000.0, best_dts / 90000.0);
1064

1065 1066 1067 1068 1069 1070 1071 1072 1073
            if (scr >= best_dts + 1 && !ignore_constraints) {
                av_log(ctx, AV_LOG_ERROR,
                    "packet too large, ignoring buffer limits to mux it\n");
                ignore_constraints = 1;
            }
            scr = FFMAX(best_dts + 1, scr);
            if (remove_decoded_packets(ctx, scr) < 0)
                return -1;
        } else if (has_premux && flush) {
1074
            av_log(ctx, AV_LOG_ERROR,
1075 1076
                  "delay too large, ignoring ...\n");
            ignore_delay = 1;
1077
            ignore_constraints = 1;
1078 1079 1080
        } else
            return 0;

1081 1082 1083
        goto retry;
    }

1084
    av_assert0(best_i >= 0);
1085

1086
    st     = ctx->streams[best_i];
1087 1088
    stream = st->priv_data;

1089
    av_assert0(av_fifo_size(stream->fifo) > 0);
1090

1091
    av_assert0(avail_space >= s->packet_size || ignore_constraints);
1092

1093 1094 1095 1096 1097 1098
    timestamp_packet = stream->premux_packet;
    if (timestamp_packet->unwritten_size == timestamp_packet->size) {
        trailer_size = 0;
    } else {
        trailer_size     = timestamp_packet->unwritten_size;
        timestamp_packet = timestamp_packet->next;
1099 1100
    }

1101
    if (timestamp_packet) {
1102
        av_log(ctx, AV_LOG_TRACE, "dts:%f pts:%f scr:%f stream:%d\n",
1103 1104 1105
                timestamp_packet->dts / 90000.0,
                timestamp_packet->pts / 90000.0,
                scr / 90000.0, best_i);
1106 1107 1108
        es_size = flush_packet(ctx, best_i, timestamp_packet->pts,
                               timestamp_packet->dts, scr, trailer_size);
    } else {
1109
        av_assert0(av_fifo_size(stream->fifo) == trailer_size);
1110 1111
        es_size = flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr,
                               trailer_size);
1112 1113 1114 1115
    }

    if (s->is_vcd) {
        /* Write one or more padding sectors, if necessary, to reach
1116
         * the constant overall bitrate. */
1117 1118
        int vcd_pad_bytes;

1119 1120
        // FIXME: pts cannot be correct here
        while ((vcd_pad_bytes = get_vcd_padding_size(ctx, stream->premux_packet->pts)) >= s->packet_size) {
1121
            put_vcd_padding_sector(ctx);
1122 1123
            // FIXME: rounding and first few bytes of each packet
            s->last_scr += s->packet_size * 90000LL / (s->mux_rate * 50LL);
1124 1125 1126 1127
        }
    }

    stream->buffer_index += es_size;
1128 1129
    // FIXME: rounding and first few bytes of each packet
    s->last_scr          += s->packet_size * 90000LL / (s->mux_rate * 50LL);
1130

1131 1132 1133 1134
    while (stream->premux_packet &&
           stream->premux_packet->unwritten_size <= es_size) {
        es_size              -= stream->premux_packet->unwritten_size;
        stream->premux_packet = stream->premux_packet->next;
1135
    }
1136 1137
    if (es_size) {
        av_assert0(stream->premux_packet);
1138
        stream->premux_packet->unwritten_size -= es_size;
1139
    }
1140

1141
    if (remove_decoded_packets(ctx, s->last_scr) < 0)
1142 1143 1144 1145 1146 1147 1148
        return -1;

    return 1;
}

static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
{
1149 1150 1151
    int stream_index = pkt->stream_index;
    int size         = pkt->size;
    uint8_t *buf     = pkt->data;
1152
    MpegMuxContext *s = ctx->priv_data;
1153
    AVStream *st      = ctx->streams[stream_index];
1154 1155 1156
    StreamInfo *stream = st->priv_data;
    int64_t pts, dts;
    PacketDesc *pkt_desc;
1157
    int preload;
1158
    const int is_iframe = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1159
                          (pkt->flags & AV_PKT_FLAG_KEY);
1160

1161 1162
    preload = av_rescale(s->preload, 90000, AV_TIME_BASE);

1163 1164
    pts = pkt->pts;
    dts = pkt->dts;
1165

1166
    if (s->last_scr == AV_NOPTS_VALUE) {
1167
        if (dts == AV_NOPTS_VALUE || (dts < preload && ctx->avoid_negative_ts) || s->is_dvd) {
1168 1169
            if (dts != AV_NOPTS_VALUE)
                s->preload += av_rescale(-dts, AV_TIME_BASE, 90000);
1170 1171
            s->last_scr = 0;
        } else {
1172 1173
            s->last_scr = dts - preload;
            s->preload = 0;
1174
        }
1175
        preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1176
        av_log(ctx, AV_LOG_DEBUG, "First SCR: %"PRId64" First DTS: %"PRId64"\n", s->last_scr, dts + preload);
1177
    }
1178 1179 1180

    if (dts != AV_NOPTS_VALUE) dts += preload;
    if (pts != AV_NOPTS_VALUE) pts += preload;
1181

1182
    av_log(ctx, AV_LOG_TRACE, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n",
1183 1184
            dts / 90000.0, pts / 90000.0, pkt->flags,
            pkt->stream_index, pts != AV_NOPTS_VALUE);
1185 1186
    if (!stream->premux_packet)
        stream->next_packet = &stream->premux_packet;
1187 1188
    *stream->next_packet     =
    pkt_desc                 = av_mallocz(sizeof(PacketDesc));
1189 1190
    if (!pkt_desc)
        return AVERROR(ENOMEM);
1191 1192
    pkt_desc->pts            = pts;
    pkt_desc->dts            = dts;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

    if (st->codecpar->codec_id == AV_CODEC_ID_PCM_DVD) {
        if (size < 3) {
            av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n", size);
            return AVERROR(EINVAL);
        }

        /* Skip first 3 bytes of packet data, which comprise PCM header
           and will be written fresh by this muxer. */
        buf += 3;
        size -= 3;
    }

1206 1207 1208 1209 1210
    pkt_desc->unwritten_size =
    pkt_desc->size           = size;
    if (!stream->predecode_packet)
        stream->predecode_packet = pkt_desc;
    stream->next_packet = &pkt_desc->next;
1211

1212
    if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1213
        return -1;
1214

1215 1216 1217 1218 1219
    if (s->is_dvd) {
        // min VOBU length 0.4 seconds (mpucoder)
        if (is_iframe &&
            (s->packet_number == 0 ||
             (pts - stream->vobu_start_pts >= 36000))) {
1220
            stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1221 1222
            stream->align_iframe    = 1;
            stream->vobu_start_pts  = pts;
1223 1224 1225
        }
    }

1226
    av_fifo_generic_write(stream->fifo, buf, size, NULL);
1227

1228 1229 1230
    for (;;) {
        int ret = output_packet(ctx, 0);
        if (ret <= 0)
1231 1232 1233 1234 1235 1236 1237 1238 1239
            return ret;
    }
}

static int mpeg_mux_end(AVFormatContext *ctx)
{
    StreamInfo *stream;
    int i;

1240 1241 1242
    for (;;) {
        int ret = output_packet(ctx, 1);
        if (ret < 0)
1243
            return ret;
1244
        else if (ret == 0)
1245 1246 1247
            break;
    }

1248
    /* End header according to MPEG-1 systems standard. We do not write
1249 1250 1251 1252
     * it as it is usually not needed by decoders and because it
     * complicates MPEG stream concatenation. */
    // avio_wb32(ctx->pb, ISO_11172_END_CODE);
    // avio_flush(ctx->pb);
1253

1254
    for (i = 0; i < ctx->nb_streams; i++) {
1255 1256
        stream = ctx->streams[i]->priv_data;

1257
        av_assert0(av_fifo_size(stream->fifo) == 0);
Lukasz Marek's avatar
Lukasz Marek committed
1258
        av_fifo_freep(&stream->fifo);
1259 1260 1261 1262
    }
    return 0;
}

1263 1264 1265
#define OFFSET(x) offsetof(MpegMuxContext, x)
#define E AV_OPT_FLAG_ENCODING_PARAM
static const AVOption options[] = {
1266
    { "muxrate", NULL,                                          OFFSET(user_mux_rate), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, ((1<<22) - 1) * (8 * 50), E },
1267
    { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload),  AV_OPT_TYPE_INT, { .i64 = 500000 }, 0, INT_MAX, E },
1268 1269 1270
    { NULL },
};

1271 1272 1273 1274 1275 1276
#define MPEGENC_CLASS(flavor)                   \
static const AVClass flavor ## _class = {       \
    .class_name = #flavor " muxer",             \
    .item_name  = av_default_item_name,         \
    .version    = LIBAVUTIL_VERSION_INT,        \
    .option     = options,                      \
1277 1278
};

1279
#if CONFIG_MPEG1SYSTEM_MUXER
1280
MPEGENC_CLASS(mpeg)
1281
AVOutputFormat ff_mpeg1system_muxer = {
1282
    .name              = "mpeg",
1283
    .long_name         = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream"),
1284 1285 1286
    .mime_type         = "video/mpeg",
    .extensions        = "mpg,mpeg",
    .priv_data_size    = sizeof(MpegMuxContext),
1287 1288
    .audio_codec       = AV_CODEC_ID_MP2,
    .video_codec       = AV_CODEC_ID_MPEG1VIDEO,
1289 1290 1291
    .write_header      = mpeg_mux_init,
    .write_packet      = mpeg_mux_write_packet,
    .write_trailer     = mpeg_mux_end,
1292
    .priv_class        = &mpeg_class,
1293 1294
};
#endif
1295

1296
#if CONFIG_MPEG1VCD_MUXER
1297
MPEGENC_CLASS(vcd)
1298
AVOutputFormat ff_mpeg1vcd_muxer = {
1299
    .name              = "vcd",
1300
    .long_name         = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream (VCD)"),
1301 1302
    .mime_type         = "video/mpeg",
    .priv_data_size    = sizeof(MpegMuxContext),
1303 1304
    .audio_codec       = AV_CODEC_ID_MP2,
    .video_codec       = AV_CODEC_ID_MPEG1VIDEO,
1305 1306 1307
    .write_header      = mpeg_mux_init,
    .write_packet      = mpeg_mux_write_packet,
    .write_trailer     = mpeg_mux_end,
1308
    .priv_class        = &vcd_class,
1309 1310
};
#endif
1311

1312
#if CONFIG_MPEG2VOB_MUXER
1313
MPEGENC_CLASS(vob)
1314
AVOutputFormat ff_mpeg2vob_muxer = {
1315
    .name              = "vob",
1316
    .long_name         = NULL_IF_CONFIG_SMALL("MPEG-2 PS (VOB)"),
1317 1318 1319
    .mime_type         = "video/mpeg",
    .extensions        = "vob",
    .priv_data_size    = sizeof(MpegMuxContext),
1320 1321
    .audio_codec       = AV_CODEC_ID_MP2,
    .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
1322 1323 1324
    .write_header      = mpeg_mux_init,
    .write_packet      = mpeg_mux_write_packet,
    .write_trailer     = mpeg_mux_end,
1325
    .priv_class        = &vob_class,
1326 1327 1328 1329
};
#endif

/* Same as mpeg2vob_mux except that the pack size is 2324 */
1330
#if CONFIG_MPEG2SVCD_MUXER
1331
MPEGENC_CLASS(svcd)
1332
AVOutputFormat ff_mpeg2svcd_muxer = {
1333
    .name              = "svcd",
1334
    .long_name         = NULL_IF_CONFIG_SMALL("MPEG-2 PS (SVCD)"),
1335 1336 1337
    .mime_type         = "video/mpeg",
    .extensions        = "vob",
    .priv_data_size    = sizeof(MpegMuxContext),
1338 1339
    .audio_codec       = AV_CODEC_ID_MP2,
    .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
1340 1341 1342
    .write_header      = mpeg_mux_init,
    .write_packet      = mpeg_mux_write_packet,
    .write_trailer     = mpeg_mux_end,
1343
    .priv_class        = &svcd_class,
1344 1345 1346 1347
};
#endif

/*  Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1348
#if CONFIG_MPEG2DVD_MUXER
1349
MPEGENC_CLASS(dvd)
1350
AVOutputFormat ff_mpeg2dvd_muxer = {
1351
    .name              = "dvd",
1352
    .long_name         = NULL_IF_CONFIG_SMALL("MPEG-2 PS (DVD VOB)"),
1353 1354 1355
    .mime_type         = "video/mpeg",
    .extensions        = "dvd",
    .priv_data_size    = sizeof(MpegMuxContext),
1356 1357
    .audio_codec       = AV_CODEC_ID_MP2,
    .video_codec       = AV_CODEC_ID_MPEG2VIDEO,
1358 1359 1360
    .write_header      = mpeg_mux_init,
    .write_packet      = mpeg_mux_write_packet,
    .write_trailer     = mpeg_mux_end,
1361
    .priv_class        = &dvd_class,
1362 1363
};
#endif