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
22 #include "libavutil/fifo.h"
23 #include "libavutil/log.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/opt.h"
26 #include "libavcodec/put_bits.h"
30 #define MAX_PAYLOAD_SIZE 4096
35 typedef struct PacketDesc {
41 struct PacketDesc *next;
47 int max_buffer_size; /* in bytes */
49 PacketDesc *predecode_packet;
50 PacketDesc *premux_packet;
51 PacketDesc **next_packet;
53 uint8_t lpcm_header[3];
57 int64_t vobu_start_pts;
62 int packet_size; /* required packet size */
64 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
65 int system_header_freq;
66 int system_header_size;
67 int mux_rate; /* bitrate in units of 50 bytes/s */
75 int64_t last_scr; /* current system clock */
77 double vcd_padding_bitrate; //FIXME floats
78 int64_t vcd_padding_bytes_written;
82 extern AVOutputFormat ff_mpeg1vcd_muxer;
83 extern AVOutputFormat ff_mpeg2dvd_muxer;
84 extern AVOutputFormat ff_mpeg2svcd_muxer;
85 extern AVOutputFormat ff_mpeg2vob_muxer;
87 static int put_pack_header(AVFormatContext *ctx,
88 uint8_t *buf, int64_t timestamp)
90 MpegMuxContext *s = ctx->priv_data;
93 init_put_bits(&pb, buf, 128);
95 put_bits32(&pb, PACK_START_CODE);
97 put_bits(&pb, 2, 0x1);
99 put_bits(&pb, 4, 0x2);
101 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
103 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
105 put_bits(&pb, 15, (uint32_t)((timestamp ) & 0x7fff));
108 /* clock extension */
112 put_bits(&pb, 22, s->mux_rate);
116 put_bits(&pb, 5, 0x1f); /* reserved */
117 put_bits(&pb, 3, 0); /* stuffing length */
120 return put_bits_ptr(&pb) - pb.buf;
123 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
125 MpegMuxContext *s = ctx->priv_data;
126 int size, i, private_stream_coded, id;
129 init_put_bits(&pb, buf, 128);
131 put_bits32(&pb, SYSTEM_HEADER_START_CODE);
132 put_bits(&pb, 16, 0);
135 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
136 put_bits(&pb, 1, 1); /* marker */
137 if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
138 /* This header applies only to the video stream (see VCD standard p. IV-7)*/
141 put_bits(&pb, 6, s->audio_bound);
144 /* see VCD standard, p. IV-7*/
148 put_bits(&pb, 1, 0); /* variable bitrate*/
149 put_bits(&pb, 1, 0); /* non constrainted bit stream */
152 if (s->is_vcd || s->is_dvd) {
153 /* see VCD standard p IV-7 */
154 put_bits(&pb, 1, 1); /* audio locked */
155 put_bits(&pb, 1, 1); /* video locked */
157 put_bits(&pb, 1, 0); /* audio locked */
158 put_bits(&pb, 1, 0); /* video locked */
161 put_bits(&pb, 1, 1); /* marker */
163 if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
164 /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
167 put_bits(&pb, 5, s->video_bound);
170 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
171 put_bits(&pb, 7, 0x7f); /* reserved byte */
173 put_bits(&pb, 8, 0xff); /* reserved byte */
175 /* DVD-Video Stream_bound entries
176 id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
177 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)
178 id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
179 id (0xBF) private stream 2, NAV packs, set to 2x1024. */
182 int P_STD_max_video = 0;
183 int P_STD_max_mpeg_audio = 0;
184 int P_STD_max_mpeg_PS1 = 0;
186 for(i=0;i<ctx->nb_streams;i++) {
187 StreamInfo *stream = ctx->streams[i]->priv_data;
190 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
191 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
192 } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
193 P_STD_max_mpeg_audio = stream->max_buffer_size;
194 } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
195 P_STD_max_video = stream->max_buffer_size;
200 put_bits(&pb, 8, 0xb9); /* stream ID */
203 put_bits(&pb, 13, P_STD_max_video / 1024);
206 if (P_STD_max_mpeg_audio == 0)
207 P_STD_max_mpeg_audio = 4096;
208 put_bits(&pb, 8, 0xb8); /* stream ID */
211 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
213 /* private stream 1 */
214 put_bits(&pb, 8, 0xbd); /* stream ID */
217 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
219 /* private stream 2 */
220 put_bits(&pb, 8, 0xbf); /* stream ID */
223 put_bits(&pb, 13, 2);
226 /* audio stream info */
227 private_stream_coded = 0;
228 for(i=0;i<ctx->nb_streams;i++) {
229 StreamInfo *stream = ctx->streams[i]->priv_data;
232 /* For VCDs, only include the stream info for the stream
233 that the pack which contains this system belongs to.
234 (see VCD standard p. IV-7) */
235 if ( !s->is_vcd || stream->id==only_for_stream_id
236 || only_for_stream_id==0) {
240 /* special case for private streams (AC-3 uses that) */
241 if (private_stream_coded)
243 private_stream_coded = 1;
246 put_bits(&pb, 8, id); /* stream ID */
251 put_bits(&pb, 13, stream->max_buffer_size / 128);
255 put_bits(&pb, 13, stream->max_buffer_size / 1024);
262 size = put_bits_ptr(&pb) - pb.buf;
263 /* patch packet size */
264 buf[4] = (size - 6) >> 8;
265 buf[5] = (size - 6) & 0xff;
270 static int get_system_header_size(AVFormatContext *ctx)
272 int buf_index, i, private_stream_coded;
274 MpegMuxContext *s = ctx->priv_data;
277 return 18; // DVD-Video system headers are 18 bytes fixed length.
280 private_stream_coded = 0;
281 for(i=0;i<ctx->nb_streams;i++) {
282 stream = ctx->streams[i]->priv_data;
283 if (stream->id < 0xc0) {
284 if (private_stream_coded)
286 private_stream_coded = 1;
293 static int mpeg_mux_init(AVFormatContext *ctx)
295 MpegMuxContext *s = ctx->priv_data;
296 int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
302 s->packet_number = 0;
303 s->is_vcd = (CONFIG_MPEG1VCD_MUXER && ctx->oformat == &ff_mpeg1vcd_muxer);
304 s->is_svcd = (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
305 s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER && ctx->oformat == &ff_mpeg2vob_muxer) ||
306 (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer) ||
307 (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
308 s->is_dvd = (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer);
310 if(ctx->packet_size) {
311 if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
312 av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
316 s->packet_size = ctx->packet_size;
318 s->packet_size = 2048;
320 s->vcd_padding_bytes_written = 0;
321 s->vcd_padding_bitrate=0;
331 for(i=0;i<ctx->nb_streams;i++) {
332 st = ctx->streams[i];
333 stream = av_mallocz(sizeof(StreamInfo));
336 st->priv_data = stream;
338 av_set_pts_info(st, 64, 1, 90000);
340 switch(st->codec->codec_type) {
341 case AVMEDIA_TYPE_AUDIO:
342 if (st->codec->codec_id == CODEC_ID_AC3) {
343 stream->id = ac3_id++;
344 } else if (st->codec->codec_id == CODEC_ID_DTS) {
345 stream->id = dts_id++;
346 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
347 stream->id = lpcm_id++;
348 for(j = 0; j < 4; j++) {
349 if (lpcm_freq_tab[j] == st->codec->sample_rate)
354 if (st->codec->channels > 8)
356 stream->lpcm_header[0] = 0x0c;
357 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
358 stream->lpcm_header[2] = 0x80;
359 stream->lpcm_align = st->codec->channels * 2;
361 stream->id = mpa_id++;
364 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
365 Right now it is also used for everything else.*/
366 stream->max_buffer_size = 4 * 1024;
369 case AVMEDIA_TYPE_VIDEO:
370 stream->id = mpv_id++;
371 if (st->codec->rc_buffer_size)
372 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
374 av_log(ctx, AV_LOG_WARNING, "VBV buffer size not set, muxing may fail\n");
375 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
378 /* see VCD standard, p. IV-7*/
379 stream->max_buffer_size = 46 * 1024;
381 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
382 Right now it is also used for everything else.*/
383 stream->max_buffer_size = 230 * 1024;
387 case AVMEDIA_TYPE_SUBTITLE:
388 stream->id = mps_id++;
389 stream->max_buffer_size = 16 * 1024;
394 stream->fifo= av_fifo_alloc(16);
401 for(i=0;i<ctx->nb_streams;i++) {
403 st = ctx->streams[i];
404 stream = (StreamInfo*) st->priv_data;
406 if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
407 codec_rate= st->codec->rc_max_rate;
409 codec_rate= st->codec->bit_rate;
412 codec_rate= (1<<21)*8*50/ctx->nb_streams;
414 bitrate += codec_rate;
416 if ((stream->id & 0xe0) == AUDIO_ID)
417 audio_bitrate += codec_rate;
418 else if (stream->id==VIDEO_ID)
419 video_bitrate += codec_rate;
424 s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
428 /* we increase slightly the bitrate to take into account the
429 headers. XXX: compute it exactly */
430 bitrate += bitrate*5/100;
432 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
436 double overhead_rate;
438 /* The VCD standard mandates that the mux_rate field is 3528
439 (see standard p. IV-6).
440 The value is actually "wrong", i.e. if you calculate
441 it using the normal formula and the 75 sectors per second transfer
442 rate you get a different value because the real pack size is 2324,
443 not 2352. But the standard explicitly specifies that the mux_rate
444 field in the header must have this value.*/
445 // s->mux_rate=2352 * 75 / 50; /* = 3528*/
447 /* The VCD standard states that the muxed stream must be
448 exactly 75 packs / second (the data rate of a single speed cdrom).
449 Since the video bitrate (probably 1150000 bits/sec) will be below
450 the theoretical maximum we have to add some padding packets
451 to make up for the lower data rate.
452 (cf. VCD standard p. IV-6 )*/
454 /* Add the header overhead to the data rate.
455 2279 data bytes per audio pack, 2294 data bytes per video pack*/
456 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
457 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
460 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
461 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
464 if (s->is_vcd || s->is_mpeg2)
466 s->pack_header_freq = 1;
468 /* every 2 seconds */
469 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
471 /* the above seems to make pack_header_freq zero sometimes */
472 if (s->pack_header_freq == 0)
473 s->pack_header_freq = 1;
476 /* every 200 packets. Need to look at the spec. */
477 s->system_header_freq = s->pack_header_freq * 40;
479 /* the standard mandates that there are only two system headers
480 in the whole file: one in the first packet of each stream.
481 (see standard p. IV-7 and IV-8) */
482 s->system_header_freq = 0x7fffffff;
484 s->system_header_freq = s->pack_header_freq * 5;
486 for(i=0;i<ctx->nb_streams;i++) {
487 stream = ctx->streams[i]->priv_data;
488 stream->packet_number = 0;
490 s->system_header_size = get_system_header_size(ctx);
494 for(i=0;i<ctx->nb_streams;i++) {
495 av_free(ctx->streams[i]->priv_data);
497 return AVERROR(ENOMEM);
500 static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
504 (((timestamp >> 30) & 0x07) << 1) |
506 avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
507 avio_wb16(pb, (uint16_t)((((timestamp ) & 0x7fff) << 1) | 1));
511 /* return the number of padding bytes that should be inserted into
512 the multiplexed stream.*/
513 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
515 MpegMuxContext *s = ctx->priv_data;
518 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
520 int64_t full_pad_bytes;
522 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
523 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
526 /* might happen if we have already padded to a later timestamp. This
527 can occur if another stream has already advanced further.*/
535 #if 0 /* unused, remove? */
536 /* return the exact available payload size for the next packet for
537 stream 'stream_index'. 'pts' and 'dts' are only used to know if
538 timestamps are needed in the packet header. */
539 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
540 int64_t pts, int64_t dts)
542 MpegMuxContext *s = ctx->priv_data;
546 stream = ctx->streams[stream_index]->priv_data;
549 if (((s->packet_number % s->pack_header_freq) == 0)) {
550 /* pack header size */
557 /* there is exactly one system header for each stream in a VCD MPEG,
558 One in the very first video packet and one in the very first
559 audio packet (see VCD standard p. IV-7 and IV-8).*/
561 if (stream->packet_number==0)
562 /* The system headers refer only to the stream they occur in,
563 so they have a constant size.*/
567 if ((s->packet_number % s->system_header_freq) == 0)
568 buf_index += s->system_header_size;
572 if ((s->is_vcd && stream->packet_number==0)
573 || (s->is_svcd && s->packet_number==0))
574 /* the first pack of each stream contains only the pack header,
575 the system header and some padding (see VCD standard p. IV-6)
576 Add the padding size, so that the actual payload becomes 0.*/
577 buf_index += s->packet_size - buf_index;
579 /* packet header size */
583 if (stream->packet_number==0)
584 buf_index += 3; /* PES extension */
585 buf_index += 1; /* obligatory stuffing byte */
587 if (pts != AV_NOPTS_VALUE) {
598 if (stream->id < 0xc0) {
599 /* AC-3/LPCM private data header */
601 if (stream->id >= 0xa0) {
604 /* NOTE: we round the payload size to an integer number of
606 n = (s->packet_size - buf_index) % stream->lpcm_align;
608 buf_index += (stream->lpcm_align - n);
612 if (s->is_vcd && (stream->id & 0xe0) == AUDIO_ID)
613 /* The VCD standard demands that 20 zero bytes follow
614 each audio packet (see standard p. IV-8).*/
617 return s->packet_size - buf_index;
621 /* Write an MPEG padding packet header. */
622 static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,int packet_bytes)
624 MpegMuxContext *s = ctx->priv_data;
627 avio_wb32(pb, PADDING_STREAM);
628 avio_wb16(pb, packet_bytes - 6);
635 for(i=0;i<packet_bytes;i++)
639 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
641 PacketDesc *pkt_desc= stream->premux_packet;
644 if(pkt_desc->size == pkt_desc->unwritten_size)
646 len -= pkt_desc->unwritten_size;
647 pkt_desc= pkt_desc->next;
653 /* flush the packet on stream stream_index */
654 static int flush_packet(AVFormatContext *ctx, int stream_index,
655 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
657 MpegMuxContext *s = ctx->priv_data;
658 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
660 int size, payload_size, startcode, id, stuffing_size, i, header_len;
663 int zero_trail_bytes = 0;
664 int pad_packet_bytes = 0;
666 int general_pack = 0; /*"general" pack without data specific to one stream?*/
671 av_dlog(ctx, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
675 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
676 /* output pack and systems header if needed */
677 size = put_pack_header(ctx, buf_ptr, scr);
682 /* there is exactly one system header for each stream in a VCD MPEG,
683 One in the very first video packet and one in the very first
684 audio packet (see VCD standard p. IV-7 and IV-8).*/
686 if (stream->packet_number==0) {
687 size = put_system_header(ctx, buf_ptr, id);
690 } else if (s->is_dvd) {
691 if (stream->align_iframe || s->packet_number == 0){
692 int PES_bytes_to_fill = s->packet_size - size - 10;
694 if (pts != AV_NOPTS_VALUE) {
696 PES_bytes_to_fill -= 5 + 5;
698 PES_bytes_to_fill -= 5;
701 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
702 size = put_system_header(ctx, buf_ptr, 0);
704 size = buf_ptr - buffer;
705 avio_write(ctx->pb, buffer, size);
707 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
708 avio_wb16(ctx->pb, 0x03d4); // length
709 avio_w8(ctx->pb, 0x00); // substream ID, 00=PCI
710 for (i = 0; i < 979; i++)
711 avio_w8(ctx->pb, 0x00);
713 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
714 avio_wb16(ctx->pb, 0x03fa); // length
715 avio_w8(ctx->pb, 0x01); // substream ID, 01=DSI
716 for (i = 0; i < 1017; i++)
717 avio_w8(ctx->pb, 0x00);
719 memset(buffer, 0, 128);
722 stream->align_iframe = 0;
723 scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
724 size = put_pack_header(ctx, buf_ptr, scr);
728 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
729 pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
733 if ((s->packet_number % s->system_header_freq) == 0) {
734 size = put_system_header(ctx, buf_ptr, 0);
739 size = buf_ptr - buffer;
740 avio_write(ctx->pb, buffer, size);
742 packet_size = s->packet_size - size;
744 if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
745 /* The VCD standard demands that 20 zero bytes follow
746 each audio pack (see standard p. IV-8).*/
747 zero_trail_bytes += 20;
749 if ((s->is_vcd && stream->packet_number==0)
750 || (s->is_svcd && s->packet_number==0)) {
751 /* for VCD the first pack of each stream contains only the pack header,
752 the system header and lots of padding (see VCD standard p. IV-6).
753 In the case of an audio pack, 20 zero bytes are also added at
755 /* For SVCD we fill the very first pack to increase compatibility with
756 some DVD players. Not mandated by the standard.*/
758 general_pack = 1; /* the system header refers to both streams and no stream data*/
759 pad_packet_bytes = packet_size - zero_trail_bytes;
762 packet_size -= pad_packet_bytes + zero_trail_bytes;
764 if (packet_size > 0) {
766 /* packet header size */
772 if (stream->packet_number==0)
773 header_len += 3; /* PES extension */
774 header_len += 1; /* obligatory stuffing byte */
778 if (pts != AV_NOPTS_VALUE) {
788 payload_size = packet_size - header_len;
790 startcode = PRIVATE_STREAM_1;
798 startcode = 0x100 + id;
801 stuffing_size = payload_size - av_fifo_size(stream->fifo);
803 // first byte does not fit -> reset pts/dts + stuffing
804 if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
808 if(pts != AV_NOPTS_VALUE)
809 timestamp_len += s->is_mpeg2 ? 5 : 4;
810 pts=dts= AV_NOPTS_VALUE;
811 header_len -= timestamp_len;
812 if (s->is_dvd && stream->align_iframe) {
813 pad_packet_bytes += timestamp_len;
814 packet_size -= timestamp_len;
816 payload_size += timestamp_len;
818 stuffing_size += timestamp_len;
819 if(payload_size > trailer_size)
820 stuffing_size += payload_size - trailer_size;
823 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
824 packet_size += pad_packet_bytes;
825 payload_size += pad_packet_bytes; // undo the previous adjustment
826 if (stuffing_size < 0) {
827 stuffing_size = pad_packet_bytes;
829 stuffing_size += pad_packet_bytes;
831 pad_packet_bytes = 0;
834 if (stuffing_size < 0)
836 if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
837 pad_packet_bytes += stuffing_size;
838 packet_size -= stuffing_size;
839 payload_size -= stuffing_size;
843 nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
845 avio_wb32(ctx->pb, startcode);
847 avio_wb16(ctx->pb, packet_size);
850 for(i=0;i<stuffing_size;i++)
851 avio_w8(ctx->pb, 0xff);
854 avio_w8(ctx->pb, 0x80); /* mpeg2 id */
858 if (pts != AV_NOPTS_VALUE) {
864 /* Both the MPEG-2 and the SVCD standards demand that the
865 P-STD_buffer_size field be included in the first packet of
866 every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
867 and MPEG-2 standard 2.7.7) */
868 if (stream->packet_number == 0)
871 avio_w8(ctx->pb, pes_flags); /* flags */
872 avio_w8(ctx->pb, header_len - 3 + stuffing_size);
874 if (pes_flags & 0x80) /*write pts*/
875 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
876 if (pes_flags & 0x40) /*write dts*/
877 put_timestamp(ctx->pb, 0x01, dts);
879 if (pes_flags & 0x01) { /*write pes extension*/
880 avio_w8(ctx->pb, 0x10); /* flags */
882 /* P-STD buffer info */
883 if ((id & 0xe0) == AUDIO_ID)
884 avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
886 avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
890 if (pts != AV_NOPTS_VALUE) {
892 put_timestamp(ctx->pb, 0x03, pts);
893 put_timestamp(ctx->pb, 0x01, dts);
895 put_timestamp(ctx->pb, 0x02, pts);
898 avio_w8(ctx->pb, 0x0f);
903 /* special stuffing byte that is always written
904 to prevent accidental generation of start codes. */
905 avio_w8(ctx->pb, 0xff);
907 for(i=0;i<stuffing_size;i++)
908 avio_w8(ctx->pb, 0xff);
911 if (startcode == PRIVATE_STREAM_1) {
912 avio_w8(ctx->pb, id);
914 /* LPCM (XXX: check nb_frames) */
916 avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
917 avio_w8(ctx->pb, stream->lpcm_header[0]);
918 avio_w8(ctx->pb, stream->lpcm_header[1]);
919 avio_w8(ctx->pb, stream->lpcm_header[2]);
920 } else if (id >= 0x40) {
922 avio_w8(ctx->pb, nb_frames);
923 avio_wb16(ctx->pb, trailer_size+1);
928 assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
929 av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, &avio_write);
930 stream->bytes_to_iframe -= payload_size - stuffing_size;
936 if (pad_packet_bytes > 0)
937 put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
939 for(i=0;i<zero_trail_bytes;i++)
940 avio_w8(ctx->pb, 0x00);
946 /* only increase the stream packet number if this pack actually contains
947 something that is specific to this stream! I.e. a dedicated header
950 stream->packet_number++;
952 return payload_size - stuffing_size;
955 static void put_vcd_padding_sector(AVFormatContext *ctx)
957 /* There are two ways to do this padding: writing a sector/pack
958 of 0 values, or writing an MPEG padding pack. Both seem to
959 work with most decoders, BUT the VCD standard only allows a 0-sector
960 (see standard p. IV-4, IV-5).
961 So a 0-sector it is...*/
963 MpegMuxContext *s = ctx->priv_data;
966 for(i=0;i<s->packet_size;i++)
969 s->vcd_padding_bytes_written += s->packet_size;
973 /* increasing the packet number is correct. The SCR of the following packs
974 is calculated from the packet_number and it has to include the padding
975 sector (it represents the sector index, not the MPEG pack index)
976 (see VCD standard p. IV-6)*/
980 #if 0 /* unused, remove? */
981 static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
983 MpegMuxContext *s = ctx->priv_data;
986 /* Since the data delivery rate is constant, SCR is computed
987 using the formula C + i * 1200 where C is the start constant
988 and i is the pack index.
989 It is recommended that SCR 0 is at the beginning of the VCD front
990 margin (a sequence of empty Form 2 sectors on the CD).
991 It is recommended that the front margin is 30 sectors long, so
992 we use C = 30*1200 = 36000
993 (Note that even if the front margin is not 30 sectors the file
994 will still be correct according to the standard. It just won't have
995 the "recommended" value).*/
996 scr = 36000 + s->packet_number * 1200;
1002 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
1003 // MpegMuxContext *s = ctx->priv_data;
1006 for(i=0; i<ctx->nb_streams; i++){
1007 AVStream *st = ctx->streams[i];
1008 StreamInfo *stream = st->priv_data;
1009 PacketDesc *pkt_desc;
1011 while((pkt_desc= stream->predecode_packet)
1012 && scr > pkt_desc->dts){ //FIXME > vs >=
1013 if(stream->buffer_index < pkt_desc->size ||
1014 stream->predecode_packet == stream->premux_packet){
1015 av_log(ctx, AV_LOG_ERROR,
1016 "buffer underflow i=%d bufi=%d size=%d\n",
1017 i, stream->buffer_index, pkt_desc->size);
1020 stream->buffer_index -= pkt_desc->size;
1022 stream->predecode_packet= pkt_desc->next;
1023 av_freep(&pkt_desc);
1030 static int output_packet(AVFormatContext *ctx, int flush){
1031 MpegMuxContext *s = ctx->priv_data;
1034 int i, avail_space=0, es_size, trailer_size;
1036 int best_score= INT_MIN;
1037 int ignore_constraints=0;
1038 int64_t scr= s->last_scr;
1039 PacketDesc *timestamp_packet;
1040 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1043 for(i=0; i<ctx->nb_streams; i++){
1044 AVStream *st = ctx->streams[i];
1045 StreamInfo *stream = st->priv_data;
1046 const int avail_data= av_fifo_size(stream->fifo);
1047 const int space= stream->max_buffer_size - stream->buffer_index;
1048 int rel_space= 1024*space / stream->max_buffer_size;
1049 PacketDesc *next_pkt= stream->premux_packet;
1051 /* for subtitle, a single PES packet must be generated,
1052 so we flush after every single subtitle packet */
1053 if(s->packet_size > avail_data && !flush
1054 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
1058 assert(avail_data>0);
1060 if(space < s->packet_size && !ignore_constraints)
1063 if(next_pkt && next_pkt->dts - scr > max_delay)
1066 if(rel_space > best_score){
1067 best_score= rel_space;
1074 int64_t best_dts= INT64_MAX;
1076 for(i=0; i<ctx->nb_streams; i++){
1077 AVStream *st = ctx->streams[i];
1078 StreamInfo *stream = st->priv_data;
1079 PacketDesc *pkt_desc= stream->predecode_packet;
1080 if(pkt_desc && pkt_desc->dts < best_dts)
1081 best_dts= pkt_desc->dts;
1084 av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
1085 scr / 90000.0, best_dts / 90000.0);
1086 if(best_dts == INT64_MAX)
1089 if(scr >= best_dts+1 && !ignore_constraints){
1090 av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1091 ignore_constraints= 1;
1093 scr= FFMAX(best_dts+1, scr);
1094 if(remove_decoded_packets(ctx, scr) < 0)
1099 assert(best_i >= 0);
1101 st = ctx->streams[best_i];
1102 stream = st->priv_data;
1104 assert(av_fifo_size(stream->fifo) > 0);
1106 assert(avail_space >= s->packet_size || ignore_constraints);
1108 timestamp_packet= stream->premux_packet;
1109 if(timestamp_packet->unwritten_size == timestamp_packet->size){
1112 trailer_size= timestamp_packet->unwritten_size;
1113 timestamp_packet= timestamp_packet->next;
1116 if(timestamp_packet){
1117 //av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f scr:%f stream:%d\n", timestamp_packet->dts/90000.0, timestamp_packet->pts/90000.0, scr/90000.0, best_i);
1118 es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1120 assert(av_fifo_size(stream->fifo) == trailer_size);
1121 es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1125 /* Write one or more padding sectors, if necessary, to reach
1126 the constant overall bitrate.*/
1129 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1130 put_vcd_padding_sector(ctx);
1131 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1135 stream->buffer_index += es_size;
1136 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1138 while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1139 es_size -= stream->premux_packet->unwritten_size;
1140 stream->premux_packet= stream->premux_packet->next;
1143 stream->premux_packet->unwritten_size -= es_size;
1145 if(remove_decoded_packets(ctx, s->last_scr) < 0)
1151 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1153 MpegMuxContext *s = ctx->priv_data;
1154 int stream_index= pkt->stream_index;
1155 int size= pkt->size;
1156 uint8_t *buf= pkt->data;
1157 AVStream *st = ctx->streams[stream_index];
1158 StreamInfo *stream = st->priv_data;
1160 PacketDesc *pkt_desc;
1161 const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
1162 const int is_iframe = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (pkt->flags & AV_PKT_FLAG_KEY);
1167 if(pts != AV_NOPTS_VALUE) pts += 2*preload;
1168 if(dts != AV_NOPTS_VALUE){
1170 s->last_scr= dts + preload;
1174 //av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n", dts/90000.0, pts/90000.0, pkt->flags, pkt->stream_index, pts != AV_NOPTS_VALUE);
1175 if (!stream->premux_packet)
1176 stream->next_packet = &stream->premux_packet;
1177 *stream->next_packet=
1178 pkt_desc= av_mallocz(sizeof(PacketDesc));
1181 pkt_desc->unwritten_size=
1182 pkt_desc->size= size;
1183 if(!stream->predecode_packet)
1184 stream->predecode_packet= pkt_desc;
1185 stream->next_packet= &pkt_desc->next;
1187 if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1191 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1192 stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1193 stream->align_iframe = 1;
1194 stream->vobu_start_pts = pts;
1198 av_fifo_generic_write(stream->fifo, buf, size, NULL);
1201 int ret= output_packet(ctx, 0);
1207 static int mpeg_mux_end(AVFormatContext *ctx)
1209 // MpegMuxContext *s = ctx->priv_data;
1214 int ret= output_packet(ctx, 1);
1221 /* End header according to MPEG1 systems standard. We do not write
1222 it as it is usually not needed by decoders and because it
1223 complicates MPEG stream concatenation. */
1224 //avio_wb32(ctx->pb, ISO_11172_END_CODE);
1225 //avio_flush(ctx->pb);
1227 for(i=0;i<ctx->nb_streams;i++) {
1228 stream = ctx->streams[i]->priv_data;
1230 assert(av_fifo_size(stream->fifo) == 0);
1231 av_fifo_free(stream->fifo);
1236 #define OFFSET(x) offsetof(MpegMuxContext, x)
1237 #define E AV_OPT_FLAG_ENCODING_PARAM
1238 static const AVOption options[] = {
1239 { "muxrate", NULL, OFFSET(mux_rate), AV_OPT_TYPE_INT, {0}, 0, INT_MAX, E },
1243 #define MPEGENC_CLASS(flavor)\
1244 static const AVClass flavor ## _class = {\
1245 .class_name = #flavor " muxer",\
1246 .item_name = av_default_item_name,\
1247 .version = LIBAVUTIL_VERSION_INT,\
1251 #if CONFIG_MPEG1SYSTEM_MUXER
1253 AVOutputFormat ff_mpeg1system_muxer = {
1255 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 System format"),
1256 .mime_type = "video/mpeg",
1257 .extensions = "mpg,mpeg",
1258 .priv_data_size = sizeof(MpegMuxContext),
1259 .audio_codec = CODEC_ID_MP2,
1260 .video_codec = CODEC_ID_MPEG1VIDEO,
1261 .write_header = mpeg_mux_init,
1262 .write_packet = mpeg_mux_write_packet,
1263 .write_trailer = mpeg_mux_end,
1264 .priv_class = &mpeg_class,
1267 #if CONFIG_MPEG1VCD_MUXER
1269 AVOutputFormat ff_mpeg1vcd_muxer = {
1271 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 System format (VCD)"),
1272 .mime_type = "video/mpeg",
1273 .priv_data_size = sizeof(MpegMuxContext),
1274 .audio_codec = CODEC_ID_MP2,
1275 .video_codec = CODEC_ID_MPEG1VIDEO,
1276 .write_header = mpeg_mux_init,
1277 .write_packet = mpeg_mux_write_packet,
1278 .write_trailer = mpeg_mux_end,
1279 .priv_class = &vcd_class,
1282 #if CONFIG_MPEG2VOB_MUXER
1284 AVOutputFormat ff_mpeg2vob_muxer = {
1286 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1287 .mime_type = "video/mpeg",
1288 .extensions = "vob",
1289 .priv_data_size = sizeof(MpegMuxContext),
1290 .audio_codec = CODEC_ID_MP2,
1291 .video_codec = CODEC_ID_MPEG2VIDEO,
1292 .write_header = mpeg_mux_init,
1293 .write_packet = mpeg_mux_write_packet,
1294 .write_trailer = mpeg_mux_end,
1295 .priv_class = &vob_class,
1299 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1300 #if CONFIG_MPEG2SVCD_MUXER
1302 AVOutputFormat ff_mpeg2svcd_muxer = {
1304 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1305 .mime_type = "video/mpeg",
1306 .extensions = "vob",
1307 .priv_data_size = sizeof(MpegMuxContext),
1308 .audio_codec = CODEC_ID_MP2,
1309 .video_codec = CODEC_ID_MPEG2VIDEO,
1310 .write_header = mpeg_mux_init,
1311 .write_packet = mpeg_mux_write_packet,
1312 .write_trailer = mpeg_mux_end,
1313 .priv_class = &svcd_class,
1317 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1318 #if CONFIG_MPEG2DVD_MUXER
1320 AVOutputFormat ff_mpeg2dvd_muxer = {
1322 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (DVD VOB)"),
1323 .mime_type = "video/mpeg",
1324 .extensions = "dvd",
1325 .priv_data_size = sizeof(MpegMuxContext),
1326 .audio_codec = CODEC_ID_MP2,
1327 .video_codec = CODEC_ID_MPEG2VIDEO,
1328 .write_header = mpeg_mux_init,
1329 .write_packet = mpeg_mux_write_packet,
1330 .write_trailer = mpeg_mux_end,
1331 .priv_class = &dvd_class,