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;
83 extern AVOutputFormat ff_mpeg1vcd_muxer;
84 extern AVOutputFormat ff_mpeg2dvd_muxer;
85 extern AVOutputFormat ff_mpeg2svcd_muxer;
86 extern AVOutputFormat ff_mpeg2vob_muxer;
88 static int put_pack_header(AVFormatContext *ctx,
89 uint8_t *buf, int64_t timestamp)
91 MpegMuxContext *s = ctx->priv_data;
94 init_put_bits(&pb, buf, 128);
96 put_bits32(&pb, PACK_START_CODE);
98 put_bits(&pb, 2, 0x1);
100 put_bits(&pb, 4, 0x2);
102 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
104 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
106 put_bits(&pb, 15, (uint32_t)((timestamp ) & 0x7fff));
109 /* clock extension */
113 put_bits(&pb, 22, s->mux_rate);
117 put_bits(&pb, 5, 0x1f); /* reserved */
118 put_bits(&pb, 3, 0); /* stuffing length */
121 return put_bits_ptr(&pb) - pb.buf;
124 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
126 MpegMuxContext *s = ctx->priv_data;
127 int size, i, private_stream_coded, id;
130 init_put_bits(&pb, buf, 128);
132 put_bits32(&pb, SYSTEM_HEADER_START_CODE);
133 put_bits(&pb, 16, 0);
136 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
137 put_bits(&pb, 1, 1); /* marker */
138 if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
139 /* This header applies only to the video stream (see VCD standard p. IV-7)*/
142 put_bits(&pb, 6, s->audio_bound);
145 /* see VCD standard, p. IV-7*/
149 put_bits(&pb, 1, 0); /* variable bitrate*/
150 put_bits(&pb, 1, 0); /* non constrainted bit stream */
153 if (s->is_vcd || s->is_dvd) {
154 /* see VCD standard p IV-7 */
155 put_bits(&pb, 1, 1); /* audio locked */
156 put_bits(&pb, 1, 1); /* video locked */
158 put_bits(&pb, 1, 0); /* audio locked */
159 put_bits(&pb, 1, 0); /* video locked */
162 put_bits(&pb, 1, 1); /* marker */
164 if (s->is_vcd && (only_for_stream_id & 0xe0) == AUDIO_ID) {
165 /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
168 put_bits(&pb, 5, s->video_bound);
171 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
172 put_bits(&pb, 7, 0x7f); /* reserved byte */
174 put_bits(&pb, 8, 0xff); /* reserved byte */
176 /* DVD-Video Stream_bound entries
177 id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
178 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)
179 id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
180 id (0xBF) private stream 2, NAV packs, set to 2x1024. */
183 int P_STD_max_video = 0;
184 int P_STD_max_mpeg_audio = 0;
185 int P_STD_max_mpeg_PS1 = 0;
187 for(i=0;i<ctx->nb_streams;i++) {
188 StreamInfo *stream = ctx->streams[i]->priv_data;
191 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
192 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
193 } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
194 P_STD_max_mpeg_audio = stream->max_buffer_size;
195 } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
196 P_STD_max_video = stream->max_buffer_size;
201 put_bits(&pb, 8, 0xb9); /* stream ID */
204 put_bits(&pb, 13, P_STD_max_video / 1024);
207 if (P_STD_max_mpeg_audio == 0)
208 P_STD_max_mpeg_audio = 4096;
209 put_bits(&pb, 8, 0xb8); /* stream ID */
212 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
214 /* private stream 1 */
215 put_bits(&pb, 8, 0xbd); /* stream ID */
218 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
220 /* private stream 2 */
221 put_bits(&pb, 8, 0xbf); /* stream ID */
224 put_bits(&pb, 13, 2);
227 /* audio stream info */
228 private_stream_coded = 0;
229 for(i=0;i<ctx->nb_streams;i++) {
230 StreamInfo *stream = ctx->streams[i]->priv_data;
233 /* For VCDs, only include the stream info for the stream
234 that the pack which contains this system belongs to.
235 (see VCD standard p. IV-7) */
236 if ( !s->is_vcd || stream->id==only_for_stream_id
237 || only_for_stream_id==0) {
241 /* special case for private streams (AC-3 uses that) */
242 if (private_stream_coded)
244 private_stream_coded = 1;
247 put_bits(&pb, 8, id); /* stream ID */
252 put_bits(&pb, 13, stream->max_buffer_size / 128);
256 put_bits(&pb, 13, stream->max_buffer_size / 1024);
263 size = put_bits_ptr(&pb) - pb.buf;
264 /* patch packet size */
265 buf[4] = (size - 6) >> 8;
266 buf[5] = (size - 6) & 0xff;
271 static int get_system_header_size(AVFormatContext *ctx)
273 int buf_index, i, private_stream_coded;
275 MpegMuxContext *s = ctx->priv_data;
278 return 18; // DVD-Video system headers are 18 bytes fixed length.
281 private_stream_coded = 0;
282 for(i=0;i<ctx->nb_streams;i++) {
283 stream = ctx->streams[i]->priv_data;
284 if (stream->id < 0xc0) {
285 if (private_stream_coded)
287 private_stream_coded = 1;
294 static int mpeg_mux_init(AVFormatContext *ctx)
296 MpegMuxContext *s = ctx->priv_data;
297 int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
303 s->packet_number = 0;
304 s->is_vcd = (CONFIG_MPEG1VCD_MUXER && ctx->oformat == &ff_mpeg1vcd_muxer);
305 s->is_svcd = (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer);
306 s->is_mpeg2 = ((CONFIG_MPEG2VOB_MUXER && ctx->oformat == &ff_mpeg2vob_muxer) ||
307 (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer) ||
308 (CONFIG_MPEG2SVCD_MUXER && ctx->oformat == &ff_mpeg2svcd_muxer));
309 s->is_dvd = (CONFIG_MPEG2DVD_MUXER && ctx->oformat == &ff_mpeg2dvd_muxer);
311 if(ctx->packet_size) {
312 if (ctx->packet_size < 20 || ctx->packet_size > (1 << 23) + 10) {
313 av_log(ctx, AV_LOG_ERROR, "Invalid packet size %d\n",
317 s->packet_size = ctx->packet_size;
319 s->packet_size = 2048;
321 s->vcd_padding_bytes_written = 0;
322 s->vcd_padding_bitrate=0;
332 for(i=0;i<ctx->nb_streams;i++) {
333 st = ctx->streams[i];
334 stream = av_mallocz(sizeof(StreamInfo));
337 st->priv_data = stream;
339 av_set_pts_info(st, 64, 1, 90000);
341 switch(st->codec->codec_type) {
342 case AVMEDIA_TYPE_AUDIO:
343 if (st->codec->codec_id == CODEC_ID_AC3) {
344 stream->id = ac3_id++;
345 } else if (st->codec->codec_id == CODEC_ID_DTS) {
346 stream->id = dts_id++;
347 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
348 stream->id = lpcm_id++;
349 for(j = 0; j < 4; j++) {
350 if (lpcm_freq_tab[j] == st->codec->sample_rate)
355 if (st->codec->channels > 8)
357 stream->lpcm_header[0] = 0x0c;
358 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
359 stream->lpcm_header[2] = 0x80;
360 stream->lpcm_align = st->codec->channels * 2;
362 stream->id = mpa_id++;
365 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
366 Right now it is also used for everything else.*/
367 stream->max_buffer_size = 4 * 1024;
370 case AVMEDIA_TYPE_VIDEO:
371 stream->id = mpv_id++;
372 if (st->codec->rc_buffer_size)
373 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
375 av_log(ctx, AV_LOG_WARNING, "VBV buffer size not set, muxing may fail\n");
376 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
379 /* see VCD standard, p. IV-7*/
380 stream->max_buffer_size = 46 * 1024;
382 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
383 Right now it is also used for everything else.*/
384 stream->max_buffer_size = 230 * 1024;
388 case AVMEDIA_TYPE_SUBTITLE:
389 stream->id = mps_id++;
390 stream->max_buffer_size = 16 * 1024;
395 stream->fifo= av_fifo_alloc(16);
402 for(i=0;i<ctx->nb_streams;i++) {
404 st = ctx->streams[i];
405 stream = (StreamInfo*) st->priv_data;
407 if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
408 codec_rate= st->codec->rc_max_rate;
410 codec_rate= st->codec->bit_rate;
413 codec_rate= (1<<21)*8*50/ctx->nb_streams;
415 bitrate += codec_rate;
417 if ((stream->id & 0xe0) == AUDIO_ID)
418 audio_bitrate += codec_rate;
419 else if (stream->id==VIDEO_ID)
420 video_bitrate += codec_rate;
425 s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
429 /* we increase slightly the bitrate to take into account the
430 headers. XXX: compute it exactly */
431 bitrate += bitrate*5/100;
433 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
437 double overhead_rate;
439 /* The VCD standard mandates that the mux_rate field is 3528
440 (see standard p. IV-6).
441 The value is actually "wrong", i.e. if you calculate
442 it using the normal formula and the 75 sectors per second transfer
443 rate you get a different value because the real pack size is 2324,
444 not 2352. But the standard explicitly specifies that the mux_rate
445 field in the header must have this value.*/
446 // s->mux_rate=2352 * 75 / 50; /* = 3528*/
448 /* The VCD standard states that the muxed stream must be
449 exactly 75 packs / second (the data rate of a single speed cdrom).
450 Since the video bitrate (probably 1150000 bits/sec) will be below
451 the theoretical maximum we have to add some padding packets
452 to make up for the lower data rate.
453 (cf. VCD standard p. IV-6 )*/
455 /* Add the header overhead to the data rate.
456 2279 data bytes per audio pack, 2294 data bytes per video pack*/
457 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
458 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
461 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
462 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
465 if (s->is_vcd || s->is_mpeg2)
467 s->pack_header_freq = 1;
469 /* every 2 seconds */
470 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
472 /* the above seems to make pack_header_freq zero sometimes */
473 if (s->pack_header_freq == 0)
474 s->pack_header_freq = 1;
477 /* every 200 packets. Need to look at the spec. */
478 s->system_header_freq = s->pack_header_freq * 40;
480 /* the standard mandates that there are only two system headers
481 in the whole file: one in the first packet of each stream.
482 (see standard p. IV-7 and IV-8) */
483 s->system_header_freq = 0x7fffffff;
485 s->system_header_freq = s->pack_header_freq * 5;
487 for(i=0;i<ctx->nb_streams;i++) {
488 stream = ctx->streams[i]->priv_data;
489 stream->packet_number = 0;
491 s->system_header_size = get_system_header_size(ctx);
495 for(i=0;i<ctx->nb_streams;i++) {
496 av_free(ctx->streams[i]->priv_data);
498 return AVERROR(ENOMEM);
501 static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
505 (((timestamp >> 30) & 0x07) << 1) |
507 avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
508 avio_wb16(pb, (uint16_t)((((timestamp ) & 0x7fff) << 1) | 1));
512 /* return the number of padding bytes that should be inserted into
513 the multiplexed stream.*/
514 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
516 MpegMuxContext *s = ctx->priv_data;
519 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
521 int64_t full_pad_bytes;
523 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
524 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
527 /* might happen if we have already padded to a later timestamp. This
528 can occur if another stream has already advanced further.*/
536 #if 0 /* unused, remove? */
537 /* return the exact available payload size for the next packet for
538 stream 'stream_index'. 'pts' and 'dts' are only used to know if
539 timestamps are needed in the packet header. */
540 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
541 int64_t pts, int64_t dts)
543 MpegMuxContext *s = ctx->priv_data;
547 stream = ctx->streams[stream_index]->priv_data;
550 if (((s->packet_number % s->pack_header_freq) == 0)) {
551 /* pack header size */
558 /* there is exactly one system header for each stream in a VCD MPEG,
559 One in the very first video packet and one in the very first
560 audio packet (see VCD standard p. IV-7 and IV-8).*/
562 if (stream->packet_number==0)
563 /* The system headers refer only to the stream they occur in,
564 so they have a constant size.*/
568 if ((s->packet_number % s->system_header_freq) == 0)
569 buf_index += s->system_header_size;
573 if ((s->is_vcd && stream->packet_number==0)
574 || (s->is_svcd && s->packet_number==0))
575 /* the first pack of each stream contains only the pack header,
576 the system header and some padding (see VCD standard p. IV-6)
577 Add the padding size, so that the actual payload becomes 0.*/
578 buf_index += s->packet_size - buf_index;
580 /* packet header size */
584 if (stream->packet_number==0)
585 buf_index += 3; /* PES extension */
586 buf_index += 1; /* obligatory stuffing byte */
588 if (pts != AV_NOPTS_VALUE) {
599 if (stream->id < 0xc0) {
600 /* AC-3/LPCM private data header */
602 if (stream->id >= 0xa0) {
605 /* NOTE: we round the payload size to an integer number of
607 n = (s->packet_size - buf_index) % stream->lpcm_align;
609 buf_index += (stream->lpcm_align - n);
613 if (s->is_vcd && (stream->id & 0xe0) == AUDIO_ID)
614 /* The VCD standard demands that 20 zero bytes follow
615 each audio packet (see standard p. IV-8).*/
618 return s->packet_size - buf_index;
622 /* Write an MPEG padding packet header. */
623 static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,int packet_bytes)
625 MpegMuxContext *s = ctx->priv_data;
628 avio_wb32(pb, PADDING_STREAM);
629 avio_wb16(pb, packet_bytes - 6);
636 for(i=0;i<packet_bytes;i++)
640 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
642 PacketDesc *pkt_desc= stream->premux_packet;
645 if(pkt_desc->size == pkt_desc->unwritten_size)
647 len -= pkt_desc->unwritten_size;
648 pkt_desc= pkt_desc->next;
654 /* flush the packet on stream stream_index */
655 static int flush_packet(AVFormatContext *ctx, int stream_index,
656 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
658 MpegMuxContext *s = ctx->priv_data;
659 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
661 int size, payload_size, startcode, id, stuffing_size, i, header_len;
664 int zero_trail_bytes = 0;
665 int pad_packet_bytes = 0;
667 int general_pack = 0; /*"general" pack without data specific to one stream?*/
672 av_dlog(ctx, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
676 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
677 /* output pack and systems header if needed */
678 size = put_pack_header(ctx, buf_ptr, scr);
683 /* there is exactly one system header for each stream in a VCD MPEG,
684 One in the very first video packet and one in the very first
685 audio packet (see VCD standard p. IV-7 and IV-8).*/
687 if (stream->packet_number==0) {
688 size = put_system_header(ctx, buf_ptr, id);
691 } else if (s->is_dvd) {
692 if (stream->align_iframe || s->packet_number == 0){
693 int PES_bytes_to_fill = s->packet_size - size - 10;
695 if (pts != AV_NOPTS_VALUE) {
697 PES_bytes_to_fill -= 5 + 5;
699 PES_bytes_to_fill -= 5;
702 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
703 size = put_system_header(ctx, buf_ptr, 0);
705 size = buf_ptr - buffer;
706 avio_write(ctx->pb, buffer, size);
708 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
709 avio_wb16(ctx->pb, 0x03d4); // length
710 avio_w8(ctx->pb, 0x00); // substream ID, 00=PCI
711 for (i = 0; i < 979; i++)
712 avio_w8(ctx->pb, 0x00);
714 avio_wb32(ctx->pb, PRIVATE_STREAM_2);
715 avio_wb16(ctx->pb, 0x03fa); // length
716 avio_w8(ctx->pb, 0x01); // substream ID, 01=DSI
717 for (i = 0; i < 1017; i++)
718 avio_w8(ctx->pb, 0x00);
720 memset(buffer, 0, 128);
723 stream->align_iframe = 0;
724 scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
725 size = put_pack_header(ctx, buf_ptr, scr);
729 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
730 pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
734 if ((s->packet_number % s->system_header_freq) == 0) {
735 size = put_system_header(ctx, buf_ptr, 0);
740 size = buf_ptr - buffer;
741 avio_write(ctx->pb, buffer, size);
743 packet_size = s->packet_size - size;
745 if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
746 /* The VCD standard demands that 20 zero bytes follow
747 each audio pack (see standard p. IV-8).*/
748 zero_trail_bytes += 20;
750 if ((s->is_vcd && stream->packet_number==0)
751 || (s->is_svcd && s->packet_number==0)) {
752 /* for VCD the first pack of each stream contains only the pack header,
753 the system header and lots of padding (see VCD standard p. IV-6).
754 In the case of an audio pack, 20 zero bytes are also added at
756 /* For SVCD we fill the very first pack to increase compatibility with
757 some DVD players. Not mandated by the standard.*/
759 general_pack = 1; /* the system header refers to both streams and no stream data*/
760 pad_packet_bytes = packet_size - zero_trail_bytes;
763 packet_size -= pad_packet_bytes + zero_trail_bytes;
765 if (packet_size > 0) {
767 /* packet header size */
773 if (stream->packet_number==0)
774 header_len += 3; /* PES extension */
775 header_len += 1; /* obligatory stuffing byte */
779 if (pts != AV_NOPTS_VALUE) {
789 payload_size = packet_size - header_len;
791 startcode = PRIVATE_STREAM_1;
799 startcode = 0x100 + id;
802 stuffing_size = payload_size - av_fifo_size(stream->fifo);
804 // first byte does not fit -> reset pts/dts + stuffing
805 if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
809 if(pts != AV_NOPTS_VALUE)
810 timestamp_len += s->is_mpeg2 ? 5 : 4;
811 pts=dts= AV_NOPTS_VALUE;
812 header_len -= timestamp_len;
813 if (s->is_dvd && stream->align_iframe) {
814 pad_packet_bytes += timestamp_len;
815 packet_size -= timestamp_len;
817 payload_size += timestamp_len;
819 stuffing_size += timestamp_len;
820 if(payload_size > trailer_size)
821 stuffing_size += payload_size - trailer_size;
824 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
825 packet_size += pad_packet_bytes;
826 payload_size += pad_packet_bytes; // undo the previous adjustment
827 if (stuffing_size < 0) {
828 stuffing_size = pad_packet_bytes;
830 stuffing_size += pad_packet_bytes;
832 pad_packet_bytes = 0;
835 if (stuffing_size < 0)
837 if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
838 pad_packet_bytes += stuffing_size;
839 packet_size -= stuffing_size;
840 payload_size -= stuffing_size;
844 nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
846 avio_wb32(ctx->pb, startcode);
848 avio_wb16(ctx->pb, packet_size);
851 for(i=0;i<stuffing_size;i++)
852 avio_w8(ctx->pb, 0xff);
855 avio_w8(ctx->pb, 0x80); /* mpeg2 id */
859 if (pts != AV_NOPTS_VALUE) {
865 /* Both the MPEG-2 and the SVCD standards demand that the
866 P-STD_buffer_size field be included in the first packet of
867 every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
868 and MPEG-2 standard 2.7.7) */
869 if (stream->packet_number == 0)
872 avio_w8(ctx->pb, pes_flags); /* flags */
873 avio_w8(ctx->pb, header_len - 3 + stuffing_size);
875 if (pes_flags & 0x80) /*write pts*/
876 put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
877 if (pes_flags & 0x40) /*write dts*/
878 put_timestamp(ctx->pb, 0x01, dts);
880 if (pes_flags & 0x01) { /*write pes extension*/
881 avio_w8(ctx->pb, 0x10); /* flags */
883 /* P-STD buffer info */
884 if ((id & 0xe0) == AUDIO_ID)
885 avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
887 avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
891 if (pts != AV_NOPTS_VALUE) {
893 put_timestamp(ctx->pb, 0x03, pts);
894 put_timestamp(ctx->pb, 0x01, dts);
896 put_timestamp(ctx->pb, 0x02, pts);
899 avio_w8(ctx->pb, 0x0f);
904 /* special stuffing byte that is always written
905 to prevent accidental generation of start codes. */
906 avio_w8(ctx->pb, 0xff);
908 for(i=0;i<stuffing_size;i++)
909 avio_w8(ctx->pb, 0xff);
912 if (startcode == PRIVATE_STREAM_1) {
913 avio_w8(ctx->pb, id);
915 /* LPCM (XXX: check nb_frames) */
917 avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
918 avio_w8(ctx->pb, stream->lpcm_header[0]);
919 avio_w8(ctx->pb, stream->lpcm_header[1]);
920 avio_w8(ctx->pb, stream->lpcm_header[2]);
921 } else if (id >= 0x40) {
923 avio_w8(ctx->pb, nb_frames);
924 avio_wb16(ctx->pb, trailer_size+1);
929 assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
930 av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, &avio_write);
931 stream->bytes_to_iframe -= payload_size - stuffing_size;
937 if (pad_packet_bytes > 0)
938 put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
940 for(i=0;i<zero_trail_bytes;i++)
941 avio_w8(ctx->pb, 0x00);
947 /* only increase the stream packet number if this pack actually contains
948 something that is specific to this stream! I.e. a dedicated header
951 stream->packet_number++;
953 return payload_size - stuffing_size;
956 static void put_vcd_padding_sector(AVFormatContext *ctx)
958 /* There are two ways to do this padding: writing a sector/pack
959 of 0 values, or writing an MPEG padding pack. Both seem to
960 work with most decoders, BUT the VCD standard only allows a 0-sector
961 (see standard p. IV-4, IV-5).
962 So a 0-sector it is...*/
964 MpegMuxContext *s = ctx->priv_data;
967 for(i=0;i<s->packet_size;i++)
970 s->vcd_padding_bytes_written += s->packet_size;
974 /* increasing the packet number is correct. The SCR of the following packs
975 is calculated from the packet_number and it has to include the padding
976 sector (it represents the sector index, not the MPEG pack index)
977 (see VCD standard p. IV-6)*/
981 #if 0 /* unused, remove? */
982 static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
984 MpegMuxContext *s = ctx->priv_data;
987 /* Since the data delivery rate is constant, SCR is computed
988 using the formula C + i * 1200 where C is the start constant
989 and i is the pack index.
990 It is recommended that SCR 0 is at the beginning of the VCD front
991 margin (a sequence of empty Form 2 sectors on the CD).
992 It is recommended that the front margin is 30 sectors long, so
993 we use C = 30*1200 = 36000
994 (Note that even if the front margin is not 30 sectors the file
995 will still be correct according to the standard. It just won't have
996 the "recommended" value).*/
997 scr = 36000 + s->packet_number * 1200;
1003 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
1004 // MpegMuxContext *s = ctx->priv_data;
1007 for(i=0; i<ctx->nb_streams; i++){
1008 AVStream *st = ctx->streams[i];
1009 StreamInfo *stream = st->priv_data;
1010 PacketDesc *pkt_desc;
1012 while((pkt_desc= stream->predecode_packet)
1013 && scr > pkt_desc->dts){ //FIXME > vs >=
1014 if(stream->buffer_index < pkt_desc->size ||
1015 stream->predecode_packet == stream->premux_packet){
1016 av_log(ctx, AV_LOG_ERROR,
1017 "buffer underflow i=%d bufi=%d size=%d\n",
1018 i, stream->buffer_index, pkt_desc->size);
1021 stream->buffer_index -= pkt_desc->size;
1023 stream->predecode_packet= pkt_desc->next;
1024 av_freep(&pkt_desc);
1031 static int output_packet(AVFormatContext *ctx, int flush){
1032 MpegMuxContext *s = ctx->priv_data;
1035 int i, avail_space=0, es_size, trailer_size;
1037 int best_score= INT_MIN;
1038 int ignore_constraints=0;
1039 int64_t scr= s->last_scr;
1040 PacketDesc *timestamp_packet;
1041 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1044 for(i=0; i<ctx->nb_streams; i++){
1045 AVStream *st = ctx->streams[i];
1046 StreamInfo *stream = st->priv_data;
1047 const int avail_data= av_fifo_size(stream->fifo);
1048 const int space= stream->max_buffer_size - stream->buffer_index;
1049 int rel_space= 1024*space / stream->max_buffer_size;
1050 PacketDesc *next_pkt= stream->premux_packet;
1052 /* for subtitle, a single PES packet must be generated,
1053 so we flush after every single subtitle packet */
1054 if(s->packet_size > avail_data && !flush
1055 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
1059 assert(avail_data>0);
1061 if(space < s->packet_size && !ignore_constraints)
1064 if(next_pkt && next_pkt->dts - scr > max_delay)
1067 if(rel_space > best_score){
1068 best_score= rel_space;
1075 int64_t best_dts= INT64_MAX;
1077 for(i=0; i<ctx->nb_streams; i++){
1078 AVStream *st = ctx->streams[i];
1079 StreamInfo *stream = st->priv_data;
1080 PacketDesc *pkt_desc= stream->predecode_packet;
1081 if(pkt_desc && pkt_desc->dts < best_dts)
1082 best_dts= pkt_desc->dts;
1085 av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
1086 scr / 90000.0, best_dts / 90000.0);
1087 if(best_dts == INT64_MAX)
1090 if(scr >= best_dts+1 && !ignore_constraints){
1091 av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1092 ignore_constraints= 1;
1094 scr= FFMAX(best_dts+1, scr);
1095 if(remove_decoded_packets(ctx, scr) < 0)
1100 assert(best_i >= 0);
1102 st = ctx->streams[best_i];
1103 stream = st->priv_data;
1105 assert(av_fifo_size(stream->fifo) > 0);
1107 assert(avail_space >= s->packet_size || ignore_constraints);
1109 timestamp_packet= stream->premux_packet;
1110 if(timestamp_packet->unwritten_size == timestamp_packet->size){
1113 trailer_size= timestamp_packet->unwritten_size;
1114 timestamp_packet= timestamp_packet->next;
1117 if(timestamp_packet){
1118 //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);
1119 es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1121 assert(av_fifo_size(stream->fifo) == trailer_size);
1122 es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1126 /* Write one or more padding sectors, if necessary, to reach
1127 the constant overall bitrate.*/
1130 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1131 put_vcd_padding_sector(ctx);
1132 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1136 stream->buffer_index += es_size;
1137 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1139 while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1140 es_size -= stream->premux_packet->unwritten_size;
1141 stream->premux_packet= stream->premux_packet->next;
1144 stream->premux_packet->unwritten_size -= es_size;
1146 if(remove_decoded_packets(ctx, s->last_scr) < 0)
1152 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1154 MpegMuxContext *s = ctx->priv_data;
1155 int stream_index= pkt->stream_index;
1156 int size= pkt->size;
1157 uint8_t *buf= pkt->data;
1158 AVStream *st = ctx->streams[stream_index];
1159 StreamInfo *stream = st->priv_data;
1161 PacketDesc *pkt_desc;
1163 const int is_iframe = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (pkt->flags & AV_PKT_FLAG_KEY);
1167 s->preload = ctx->preload;
1169 preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1174 if(pts != AV_NOPTS_VALUE) pts += 2*preload;
1175 if(dts != AV_NOPTS_VALUE){
1177 s->last_scr= dts + preload;
1181 //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);
1182 if (!stream->premux_packet)
1183 stream->next_packet = &stream->premux_packet;
1184 *stream->next_packet=
1185 pkt_desc= av_mallocz(sizeof(PacketDesc));
1188 pkt_desc->unwritten_size=
1189 pkt_desc->size= size;
1190 if(!stream->predecode_packet)
1191 stream->predecode_packet= pkt_desc;
1192 stream->next_packet= &pkt_desc->next;
1194 if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1198 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1199 stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1200 stream->align_iframe = 1;
1201 stream->vobu_start_pts = pts;
1205 av_fifo_generic_write(stream->fifo, buf, size, NULL);
1208 int ret= output_packet(ctx, 0);
1214 static int mpeg_mux_end(AVFormatContext *ctx)
1216 // MpegMuxContext *s = ctx->priv_data;
1221 int ret= output_packet(ctx, 1);
1228 /* End header according to MPEG1 systems standard. We do not write
1229 it as it is usually not needed by decoders and because it
1230 complicates MPEG stream concatenation. */
1231 //avio_wb32(ctx->pb, ISO_11172_END_CODE);
1232 //avio_flush(ctx->pb);
1234 for(i=0;i<ctx->nb_streams;i++) {
1235 stream = ctx->streams[i]->priv_data;
1237 assert(av_fifo_size(stream->fifo) == 0);
1238 av_fifo_free(stream->fifo);
1243 #define OFFSET(x) offsetof(MpegMuxContext, x)
1244 #define E AV_OPT_FLAG_ENCODING_PARAM
1245 static const AVOption options[] = {
1246 { "muxrate", NULL, OFFSET(mux_rate), AV_OPT_TYPE_INT, {0}, 0, INT_MAX, E },
1247 { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload), AV_OPT_TYPE_INT, {500000}, 0, INT_MAX, E},
1251 #define MPEGENC_CLASS(flavor)\
1252 static const AVClass flavor ## _class = {\
1253 .class_name = #flavor " muxer",\
1254 .item_name = av_default_item_name,\
1255 .version = LIBAVUTIL_VERSION_INT,\
1259 #if CONFIG_MPEG1SYSTEM_MUXER
1261 AVOutputFormat ff_mpeg1system_muxer = {
1263 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 System format"),
1264 .mime_type = "video/mpeg",
1265 .extensions = "mpg,mpeg",
1266 .priv_data_size = sizeof(MpegMuxContext),
1267 .audio_codec = CODEC_ID_MP2,
1268 .video_codec = CODEC_ID_MPEG1VIDEO,
1269 .write_header = mpeg_mux_init,
1270 .write_packet = mpeg_mux_write_packet,
1271 .write_trailer = mpeg_mux_end,
1272 .priv_class = &mpeg_class,
1275 #if CONFIG_MPEG1VCD_MUXER
1277 AVOutputFormat ff_mpeg1vcd_muxer = {
1279 .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 System format (VCD)"),
1280 .mime_type = "video/mpeg",
1281 .priv_data_size = sizeof(MpegMuxContext),
1282 .audio_codec = CODEC_ID_MP2,
1283 .video_codec = CODEC_ID_MPEG1VIDEO,
1284 .write_header = mpeg_mux_init,
1285 .write_packet = mpeg_mux_write_packet,
1286 .write_trailer = mpeg_mux_end,
1287 .priv_class = &vcd_class,
1290 #if CONFIG_MPEG2VOB_MUXER
1292 AVOutputFormat ff_mpeg2vob_muxer = {
1294 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1295 .mime_type = "video/mpeg",
1296 .extensions = "vob",
1297 .priv_data_size = sizeof(MpegMuxContext),
1298 .audio_codec = CODEC_ID_MP2,
1299 .video_codec = CODEC_ID_MPEG2VIDEO,
1300 .write_header = mpeg_mux_init,
1301 .write_packet = mpeg_mux_write_packet,
1302 .write_trailer = mpeg_mux_end,
1303 .priv_class = &vob_class,
1307 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1308 #if CONFIG_MPEG2SVCD_MUXER
1310 AVOutputFormat ff_mpeg2svcd_muxer = {
1312 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (VOB)"),
1313 .mime_type = "video/mpeg",
1314 .extensions = "vob",
1315 .priv_data_size = sizeof(MpegMuxContext),
1316 .audio_codec = CODEC_ID_MP2,
1317 .video_codec = CODEC_ID_MPEG2VIDEO,
1318 .write_header = mpeg_mux_init,
1319 .write_packet = mpeg_mux_write_packet,
1320 .write_trailer = mpeg_mux_end,
1321 .priv_class = &svcd_class,
1325 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1326 #if CONFIG_MPEG2DVD_MUXER
1328 AVOutputFormat ff_mpeg2dvd_muxer = {
1330 .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS format (DVD VOB)"),
1331 .mime_type = "video/mpeg",
1332 .extensions = "dvd",
1333 .priv_data_size = sizeof(MpegMuxContext),
1334 .audio_codec = CODEC_ID_MP2,
1335 .video_codec = CODEC_ID_MPEG2VIDEO,
1336 .write_header = mpeg_mux_init,
1337 .write_packet = mpeg_mux_write_packet,
1338 .write_trailer = mpeg_mux_end,
1339 .priv_class = &dvd_class,