3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
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 #include "libavcodec/put_bits.h"
34 #define MAX_PAYLOAD_SIZE 4096
39 typedef struct PacketDesc {
45 struct PacketDesc *next;
51 int max_buffer_size; /* in bytes */
53 PacketDesc *predecode_packet;
54 PacketDesc *premux_packet;
55 PacketDesc **next_packet;
57 uint8_t lpcm_header[3];
61 int64_t vobu_start_pts;
66 int packet_size; /* required packet size */
68 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
69 int system_header_freq;
70 int system_header_size;
71 int user_mux_rate; /* bitrate in units of bits/s */
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,
94 uint8_t *buf, int64_t timestamp)
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);
107 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
109 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
111 put_bits(&pb, 15, (uint32_t)((timestamp ) & 0x7fff));
114 /* clock extension */
118 put_bits(&pb, 22, s->mux_rate);
122 put_bits(&pb, 5, 0x1f); /* reserved */
123 put_bits(&pb, 3, 0); /* stuffing length */
126 return put_bits_ptr(&pb) - pb.buf;
129 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
131 MpegMuxContext *s = ctx->priv_data;
132 int size, i, private_stream_coded, id;
135 init_put_bits(&pb, buf, 128);
137 put_bits32(&pb, SYSTEM_HEADER_START_CODE);
138 put_bits(&pb, 16, 0);
141 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
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 (see VCD standard p. IV-7)*/
147 put_bits(&pb, 6, s->audio_bound);
150 /* see VCD standard, p. IV-7*/
154 put_bits(&pb, 1, 0); /* variable bitrate*/
155 put_bits(&pb, 1, 0); /* non constrainted bit stream */
158 if (s->is_vcd || s->is_dvd) {
159 /* see VCD standard p IV-7 */
160 put_bits(&pb, 1, 1); /* audio locked */
161 put_bits(&pb, 1, 1); /* video locked */
163 put_bits(&pb, 1, 0); /* audio locked */
164 put_bits(&pb, 1, 0); /* video locked */
167 put_bits(&pb, 1, 1); /* marker */
169 if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
170 /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
173 put_bits(&pb, 5, s->video_bound);
176 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
177 put_bits(&pb, 7, 0x7f); /* reserved byte */
179 put_bits(&pb, 8, 0xff); /* reserved byte */
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. */
188 int P_STD_max_video = 0;
189 int P_STD_max_mpeg_audio = 0;
190 int P_STD_max_mpeg_PS1 = 0;
192 for(i=0;i<ctx->nb_streams;i++) {
193 StreamInfo *stream = ctx->streams[i]->priv_data;
196 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
197 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
198 } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
199 P_STD_max_mpeg_audio = stream->max_buffer_size;
200 } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
201 P_STD_max_video = stream->max_buffer_size;
206 put_bits(&pb, 8, 0xb9); /* stream ID */
209 put_bits(&pb, 13, P_STD_max_video / 1024);
212 if (P_STD_max_mpeg_audio == 0)
213 P_STD_max_mpeg_audio = 4096;
214 put_bits(&pb, 8, 0xb8); /* stream ID */
217 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
219 /* private stream 1 */
220 put_bits(&pb, 8, 0xbd); /* stream ID */
223 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
225 /* private stream 2 */
226 put_bits(&pb, 8, 0xbf); /* stream ID */
229 put_bits(&pb, 13, 2);
232 /* audio stream info */
233 private_stream_coded = 0;
234 for(i=0;i<ctx->nb_streams;i++) {
235 StreamInfo *stream = ctx->streams[i]->priv_data;
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 if ( !s->is_vcd || stream->id==only_for_stream_id
242 || only_for_stream_id==0) {
246 /* special case for private streams (AC-3 uses that) */
247 if (private_stream_coded)
249 private_stream_coded = 1;
252 put_bits(&pb, 8, id); /* stream ID */
257 put_bits(&pb, 13, stream->max_buffer_size / 128);
261 put_bits(&pb, 13, stream->max_buffer_size / 1024);
268 size = put_bits_ptr(&pb) - pb.buf;
269 /* patch packet size */
270 AV_WB16(buf + 4, size - 6);
275 static int get_system_header_size(AVFormatContext *ctx)
277 int buf_index, i, private_stream_coded;
279 MpegMuxContext *s = ctx->priv_data;
282 return 18; // DVD-Video system headers are 18 bytes fixed length.
285 private_stream_coded = 0;
286 for(i=0;i<ctx->nb_streams;i++) {
287 stream = ctx->streams[i]->priv_data;
288 if (stream->id < 0xc0) {
289 if (private_stream_coded)
291 private_stream_coded = 1;
298 static av_cold int mpeg_mux_init(AVFormatContext *ctx)
300 MpegMuxContext *s = ctx->priv_data;
301 int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
307 s->packet_number = 0;
308 s->is_vcd = (CONFIG_MPEG1VCD_MUXER && ctx->oformat == &ff_mpeg1vcd_muxer);
309 s->is_svcd = (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
310 s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER && ctx->oformat == &ff_mpeg2vob_muxer) ||
311 (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer) ||
312 (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
313 s->is_dvd = (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer);
315 if(ctx->packet_size) {
316 if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
317 av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
321 s->packet_size = ctx->packet_size;
323 s->packet_size = 2048;
324 if (ctx->max_delay < 0) /* Not set by the caller */
325 ctx->max_delay = 0.7*AV_TIME_BASE;
327 s->vcd_padding_bytes_written = 0;
328 s->vcd_padding_bitrate=0;
338 for(i=0;i<ctx->nb_streams;i++) {
339 st = ctx->streams[i];
340 stream = av_mallocz(sizeof(StreamInfo));
343 st->priv_data = stream;
345 avpriv_set_pts_info(st, 64, 1, 90000);
347 switch(st->codec->codec_type) {
348 case AVMEDIA_TYPE_AUDIO:
350 (st->codec->codec_id == AV_CODEC_ID_AC3 ||
351 st->codec->codec_id == AV_CODEC_ID_DTS ||
352 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE))
353 av_log(ctx, AV_LOG_WARNING,
354 "%s in MPEG-1 system streams is not widely supported, "
355 "consider using the vob or the dvd muxer "
356 "to force a MPEG-2 program stream.\n",
357 avcodec_get_name(st->codec->codec_id));
358 if (st->codec->codec_id == AV_CODEC_ID_AC3) {
359 stream->id = ac3_id++;
360 } else if (st->codec->codec_id == AV_CODEC_ID_DTS) {
361 stream->id = dts_id++;
362 } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {
363 stream->id = lpcm_id++;
364 for(j = 0; j < 4; j++) {
365 if (lpcm_freq_tab[j] == st->codec->sample_rate)
370 if (st->codec->channels > 8)
372 stream->lpcm_header[0] = 0x0c;
373 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
374 stream->lpcm_header[2] = 0x80;
375 stream->lpcm_align = st->codec->channels * 2;
377 stream->id = mpa_id++;
380 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
381 Right now it is also used for everything else.*/
382 stream->max_buffer_size = 4 * 1024;
385 case AVMEDIA_TYPE_VIDEO:
386 stream->id = mpv_id++;
387 if (st->codec->rc_buffer_size)
388 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
390 av_log(ctx, AV_LOG_WARNING, "VBV buffer size not set, muxing may fail\n");
391 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
393 if (stream->max_buffer_size > 1024 * 8191) {
394 av_log(ctx, AV_LOG_WARNING, "buffer size %d, too large\n", stream->max_buffer_size);
395 stream->max_buffer_size = 1024 * 8191;
399 case AVMEDIA_TYPE_SUBTITLE:
400 stream->id = mps_id++;
401 stream->max_buffer_size = 16 * 1024;
406 stream->fifo= av_fifo_alloc(16);
413 for(i=0;i<ctx->nb_streams;i++) {
415 st = ctx->streams[i];
416 stream = (StreamInfo*) st->priv_data;
418 if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
419 codec_rate= st->codec->rc_max_rate;
421 codec_rate= st->codec->bit_rate;
424 codec_rate= (1<<21)*8*50/ctx->nb_streams;
426 bitrate += codec_rate;
428 if ((stream->id & 0xe0) == AUDIO_ID)
429 audio_bitrate += codec_rate;
430 else if (stream->id==VIDEO_ID)
431 video_bitrate += codec_rate;
434 if (s->user_mux_rate) {
435 s->mux_rate = (s->user_mux_rate + (8 * 50) - 1) / (8 * 50);
437 /* we increase slightly the bitrate to take into account the
438 headers. XXX: compute it exactly */
439 bitrate += bitrate / 20;
441 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
442 if (s->mux_rate >= (1<<22)) {
443 av_log(ctx, AV_LOG_WARNING, "mux rate %d is too large\n", s->mux_rate);
444 s->mux_rate = (1<<22) - 1;
449 double overhead_rate;
451 /* The VCD standard mandates that the mux_rate field is 3528
452 (see standard p. IV-6).
453 The value is actually "wrong", i.e. if you calculate
454 it using the normal formula and the 75 sectors per second transfer
455 rate you get a different value because the real pack size is 2324,
456 not 2352. But the standard explicitly specifies that the mux_rate
457 field in the header must have this value.*/
458 // s->mux_rate=2352 * 75 / 50; /* = 3528*/
460 /* The VCD standard states that the muxed stream must be
461 exactly 75 packs / second (the data rate of a single speed cdrom).
462 Since the video bitrate (probably 1150000 bits/sec) will be below
463 the theoretical maximum we have to add some padding packets
464 to make up for the lower data rate.
465 (cf. VCD standard p. IV-6 )*/
467 /* Add the header overhead to the data rate.
468 2279 data bytes per audio pack, 2294 data bytes per video pack*/
469 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
470 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
473 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
474 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
477 if (s->is_vcd || s->is_mpeg2)
479 s->pack_header_freq = 1;
481 /* every 2 seconds */
482 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
484 /* the above seems to make pack_header_freq zero sometimes */
485 if (s->pack_header_freq == 0)
486 s->pack_header_freq = 1;
489 /* every 200 packets. Need to look at the spec. */
490 s->system_header_freq = s->pack_header_freq * 40;
492 /* the standard mandates that there are only two system headers
493 in the whole file: one in the first packet of each stream.
494 (see standard p. IV-7 and IV-8) */
495 s->system_header_freq = 0x7fffffff;
497 s->system_header_freq = s->pack_header_freq * 5;
499 for(i=0;i<ctx->nb_streams;i++) {
500 stream = ctx->streams[i]->priv_data;
501 stream->packet_number = 0;
503 s->system_header_size = get_system_header_size(ctx);
504 s->last_scr = AV_NOPTS_VALUE;
507 for(i=0;i<ctx->nb_streams;i++) {
508 av_free(ctx->streams[i]->priv_data);
510 return AVERROR(ENOMEM);
513 static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
517 (((timestamp >> 30) & 0x07) << 1) |
519 avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
520 avio_wb16(pb, (uint16_t)((((timestamp ) & 0x7fff) << 1) | 1));
524 /* return the number of padding bytes that should be inserted into
525 the multiplexed stream.*/
526 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
528 MpegMuxContext *s = ctx->priv_data;
531 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
533 int64_t full_pad_bytes;
535 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
536 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
539 /* might happen if we have already padded to a later timestamp. This
540 can occur if another stream has already advanced further.*/
548 /* Write an MPEG padding packet header. */
549 static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,int packet_bytes)
551 MpegMuxContext *s = ctx->priv_data;
554 avio_wb32(pb, PADDING_STREAM);
555 avio_wb16(pb, packet_bytes - 6);
562 for(i=0;i<packet_bytes;i++)
566 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
568 PacketDesc *pkt_desc= stream->premux_packet;
571 if(pkt_desc->size == pkt_desc->unwritten_size)
573 len -= pkt_desc->unwritten_size;
574 pkt_desc= pkt_desc->next;
580 /* flush the packet on stream stream_index */
581 static int flush_packet(AVFormatContext *ctx, int stream_index,
582 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
584 MpegMuxContext *s = ctx->priv_data;
585 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
587 int size, payload_size, startcode, id, stuffing_size, i, header_len;
590 int zero_trail_bytes = 0;
591 int pad_packet_bytes = 0;
593 int general_pack = 0; /*"general" pack without data specific to one stream?*/
598 av_dlog(ctx, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
602 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
603 /* output pack and systems header if needed */
604 size = put_pack_header(ctx, buf_ptr, scr);
609 /* there is exactly one system header for each stream in a VCD MPEG,
610 One in the very first video packet and one in the very first
611 audio packet (see VCD standard p. IV-7 and IV-8).*/
613 if (stream->packet_number==0) {
614 size = put_system_header(ctx, buf_ptr, id);
617 } else if (s->is_dvd) {
618 if (stream->align_iframe || s->packet_number == 0){
619 int PES_bytes_to_fill = s->packet_size - size - 10;
621 if (pts != AV_NOPTS_VALUE) {
623 PES_bytes_to_fill -= 5 + 5;
625 PES_bytes_to_fill -= 5;
628 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
629 size = put_system_header(ctx, buf_ptr, 0);
631 size = buf_ptr - buffer;
632 avio_write(ctx->pb, buffer, size);
634 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
635 avio_wb16(ctx->pb, 0x03d4); // length
636 avio_w8(ctx->pb, 0x00); // substream ID, 00=PCI
637 for (i = 0; i < 979; i++)
638 avio_w8(ctx->pb, 0x00);
640 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
641 avio_wb16(ctx->pb, 0x03fa); // length
642 avio_w8(ctx->pb, 0x01); // substream ID, 01=DSI
643 for (i = 0; i < 1017; i++)
644 avio_w8(ctx->pb, 0x00);
646 memset(buffer, 0, 128);
649 stream->align_iframe = 0;
650 scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
651 size = put_pack_header(ctx, buf_ptr, scr);
655 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
656 pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
660 if ((s->packet_number % s->system_header_freq) == 0) {
661 size = put_system_header(ctx, buf_ptr, 0);
666 size = buf_ptr - buffer;
667 avio_write(ctx->pb, buffer, size);
669 packet_size = s->packet_size - size;
671 if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
672 /* The VCD standard demands that 20 zero bytes follow
673 each audio pack (see standard p. IV-8).*/
674 zero_trail_bytes += 20;
676 if ((s->is_vcd && stream->packet_number==0)
677 || (s->is_svcd && s->packet_number==0)) {
678 /* for VCD the first pack of each stream contains only the pack header,
679 the system header and lots of padding (see VCD standard p. IV-6).
680 In the case of an audio pack, 20 zero bytes are also added at
682 /* For SVCD we fill the very first pack to increase compatibility with
683 some DVD players. Not mandated by the standard.*/
685 general_pack = 1; /* 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) {
693 /* packet header size */
699 if (stream->packet_number==0)
700 header_len += 3; /* PES extension */
701 header_len += 1; /* obligatory stuffing byte */
705 if (pts != AV_NOPTS_VALUE) {
715 payload_size = packet_size - header_len;
717 startcode = PRIVATE_STREAM_1;
725 startcode = 0x100 + id;
728 stuffing_size = payload_size - av_fifo_size(stream->fifo);
730 // first byte does not fit -> reset pts/dts + stuffing
731 if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
735 if(pts != AV_NOPTS_VALUE)
736 timestamp_len += s->is_mpeg2 ? 5 : 4;
737 pts=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 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
751 packet_size += pad_packet_bytes;
752 payload_size += pad_packet_bytes; // undo the previous adjustment
753 if (stuffing_size < 0) {
754 stuffing_size = pad_packet_bytes;
756 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);
823 if (pts != AV_NOPTS_VALUE) {
825 put_timestamp(ctx->pb, 0x03, pts);
826 put_timestamp(ctx->pb, 0x01, dts);
828 put_timestamp(ctx->pb, 0x02, pts);
831 avio_w8(ctx->pb, 0x0f);
836 /* special stuffing byte that is always written
837 to prevent accidental generation of start codes. */
838 avio_w8(ctx->pb, 0xff);
840 for(i=0;i<stuffing_size;i++)
841 avio_w8(ctx->pb, 0xff);
844 if (startcode == PRIVATE_STREAM_1) {
845 avio_w8(ctx->pb, id);
847 /* LPCM (XXX: check nb_frames) */
849 avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
850 avio_w8(ctx->pb, stream->lpcm_header[0]);
851 avio_w8(ctx->pb, stream->lpcm_header[1]);
852 avio_w8(ctx->pb, stream->lpcm_header[2]);
853 } else if (id >= 0x40) {
855 avio_w8(ctx->pb, nb_frames);
856 avio_wb16(ctx->pb, trailer_size+1);
861 assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
862 av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, (void*)avio_write);
863 stream->bytes_to_iframe -= payload_size - stuffing_size;
869 if (pad_packet_bytes > 0)
870 put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
872 for(i=0;i<zero_trail_bytes;i++)
873 avio_w8(ctx->pb, 0x00);
879 /* only increase the stream packet number if this pack actually contains
880 something that is specific to this stream! I.e. a dedicated header
883 stream->packet_number++;
885 return payload_size - stuffing_size;
888 static void put_vcd_padding_sector(AVFormatContext *ctx)
890 /* There are two ways to do this padding: writing a sector/pack
891 of 0 values, or writing an MPEG padding pack. Both seem to
892 work with most decoders, BUT the VCD standard only allows a 0-sector
893 (see standard p. IV-4, IV-5).
894 So a 0-sector it is...*/
896 MpegMuxContext *s = ctx->priv_data;
899 for(i=0;i<s->packet_size;i++)
902 s->vcd_padding_bytes_written += s->packet_size;
906 /* increasing the packet number is correct. The SCR of the following packs
907 is calculated from the packet_number and it has to include the padding
908 sector (it represents the sector index, not the MPEG pack index)
909 (see VCD standard p. IV-6)*/
913 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
914 // MpegMuxContext *s = ctx->priv_data;
917 for(i=0; i<ctx->nb_streams; i++){
918 AVStream *st = ctx->streams[i];
919 StreamInfo *stream = st->priv_data;
920 PacketDesc *pkt_desc;
922 while((pkt_desc= stream->predecode_packet)
923 && scr > pkt_desc->dts){ //FIXME > vs >=
924 if(stream->buffer_index < pkt_desc->size ||
925 stream->predecode_packet == stream->premux_packet){
926 av_log(ctx, AV_LOG_ERROR,
927 "buffer underflow st=%d bufi=%d size=%d\n",
928 i, stream->buffer_index, pkt_desc->size);
931 stream->buffer_index -= pkt_desc->size;
933 stream->predecode_packet= pkt_desc->next;
941 static int output_packet(AVFormatContext *ctx, int flush){
942 MpegMuxContext *s = ctx->priv_data;
945 int i, avail_space=0, es_size, trailer_size;
947 int best_score= INT_MIN;
948 int ignore_constraints=0;
949 int64_t scr= s->last_scr;
950 PacketDesc *timestamp_packet;
951 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
954 for(i=0; i<ctx->nb_streams; i++){
955 AVStream *st = ctx->streams[i];
956 StreamInfo *stream = st->priv_data;
957 const int avail_data= av_fifo_size(stream->fifo);
958 const int space= stream->max_buffer_size - stream->buffer_index;
959 int rel_space= 1024LL*space / stream->max_buffer_size;
960 PacketDesc *next_pkt= stream->premux_packet;
962 /* for subtitle, a single PES packet must be generated,
963 so we flush after every single subtitle packet */
964 if(s->packet_size > avail_data && !flush
965 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
969 av_assert0(avail_data>0);
971 if(space < s->packet_size && !ignore_constraints)
974 if(next_pkt && next_pkt->dts - scr > max_delay)
976 if ( stream->predecode_packet
977 && stream->predecode_packet->size > stream->buffer_index)
979 if(rel_space > best_score){
980 best_score= rel_space;
987 int64_t best_dts= INT64_MAX;
989 for(i=0; i<ctx->nb_streams; i++){
990 AVStream *st = ctx->streams[i];
991 StreamInfo *stream = st->priv_data;
992 PacketDesc *pkt_desc= stream->predecode_packet;
993 if(pkt_desc && pkt_desc->dts < best_dts)
994 best_dts= pkt_desc->dts;
997 av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
998 scr / 90000.0, best_dts / 90000.0);
999 if(best_dts == INT64_MAX)
1002 if(scr >= best_dts+1 && !ignore_constraints){
1003 av_log(ctx, AV_LOG_ERROR, "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_dlog(ctx, "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, timestamp_packet->dts, scr, trailer_size);
1036 assert(av_fifo_size(stream->fifo) == trailer_size);
1037 es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1041 /* Write one or more padding sectors, if necessary, to reach
1042 the constant overall bitrate.*/
1045 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1046 put_vcd_padding_sector(ctx);
1047 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1051 stream->buffer_index += es_size;
1052 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1054 while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1055 es_size -= stream->premux_packet->unwritten_size;
1056 stream->premux_packet= stream->premux_packet->next;
1059 stream->premux_packet->unwritten_size -= es_size;
1061 if(remove_decoded_packets(ctx, s->last_scr) < 0)
1067 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1069 MpegMuxContext *s = ctx->priv_data;
1070 int stream_index= pkt->stream_index;
1071 int size= pkt->size;
1072 uint8_t *buf= pkt->data;
1073 AVStream *st = ctx->streams[stream_index];
1074 StreamInfo *stream = st->priv_data;
1076 PacketDesc *pkt_desc;
1078 const int is_iframe = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (pkt->flags & AV_PKT_FLAG_KEY);
1080 preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1085 if (s->last_scr == AV_NOPTS_VALUE) {
1086 if (dts == AV_NOPTS_VALUE || (dts < preload && ctx->avoid_negative_ts) || s->is_dvd) {
1087 if (dts != AV_NOPTS_VALUE)
1088 s->preload += av_rescale(-dts, AV_TIME_BASE, 90000);
1091 s->last_scr = dts - preload;
1094 preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1095 av_log(ctx, AV_LOG_DEBUG, "First SCR: %"PRId64" First DTS: %"PRId64"\n", s->last_scr, dts + preload);
1098 if (dts != AV_NOPTS_VALUE) dts += preload;
1099 if (pts != AV_NOPTS_VALUE) pts += preload;
1101 av_dlog(ctx, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n",
1102 dts / 90000.0, pts / 90000.0, pkt->flags,
1103 pkt->stream_index, pts != AV_NOPTS_VALUE);
1104 if (!stream->premux_packet)
1105 stream->next_packet = &stream->premux_packet;
1106 *stream->next_packet=
1107 pkt_desc= av_mallocz(sizeof(PacketDesc));
1110 pkt_desc->unwritten_size=
1111 pkt_desc->size= size;
1112 if(!stream->predecode_packet)
1113 stream->predecode_packet= pkt_desc;
1114 stream->next_packet= &pkt_desc->next;
1116 if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1120 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1121 stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1122 stream->align_iframe = 1;
1123 stream->vobu_start_pts = pts;
1127 av_fifo_generic_write(stream->fifo, buf, size, NULL);
1130 int ret= output_packet(ctx, 0);
1136 static int mpeg_mux_end(AVFormatContext *ctx)
1138 // MpegMuxContext *s = ctx->priv_data;
1143 int ret= output_packet(ctx, 1);
1150 /* End header according to MPEG1 systems standard. We do not write
1151 it as it is usually not needed by decoders and because it
1152 complicates MPEG stream concatenation. */
1153 //avio_wb32(ctx->pb, ISO_11172_END_CODE);
1154 //avio_flush(ctx->pb);
1156 for(i=0;i<ctx->nb_streams;i++) {
1157 stream = ctx->streams[i]->priv_data;
1159 assert(av_fifo_size(stream->fifo) == 0);
1160 av_fifo_free(stream->fifo);
1165 #define OFFSET(x) offsetof(MpegMuxContext, x)
1166 #define E AV_OPT_FLAG_ENCODING_PARAM
1167 static const AVOption options[] = {
1168 { "muxrate", NULL, OFFSET(user_mux_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, ((1<<22) - 1) * (8 * 50), E },
1169 { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload), AV_OPT_TYPE_INT, {.i64 = 500000}, 0, INT_MAX, E},
1173 #define MPEGENC_CLASS(flavor)\
1174 static const AVClass flavor ## _class = {\
1175 .class_name = #flavor " muxer",\
1176 .item_name = av_default_item_name,\
1177 .version = LIBAVUTIL_VERSION_INT,\
1181 #if CONFIG_MPEG1SYSTEM_MUXER
1183 AVOutputFormat ff_mpeg1system_muxer = {
1185 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream"),
1186 .mime_type = "video/mpeg",
1187 .extensions = "mpg,mpeg",
1188 .priv_data_size = sizeof(MpegMuxContext),
1189 .audio_codec = AV_CODEC_ID_MP2,
1190 .video_codec = AV_CODEC_ID_MPEG1VIDEO,
1191 .write_header = mpeg_mux_init,
1192 .write_packet = mpeg_mux_write_packet,
1193 .write_trailer = mpeg_mux_end,
1194 .priv_class = &mpeg_class,
1197 #if CONFIG_MPEG1VCD_MUXER
1199 AVOutputFormat ff_mpeg1vcd_muxer = {
1201 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream (VCD)"),
1202 .mime_type = "video/mpeg",
1203 .priv_data_size = sizeof(MpegMuxContext),
1204 .audio_codec = AV_CODEC_ID_MP2,
1205 .video_codec = AV_CODEC_ID_MPEG1VIDEO,
1206 .write_header = mpeg_mux_init,
1207 .write_packet = mpeg_mux_write_packet,
1208 .write_trailer = mpeg_mux_end,
1209 .priv_class = &vcd_class,
1212 #if CONFIG_MPEG2VOB_MUXER
1214 AVOutputFormat ff_mpeg2vob_muxer = {
1216 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (VOB)"),
1217 .mime_type = "video/mpeg",
1218 .extensions = "vob",
1219 .priv_data_size = sizeof(MpegMuxContext),
1220 .audio_codec = AV_CODEC_ID_MP2,
1221 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1222 .write_header = mpeg_mux_init,
1223 .write_packet = mpeg_mux_write_packet,
1224 .write_trailer = mpeg_mux_end,
1225 .priv_class = &vob_class,
1229 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1230 #if CONFIG_MPEG2SVCD_MUXER
1232 AVOutputFormat ff_mpeg2svcd_muxer = {
1234 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (SVCD)"),
1235 .mime_type = "video/mpeg",
1236 .extensions = "vob",
1237 .priv_data_size = sizeof(MpegMuxContext),
1238 .audio_codec = AV_CODEC_ID_MP2,
1239 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1240 .write_header = mpeg_mux_init,
1241 .write_packet = mpeg_mux_write_packet,
1242 .write_trailer = mpeg_mux_end,
1243 .priv_class = &svcd_class,
1247 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1248 #if CONFIG_MPEG2DVD_MUXER
1250 AVOutputFormat ff_mpeg2dvd_muxer = {
1252 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (DVD VOB)"),
1253 .mime_type = "video/mpeg",
1254 .extensions = "dvd",
1255 .priv_data_size = sizeof(MpegMuxContext),
1256 .audio_codec = AV_CODEC_ID_MP2,
1257 .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1258 .write_header = mpeg_mux_init,
1259 .write_packet = mpeg_mux_write_packet,
1260 .write_trailer = mpeg_mux_end,
1261 .priv_class = &dvd_class,