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
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"
31 #define MAX_PAYLOAD_SIZE 4096
36 typedef struct PacketDesc {
42 struct PacketDesc *next;
48 int max_buffer_size; /* in bytes */
50 PacketDesc *predecode_packet;
51 PacketDesc *premux_packet;
52 PacketDesc **next_packet;
54 uint8_t lpcm_header[3];
58 int64_t vobu_start_pts;
63 int packet_size; /* required packet size */
65 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
66 int system_header_freq;
67 int system_header_size;
68 int mux_rate; /* bitrate in units of 50 bytes/s */
76 int64_t last_scr; /* current system clock */
78 double vcd_padding_bitrate; //FIXME floats
79 int64_t vcd_padding_bytes_written;
84 extern AVOutputFormat ff_mpeg1vcd_muxer;
85 extern AVOutputFormat ff_mpeg2dvd_muxer;
86 extern AVOutputFormat ff_mpeg2svcd_muxer;
87 extern AVOutputFormat ff_mpeg2vob_muxer;
89 static int put_pack_header(AVFormatContext *ctx,
90 uint8_t *buf, int64_t timestamp)
92 MpegMuxContext *s = ctx->priv_data;
95 init_put_bits(&pb, buf, 128);
97 put_bits32(&pb, PACK_START_CODE);
99 put_bits(&pb, 2, 0x1);
101 put_bits(&pb, 4, 0x2);
103 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
105 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
107 put_bits(&pb, 15, (uint32_t)((timestamp ) & 0x7fff));
110 /* clock extension */
114 put_bits(&pb, 22, s->mux_rate);
118 put_bits(&pb, 5, 0x1f); /* reserved */
119 put_bits(&pb, 3, 0); /* stuffing length */
122 return put_bits_ptr(&pb) - pb.buf;
125 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
127 MpegMuxContext *s = ctx->priv_data;
128 int size, i, private_stream_coded, id;
131 init_put_bits(&pb, buf, 128);
133 put_bits32(&pb, SYSTEM_HEADER_START_CODE);
134 put_bits(&pb, 16, 0);
137 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
138 put_bits(&pb, 1, 1); /* marker */
139 if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
140 /* This header applies only to the video stream (see VCD standard p. IV-7)*/
143 put_bits(&pb, 6, s->audio_bound);
146 /* see VCD standard, p. IV-7*/
150 put_bits(&pb, 1, 0); /* variable bitrate*/
151 put_bits(&pb, 1, 0); /* non constrainted bit stream */
154 if (s->is_vcd || s->is_dvd) {
155 /* see VCD standard p IV-7 */
156 put_bits(&pb, 1, 1); /* audio locked */
157 put_bits(&pb, 1, 1); /* video locked */
159 put_bits(&pb, 1, 0); /* audio locked */
160 put_bits(&pb, 1, 0); /* video locked */
163 put_bits(&pb, 1, 1); /* marker */
165 if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
166 /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
169 put_bits(&pb, 5, s->video_bound);
172 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
173 put_bits(&pb, 7, 0x7f); /* reserved byte */
175 put_bits(&pb, 8, 0xff); /* reserved byte */
177 /* DVD-Video Stream_bound entries
178 id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
179 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)
180 id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
181 id (0xBF) private stream 2, NAV packs, set to 2x1024. */
184 int P_STD_max_video = 0;
185 int P_STD_max_mpeg_audio = 0;
186 int P_STD_max_mpeg_PS1 = 0;
188 for(i=0;i<ctx->nb_streams;i++) {
189 StreamInfo *stream = ctx->streams[i]->priv_data;
192 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
193 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
194 } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
195 P_STD_max_mpeg_audio = stream->max_buffer_size;
196 } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
197 P_STD_max_video = stream->max_buffer_size;
202 put_bits(&pb, 8, 0xb9); /* stream ID */
205 put_bits(&pb, 13, P_STD_max_video / 1024);
208 if (P_STD_max_mpeg_audio == 0)
209 P_STD_max_mpeg_audio = 4096;
210 put_bits(&pb, 8, 0xb8); /* stream ID */
213 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
215 /* private stream 1 */
216 put_bits(&pb, 8, 0xbd); /* stream ID */
219 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
221 /* private stream 2 */
222 put_bits(&pb, 8, 0xbf); /* stream ID */
225 put_bits(&pb, 13, 2);
228 /* audio stream info */
229 private_stream_coded = 0;
230 for(i=0;i<ctx->nb_streams;i++) {
231 StreamInfo *stream = ctx->streams[i]->priv_data;
234 /* For VCDs, only include the stream info for the stream
235 that the pack which contains this system belongs to.
236 (see VCD standard p. IV-7) */
237 if ( !s->is_vcd || stream->id==only_for_stream_id
238 || only_for_stream_id==0) {
242 /* special case for private streams (AC-3 uses that) */
243 if (private_stream_coded)
245 private_stream_coded = 1;
248 put_bits(&pb, 8, id); /* stream ID */
253 put_bits(&pb, 13, stream->max_buffer_size / 128);
257 put_bits(&pb, 13, stream->max_buffer_size / 1024);
264 size = put_bits_ptr(&pb) - pb.buf;
265 /* patch packet size */
266 buf[4] = (size - 6) >> 8;
267 buf[5] = (size - 6) & 0xff;
272 static int get_system_header_size(AVFormatContext *ctx)
274 int buf_index, i, private_stream_coded;
276 MpegMuxContext *s = ctx->priv_data;
279 return 18; // DVD-Video system headers are 18 bytes fixed length.
282 private_stream_coded = 0;
283 for(i=0;i<ctx->nb_streams;i++) {
284 stream = ctx->streams[i]->priv_data;
285 if (stream->id < 0xc0) {
286 if (private_stream_coded)
288 private_stream_coded = 1;
295 static int mpeg_mux_init(AVFormatContext *ctx)
297 MpegMuxContext *s = ctx->priv_data;
298 int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
304 s->packet_number = 0;
305 s->is_vcd = (CONFIG_MPEG1VCD_MUXER && ctx->oformat == &ff_mpeg1vcd_muxer);
306 s->is_svcd = (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
307 s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER && ctx->oformat == &ff_mpeg2vob_muxer) ||
308 (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer) ||
309 (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
310 s->is_dvd = (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer);
312 if(ctx->packet_size) {
313 if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
314 av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
318 s->packet_size = ctx->packet_size;
320 s->packet_size = 2048;
322 s->vcd_padding_bytes_written = 0;
323 s->vcd_padding_bitrate=0;
333 for(i=0;i<ctx->nb_streams;i++) {
334 st = ctx->streams[i];
335 stream = av_mallocz(sizeof(StreamInfo));
338 st->priv_data = stream;
340 avpriv_set_pts_info(st, 64, 1, 90000);
342 switch(st->codec->codec_type) {
343 case AVMEDIA_TYPE_AUDIO:
344 if (st->codec->codec_id == CODEC_ID_AC3) {
345 stream->id = ac3_id++;
346 } else if (st->codec->codec_id == CODEC_ID_DTS) {
347 stream->id = dts_id++;
348 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
349 stream->id = lpcm_id++;
350 for(j = 0; j < 4; j++) {
351 if (lpcm_freq_tab[j] == st->codec->sample_rate)
356 if (st->codec->channels > 8)
358 stream->lpcm_header[0] = 0x0c;
359 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
360 stream->lpcm_header[2] = 0x80;
361 stream->lpcm_align = st->codec->channels * 2;
363 stream->id = mpa_id++;
366 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
367 Right now it is also used for everything else.*/
368 stream->max_buffer_size = 4 * 1024;
371 case AVMEDIA_TYPE_VIDEO:
372 stream->id = mpv_id++;
373 if (st->codec->rc_buffer_size)
374 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
376 av_log(ctx, AV_LOG_WARNING, "VBV buffer size not set, muxing may fail\n");
377 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
380 /* see VCD standard, p. IV-7*/
381 stream->max_buffer_size = 46 * 1024;
383 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
384 Right now it is also used for everything else.*/
385 stream->max_buffer_size = 230 * 1024;
389 case AVMEDIA_TYPE_SUBTITLE:
390 stream->id = mps_id++;
391 stream->max_buffer_size = 16 * 1024;
396 stream->fifo= av_fifo_alloc(16);
403 for(i=0;i<ctx->nb_streams;i++) {
405 st = ctx->streams[i];
406 stream = (StreamInfo*) st->priv_data;
408 if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
409 codec_rate= st->codec->rc_max_rate;
411 codec_rate= st->codec->bit_rate;
414 codec_rate= (1<<21)*8*50/ctx->nb_streams;
416 bitrate += codec_rate;
418 if ((stream->id & 0xe0) == AUDIO_ID)
419 audio_bitrate += codec_rate;
420 else if (stream->id==VIDEO_ID)
421 video_bitrate += codec_rate;
426 s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
430 /* we increase slightly the bitrate to take into account the
431 headers. XXX: compute it exactly */
432 bitrate += bitrate*5/100;
434 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
438 double overhead_rate;
440 /* The VCD standard mandates that the mux_rate field is 3528
441 (see standard p. IV-6).
442 The value is actually "wrong", i.e. if you calculate
443 it using the normal formula and the 75 sectors per second transfer
444 rate you get a different value because the real pack size is 2324,
445 not 2352. But the standard explicitly specifies that the mux_rate
446 field in the header must have this value.*/
447 // s->mux_rate=2352 * 75 / 50; /* = 3528*/
449 /* The VCD standard states that the muxed stream must be
450 exactly 75 packs / second (the data rate of a single speed cdrom).
451 Since the video bitrate (probably 1150000 bits/sec) will be below
452 the theoretical maximum we have to add some padding packets
453 to make up for the lower data rate.
454 (cf. VCD standard p. IV-6 )*/
456 /* Add the header overhead to the data rate.
457 2279 data bytes per audio pack, 2294 data bytes per video pack*/
458 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
459 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
462 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
463 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
466 if (s->is_vcd || s->is_mpeg2)
468 s->pack_header_freq = 1;
470 /* every 2 seconds */
471 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
473 /* the above seems to make pack_header_freq zero sometimes */
474 if (s->pack_header_freq == 0)
475 s->pack_header_freq = 1;
478 /* every 200 packets. Need to look at the spec. */
479 s->system_header_freq = s->pack_header_freq * 40;
481 /* the standard mandates that there are only two system headers
482 in the whole file: one in the first packet of each stream.
483 (see standard p. IV-7 and IV-8) */
484 s->system_header_freq = 0x7fffffff;
486 s->system_header_freq = s->pack_header_freq * 5;
488 for(i=0;i<ctx->nb_streams;i++) {
489 stream = ctx->streams[i]->priv_data;
490 stream->packet_number = 0;
492 s->system_header_size = get_system_header_size(ctx);
496 for(i=0;i<ctx->nb_streams;i++) {
497 av_free(ctx->streams[i]->priv_data);
499 return AVERROR(ENOMEM);
502 static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
506 (((timestamp >> 30) & 0x07) << 1) |
508 avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
509 avio_wb16(pb, (uint16_t)((((timestamp ) & 0x7fff) << 1) | 1));
513 /* return the number of padding bytes that should be inserted into
514 the multiplexed stream.*/
515 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
517 MpegMuxContext *s = ctx->priv_data;
520 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
522 int64_t full_pad_bytes;
524 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
525 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
528 /* might happen if we have already padded to a later timestamp. This
529 can occur if another stream has already advanced further.*/
537 #if 0 /* unused, remove? */
538 /* return the exact available payload size for the next packet for
539 stream 'stream_index'. 'pts' and 'dts' are only used to know if
540 timestamps are needed in the packet header. */
541 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
542 int64_t pts, int64_t dts)
544 MpegMuxContext *s = ctx->priv_data;
548 stream = ctx->streams[stream_index]->priv_data;
551 if (((s->packet_number % s->pack_header_freq) == 0)) {
552 /* pack header size */
559 /* there is exactly one system header for each stream in a VCD MPEG,
560 One in the very first video packet and one in the very first
561 audio packet (see VCD standard p. IV-7 and IV-8).*/
563 if (stream->packet_number==0)
564 /* The system headers refer only to the stream they occur in,
565 so they have a constant size.*/
569 if ((s->packet_number % s->system_header_freq) == 0)
570 buf_index += s->system_header_size;
574 if ((s->is_vcd && stream->packet_number==0)
575 || (s->is_svcd && s->packet_number==0))
576 /* the first pack of each stream contains only the pack header,
577 the system header and some padding (see VCD standard p. IV-6)
578 Add the padding size, so that the actual payload becomes 0.*/
579 buf_index += s->packet_size - buf_index;
581 /* packet header size */
585 if (stream->packet_number==0)
586 buf_index += 3; /* PES extension */
587 buf_index += 1; /* obligatory stuffing byte */
589 if (pts != AV_NOPTS_VALUE) {
600 if (stream->id < 0xc0) {
601 /* AC-3/LPCM private data header */
603 if (stream->id >= 0xa0) {
606 /* NOTE: we round the payload size to an integer number of
608 n = (s->packet_size - buf_index) % stream->lpcm_align;
610 buf_index += (stream->lpcm_align - n);
614 if (s->is_vcd && (stream->id & 0xe0) == AUDIO_ID)
615 /* The VCD standard demands that 20 zero bytes follow
616 each audio packet (see standard p. IV-8).*/
619 return s->packet_size - buf_index;
623 /* Write an MPEG padding packet header. */
624 static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,int packet_bytes)
626 MpegMuxContext *s = ctx->priv_data;
629 avio_wb32(pb, PADDING_STREAM);
630 avio_wb16(pb, packet_bytes - 6);
637 for(i=0;i<packet_bytes;i++)
641 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
643 PacketDesc *pkt_desc= stream->premux_packet;
646 if(pkt_desc->size == pkt_desc->unwritten_size)
648 len -= pkt_desc->unwritten_size;
649 pkt_desc= pkt_desc->next;
655 /* flush the packet on stream stream_index */
656 static int flush_packet(AVFormatContext *ctx, int stream_index,
657 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
659 MpegMuxContext *s = ctx->priv_data;
660 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
662 int size, payload_size, startcode, id, stuffing_size, i, header_len;
665 int zero_trail_bytes = 0;
666 int pad_packet_bytes = 0;
668 int general_pack = 0; /*"general" pack without data specific to one stream?*/
673 av_dlog(ctx, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
677 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
678 /* output pack and systems header if needed */
679 size = put_pack_header(ctx, buf_ptr, scr);
684 /* there is exactly one system header for each stream in a VCD MPEG,
685 One in the very first video packet and one in the very first
686 audio packet (see VCD standard p. IV-7 and IV-8).*/
688 if (stream->packet_number==0) {
689 size = put_system_header(ctx, buf_ptr, id);
692 } else if (s->is_dvd) {
693 if (stream->align_iframe || s->packet_number == 0){
694 int PES_bytes_to_fill = s->packet_size - size - 10;
696 if (pts != AV_NOPTS_VALUE) {
698 PES_bytes_to_fill -= 5 + 5;
700 PES_bytes_to_fill -= 5;
703 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
704 size = put_system_header(ctx, buf_ptr, 0);
706 size = buf_ptr - buffer;
707 avio_write(ctx->pb, buffer, size);
709 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
710 avio_wb16(ctx->pb, 0x03d4); // length
711 avio_w8(ctx->pb, 0x00); // substream ID, 00=PCI
712 for (i = 0; i < 979; i++)
713 avio_w8(ctx->pb, 0x00);
715 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
716 avio_wb16(ctx->pb, 0x03fa); // length
717 avio_w8(ctx->pb, 0x01); // substream ID, 01=DSI
718 for (i = 0; i < 1017; i++)
719 avio_w8(ctx->pb, 0x00);
721 memset(buffer, 0, 128);
724 stream->align_iframe = 0;
725 scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
726 size = put_pack_header(ctx, buf_ptr, scr);
730 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
731 pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
735 if ((s->packet_number % s->system_header_freq) == 0) {
736 size = put_system_header(ctx, buf_ptr, 0);
741 size = buf_ptr - buffer;
742 avio_write(ctx->pb, buffer, size);
744 packet_size = s->packet_size - size;
746 if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
747 /* The VCD standard demands that 20 zero bytes follow
748 each audio pack (see standard p. IV-8).*/
749 zero_trail_bytes += 20;
751 if ((s->is_vcd && stream->packet_number==0)
752 || (s->is_svcd && s->packet_number==0)) {
753 /* for VCD the first pack of each stream contains only the pack header,
754 the system header and lots of padding (see VCD standard p. IV-6).
755 In the case of an audio pack, 20 zero bytes are also added at
757 /* For SVCD we fill the very first pack to increase compatibility with
758 some DVD players. Not mandated by the standard.*/
760 general_pack = 1; /* the system header refers to both streams and no stream data*/
761 pad_packet_bytes = packet_size - zero_trail_bytes;
764 packet_size -= pad_packet_bytes + zero_trail_bytes;
766 if (packet_size > 0) {
768 /* packet header size */
774 if (stream->packet_number==0)
775 header_len += 3; /* PES extension */
776 header_len += 1; /* obligatory stuffing byte */
780 if (pts != AV_NOPTS_VALUE) {
790 payload_size = packet_size - header_len;
792 startcode = PRIVATE_STREAM_1;
800 startcode = 0x100 + id;
803 stuffing_size = payload_size - av_fifo_size(stream->fifo);
805 // first byte does not fit -> reset pts/dts + stuffing
806 if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
810 if(pts != AV_NOPTS_VALUE)
811 timestamp_len += s->is_mpeg2 ? 5 : 4;
812 pts=dts= AV_NOPTS_VALUE;
813 header_len -= timestamp_len;
814 if (s->is_dvd && stream->align_iframe) {
815 pad_packet_bytes += timestamp_len;
816 packet_size -= timestamp_len;
818 payload_size += timestamp_len;
820 stuffing_size += timestamp_len;
821 if(payload_size > trailer_size)
822 stuffing_size += payload_size - trailer_size;
825 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
826 packet_size += pad_packet_bytes;
827 payload_size += pad_packet_bytes; // undo the previous adjustment
828 if (stuffing_size < 0) {
829 stuffing_size = pad_packet_bytes;
831 stuffing_size += pad_packet_bytes;
833 pad_packet_bytes = 0;
836 if (stuffing_size < 0)
838 if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
839 pad_packet_bytes += stuffing_size;
840 packet_size -= stuffing_size;
841 payload_size -= stuffing_size;
845 nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
847 avio_wb32(ctx->pb, startcode);
849 avio_wb16(ctx->pb, packet_size);
852 for(i=0;i<stuffing_size;i++)
853 avio_w8(ctx->pb, 0xff);
856 avio_w8(ctx->pb, 0x80); /* mpeg2 id */
860 if (pts != AV_NOPTS_VALUE) {
866 /* Both the MPEG-2 and the SVCD standards demand that the
867 P-STD_buffer_size field be included in the first packet of
868 every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
869 and MPEG-2 standard 2.7.7) */
870 if (stream->packet_number == 0)
873 avio_w8(ctx->pb, pes_flags); /* flags */
874 avio_w8(ctx->pb, header_len - 3 + stuffing_size);
876 if (pes_flags & 0x80) /*write pts*/
877 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
878 if (pes_flags & 0x40) /*write dts*/
879 put_timestamp(ctx->pb, 0x01, dts);
881 if (pes_flags & 0x01) { /*write pes extension*/
882 avio_w8(ctx->pb, 0x10); /* flags */
884 /* P-STD buffer info */
885 if ((id & 0xe0) == AUDIO_ID)
886 avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
888 avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
892 if (pts != AV_NOPTS_VALUE) {
894 put_timestamp(ctx->pb, 0x03, pts);
895 put_timestamp(ctx->pb, 0x01, dts);
897 put_timestamp(ctx->pb, 0x02, pts);
900 avio_w8(ctx->pb, 0x0f);
905 /* special stuffing byte that is always written
906 to prevent accidental generation of start codes. */
907 avio_w8(ctx->pb, 0xff);
909 for(i=0;i<stuffing_size;i++)
910 avio_w8(ctx->pb, 0xff);
913 if (startcode == PRIVATE_STREAM_1) {
914 avio_w8(ctx->pb, id);
916 /* LPCM (XXX: check nb_frames) */
918 avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
919 avio_w8(ctx->pb, stream->lpcm_header[0]);
920 avio_w8(ctx->pb, stream->lpcm_header[1]);
921 avio_w8(ctx->pb, stream->lpcm_header[2]);
922 } else if (id >= 0x40) {
924 avio_w8(ctx->pb, nb_frames);
925 avio_wb16(ctx->pb, trailer_size+1);
930 assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
931 av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, (void*)avio_write);
932 stream->bytes_to_iframe -= payload_size - stuffing_size;
938 if (pad_packet_bytes > 0)
939 put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
941 for(i=0;i<zero_trail_bytes;i++)
942 avio_w8(ctx->pb, 0x00);
948 /* only increase the stream packet number if this pack actually contains
949 something that is specific to this stream! I.e. a dedicated header
952 stream->packet_number++;
954 return payload_size - stuffing_size;
957 static void put_vcd_padding_sector(AVFormatContext *ctx)
959 /* There are two ways to do this padding: writing a sector/pack
960 of 0 values, or writing an MPEG padding pack. Both seem to
961 work with most decoders, BUT the VCD standard only allows a 0-sector
962 (see standard p. IV-4, IV-5).
963 So a 0-sector it is...*/
965 MpegMuxContext *s = ctx->priv_data;
968 for(i=0;i<s->packet_size;i++)
971 s->vcd_padding_bytes_written += s->packet_size;
975 /* increasing the packet number is correct. The SCR of the following packs
976 is calculated from the packet_number and it has to include the padding
977 sector (it represents the sector index, not the MPEG pack index)
978 (see VCD standard p. IV-6)*/
982 #if 0 /* unused, remove? */
983 static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
985 MpegMuxContext *s = ctx->priv_data;
988 /* Since the data delivery rate is constant, SCR is computed
989 using the formula C + i * 1200 where C is the start constant
990 and i is the pack index.
991 It is recommended that SCR 0 is at the beginning of the VCD front
992 margin (a sequence of empty Form 2 sectors on the CD).
993 It is recommended that the front margin is 30 sectors long, so
994 we use C = 30*1200 = 36000
995 (Note that even if the front margin is not 30 sectors the file
996 will still be correct according to the standard. It just won't have
997 the "recommended" value).*/
998 scr = 36000 + s->packet_number * 1200;
1004 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
1005 // MpegMuxContext *s = ctx->priv_data;
1008 for(i=0; i<ctx->nb_streams; i++){
1009 AVStream *st = ctx->streams[i];
1010 StreamInfo *stream = st->priv_data;
1011 PacketDesc *pkt_desc;
1013 while((pkt_desc= stream->predecode_packet)
1014 && scr > pkt_desc->dts){ //FIXME > vs >=
1015 if(stream->buffer_index < pkt_desc->size ||
1016 stream->predecode_packet == stream->premux_packet){
1017 av_log(ctx, AV_LOG_ERROR,
1018 "buffer underflow i=%d bufi=%d size=%d\n",
1019 i, stream->buffer_index, pkt_desc->size);
1022 stream->buffer_index -= pkt_desc->size;
1024 stream->predecode_packet= pkt_desc->next;
1025 av_freep(&pkt_desc);
1032 static int output_packet(AVFormatContext *ctx, int flush){
1033 MpegMuxContext *s = ctx->priv_data;
1036 int i, avail_space=0, es_size, trailer_size;
1038 int best_score= INT_MIN;
1039 int ignore_constraints=0;
1040 int64_t scr= s->last_scr;
1041 PacketDesc *timestamp_packet;
1042 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1045 for(i=0; i<ctx->nb_streams; i++){
1046 AVStream *st = ctx->streams[i];
1047 StreamInfo *stream = st->priv_data;
1048 const int avail_data= av_fifo_size(stream->fifo);
1049 const int space= stream->max_buffer_size - stream->buffer_index;
1050 int rel_space= 1024*space / stream->max_buffer_size;
1051 PacketDesc *next_pkt= stream->premux_packet;
1053 /* for subtitle, a single PES packet must be generated,
1054 so we flush after every single subtitle packet */
1055 if(s->packet_size > avail_data && !flush
1056 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
1060 assert(avail_data>0);
1062 if(space < s->packet_size && !ignore_constraints)
1065 if(next_pkt && next_pkt->dts - scr > max_delay)
1068 if(rel_space > best_score){
1069 best_score= rel_space;
1076 int64_t best_dts= INT64_MAX;
1078 for(i=0; i<ctx->nb_streams; i++){
1079 AVStream *st = ctx->streams[i];
1080 StreamInfo *stream = st->priv_data;
1081 PacketDesc *pkt_desc= stream->predecode_packet;
1082 if(pkt_desc && pkt_desc->dts < best_dts)
1083 best_dts= pkt_desc->dts;
1086 av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
1087 scr / 90000.0, best_dts / 90000.0);
1088 if(best_dts == INT64_MAX)
1091 if(scr >= best_dts+1 && !ignore_constraints){
1092 av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1093 ignore_constraints= 1;
1095 scr= FFMAX(best_dts+1, scr);
1096 if(remove_decoded_packets(ctx, scr) < 0)
1101 assert(best_i >= 0);
1103 st = ctx->streams[best_i];
1104 stream = st->priv_data;
1106 assert(av_fifo_size(stream->fifo) > 0);
1108 assert(avail_space >= s->packet_size || ignore_constraints);
1110 timestamp_packet= stream->premux_packet;
1111 if(timestamp_packet->unwritten_size == timestamp_packet->size){
1114 trailer_size= timestamp_packet->unwritten_size;
1115 timestamp_packet= timestamp_packet->next;
1118 if(timestamp_packet){
1119 //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);
1120 es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1122 assert(av_fifo_size(stream->fifo) == trailer_size);
1123 es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1127 /* Write one or more padding sectors, if necessary, to reach
1128 the constant overall bitrate.*/
1131 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1132 put_vcd_padding_sector(ctx);
1133 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1137 stream->buffer_index += es_size;
1138 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1140 while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1141 es_size -= stream->premux_packet->unwritten_size;
1142 stream->premux_packet= stream->premux_packet->next;
1145 stream->premux_packet->unwritten_size -= es_size;
1147 if(remove_decoded_packets(ctx, s->last_scr) < 0)
1153 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1155 MpegMuxContext *s = ctx->priv_data;
1156 int stream_index= pkt->stream_index;
1157 int size= pkt->size;
1158 uint8_t *buf= pkt->data;
1159 AVStream *st = ctx->streams[stream_index];
1160 StreamInfo *stream = st->priv_data;
1162 PacketDesc *pkt_desc;
1164 const int is_iframe = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (pkt->flags & AV_PKT_FLAG_KEY);
1168 s->preload = ctx->preload;
1170 preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1175 if(pts != AV_NOPTS_VALUE) pts += 2*preload;
1176 if(dts != AV_NOPTS_VALUE){
1178 s->last_scr= dts + preload;
1182 //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);
1183 if (!stream->premux_packet)
1184 stream->next_packet = &stream->premux_packet;
1185 *stream->next_packet=
1186 pkt_desc= av_mallocz(sizeof(PacketDesc));
1189 pkt_desc->unwritten_size=
1190 pkt_desc->size= size;
1191 if(!stream->predecode_packet)
1192 stream->predecode_packet= pkt_desc;
1193 stream->next_packet= &pkt_desc->next;
1195 if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1199 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1200 stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1201 stream->align_iframe = 1;
1202 stream->vobu_start_pts = pts;
1206 av_fifo_generic_write(stream->fifo, buf, size, NULL);
1209 int ret= output_packet(ctx, 0);
1215 static int mpeg_mux_end(AVFormatContext *ctx)
1217 // MpegMuxContext *s = ctx->priv_data;
1222 int ret= output_packet(ctx, 1);
1229 /* End header according to MPEG1 systems standard. We do not write
1230 it as it is usually not needed by decoders and because it
1231 complicates MPEG stream concatenation. */
1232 //avio_wb32(ctx->pb, ISO_11172_END_CODE);
1233 //avio_flush(ctx->pb);
1235 for(i=0;i<ctx->nb_streams;i++) {
1236 stream = ctx->streams[i]->priv_data;
1238 assert(av_fifo_size(stream->fifo) == 0);
1239 av_fifo_free(stream->fifo);
1244 #define OFFSET(x) offsetof(MpegMuxContext, x)
1245 #define E AV_OPT_FLAG_ENCODING_PARAM
1246 static const AVOption options[] = {
1247 { "muxrate", NULL, OFFSET(mux_rate), AV_OPT_TYPE_INT, {0}, 0, INT_MAX, E },
1248 { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload), AV_OPT_TYPE_INT, {500000}, 0, INT_MAX, E},
1252 #define MPEGENC_CLASS(flavor)\
1253 static const AVClass flavor ## _class = {\
1254 .class_name = #flavor " muxer",\
1255 .item_name = av_default_item_name,\
1256 .version = LIBAVUTIL_VERSION_INT,\
1260 #if CONFIG_MPEG1SYSTEM_MUXER
1262 AVOutputFormat ff_mpeg1system_muxer = {
1264 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 System format"),
1265 .mime_type = "video/mpeg",
1266 .extensions = "mpg,mpeg",
1267 .priv_data_size = sizeof(MpegMuxContext),
1268 .audio_codec = CODEC_ID_MP2,
1269 .video_codec = CODEC_ID_MPEG1VIDEO,
1270 .write_header = mpeg_mux_init,
1271 .write_packet = mpeg_mux_write_packet,
1272 .write_trailer = mpeg_mux_end,
1273 .priv_class = &mpeg_class,
1276 #if CONFIG_MPEG1VCD_MUXER
1278 AVOutputFormat ff_mpeg1vcd_muxer = {
1280 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 System format (VCD)"),
1281 .mime_type = "video/mpeg",
1282 .priv_data_size = sizeof(MpegMuxContext),
1283 .audio_codec = CODEC_ID_MP2,
1284 .video_codec = CODEC_ID_MPEG1VIDEO,
1285 .write_header = mpeg_mux_init,
1286 .write_packet = mpeg_mux_write_packet,
1287 .write_trailer = mpeg_mux_end,
1288 .priv_class = &vcd_class,
1291 #if CONFIG_MPEG2VOB_MUXER
1293 AVOutputFormat ff_mpeg2vob_muxer = {
1295 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1296 .mime_type = "video/mpeg",
1297 .extensions = "vob",
1298 .priv_data_size = sizeof(MpegMuxContext),
1299 .audio_codec = CODEC_ID_MP2,
1300 .video_codec = CODEC_ID_MPEG2VIDEO,
1301 .write_header = mpeg_mux_init,
1302 .write_packet = mpeg_mux_write_packet,
1303 .write_trailer = mpeg_mux_end,
1304 .priv_class = &vob_class,
1308 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1309 #if CONFIG_MPEG2SVCD_MUXER
1311 AVOutputFormat ff_mpeg2svcd_muxer = {
1313 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1314 .mime_type = "video/mpeg",
1315 .extensions = "vob",
1316 .priv_data_size = sizeof(MpegMuxContext),
1317 .audio_codec = CODEC_ID_MP2,
1318 .video_codec = CODEC_ID_MPEG2VIDEO,
1319 .write_header = mpeg_mux_init,
1320 .write_packet = mpeg_mux_write_packet,
1321 .write_trailer = mpeg_mux_end,
1322 .priv_class = &svcd_class,
1326 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1327 #if CONFIG_MPEG2DVD_MUXER
1329 AVOutputFormat ff_mpeg2dvd_muxer = {
1331 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (DVD VOB)"),
1332 .mime_type = "video/mpeg",
1333 .extensions = "dvd",
1334 .priv_data_size = sizeof(MpegMuxContext),
1335 .audio_codec = CODEC_ID_MP2,
1336 .video_codec = CODEC_ID_MPEG2VIDEO,
1337 .write_header = mpeg_mux_init,
1338 .write_packet = mpeg_mux_write_packet,
1339 .write_trailer = mpeg_mux_end,
1340 .priv_class = &dvd_class,