3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #define MAX_PAYLOAD_SIZE 4096
28 uint8_t buffer[MAX_PAYLOAD_SIZE];
30 int nb_frames; /* number of starting frame encountered (AC3) */
31 int frame_start_offset; /* starting offset of the frame + 1 (0 if none) */
33 int max_buffer_size; /* in bytes */
37 uint8_t lpcm_header[3];
42 int packet_size; /* required packet size */
44 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
45 int system_header_freq;
46 int system_header_size;
47 int mux_rate; /* bitrate in units of 50 bytes/s */
54 int scr_stream_index; /* stream from which the system clock is
55 computed (VBR case) */
56 int64_t last_scr; /* current system clock */
58 double vcd_padding_bitrate;
59 int64_t vcd_padding_bytes_written;
63 #define PACK_START_CODE ((unsigned int)0x000001ba)
64 #define SYSTEM_HEADER_START_CODE ((unsigned int)0x000001bb)
65 #define SEQUENCE_END_CODE ((unsigned int)0x000001b7)
66 #define PACKET_START_CODE_MASK ((unsigned int)0xffffff00)
67 #define PACKET_START_CODE_PREFIX ((unsigned int)0x00000100)
68 #define ISO_11172_END_CODE ((unsigned int)0x000001b9)
71 #define PROGRAM_STREAM_MAP 0x1bc
72 #define PRIVATE_STREAM_1 0x1bd
73 #define PADDING_STREAM 0x1be
74 #define PRIVATE_STREAM_2 0x1bf
82 static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
84 #ifdef CONFIG_ENCODERS
85 extern AVOutputFormat mpeg1system_mux;
86 extern AVOutputFormat mpeg1vcd_mux;
87 extern AVOutputFormat mpeg2vob_mux;
88 extern AVOutputFormat mpeg2svcd_mux;
90 static int put_pack_header(AVFormatContext *ctx,
91 uint8_t *buf, int64_t timestamp)
93 MpegMuxContext *s = ctx->priv_data;
96 init_put_bits(&pb, buf, 128);
98 put_bits(&pb, 32, PACK_START_CODE);
100 put_bits(&pb, 2, 0x1);
102 put_bits(&pb, 4, 0x2);
104 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
106 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
108 put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
111 /* clock extension */
115 put_bits(&pb, 22, s->mux_rate);
119 put_bits(&pb, 5, 0x1f); /* reserved */
120 put_bits(&pb, 3, 0); /* stuffing length */
123 return pbBufPtr(&pb) - pb.buf;
126 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
128 MpegMuxContext *s = ctx->priv_data;
129 int size, rate_bound, i, private_stream_coded, id;
132 init_put_bits(&pb, buf, 128);
134 put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
135 put_bits(&pb, 16, 0);
138 rate_bound = s->mux_rate; /* maximum bit rate of the multiplexed stream */
139 put_bits(&pb, 22, rate_bound);
140 put_bits(&pb, 1, 1); /* marker */
141 if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
142 /* This header applies only to the video stream (see VCD standard p. IV-7)*/
145 put_bits(&pb, 6, s->audio_bound);
148 put_bits(&pb, 1, 0); /* see VCD standard, p. IV-7*/
150 put_bits(&pb, 1, 1); /* variable bitrate*/
151 put_bits(&pb, 1, 1); /* non constrainted bit stream */
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==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);
170 put_bits(&pb, 8, 0xff); /* reserved byte */
172 /* audio stream info */
173 private_stream_coded = 0;
174 for(i=0;i<ctx->nb_streams;i++) {
175 StreamInfo *stream = ctx->streams[i]->priv_data;
177 /* For VCDs, only include the stream info for the stream
178 that the pack which contains this system belongs to.
179 (see VCD standard p. IV-7) */
180 if ( !s->is_vcd || stream->id==only_for_stream_id
181 || only_for_stream_id==0) {
185 /* special case for private streams (AC3 use that) */
186 if (private_stream_coded)
188 private_stream_coded = 1;
191 put_bits(&pb, 8, id); /* stream ID */
196 put_bits(&pb, 13, stream->max_buffer_size / 128);
200 put_bits(&pb, 13, stream->max_buffer_size / 1024);
205 size = pbBufPtr(&pb) - pb.buf;
206 /* patch packet size */
207 buf[4] = (size - 6) >> 8;
208 buf[5] = (size - 6) & 0xff;
213 static int get_system_header_size(AVFormatContext *ctx)
215 int buf_index, i, private_stream_coded;
219 private_stream_coded = 0;
220 for(i=0;i<ctx->nb_streams;i++) {
221 stream = ctx->streams[i]->priv_data;
222 if (stream->id < 0xc0) {
223 if (private_stream_coded)
225 private_stream_coded = 1;
232 static int mpeg_mux_init(AVFormatContext *ctx)
234 MpegMuxContext *s = ctx->priv_data;
235 int bitrate, i, mpa_id, mpv_id, ac3_id, lpcm_id, j;
241 s->packet_number = 0;
242 s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
243 s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
244 s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux);
246 if (s->is_vcd || s->is_svcd)
247 s->packet_size = 2324; /* VCD/SVCD packet size */
249 s->packet_size = 2048;
251 s->vcd_padding_bytes_written = 0;
252 s->vcd_padding_bitrate=0;
260 s->scr_stream_index = -1;
261 for(i=0;i<ctx->nb_streams;i++) {
262 st = ctx->streams[i];
263 stream = av_mallocz(sizeof(StreamInfo));
266 st->priv_data = stream;
268 switch(st->codec.codec_type) {
269 case CODEC_TYPE_AUDIO:
270 if (st->codec.codec_id == CODEC_ID_AC3) {
271 stream->id = ac3_id++;
272 } else if (st->codec.codec_id == CODEC_ID_PCM_S16BE) {
273 stream->id = lpcm_id++;
274 for(j = 0; j < 4; j++) {
275 if (lpcm_freq_tab[j] == st->codec.sample_rate)
280 if (st->codec.channels > 8)
282 stream->lpcm_header[0] = 0x0c;
283 stream->lpcm_header[1] = (st->codec.channels - 1) | (j << 4);
284 stream->lpcm_header[2] = 0x80;
285 stream->lpcm_align = st->codec.channels * 2;
287 stream->id = mpa_id++;
289 stream->max_buffer_size = 4 * 1024;
292 case CODEC_TYPE_VIDEO:
293 /* by default, video is used for the SCR computation */
294 if (s->scr_stream_index == -1)
295 s->scr_stream_index = i;
296 stream->id = mpv_id++;
297 stream->max_buffer_size = 46 * 1024;
304 /* if no SCR, use first stream (audio) */
305 if (s->scr_stream_index == -1)
306 s->scr_stream_index = 0;
311 for(i=0;i<ctx->nb_streams;i++) {
312 st = ctx->streams[i];
313 stream = (StreamInfo*) st->priv_data;
315 bitrate += st->codec.bit_rate;
317 if (stream->id==AUDIO_ID)
318 audio_bitrate += st->codec.bit_rate;
319 else if (stream->id==VIDEO_ID)
320 video_bitrate += st->codec.bit_rate;
324 double overhead_rate;
326 /* The VCD standard mandates that the mux_rate field is 3528
327 (see standard p. IV-6).
328 The value is actually "wrong", i.e. if you calculate
329 it using the normal formula and the 75 sectors per second transfer
330 rate you get a different value because the real pack size is 2324,
331 not 2352. But the standard explicitly specifies that the mux_rate
332 field in the header must have this value.*/
333 s->mux_rate=2352 * 75 / 50; /* = 3528*/
335 /* The VCD standard states that the muxed stream must be
336 exactly 75 packs / second (the data rate of a single speed cdrom).
337 Since the video bitrate (probably 1150000 bits/sec) will be below
338 the theoretical maximum we have to add some padding packets
339 to make up for the lower data rate.
340 (cf. VCD standard p. IV-6 )*/
342 /* Add the header overhead to the data rate.
343 2279 data bytes per audio pack, 2294 data bytes per video pack*/
344 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
345 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
348 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
349 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
352 /* we increase slightly the bitrate to take into account the
353 headers. XXX: compute it exactly */
355 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
358 if (s->is_vcd || s->is_mpeg2)
360 s->pack_header_freq = 1;
362 /* every 2 seconds */
363 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
365 /* the above seems to make pack_header_freq zero sometimes */
366 if (s->pack_header_freq == 0)
367 s->pack_header_freq = 1;
370 /* every 200 packets. Need to look at the spec. */
371 s->system_header_freq = s->pack_header_freq * 40;
373 /* the standard mandates that there are only two system headers
374 in the whole file: one in the first packet of each stream.
375 (see standard p. IV-7 and IV-8) */
376 s->system_header_freq = 0x7fffffff;
378 s->system_header_freq = s->pack_header_freq * 5;
380 for(i=0;i<ctx->nb_streams;i++) {
381 stream = ctx->streams[i]->priv_data;
382 stream->buffer_ptr = 0;
383 stream->packet_number = 0;
384 stream->start_pts = AV_NOPTS_VALUE;
385 stream->start_dts = AV_NOPTS_VALUE;
387 s->system_header_size = get_system_header_size(ctx);
391 for(i=0;i<ctx->nb_streams;i++) {
392 av_free(ctx->streams[i]->priv_data);
397 static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
401 (((timestamp >> 30) & 0x07) << 1) |
403 put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
404 put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
408 /* return the number of padding bytes that should be inserted into
409 the multiplexed stream.*/
410 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
412 MpegMuxContext *s = ctx->priv_data;
415 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
417 int64_t full_pad_bytes;
419 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0);
420 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
423 /* might happen if we have already padded to a later timestamp. This
424 can occur if another stream has already advanced further.*/
432 /* return the exact available payload size for the next packet for
433 stream 'stream_index'. 'pts' and 'dts' are only used to know if
434 timestamps are needed in the packet header. */
435 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
436 int64_t pts, int64_t dts)
438 MpegMuxContext *s = ctx->priv_data;
442 stream = ctx->streams[stream_index]->priv_data;
445 if (((s->packet_number % s->pack_header_freq) == 0)) {
446 /* pack header size */
453 /* there is exactly one system header for each stream in a VCD MPEG,
454 One in the very first video packet and one in the very first
455 audio packet (see VCD standard p. IV-7 and IV-8).*/
457 if (stream->packet_number==0)
458 /* The system headers refer only to the stream they occur in,
459 so they have a constant size.*/
463 if ((s->packet_number % s->system_header_freq) == 0)
464 buf_index += s->system_header_size;
468 if (s->is_vcd && stream->packet_number==0)
469 /* the first pack of each stream contains only the pack header,
470 the system header and some padding (see VCD standard p. IV-6)
471 Add the padding size, so that the actual payload becomes 0.*/
472 buf_index += s->packet_size - buf_index;
474 /* packet header size */
478 if (pts != AV_NOPTS_VALUE) {
489 if (stream->id < 0xc0) {
490 /* AC3/LPCM private data header */
492 if (stream->id >= 0xa0) {
495 /* NOTE: we round the payload size to an integer number of
497 n = (s->packet_size - buf_index) % stream->lpcm_align;
499 buf_index += (stream->lpcm_align - n);
503 if (s->is_vcd && stream->id == AUDIO_ID)
504 /* The VCD standard demands that 20 zero bytes follow
505 each audio packet (see standard p. IV-8).*/
508 return s->packet_size - buf_index;
511 /* Write an MPEG padding packet header. */
512 static int put_padding_header(AVFormatContext *ctx,uint8_t* buf, int full_padding_size)
514 MpegMuxContext *s = ctx->priv_data;
515 int size = full_padding_size - 6; /* subtract header length */
517 buf[0] = (uint8_t)(PADDING_STREAM >> 24);
518 buf[1] = (uint8_t)(PADDING_STREAM >> 16);
519 buf[2] = (uint8_t)(PADDING_STREAM >> 8);
520 buf[3] = (uint8_t)(PADDING_STREAM);
521 buf[4] = (uint8_t)(size >> 8);
522 buf[5] = (uint8_t)(size & 0xff);
531 static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
536 size = put_padding_header(ctx,buffer, packet_bytes);
537 put_buffer(pb, buffer, size);
538 packet_bytes -= size;
540 for(i=0;i<packet_bytes;i++)
545 /* flush the packet on stream stream_index */
546 static void flush_packet(AVFormatContext *ctx, int stream_index,
547 int64_t pts, int64_t dts, int64_t scr)
549 MpegMuxContext *s = ctx->priv_data;
550 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
552 int size, payload_size, startcode, id, stuffing_size, i, header_len;
555 int zero_trail_bytes = 0;
556 int pad_packet_bytes = 0;
561 printf("packet ID=%2x PTS=%0.3f\n",
567 if (((s->packet_number % s->pack_header_freq) == 0)) {
568 /* output pack and systems header if needed */
569 size = put_pack_header(ctx, buf_ptr, scr);
573 /* there is exactly one system header for each stream in a VCD MPEG,
574 One in the very first video packet and one in the very first
575 audio packet (see VCD standard p. IV-7 and IV-8).*/
577 if (stream->packet_number==0) {
578 size = put_system_header(ctx, buf_ptr, id);
582 if ((s->packet_number % s->system_header_freq) == 0) {
583 size = put_system_header(ctx, buf_ptr, 0);
588 size = buf_ptr - buffer;
589 put_buffer(&ctx->pb, buffer, size);
591 packet_size = s->packet_size - size;
593 if (s->is_vcd && id == AUDIO_ID)
594 /* The VCD standard demands that 20 zero bytes follow
595 each audio pack (see standard p. IV-8).*/
596 zero_trail_bytes += 20;
598 if (s->is_vcd && stream->packet_number==0) {
599 /* the first pack of each stream contains only the pack header,
600 the system header and lots of padding (see VCD standard p. IV-6).
601 In the case of an audio pack, 20 zero bytes are also added at
603 pad_packet_bytes = packet_size - zero_trail_bytes;
606 packet_size -= pad_packet_bytes + zero_trail_bytes;
608 if (packet_size > 0) {
610 /* packet header size */
619 if (pts != AV_NOPTS_VALUE) {
629 payload_size = packet_size - header_len;
631 startcode = PRIVATE_STREAM_1;
636 startcode = 0x100 + id;
639 stuffing_size = payload_size - stream->buffer_ptr;
640 if (stuffing_size < 0)
642 put_be32(&ctx->pb, startcode);
644 put_be16(&ctx->pb, packet_size);
647 for(i=0;i<stuffing_size;i++)
648 put_byte(&ctx->pb, 0xff);
651 put_byte(&ctx->pb, 0x80); /* mpeg2 id */
653 if (pts != AV_NOPTS_VALUE) {
655 put_byte(&ctx->pb, 0xc0); /* flags */
656 put_byte(&ctx->pb, header_len - 3 + stuffing_size);
657 put_timestamp(&ctx->pb, 0x03, pts);
658 put_timestamp(&ctx->pb, 0x01, dts);
660 put_byte(&ctx->pb, 0x80); /* flags */
661 put_byte(&ctx->pb, header_len - 3 + stuffing_size);
662 put_timestamp(&ctx->pb, 0x02, pts);
665 put_byte(&ctx->pb, 0x00); /* flags */
666 put_byte(&ctx->pb, header_len - 3 + stuffing_size);
669 if (pts != AV_NOPTS_VALUE) {
671 put_timestamp(&ctx->pb, 0x03, pts);
672 put_timestamp(&ctx->pb, 0x01, dts);
674 put_timestamp(&ctx->pb, 0x02, pts);
677 put_byte(&ctx->pb, 0x0f);
681 if (startcode == PRIVATE_STREAM_1) {
682 put_byte(&ctx->pb, id);
684 /* LPCM (XXX: check nb_frames) */
685 put_byte(&ctx->pb, 7);
686 put_be16(&ctx->pb, 4); /* skip 3 header bytes */
687 put_byte(&ctx->pb, stream->lpcm_header[0]);
688 put_byte(&ctx->pb, stream->lpcm_header[1]);
689 put_byte(&ctx->pb, stream->lpcm_header[2]);
692 put_byte(&ctx->pb, stream->nb_frames);
693 put_be16(&ctx->pb, stream->frame_start_offset);
698 for(i=0;i<stuffing_size;i++)
699 put_byte(&ctx->pb, 0xff);
702 put_buffer(&ctx->pb, stream->buffer, payload_size - stuffing_size);
705 if (pad_packet_bytes > 0)
706 put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);
708 for(i=0;i<zero_trail_bytes;i++)
709 put_byte(&ctx->pb, 0x00);
711 put_flush_packet(&ctx->pb);
714 stream->packet_number++;
715 stream->nb_frames = 0;
716 stream->frame_start_offset = 0;
719 static void put_vcd_padding_sector(AVFormatContext *ctx)
721 /* There are two ways to do this padding: writing a sector/pack
722 of 0 values, or writing an MPEG padding pack. Both seem to
723 work with most decoders, BUT the VCD standard only allows a 0-sector
724 (see standard p. IV-4, IV-5).
725 So a 0-sector it is...*/
727 MpegMuxContext *s = ctx->priv_data;
730 for(i=0;i<s->packet_size;i++)
731 put_byte(&ctx->pb, 0);
733 s->vcd_padding_bytes_written += s->packet_size;
735 put_flush_packet(&ctx->pb);
737 /* increasing the packet number is correct. The SCR of the following packs
738 is calculated from the packet_number and it has to include the padding
739 sector (it represents the sector index, not the MPEG pack index)
740 (see VCD standard p. IV-6)*/
744 /* XXX: move that to upper layer */
745 /* XXX: we assume that there are always 'max_b_frames' between
746 reference frames. A better solution would be to use the AVFrame pts
748 static void compute_pts_dts(AVStream *st, int64_t *ppts, int64_t *pdts,
754 if (st->codec.codec_type == CODEC_TYPE_VIDEO &&
755 st->codec.max_b_frames != 0) {
756 frame_delay = (st->codec.frame_rate_base * 90000LL) /
757 st->codec.frame_rate;
758 if (timestamp == 0) {
759 /* specific case for first frame : DTS just before */
761 dts = timestamp - frame_delay;
763 timestamp -= frame_delay;
764 if (st->codec.coded_frame->pict_type == FF_B_TYPE) {
765 /* B frames has identical pts/dts */
769 /* a reference frame has a pts equal to the dts of the
772 pts = timestamp + (st->codec.max_b_frames + 1) * frame_delay;
776 printf("pts=%0.3f dts=%0.3f pict_type=%c\n",
777 pts / 90000.0, dts / 90000.0,
778 av_get_pict_type_char(st->codec.coded_frame->pict_type));
784 *ppts = pts & ((1LL << 33) - 1);
785 *pdts = dts & ((1LL << 33) - 1);
788 static int64_t update_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
790 MpegMuxContext *s = ctx->priv_data;
794 /* Since the data delivery rate is constant, SCR is computed
795 using the formula C + i * 1200 where C is the start constant
796 and i is the pack index.
797 It is recommended that SCR 0 is at the beginning of the VCD front
798 margin (a sequence of empty Form 2 sectors on the CD).
799 It is recommended that the front margin is 30 sectors long, so
800 we use C = 30*1200 = 36000
801 (Note that even if the front margin is not 30 sectors the file
802 will still be correct according to the standard. It just won't have
803 the "recommended" value).*/
804 scr = 36000 + s->packet_number * 1200;
806 /* XXX I believe this calculation of SCR is wrong. SCR
807 specifies at which time the data should enter the decoder.
808 Two packs cannot enter the decoder at the same time. */
810 /* XXX: system clock should be computed precisely, especially for
811 CBR case. The current mode gives at least something coherent */
812 if (stream_index == s->scr_stream_index
813 && pts != AV_NOPTS_VALUE)
825 static int mpeg_mux_write_packet(AVFormatContext *ctx, int stream_index,
826 const uint8_t *buf, int size,
829 MpegMuxContext *s = ctx->priv_data;
830 AVStream *st = ctx->streams[stream_index];
831 StreamInfo *stream = st->priv_data;
832 int64_t pts, dts, new_start_pts, new_start_dts;
835 compute_pts_dts(st, &pts, &dts, timestamp);
839 update_scr(ctx,stream_index,pts);
841 printf("%d: pts=%0.3f dts=%0.3f scr=%0.3f\n",
845 s->last_scr / 90000.0);
848 /* we assume here that pts != AV_NOPTS_VALUE */
849 new_start_pts = stream->start_pts;
850 new_start_dts = stream->start_dts;
852 if (stream->start_pts == AV_NOPTS_VALUE) {
856 avail_size = get_packet_payload_size(ctx, stream_index,
859 if (stream->buffer_ptr >= avail_size) {
861 update_scr(ctx,stream_index,stream->start_pts);
863 /* unlikely case: outputing the pts or dts increase the packet
864 size so that we cannot write the start of the next
865 packet. In this case, we must flush the current packet with
867 Note: this always happens for the first audio and video packet
868 in a VCD file, since they do not carry any data.*/
869 flush_packet(ctx, stream_index,
870 stream->start_pts, stream->start_dts, s->last_scr);
871 stream->buffer_ptr = 0;
873 stream->start_pts = new_start_pts;
874 stream->start_dts = new_start_dts;
876 if (stream->frame_start_offset == 0)
877 stream->frame_start_offset = stream->buffer_ptr;
879 avail_size = get_packet_payload_size(ctx, stream_index,
882 len = avail_size - stream->buffer_ptr;
885 memcpy(stream->buffer + stream->buffer_ptr, buf, len);
886 stream->buffer_ptr += len;
889 if (stream->buffer_ptr >= avail_size) {
891 update_scr(ctx,stream_index,stream->start_pts);
893 /* if packet full, we send it now */
894 flush_packet(ctx, stream_index,
895 stream->start_pts, stream->start_dts, s->last_scr);
896 stream->buffer_ptr = 0;
899 /* Write one or more padding sectors, if necessary, to reach
900 the constant overall bitrate.*/
903 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->start_pts) ) >= s->packet_size)
904 put_vcd_padding_sector(ctx);
907 /* Make sure only the FIRST pes packet for this frame has
909 stream->start_pts = AV_NOPTS_VALUE;
910 stream->start_dts = AV_NOPTS_VALUE;
917 static int mpeg_mux_end(AVFormatContext *ctx)
919 MpegMuxContext *s = ctx->priv_data;
923 /* flush each packet */
924 for(i=0;i<ctx->nb_streams;i++) {
925 stream = ctx->streams[i]->priv_data;
926 if (stream->buffer_ptr > 0) {
927 update_scr(ctx,i,stream->start_pts);
929 /* NOTE: we can always write the remaining data as it was
930 tested before in mpeg_mux_write_packet() */
931 flush_packet(ctx, i, stream->start_pts, stream->start_dts,
936 /* End header according to MPEG1 systems standard. We do not write
937 it as it is usually not needed by decoders and because it
938 complicates MPEG stream concatenation. */
939 //put_be32(&ctx->pb, ISO_11172_END_CODE);
940 //put_flush_packet(&ctx->pb);
942 for(i=0;i<ctx->nb_streams;i++)
943 av_freep(&ctx->streams[i]->priv_data);
947 #endif //CONFIG_ENCODERS
949 /*********************************************/
952 #define MAX_SYNC_SIZE 100000
954 static int mpegps_probe(AVProbeData *p)
959 /* we search the first start code. If it is a packet start code,
960 then we decide it is mpeg ps. We do not send highest value to
961 give a chance to mpegts */
962 /* NOTE: the search range was restricted to avoid too many false
968 for (i = 0; i < 20; i++) {
970 code = (code << 8) | c;
971 if ((code & 0xffffff00) == 0x100) {
972 if (code == PACK_START_CODE ||
973 code == SYSTEM_HEADER_START_CODE ||
974 (code >= 0x1e0 && code <= 0x1ef) ||
975 (code >= 0x1c0 && code <= 0x1df) ||
976 code == PRIVATE_STREAM_2 ||
977 code == PROGRAM_STREAM_MAP ||
978 code == PRIVATE_STREAM_1 ||
979 code == PADDING_STREAM)
980 return AVPROBE_SCORE_MAX - 2;
989 typedef struct MpegDemuxContext {
993 static int mpegps_read_header(AVFormatContext *s,
994 AVFormatParameters *ap)
996 MpegDemuxContext *m = s->priv_data;
997 m->header_state = 0xff;
998 s->ctx_flags |= AVFMTCTX_NOHEADER;
1000 /* no need to do more */
1004 static int64_t get_pts(ByteIOContext *pb, int c)
1011 pts = (int64_t)((c >> 1) & 0x07) << 30;
1013 pts |= (int64_t)(val >> 1) << 15;
1015 pts |= (int64_t)(val >> 1);
1019 static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
1020 uint32_t *header_state)
1022 unsigned int state, v;
1025 state = *header_state;
1032 if (state == 0x000001) {
1033 state = ((state << 8) | v) & 0xffffff;
1037 state = ((state << 8) | v) & 0xffffff;
1041 *header_state = state;
1047 static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
1049 int64_t pos, pos_start;
1050 int max_size, start_code;
1052 max_size = *size_ptr;
1053 pos_start = url_ftell(pb);
1055 /* in order to go faster, we fill the buffer */
1056 pos = pos_start - 16386;
1059 url_fseek(pb, pos, SEEK_SET);
1065 if (pos < 0 || (pos_start - pos) >= max_size) {
1069 url_fseek(pb, pos, SEEK_SET);
1070 start_code = get_be32(pb);
1071 if ((start_code & 0xffffff00) == 0x100)
1075 *size_ptr = pos_start - pos;
1079 /* read the next (or previous) PES header. Return its position in ppos
1080 (if not NULL), and its start code, pts and dts.
1082 static int mpegps_read_pes_header(AVFormatContext *s,
1083 int64_t *ppos, int *pstart_code,
1084 int64_t *ppts, int64_t *pdts, int find_next)
1086 MpegDemuxContext *m = s->priv_data;
1087 int len, size, startcode, c, flags, header_len;
1088 int64_t pts, dts, last_pos;
1093 /* next start code (should be immediately after) */
1094 m->header_state = 0xff;
1095 size = MAX_SYNC_SIZE;
1096 startcode = find_next_start_code(&s->pb, &size, &m->header_state);
1099 url_fseek(&s->pb, last_pos, SEEK_SET);
1100 size = MAX_SYNC_SIZE;
1101 startcode = find_prev_start_code(&s->pb, &size);
1102 last_pos = url_ftell(&s->pb) - 4;
1104 //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
1107 if (startcode == PACK_START_CODE)
1109 if (startcode == SYSTEM_HEADER_START_CODE)
1111 if (startcode == PADDING_STREAM ||
1112 startcode == PRIVATE_STREAM_2) {
1114 len = get_be16(&s->pb);
1115 url_fskip(&s->pb, len);
1118 /* find matching stream */
1119 if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
1120 (startcode >= 0x1e0 && startcode <= 0x1ef) ||
1121 (startcode == 0x1bd)))
1124 *ppos = url_ftell(&s->pb) - 4;
1126 len = get_be16(&s->pb);
1127 pts = AV_NOPTS_VALUE;
1128 dts = AV_NOPTS_VALUE;
1133 c = get_byte(&s->pb);
1135 /* XXX: for mpeg1, should test only bit 7 */
1139 if ((c & 0xc0) == 0x40) {
1140 /* buffer scale & size */
1144 c = get_byte(&s->pb);
1147 if ((c & 0xf0) == 0x20) {
1150 dts = pts = get_pts(&s->pb, c);
1152 } else if ((c & 0xf0) == 0x30) {
1155 pts = get_pts(&s->pb, c);
1156 dts = get_pts(&s->pb, -1);
1158 } else if ((c & 0xc0) == 0x80) {
1160 if ((c & 0x30) != 0) {
1161 /* Encrypted multiplex not handled */
1164 flags = get_byte(&s->pb);
1165 header_len = get_byte(&s->pb);
1167 if (header_len > len)
1169 if ((flags & 0xc0) == 0x80) {
1170 dts = pts = get_pts(&s->pb, -1);
1175 } if ((flags & 0xc0) == 0xc0) {
1176 pts = get_pts(&s->pb, -1);
1177 dts = get_pts(&s->pb, -1);
1178 if (header_len < 10)
1184 while (header_len > 0) {
1189 if (startcode == 0x1bd) {
1192 startcode = get_byte(&s->pb);
1194 if (startcode >= 0x80 && startcode <= 0xbf) {
1195 /* audio: skip header */
1204 if(dts != AV_NOPTS_VALUE && ppos){
1206 for(i=0; i<s->nb_streams; i++){
1207 if(startcode == s->streams[i]->id) {
1208 av_add_index_entry(s->streams[i], *ppos, dts, 0, 0 /* FIXME keyframe? */);
1213 *pstart_code = startcode;
1219 static int mpegps_read_packet(AVFormatContext *s,
1223 int len, startcode, i, type, codec_id;
1224 int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
1227 len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts, 1);
1231 /* now find stream */
1232 for(i=0;i<s->nb_streams;i++) {
1234 if (st->id == startcode)
1237 if (startcode >= 0x1e0 && startcode <= 0x1ef) {
1238 type = CODEC_TYPE_VIDEO;
1239 codec_id = CODEC_ID_MPEG2VIDEO;
1240 } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
1241 type = CODEC_TYPE_AUDIO;
1242 codec_id = CODEC_ID_MP2;
1243 } else if (startcode >= 0x80 && startcode <= 0x9f) {
1244 type = CODEC_TYPE_AUDIO;
1245 codec_id = CODEC_ID_AC3;
1246 } else if (startcode >= 0xa0 && startcode <= 0xbf) {
1247 type = CODEC_TYPE_AUDIO;
1248 codec_id = CODEC_ID_PCM_S16BE;
1252 url_fskip(&s->pb, len);
1255 /* no stream found: add a new stream */
1256 st = av_new_stream(s, startcode);
1259 st->codec.codec_type = type;
1260 st->codec.codec_id = codec_id;
1261 if (codec_id != CODEC_ID_PCM_S16BE)
1262 st->need_parsing = 1;
1264 if (startcode >= 0xa0 && startcode <= 0xbf) {
1267 /* for LPCM, we just skip the header and consider it is raw
1271 get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
1272 b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
1273 get_byte(&s->pb); /* dynamic range control (0x80 = off) */
1275 freq = (b1 >> 4) & 3;
1276 st->codec.sample_rate = lpcm_freq_tab[freq];
1277 st->codec.channels = 1 + (b1 & 7);
1278 st->codec.bit_rate = st->codec.channels * st->codec.sample_rate * 2;
1280 av_new_packet(pkt, len);
1281 get_buffer(&s->pb, pkt->data, pkt->size);
1284 pkt->stream_index = st->index;
1286 printf("%d: pts=%0.3f dts=%0.3f\n",
1287 pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0);
1292 static int mpegps_read_close(AVFormatContext *s)
1297 static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
1298 int64_t *ppos, int find_next)
1301 int64_t pos, pts, dts;
1305 printf("read_dts: pos=0x%llx next=%d -> ", pos, find_next);
1307 url_fseek(&s->pb, pos, SEEK_SET);
1309 len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts, find_next);
1312 printf("none (ret=%d)\n", len);
1314 return AV_NOPTS_VALUE;
1316 if (startcode == s->streams[stream_index]->id &&
1317 dts != AV_NOPTS_VALUE) {
1321 url_fskip(&s->pb, len);
1323 url_fseek(&s->pb, pos, SEEK_SET);
1327 printf("pos=0x%llx dts=0x%llx %0.3f\n", pos, dts, dts / 90000.0);
1333 static int mpegps_read_seek(AVFormatContext *s,
1334 int stream_index, int64_t timestamp)
1336 int64_t pos_min, pos_max, pos, pos_limit;
1337 int64_t dts_min, dts_max, dts;
1338 int index, no_change;
1341 timestamp = (timestamp * 90000) / AV_TIME_BASE;
1344 printf("read_seek: %d %0.3f\n", stream_index, timestamp / 90000.0);
1347 /* XXX: find stream_index by looking at the first PES packet found */
1348 if (stream_index < 0) {
1349 stream_index = av_find_default_stream_index(s);
1350 if (stream_index < 0)
1355 dts_min= AV_NOPTS_VALUE;
1356 pos_limit= -1; //gcc falsely says it may be uninitalized
1358 st= s->streams[stream_index];
1359 if(st->index_entries){
1362 index= av_index_search_timestamp(st, timestamp);
1363 e= &st->index_entries[index];
1364 if(e->timestamp <= timestamp){
1366 dts_min= e->timestamp;
1368 printf("unsing cached pos_min=0x%llx dts_min=%0.3f\n",
1369 pos_min,dts_min / 90000.0);
1375 if(index < st->nb_index_entries){
1376 e= &st->index_entries[index];
1377 assert(e->timestamp >= timestamp);
1379 dts_max= e->timestamp;
1380 pos_limit= pos_max - e->min_distance;
1382 printf("unsing cached pos_max=0x%llx dts_max=%0.3f\n",
1383 pos_max,dts_max / 90000.0);
1388 if(dts_min == AV_NOPTS_VALUE){
1390 dts_min = mpegps_read_dts(s, stream_index, &pos_min, 1);
1391 if (dts_min == AV_NOPTS_VALUE) {
1392 /* we can reach this case only if no PTS are present in
1397 if(dts_max == AV_NOPTS_VALUE){
1398 pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1399 dts_max = mpegps_read_dts(s, stream_index, &pos_max, 0);
1404 while (pos_min < pos_limit) {
1406 printf("pos_min=0x%llx pos_max=0x%llx dts_min=%0.3f dts_max=%0.3f\n",
1408 dts_min / 90000.0, dts_max / 90000.0);
1411 assert(pos_limit <= pos_max);
1414 int64_t approximate_keyframe_distance= pos_max - pos_limit;
1415 // interpolate position (better than dichotomy)
1416 pos = (int64_t)((double)(pos_max - pos_min) *
1417 (double)(timestamp - dts_min) /
1418 (double)(dts_max - dts_min)) + pos_min - approximate_keyframe_distance;
1419 }else if(no_change==1){
1420 // bisection, if interpolation failed to change min or max pos last time
1421 pos = (pos_min + pos_limit)>>1;
1423 // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1428 else if(pos > pos_limit)
1432 // read the next timestamp
1433 dts = mpegps_read_dts(s, stream_index, &pos, 1);
1439 printf("%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, dts_min, dts, dts_max, timestamp, pos_limit, start_pos, no_change);
1441 assert(dts != AV_NOPTS_VALUE);
1442 if (timestamp < dts) {
1443 pos_limit = start_pos - 1;
1449 /* check if we are lucky */
1450 if (timestamp == dts)
1458 dts_min = mpegps_read_dts(s, stream_index, &pos_min, 1);
1460 dts_max = mpegps_read_dts(s, stream_index, &pos_min, 1);
1461 printf("pos=0x%llx %0.3f<=%0.3f<=%0.3f\n",
1462 pos, dts_min / 90000.0, timestamp / 90000.0, dts_max / 90000.0);
1465 url_fseek(&s->pb, pos, SEEK_SET);
1469 #ifdef CONFIG_ENCODERS
1470 static AVOutputFormat mpeg1system_mux = {
1472 "MPEG1 System format",
1475 sizeof(MpegMuxContext),
1477 CODEC_ID_MPEG1VIDEO,
1479 mpeg_mux_write_packet,
1483 static AVOutputFormat mpeg1vcd_mux = {
1485 "MPEG1 System format (VCD)",
1488 sizeof(MpegMuxContext),
1490 CODEC_ID_MPEG1VIDEO,
1492 mpeg_mux_write_packet,
1496 static AVOutputFormat mpeg2vob_mux = {
1498 "MPEG2 PS format (VOB)",
1501 sizeof(MpegMuxContext),
1503 CODEC_ID_MPEG2VIDEO,
1505 mpeg_mux_write_packet,
1509 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1510 static AVOutputFormat mpeg2svcd_mux = {
1512 "MPEG2 PS format (VOB)",
1515 sizeof(MpegMuxContext),
1517 CODEC_ID_MPEG2VIDEO,
1519 mpeg_mux_write_packet,
1525 #endif //CONFIG_ENCODERS
1527 AVInputFormat mpegps_demux = {
1530 sizeof(MpegDemuxContext),
1538 int mpegps_init(void)
1540 #ifdef CONFIG_ENCODERS
1541 av_register_output_format(&mpeg1system_mux);
1542 av_register_output_format(&mpeg1vcd_mux);
1543 av_register_output_format(&mpeg2vob_mux);
1544 av_register_output_format(&mpeg2svcd_mux);
1545 #endif //CONFIG_ENCODERS
1546 av_register_input_format(&mpegps_demux);