3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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.
12 * Libav 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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"
30 #include "libavcodec/put_bits.h"
36 #define MAX_PAYLOAD_SIZE 4096
41 typedef struct PacketDesc {
46 struct PacketDesc *next;
49 typedef struct StreamInfo {
52 int max_buffer_size; /* in bytes */
54 PacketDesc *predecode_packet;
55 PacketDesc *premux_packet;
56 PacketDesc **next_packet;
58 uint8_t lpcm_header[3];
62 int64_t vobu_start_pts;
65 typedef struct MpegMuxContext {
67 int packet_size; /* required packet size */
69 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
70 int system_header_freq;
71 int system_header_size;
72 int mux_rate; /* bitrate in units of 50 bytes/s */
80 int64_t last_scr; /* current system clock */
82 double vcd_padding_bitrate; // FIXME floats
83 int64_t vcd_padding_bytes_written;
88 extern AVOutputFormat ff_mpeg1vcd_muxer;
89 extern AVOutputFormat ff_mpeg2dvd_muxer;
90 extern AVOutputFormat ff_mpeg2svcd_muxer;
91 extern AVOutputFormat ff_mpeg2vob_muxer;
93 static int put_pack_header(AVFormatContext *ctx, uint8_t *buf,
96 MpegMuxContext *s = ctx->priv_data;
99 init_put_bits(&pb, buf, 128);
101 put_bits32(&pb, PACK_START_CODE);
103 put_bits(&pb, 2, 0x1);
105 put_bits(&pb, 4, 0x2);
106 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
108 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
110 put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
113 /* clock extension */
116 put_bits(&pb, 22, s->mux_rate);
120 put_bits(&pb, 5, 0x1f); /* reserved */
121 put_bits(&pb, 3, 0); /* stuffing length */
124 return put_bits_ptr(&pb) - pb.buf;
127 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,
128 int only_for_stream_id)
130 MpegMuxContext *s = ctx->priv_data;
131 int size, i, private_stream_coded, id;
134 init_put_bits(&pb, buf, 128);
136 put_bits32(&pb, SYSTEM_HEADER_START_CODE);
137 put_bits(&pb, 16, 0);
140 /* maximum bit rate of the multiplexed stream */
141 put_bits(&pb, 22, s->mux_rate);
142 put_bits(&pb, 1, 1); /* marker */
143 if (s->is_vcd && only_for_stream_id == VIDEO_ID) {
144 /* This header applies only to the video stream
145 * (see VCD standard p. IV-7) */
148 put_bits(&pb, 6, s->audio_bound);
151 /* see VCD standard, p. IV-7 */
155 put_bits(&pb, 1, 0); /* variable bitrate */
156 put_bits(&pb, 1, 0); /* non constrainted bit stream */
159 if (s->is_vcd || s->is_dvd) {
160 /* see VCD standard p IV-7 */
161 put_bits(&pb, 1, 1); /* audio locked */
162 put_bits(&pb, 1, 1); /* video locked */
164 put_bits(&pb, 1, 0); /* audio locked */
165 put_bits(&pb, 1, 0); /* video locked */
168 put_bits(&pb, 1, 1); /* marker */
170 if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
171 /* This header applies only to the audio stream
172 * (see VCD standard p. IV-7) */
175 put_bits(&pb, 5, s->video_bound);
178 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
179 put_bits(&pb, 7, 0x7f); /* reserved byte */
181 put_bits(&pb, 8, 0xff); /* reserved byte */
183 /* DVD-Video Stream_bound entries
184 * id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
185 * 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)
186 * id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
187 * id (0xBF) private stream 2, NAV packs, set to 2x1024. */
190 int P_STD_max_video = 0;
191 int P_STD_max_mpeg_audio = 0;
192 int P_STD_max_mpeg_PS1 = 0;
194 for (i = 0; i < ctx->nb_streams; i++) {
195 StreamInfo *stream = ctx->streams[i]->priv_data;
198 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
199 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
200 } else if (id >= 0xc0 && id <= 0xc7 &&
201 stream->max_buffer_size > P_STD_max_mpeg_audio) {
202 P_STD_max_mpeg_audio = stream->max_buffer_size;
203 } else if (id == 0xe0 &&
204 stream->max_buffer_size > P_STD_max_video) {
205 P_STD_max_video = stream->max_buffer_size;
210 put_bits(&pb, 8, 0xb9); /* stream ID */
213 put_bits(&pb, 13, P_STD_max_video / 1024);
216 if (P_STD_max_mpeg_audio == 0)
217 P_STD_max_mpeg_audio = 4096;
218 put_bits(&pb, 8, 0xb8); /* stream ID */
221 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
223 /* private stream 1 */
224 put_bits(&pb, 8, 0xbd); /* stream ID */
227 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
229 /* private stream 2 */
230 put_bits(&pb, 8, 0xbf); /* stream ID */
233 put_bits(&pb, 13, 2);
235 /* audio stream info */
236 private_stream_coded = 0;
237 for (i = 0; i < ctx->nb_streams; i++) {
238 StreamInfo *stream = ctx->streams[i]->priv_data;
240 /* For VCDs, only include the stream info for the stream
241 * that the pack which contains this system belongs to.
242 * (see VCD standard p. IV-7) */
243 if (!s->is_vcd || stream->id == only_for_stream_id ||
244 only_for_stream_id == 0) {
247 /* special case for private streams (AC-3 uses that) */
248 if (private_stream_coded)
250 private_stream_coded = 1;
253 put_bits(&pb, 8, id); /* stream ID */
258 put_bits(&pb, 13, stream->max_buffer_size / 128);
262 put_bits(&pb, 13, stream->max_buffer_size / 1024);
269 size = put_bits_ptr(&pb) - pb.buf;
270 /* patch packet size */
271 buf[4] = (size - 6) >> 8;
272 buf[5] = (size - 6) & 0xff;
277 static int get_system_header_size(AVFormatContext *ctx)
279 int buf_index, i, private_stream_coded;
281 MpegMuxContext *s = ctx->priv_data;
284 return 18; // DVD-Video system headers are 18 bytes fixed length.
287 private_stream_coded = 0;
288 for (i = 0; i < ctx->nb_streams; i++) {
289 stream = ctx->streams[i]->priv_data;
290 if (stream->id < 0xc0) {
291 if (private_stream_coded)
293 private_stream_coded = 1;
300 static av_cold int mpeg_mux_init(AVFormatContext *ctx)
302 MpegMuxContext *s = ctx->priv_data;
303 int bitrate, i, mpa_id, mpv_id, h264_id, mps_id, ac3_id, dts_id, lpcm_id, j;
309 s->packet_number = 0;
310 s->is_vcd = (CONFIG_MPEG1VCD_MUXER && ctx->oformat == &ff_mpeg1vcd_muxer);
311 s->is_svcd = (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
312 s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER && ctx->oformat == &ff_mpeg2vob_muxer) ||
313 (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer) ||
314 (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
315 s->is_dvd = (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer);
317 if (ctx->packet_size) {
318 if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
319 av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
323 s->packet_size = ctx->packet_size;
325 s->packet_size = 2048;
326 if (ctx->max_delay < 0) /* Not set by the caller */
329 s->vcd_padding_bytes_written = 0;
330 s->vcd_padding_bitrate = 0;
343 for (i = 0; i < ctx->nb_streams; i++) {
344 AVCPBProperties *props;
346 st = ctx->streams[i];
347 stream = av_mallocz(sizeof(StreamInfo));
350 st->priv_data = stream;
352 avpriv_set_pts_info(st, 64, 1, 90000);
354 switch (st->codec->codec_type) {
355 case AVMEDIA_TYPE_AUDIO:
356 if (st->codec->codec_id == AV_CODEC_ID_AC3) {
357 stream->id = ac3_id++;
358 } else if (st->codec->codec_id == AV_CODEC_ID_DTS) {
359 stream->id = dts_id++;
360 } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {
361 stream->id = lpcm_id++;
362 for (j = 0; j < 4; j++) {
363 if (lpcm_freq_tab[j] == st->codec->sample_rate)
368 if (st->codec->channels > 8)
370 stream->lpcm_header[0] = 0x0c;
371 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
372 stream->lpcm_header[2] = 0x80;
373 stream->lpcm_align = st->codec->channels * 2;
375 stream->id = mpa_id++;
378 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
379 * Right now it is also used for everything else. */
380 stream->max_buffer_size = 4 * 1024;
383 case AVMEDIA_TYPE_VIDEO:
384 if (st->codec->codec_id == AV_CODEC_ID_H264)
385 stream->id = h264_id++;
387 stream->id = mpv_id++;
389 props = (AVCPBProperties*)av_stream_get_side_data(st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
390 if (props && props->buffer_size)
391 stream->max_buffer_size = 6 * 1024 + props->buffer_size / 8;
393 av_log(ctx, AV_LOG_WARNING,
394 "VBV buffer size not set, muxing may fail\n");
395 // FIXME: this is probably too small as default
396 stream->max_buffer_size = 230 * 1024;
400 case AVMEDIA_TYPE_SUBTITLE:
401 stream->id = mps_id++;
402 stream->max_buffer_size = 16 * 1024;
407 stream->fifo = av_fifo_alloc(16);
414 for (i = 0; i < ctx->nb_streams; i++) {
415 AVCPBProperties *props;
417 st = ctx->streams[i];
418 stream = (StreamInfo *)st->priv_data;
420 props = (AVCPBProperties*)av_stream_get_side_data(st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
422 codec_rate = props->max_bitrate;
424 codec_rate = st->codec->bit_rate;
427 codec_rate = (1 << 21) * 8 * 50 / ctx->nb_streams;
429 bitrate += codec_rate;
431 if ((stream->id & 0xe0) == AUDIO_ID)
432 audio_bitrate += codec_rate;
433 else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
434 video_bitrate += codec_rate;
438 /* we increase slightly the bitrate to take into account the
439 * headers. XXX: compute it exactly */
440 bitrate += bitrate / 20;
442 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
446 double overhead_rate;
448 /* The VCD standard mandates that the mux_rate field is 3528
449 * (see standard p. IV-6).
450 * The value is actually "wrong", i.e. if you calculate
451 * it using the normal formula and the 75 sectors per second transfer
452 * rate you get a different value because the real pack size is 2324,
453 * not 2352. But the standard explicitly specifies that the mux_rate
454 * field in the header must have this value. */
455 // s->mux_rate = 2352 * 75 / 50; /* = 3528 */
457 /* The VCD standard states that the muxed stream must be
458 * exactly 75 packs / second (the data rate of a single speed cdrom).
459 * Since the video bitrate (probably 1150000 bits/sec) will be below
460 * the theoretical maximum we have to add some padding packets
461 * to make up for the lower data rate.
462 * (cf. VCD standard p. IV-6 ) */
464 /* Add the header overhead to the data rate.
465 * 2279 data bytes per audio pack, 2294 data bytes per video pack */
466 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
467 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
470 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
471 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
474 if (s->is_vcd || s->is_mpeg2)
476 s->pack_header_freq = 1;
478 /* every 2 seconds */
479 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
481 /* the above seems to make pack_header_freq zero sometimes */
482 if (s->pack_header_freq == 0)
483 s->pack_header_freq = 1;
486 /* every 200 packets. Need to look at the spec. */
487 s->system_header_freq = s->pack_header_freq * 40;
489 /* the standard mandates that there are only two system headers
490 * in the whole file: one in the first packet of each stream.
491 * (see standard p. IV-7 and IV-8) */
492 s->system_header_freq = 0x7fffffff;
494 s->system_header_freq = s->pack_header_freq * 5;
496 for (i = 0; i < ctx->nb_streams; i++) {
497 stream = ctx->streams[i]->priv_data;
498 stream->packet_number = 0;
500 s->system_header_size = get_system_header_size(ctx);
505 for (i = 0; i < ctx->nb_streams; i++)
506 av_free(ctx->streams[i]->priv_data);
507 return AVERROR(ENOMEM);
510 static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
512 avio_w8(pb, (id << 4) | (((timestamp >> 30) & 0x07) << 1) | 1);
513 avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
514 avio_wb16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
517 /* return the number of padding bytes that should be inserted into
518 * the multiplexed stream. */
519 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
521 MpegMuxContext *s = ctx->priv_data;
524 if (s->vcd_padding_bitrate > 0 && pts != AV_NOPTS_VALUE) {
525 int64_t full_pad_bytes;
527 // FIXME: this is wrong
529 (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0);
530 pad_bytes = (int)(full_pad_bytes - s->vcd_padding_bytes_written);
533 /* might happen if we have already padded to a later timestamp. This
534 * can occur if another stream has already advanced further. */
541 /* Write an MPEG padding packet header. */
542 static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,
545 MpegMuxContext *s = ctx->priv_data;
548 avio_wb32(pb, PADDING_STREAM);
549 avio_wb16(pb, packet_bytes - 6);
556 for (i = 0; i < packet_bytes; i++)
560 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len)
563 PacketDesc *pkt_desc = stream->premux_packet;
566 if (pkt_desc->size == pkt_desc->unwritten_size)
568 len -= pkt_desc->unwritten_size;
569 pkt_desc = pkt_desc->next;
575 /* flush the packet on stream stream_index */
576 static int flush_packet(AVFormatContext *ctx, int stream_index,
577 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
579 MpegMuxContext *s = ctx->priv_data;
580 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
582 int size, payload_size, startcode, id, stuffing_size, i, header_len;
585 int zero_trail_bytes = 0;
586 int pad_packet_bytes = 0;
588 /* "general" pack without data specific to one stream? */
589 int general_pack = 0;
594 av_log(ctx, AV_LOG_TRACE, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
598 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
599 /* output pack and systems header if needed */
600 size = put_pack_header(ctx, buf_ptr, scr);
605 /* there is exactly one system header for each stream in a VCD MPEG,
606 * One in the very first video packet and one in the very first
607 * audio packet (see VCD standard p. IV-7 and IV-8). */
609 if (stream->packet_number == 0) {
610 size = put_system_header(ctx, buf_ptr, id);
613 } else if (s->is_dvd) {
614 if (stream->align_iframe || s->packet_number == 0) {
615 int PES_bytes_to_fill = s->packet_size - size - 10;
617 if (pts != AV_NOPTS_VALUE) {
619 PES_bytes_to_fill -= 5 + 5;
621 PES_bytes_to_fill -= 5;
624 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
625 size = put_system_header(ctx, buf_ptr, 0);
627 size = buf_ptr - buffer;
628 avio_write(ctx->pb, buffer, size);
630 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
631 avio_wb16(ctx->pb, 0x03d4); // length
632 avio_w8(ctx->pb, 0x00); // substream ID, 00=PCI
633 for (i = 0; i < 979; i++)
634 avio_w8(ctx->pb, 0x00);
636 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
637 avio_wb16(ctx->pb, 0x03fa); // length
638 avio_w8(ctx->pb, 0x01); // substream ID, 01=DSI
639 for (i = 0; i < 1017; i++)
640 avio_w8(ctx->pb, 0x00);
642 memset(buffer, 0, 128);
645 stream->align_iframe = 0;
646 // FIXME: rounding and first few bytes of each packet
647 scr += s->packet_size * 90000LL /
648 (s->mux_rate * 50LL);
649 size = put_pack_header(ctx, buf_ptr, scr);
653 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
654 pad_packet_bytes = PES_bytes_to_fill -
655 stream->bytes_to_iframe;
659 if ((s->packet_number % s->system_header_freq) == 0) {
660 size = put_system_header(ctx, buf_ptr, 0);
665 size = buf_ptr - buffer;
666 avio_write(ctx->pb, buffer, size);
668 packet_size = s->packet_size - size;
670 if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
671 /* The VCD standard demands that 20 zero bytes follow
672 * each audio pack (see standard p. IV-8). */
673 zero_trail_bytes += 20;
675 if ((s->is_vcd && stream->packet_number == 0) ||
676 (s->is_svcd && s->packet_number == 0)) {
677 /* for VCD the first pack of each stream contains only the pack header,
678 * the system header and lots of padding (see VCD standard p. IV-6).
679 * In the case of an audio pack, 20 zero bytes are also added at
681 /* For SVCD we fill the very first pack to increase compatibility with
682 * some DVD players. Not mandated by the standard. */
684 /* the system header refers to both streams and no stream data */
686 pad_packet_bytes = packet_size - zero_trail_bytes;
689 packet_size -= pad_packet_bytes + zero_trail_bytes;
691 if (packet_size > 0) {
692 /* packet header size */
698 if (stream->packet_number == 0)
699 header_len += 3; /* PES extension */
700 header_len += 1; /* obligatory stuffing byte */
704 if (pts != AV_NOPTS_VALUE) {
714 payload_size = packet_size - header_len;
716 startcode = PRIVATE_STREAM_1;
724 startcode = 0x100 + id;
727 stuffing_size = payload_size - av_fifo_size(stream->fifo);
729 // first byte does not fit -> reset pts/dts + stuffing
730 if (payload_size <= trailer_size && pts != AV_NOPTS_VALUE) {
731 int timestamp_len = 0;
734 if (pts != AV_NOPTS_VALUE)
735 timestamp_len += s->is_mpeg2 ? 5 : 4;
737 dts = AV_NOPTS_VALUE;
738 header_len -= timestamp_len;
739 if (s->is_dvd && stream->align_iframe) {
740 pad_packet_bytes += timestamp_len;
741 packet_size -= timestamp_len;
743 payload_size += timestamp_len;
745 stuffing_size += timestamp_len;
746 if (payload_size > trailer_size)
747 stuffing_size += payload_size - trailer_size;
750 // can't use padding, so use stuffing
751 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) {
752 packet_size += pad_packet_bytes;
753 payload_size += pad_packet_bytes; // undo the previous adjustment
754 if (stuffing_size < 0)
755 stuffing_size = pad_packet_bytes;
757 stuffing_size += pad_packet_bytes;
758 pad_packet_bytes = 0;
761 if (stuffing_size < 0)
764 if (startcode == PRIVATE_STREAM_1 && id >= 0xa0) {
765 if (payload_size < av_fifo_size(stream->fifo))
766 stuffing_size += payload_size % stream->lpcm_align;
769 if (stuffing_size > 16) { /* <=16 for MPEG-1, <=32 for MPEG-2 */
770 pad_packet_bytes += stuffing_size;
771 packet_size -= stuffing_size;
772 payload_size -= stuffing_size;
776 nb_frames = get_nb_frames(ctx, stream, payload_size - stuffing_size);
778 avio_wb32(ctx->pb, startcode);
780 avio_wb16(ctx->pb, packet_size);
783 for (i = 0; i < stuffing_size; i++)
784 avio_w8(ctx->pb, 0xff);
787 avio_w8(ctx->pb, 0x80); /* mpeg2 id */
791 if (pts != AV_NOPTS_VALUE) {
797 /* Both the MPEG-2 and the SVCD standards demand that the
798 * P-STD_buffer_size field be included in the first packet of
799 * every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
800 * and MPEG-2 standard 2.7.7) */
801 if (stream->packet_number == 0)
804 avio_w8(ctx->pb, pes_flags); /* flags */
805 avio_w8(ctx->pb, header_len - 3 + stuffing_size);
807 if (pes_flags & 0x80) /* write pts */
808 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
809 if (pes_flags & 0x40) /* write dts */
810 put_timestamp(ctx->pb, 0x01, dts);
812 if (pes_flags & 0x01) { /* write pes extension */
813 avio_w8(ctx->pb, 0x10); /* flags */
815 /* P-STD buffer info */
816 if ((id & 0xe0) == AUDIO_ID)
817 avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size / 128);
819 avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size / 1024);
822 if (pts != AV_NOPTS_VALUE) {
824 put_timestamp(ctx->pb, 0x03, pts);
825 put_timestamp(ctx->pb, 0x01, dts);
827 put_timestamp(ctx->pb, 0x02, pts);
830 avio_w8(ctx->pb, 0x0f);
835 /* special stuffing byte that is always written
836 * to prevent accidental generation of start codes. */
837 avio_w8(ctx->pb, 0xff);
839 for (i = 0; i < stuffing_size; i++)
840 avio_w8(ctx->pb, 0xff);
843 if (startcode == PRIVATE_STREAM_1) {
844 avio_w8(ctx->pb, id);
846 /* LPCM (XXX: check nb_frames) */
848 avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
849 avio_w8(ctx->pb, stream->lpcm_header[0]);
850 avio_w8(ctx->pb, stream->lpcm_header[1]);
851 avio_w8(ctx->pb, stream->lpcm_header[2]);
852 } else if (id >= 0x40) {
854 avio_w8(ctx->pb, nb_frames);
855 avio_wb16(ctx->pb, trailer_size + 1);
860 assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
861 av_fifo_generic_read(stream->fifo, ctx->pb,
862 payload_size - stuffing_size,
863 (void (*)(void*, void*, int))avio_write);
864 stream->bytes_to_iframe -= payload_size - stuffing_size;
870 if (pad_packet_bytes > 0)
871 put_padding_packet(ctx, ctx->pb, pad_packet_bytes);
873 for (i = 0; i < zero_trail_bytes; i++)
874 avio_w8(ctx->pb, 0x00);
880 /* only increase the stream packet number if this pack actually contains
881 * something that is specific to this stream! I.e. a dedicated header
884 stream->packet_number++;
886 return payload_size - stuffing_size;
889 static void put_vcd_padding_sector(AVFormatContext *ctx)
891 /* There are two ways to do this padding: writing a sector/pack
892 * of 0 values, or writing an MPEG padding pack. Both seem to
893 * work with most decoders, BUT the VCD standard only allows a 0-sector
894 * (see standard p. IV-4, IV-5).
895 * So a 0-sector it is... */
897 MpegMuxContext *s = ctx->priv_data;
900 for (i = 0; i < s->packet_size; i++)
903 s->vcd_padding_bytes_written += s->packet_size;
907 /* increasing the packet number is correct. The SCR of the following packs
908 * is calculated from the packet_number and it has to include the padding
909 * sector (it represents the sector index, not the MPEG pack index)
910 * (see VCD standard p. IV-6) */
914 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr)
918 for (i = 0; i < ctx->nb_streams; i++) {
919 AVStream *st = ctx->streams[i];
920 StreamInfo *stream = st->priv_data;
921 PacketDesc *pkt_desc;
923 while ((pkt_desc = stream->predecode_packet) &&
924 scr > pkt_desc->dts) { // FIXME: > vs >=
925 if (stream->buffer_index < pkt_desc->size ||
926 stream->predecode_packet == stream->premux_packet) {
927 av_log(ctx, AV_LOG_ERROR,
928 "buffer underflow i=%d bufi=%d size=%d\n",
929 i, stream->buffer_index, pkt_desc->size);
932 stream->buffer_index -= pkt_desc->size;
933 stream->predecode_packet = pkt_desc->next;
941 static int output_packet(AVFormatContext *ctx, int flush)
943 MpegMuxContext *s = ctx->priv_data;
946 int i, avail_space = 0, es_size, trailer_size;
948 int best_score = INT_MIN;
949 int ignore_constraints = 0;
950 int64_t scr = s->last_scr;
951 PacketDesc *timestamp_packet;
952 const int64_t max_delay = av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
955 for (i = 0; i < ctx->nb_streams; i++) {
956 AVStream *st = ctx->streams[i];
957 StreamInfo *stream = st->priv_data;
958 const int avail_data = av_fifo_size(stream->fifo);
959 const int space = stream->max_buffer_size - stream->buffer_index;
960 int rel_space = 1024 * space / stream->max_buffer_size;
961 PacketDesc *next_pkt = stream->premux_packet;
963 /* for subtitle, a single PES packet must be generated,
964 * so we flush after every single subtitle packet */
965 if (s->packet_size > avail_data && !flush
966 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
970 assert(avail_data > 0);
972 if (space < s->packet_size && !ignore_constraints)
975 if (next_pkt && next_pkt->dts - scr > max_delay)
978 if (rel_space > best_score) {
979 best_score = rel_space;
986 int64_t best_dts = INT64_MAX;
988 for (i = 0; i < ctx->nb_streams; i++) {
989 AVStream *st = ctx->streams[i];
990 StreamInfo *stream = st->priv_data;
991 PacketDesc *pkt_desc = stream->predecode_packet;
992 if (pkt_desc && pkt_desc->dts < best_dts)
993 best_dts = pkt_desc->dts;
996 av_log(ctx, AV_LOG_TRACE, "bumping scr, scr:%f, dts:%f\n",
997 scr / 90000.0, best_dts / 90000.0);
998 if (best_dts == INT64_MAX)
1001 if (scr >= best_dts + 1 && !ignore_constraints) {
1002 av_log(ctx, AV_LOG_ERROR,
1003 "packet too large, ignoring buffer limits to mux it\n");
1004 ignore_constraints = 1;
1006 scr = FFMAX(best_dts + 1, scr);
1007 if (remove_decoded_packets(ctx, scr) < 0)
1012 assert(best_i >= 0);
1014 st = ctx->streams[best_i];
1015 stream = st->priv_data;
1017 assert(av_fifo_size(stream->fifo) > 0);
1019 assert(avail_space >= s->packet_size || ignore_constraints);
1021 timestamp_packet = stream->premux_packet;
1022 if (timestamp_packet->unwritten_size == timestamp_packet->size) {
1025 trailer_size = timestamp_packet->unwritten_size;
1026 timestamp_packet = timestamp_packet->next;
1029 if (timestamp_packet) {
1030 av_log(ctx, AV_LOG_TRACE, "dts:%f pts:%f scr:%f stream:%d\n",
1031 timestamp_packet->dts / 90000.0,
1032 timestamp_packet->pts / 90000.0,
1033 scr / 90000.0, best_i);
1034 es_size = flush_packet(ctx, best_i, timestamp_packet->pts,
1035 timestamp_packet->dts, scr, trailer_size);
1037 assert(av_fifo_size(stream->fifo) == trailer_size);
1038 es_size = flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr,
1043 /* Write one or more padding sectors, if necessary, to reach
1044 * the constant overall bitrate. */
1047 // FIXME: pts cannot be correct here
1048 while ((vcd_pad_bytes = get_vcd_padding_size(ctx, stream->premux_packet->pts)) >= s->packet_size) {
1049 put_vcd_padding_sector(ctx);
1050 // FIXME: rounding and first few bytes of each packet
1051 s->last_scr += s->packet_size * 90000LL / (s->mux_rate * 50LL);
1055 stream->buffer_index += es_size;
1056 // FIXME: rounding and first few bytes of each packet
1057 s->last_scr += s->packet_size * 90000LL / (s->mux_rate * 50LL);
1059 while (stream->premux_packet &&
1060 stream->premux_packet->unwritten_size <= es_size) {
1061 es_size -= stream->premux_packet->unwritten_size;
1062 stream->premux_packet = stream->premux_packet->next;
1064 if (stream->premux_packet && es_size)
1065 stream->premux_packet->unwritten_size -= es_size;
1067 if (remove_decoded_packets(ctx, s->last_scr) < 0)
1073 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1075 int stream_index = pkt->stream_index;
1076 int size = pkt->size;
1077 uint8_t *buf = pkt->data;
1078 MpegMuxContext *s = ctx->priv_data;
1079 AVStream *st = ctx->streams[stream_index];
1080 StreamInfo *stream = st->priv_data;
1082 PacketDesc *pkt_desc;
1084 const int is_iframe = st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
1085 (pkt->flags & AV_PKT_FLAG_KEY);
1087 preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1092 if (pts != AV_NOPTS_VALUE)
1094 if (dts != AV_NOPTS_VALUE) {
1096 s->last_scr = dts + preload;
1100 av_log(ctx, AV_LOG_TRACE, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n",
1101 dts / 90000.0, pts / 90000.0, pkt->flags,
1102 pkt->stream_index, pts != AV_NOPTS_VALUE);
1103 if (!stream->premux_packet)
1104 stream->next_packet = &stream->premux_packet;
1105 *stream->next_packet =
1106 pkt_desc = av_mallocz(sizeof(PacketDesc));
1107 pkt_desc->pts = pts;
1108 pkt_desc->dts = dts;
1109 pkt_desc->unwritten_size =
1110 pkt_desc->size = size;
1111 if (!stream->predecode_packet)
1112 stream->predecode_packet = pkt_desc;
1113 stream->next_packet = &pkt_desc->next;
1115 if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1119 // min VOBU length 0.4 seconds (mpucoder)
1121 (s->packet_number == 0 ||
1122 (pts - stream->vobu_start_pts >= 36000))) {
1123 stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1124 stream->align_iframe = 1;
1125 stream->vobu_start_pts = pts;
1129 av_fifo_generic_write(stream->fifo, buf, size, NULL);
1132 int ret = output_packet(ctx, 0);
1138 static int mpeg_mux_end(AVFormatContext *ctx)
1144 int ret = output_packet(ctx, 1);
1151 /* End header according to MPEG1 systems standard. We do not write
1152 * it as it is usually not needed by decoders and because it
1153 * complicates MPEG stream concatenation. */
1154 // avio_wb32(ctx->pb, ISO_11172_END_CODE);
1155 // avio_flush(ctx->pb);
1157 for (i = 0; i < ctx->nb_streams; i++) {
1158 stream = ctx->streams[i]->priv_data;
1160 assert(av_fifo_size(stream->fifo) == 0);
1161 av_fifo_free(stream->fifo);
1166 #define OFFSET(x) offsetof(MpegMuxContext, x)
1167 #define E AV_OPT_FLAG_ENCODING_PARAM
1168 static const AVOption options[] = {
1169 { "muxrate", NULL, OFFSET(mux_rate), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, (1 << 22) - 1, E },
1170 { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload), AV_OPT_TYPE_INT, { .i64 = 500000 }, 0, INT_MAX, E },
1174 #define MPEGENC_CLASS(flavor) \
1175 static const AVClass flavor ## _class = { \
1176 .class_name = #flavor " muxer", \
1177 .item_name = av_default_item_name, \
1178 .version = LIBAVUTIL_VERSION_INT, \
1179 .option = options, \
1182 #if CONFIG_MPEG1SYSTEM_MUXER
1184 AVOutputFormat ff_mpeg1system_muxer = {
1186 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream"),
1187 .mime_type = "video/mpeg",
1188 .extensions = "mpg,mpeg",
1189 .priv_data_size = sizeof(MpegMuxContext),
1190 .audio_codec = AV_CODEC_ID_MP2,
1191 .video_codec = AV_CODEC_ID_MPEG1VIDEO,
1192 .write_header = mpeg_mux_init,
1193 .write_packet = mpeg_mux_write_packet,
1194 .write_trailer = mpeg_mux_end,
1195 .priv_class = &mpeg_class,
1199 #if CONFIG_MPEG1VCD_MUXER
1201 AVOutputFormat ff_mpeg1vcd_muxer = {
1203 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream (VCD)"),
1204 .mime_type = "video/mpeg",
1205 .priv_data_size = sizeof(MpegMuxContext),
1206 .audio_codec = AV_CODEC_ID_MP2,
1207 .video_codec = AV_CODEC_ID_MPEG1VIDEO,
1208 .write_header = mpeg_mux_init,
1209 .write_packet = mpeg_mux_write_packet,
1210 .write_trailer = mpeg_mux_end,
1211 .priv_class = &vcd_class,
1215 #if CONFIG_MPEG2VOB_MUXER
1217 AVOutputFormat ff_mpeg2vob_muxer = {
1219 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (VOB)"),
1220 .mime_type = "video/mpeg",
1221 .extensions = "vob",
1222 .priv_data_size = sizeof(MpegMuxContext),
1223 .audio_codec = AV_CODEC_ID_MP2,
1224 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1225 .write_header = mpeg_mux_init,
1226 .write_packet = mpeg_mux_write_packet,
1227 .write_trailer = mpeg_mux_end,
1228 .priv_class = &vob_class,
1232 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1233 #if CONFIG_MPEG2SVCD_MUXER
1235 AVOutputFormat ff_mpeg2svcd_muxer = {
1237 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (SVCD)"),
1238 .mime_type = "video/mpeg",
1239 .extensions = "vob",
1240 .priv_data_size = sizeof(MpegMuxContext),
1241 .audio_codec = AV_CODEC_ID_MP2,
1242 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1243 .write_header = mpeg_mux_init,
1244 .write_packet = mpeg_mux_write_packet,
1245 .write_trailer = mpeg_mux_end,
1246 .priv_class = &svcd_class,
1250 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1251 #if CONFIG_MPEG2DVD_MUXER
1253 AVOutputFormat ff_mpeg2dvd_muxer = {
1255 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (DVD VOB)"),
1256 .mime_type = "video/mpeg",
1257 .extensions = "dvd",
1258 .priv_data_size = sizeof(MpegMuxContext),
1259 .audio_codec = AV_CODEC_ID_MP2,
1260 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1261 .write_header = mpeg_mux_init,
1262 .write_packet = mpeg_mux_write_packet,
1263 .write_trailer = mpeg_mux_end,
1264 .priv_class = &dvd_class,