]> git.sesse.net Git - ffmpeg/blob - libavformat/mpeg.c
adf871a6699fb64ad12300d17751c5bb192fac32
[ffmpeg] / libavformat / mpeg.c
1 /*
2  * MPEG1/2 mux/demux
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
4  *
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.
9  *
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.
14  *
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
18  */
19 #include "avformat.h"
20
21 #define MAX_PAYLOAD_SIZE 4096
22 //#define DEBUG_SEEK
23
24 #undef NDEBUG
25 #include <assert.h>
26
27 typedef struct {
28     uint8_t buffer[MAX_PAYLOAD_SIZE];
29     int buffer_ptr;
30     int nb_frames;    /* number of starting frame encountered (AC3) */
31     int frame_start_offset; /* starting offset of the frame + 1 (0 if none) */
32     uint8_t id;
33     int max_buffer_size; /* in bytes */
34     int packet_number;
35     int64_t start_pts;
36     int64_t start_dts;
37     uint8_t lpcm_header[3];
38     int lpcm_align;
39 } StreamInfo;
40
41 typedef struct {
42     int packet_size; /* required packet size */
43     int packet_number;
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 */
48     /* stream info */
49     int audio_bound;
50     int video_bound;
51     int is_mpeg2;
52     int is_vcd;
53     int is_svcd;
54     int scr_stream_index; /* stream from which the system clock is
55                              computed (VBR case) */
56     int64_t last_scr; /* current system clock */
57
58     double vcd_padding_bitrate;
59     int64_t vcd_padding_bytes_written;
60
61 } MpegMuxContext;
62
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)
69   
70 /* mpeg2 */
71 #define PROGRAM_STREAM_MAP 0x1bc
72 #define PRIVATE_STREAM_1   0x1bd
73 #define PADDING_STREAM     0x1be
74 #define PRIVATE_STREAM_2   0x1bf
75
76
77 #define AUDIO_ID 0xc0
78 #define VIDEO_ID 0xe0
79 #define AC3_ID   0x80
80 #define DTS_ID   0x8a
81 #define LPCM_ID  0xa0
82
83 static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
84
85 #ifdef CONFIG_ENCODERS
86 static AVOutputFormat mpeg1system_mux;
87 static AVOutputFormat mpeg1vcd_mux;
88 static AVOutputFormat mpeg2vob_mux;
89 static AVOutputFormat mpeg2svcd_mux;
90
91 static int put_pack_header(AVFormatContext *ctx, 
92                            uint8_t *buf, int64_t timestamp)
93 {
94     MpegMuxContext *s = ctx->priv_data;
95     PutBitContext pb;
96     
97     init_put_bits(&pb, buf, 128);
98
99     put_bits(&pb, 32, PACK_START_CODE);
100     if (s->is_mpeg2) {
101         put_bits(&pb, 2, 0x1);
102     } else {
103         put_bits(&pb, 4, 0x2);
104     }
105     put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
106     put_bits(&pb, 1, 1);
107     put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
108     put_bits(&pb, 1, 1);
109     put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
110     put_bits(&pb, 1, 1);
111     if (s->is_mpeg2) {
112         /* clock extension */
113         put_bits(&pb, 9, 0);
114     }
115     put_bits(&pb, 1, 1);
116     put_bits(&pb, 22, s->mux_rate);
117     put_bits(&pb, 1, 1);
118     if (s->is_mpeg2) {
119         put_bits(&pb, 1, 1);
120         put_bits(&pb, 5, 0x1f); /* reserved */
121         put_bits(&pb, 3, 0); /* stuffing length */
122     }
123     flush_put_bits(&pb);
124     return pbBufPtr(&pb) - pb.buf;
125 }
126
127 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
128 {
129     MpegMuxContext *s = ctx->priv_data;
130     int size, rate_bound, i, private_stream_coded, id;
131     PutBitContext pb;
132
133     init_put_bits(&pb, buf, 128);
134
135     put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
136     put_bits(&pb, 16, 0);
137     put_bits(&pb, 1, 1);
138     
139     rate_bound = s->mux_rate; /* maximum bit rate of the multiplexed stream */
140     put_bits(&pb, 22, rate_bound);
141     put_bits(&pb, 1, 1); /* marker */
142     if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
143         /* This header applies only to the video stream (see VCD standard p. IV-7)*/
144         put_bits(&pb, 6, 0);
145     } else
146         put_bits(&pb, 6, s->audio_bound);
147
148     if (s->is_vcd) {
149         /* see VCD standard, p. IV-7*/
150         put_bits(&pb, 1, 0); 
151         put_bits(&pb, 1, 1);
152     } else {
153         put_bits(&pb, 1, 0); /* variable bitrate*/
154         put_bits(&pb, 1, 0); /* non constrainted bit stream */
155     }
156     
157     if (s->is_vcd) {
158         /* see VCD standard p IV-7 */
159         put_bits(&pb, 1, 1); /* audio locked */
160         put_bits(&pb, 1, 1); /* video locked */
161     } else {
162         put_bits(&pb, 1, 0); /* audio locked */
163         put_bits(&pb, 1, 0); /* video locked */
164     }
165
166     put_bits(&pb, 1, 1); /* marker */
167
168     if (s->is_vcd && only_for_stream_id==AUDIO_ID) {
169         /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
170         put_bits(&pb, 5, 0);
171     } else
172         put_bits(&pb, 5, s->video_bound);
173
174     put_bits(&pb, 8, 0xff); /* reserved byte */
175     
176     /* audio stream info */
177     private_stream_coded = 0;
178     for(i=0;i<ctx->nb_streams;i++) {
179         StreamInfo *stream = ctx->streams[i]->priv_data;
180         
181         /* For VCDs, only include the stream info for the stream
182            that the pack which contains this system belongs to.
183            (see VCD standard p. IV-7) */
184         if ( !s->is_vcd || stream->id==only_for_stream_id
185             || only_for_stream_id==0) {
186
187             id = stream->id;
188             if (id < 0xc0) {
189                 /* special case for private streams (AC3 use that) */
190                 if (private_stream_coded)
191                     continue;
192                 private_stream_coded = 1;
193                 id = 0xbd;
194             }
195             put_bits(&pb, 8, id); /* stream ID */
196             put_bits(&pb, 2, 3);
197             if (id < 0xe0) {
198                 /* audio */
199                 put_bits(&pb, 1, 0);
200                 put_bits(&pb, 13, stream->max_buffer_size / 128);
201             } else {
202                 /* video */
203                 put_bits(&pb, 1, 1);
204                 put_bits(&pb, 13, stream->max_buffer_size / 1024);
205             }
206         }
207     }
208     flush_put_bits(&pb);
209     size = pbBufPtr(&pb) - pb.buf;
210     /* patch packet size */
211     buf[4] = (size - 6) >> 8;
212     buf[5] = (size - 6) & 0xff;
213
214     return size;
215 }
216
217 static int get_system_header_size(AVFormatContext *ctx)
218 {
219     int buf_index, i, private_stream_coded;
220     StreamInfo *stream;
221
222     buf_index = 12;
223     private_stream_coded = 0;
224     for(i=0;i<ctx->nb_streams;i++) {
225         stream = ctx->streams[i]->priv_data;
226         if (stream->id < 0xc0) {
227             if (private_stream_coded)
228                 continue;
229             private_stream_coded = 1;
230         }
231         buf_index += 3;
232     }
233     return buf_index;
234 }
235
236 static int mpeg_mux_init(AVFormatContext *ctx)
237 {
238     MpegMuxContext *s = ctx->priv_data;
239     int bitrate, i, mpa_id, mpv_id, ac3_id, dts_id, lpcm_id, j;
240     AVStream *st;
241     StreamInfo *stream;
242     int audio_bitrate;
243     int video_bitrate;
244
245     s->packet_number = 0;
246     s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
247     s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
248     s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux);
249     
250     if (s->is_vcd || s->is_svcd)
251         s->packet_size = 2324; /* VCD/SVCD packet size */
252     else
253         s->packet_size = 2048;
254
255     s->vcd_padding_bytes_written = 0;
256     s->vcd_padding_bitrate=0;
257         
258     s->audio_bound = 0;
259     s->video_bound = 0;
260     mpa_id = AUDIO_ID;
261     ac3_id = AC3_ID;
262     dts_id = DTS_ID;
263     mpv_id = VIDEO_ID;
264     lpcm_id = LPCM_ID;
265     s->scr_stream_index = -1;
266     for(i=0;i<ctx->nb_streams;i++) {
267         st = ctx->streams[i];
268         stream = av_mallocz(sizeof(StreamInfo));
269         if (!stream)
270             goto fail;
271         st->priv_data = stream;
272
273         switch(st->codec.codec_type) {
274         case CODEC_TYPE_AUDIO:
275             if (st->codec.codec_id == CODEC_ID_AC3) {
276                 stream->id = ac3_id++;
277             } else if (st->codec.codec_id == CODEC_ID_DTS) {
278                 stream->id = dts_id++;
279             } else if (st->codec.codec_id == CODEC_ID_PCM_S16BE) {
280                 stream->id = lpcm_id++;
281                 for(j = 0; j < 4; j++) {
282                     if (lpcm_freq_tab[j] == st->codec.sample_rate)
283                         break;
284                 }
285                 if (j == 4)
286                     goto fail;
287                 if (st->codec.channels > 8)
288                     return -1;
289                 stream->lpcm_header[0] = 0x0c;
290                 stream->lpcm_header[1] = (st->codec.channels - 1) | (j << 4);
291                 stream->lpcm_header[2] = 0x80;
292                 stream->lpcm_align = st->codec.channels * 2;
293             } else {
294                 stream->id = mpa_id++;
295             }
296
297             /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
298                Right now it is also used for everything else.*/
299             stream->max_buffer_size = 4 * 1024; 
300             s->audio_bound++;
301             break;
302         case CODEC_TYPE_VIDEO:
303             /* by default, video is used for the SCR computation */
304             if (s->scr_stream_index == -1)
305                 s->scr_stream_index = i;
306             stream->id = mpv_id++;
307             if (s->is_vcd)
308                 /* see VCD standard, p. IV-7*/
309                 stream->max_buffer_size = 46 * 1024; 
310             else
311                 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
312                    Right now it is also used for everything else.*/
313                 stream->max_buffer_size = 230 * 1024; 
314             s->video_bound++;
315             break;
316         default:
317             av_abort();
318         }
319     }
320     /* if no SCR, use first stream (audio) */
321     if (s->scr_stream_index == -1)
322         s->scr_stream_index = 0;
323
324     bitrate = 0;
325     audio_bitrate = 0;
326     video_bitrate = 0;
327     for(i=0;i<ctx->nb_streams;i++) {
328         st = ctx->streams[i];
329         stream = (StreamInfo*) st->priv_data;
330         
331         bitrate += st->codec.bit_rate;
332
333         if (stream->id==AUDIO_ID)
334             audio_bitrate += st->codec.bit_rate;
335         else if (stream->id==VIDEO_ID)
336             video_bitrate += st->codec.bit_rate;
337     }
338
339     if (s->is_vcd) {
340         double overhead_rate;
341
342         /* The VCD standard mandates that the mux_rate field is 3528
343            (see standard p. IV-6).
344            The value is actually "wrong", i.e. if you calculate
345            it using the normal formula and the 75 sectors per second transfer
346            rate you get a different value because the real pack size is 2324,
347            not 2352. But the standard explicitly specifies that the mux_rate
348            field in the header must have this value.*/
349         s->mux_rate=2352 * 75 / 50;    /* = 3528*/
350
351         /* The VCD standard states that the muxed stream must be
352            exactly 75 packs / second (the data rate of a single speed cdrom).
353            Since the video bitrate (probably 1150000 bits/sec) will be below
354            the theoretical maximum we have to add some padding packets
355            to make up for the lower data rate.
356            (cf. VCD standard p. IV-6 )*/
357
358         /* Add the header overhead to the data rate.
359            2279 data bytes per audio pack, 2294 data bytes per video pack*/
360         overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
361         overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
362         overhead_rate *= 8;
363         
364         /* Add padding so that the full bitrate is 2324*75 bytes/sec */
365         s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
366
367     } else {
368         /* we increase slightly the bitrate to take into account the
369            headers. XXX: compute it exactly */
370         bitrate += 2000;
371         s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
372     }
373     
374     if (s->is_vcd || s->is_mpeg2)
375         /* every packet */
376         s->pack_header_freq = 1;
377     else
378         /* every 2 seconds */
379         s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
380
381     /* the above seems to make pack_header_freq zero sometimes */
382     if (s->pack_header_freq == 0)
383        s->pack_header_freq = 1;
384     
385     if (s->is_mpeg2)
386         /* every 200 packets. Need to look at the spec.  */
387         s->system_header_freq = s->pack_header_freq * 40;
388     else if (s->is_vcd)
389         /* the standard mandates that there are only two system headers
390            in the whole file: one in the first packet of each stream.
391            (see standard p. IV-7 and IV-8) */
392         s->system_header_freq = 0x7fffffff;
393     else
394         s->system_header_freq = s->pack_header_freq * 5;
395     
396     for(i=0;i<ctx->nb_streams;i++) {
397         stream = ctx->streams[i]->priv_data;
398         stream->buffer_ptr = 0;
399         stream->packet_number = 0;
400         stream->start_pts = AV_NOPTS_VALUE;
401         stream->start_dts = AV_NOPTS_VALUE;
402     }
403     s->system_header_size = get_system_header_size(ctx);
404     s->last_scr = 0;
405     return 0;
406  fail:
407     for(i=0;i<ctx->nb_streams;i++) {
408         av_free(ctx->streams[i]->priv_data);
409     }
410     return -ENOMEM;
411 }
412
413 static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
414 {
415     put_byte(pb, 
416              (id << 4) | 
417              (((timestamp >> 30) & 0x07) << 1) | 
418              1);
419     put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
420     put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
421 }
422
423
424 /* return the number of padding bytes that should be inserted into
425    the multiplexed stream.*/
426 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
427 {
428     MpegMuxContext *s = ctx->priv_data;
429     int pad_bytes = 0;
430
431     if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
432     {
433         int64_t full_pad_bytes;
434         
435         full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0);
436         pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
437
438         if (pad_bytes<0)
439             /* might happen if we have already padded to a later timestamp. This
440                can occur if another stream has already advanced further.*/
441             pad_bytes=0;
442     }
443
444     return pad_bytes;
445 }
446
447
448 /* return the exact available payload size for the next packet for
449    stream 'stream_index'. 'pts' and 'dts' are only used to know if
450    timestamps are needed in the packet header. */
451 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
452                                    int64_t pts, int64_t dts)
453 {
454     MpegMuxContext *s = ctx->priv_data;
455     int buf_index;
456     StreamInfo *stream;
457
458     stream = ctx->streams[stream_index]->priv_data;
459
460     buf_index = 0;
461     if (((s->packet_number % s->pack_header_freq) == 0)) {
462         /* pack header size */
463         if (s->is_mpeg2) 
464             buf_index += 14;
465         else
466             buf_index += 12;
467         
468         if (s->is_vcd) {
469             /* there is exactly one system header for each stream in a VCD MPEG,
470                One in the very first video packet and one in the very first
471                audio packet (see VCD standard p. IV-7 and IV-8).*/
472             
473             if (stream->packet_number==0)
474                 /* The system headers refer only to the stream they occur in,
475                    so they have a constant size.*/
476                 buf_index += 15;
477
478         } else {            
479             if ((s->packet_number % s->system_header_freq) == 0)
480                 buf_index += s->system_header_size;
481         }
482     }
483
484     if ((s->is_vcd && stream->packet_number==0)
485         || (s->is_svcd && s->packet_number==0))
486         /* the first pack of each stream contains only the pack header,
487            the system header and some padding (see VCD standard p. IV-6) 
488            Add the padding size, so that the actual payload becomes 0.*/
489         buf_index += s->packet_size - buf_index;
490     else {
491         /* packet header size */
492         buf_index += 6;
493         if (s->is_mpeg2) {
494             buf_index += 3;
495             if (stream->packet_number==0)
496                 buf_index += 3; /* PES extension */
497             buf_index += 1;    /* obligatory stuffing byte */
498         }
499         if (pts != AV_NOPTS_VALUE) {
500             if (dts != pts)
501                 buf_index += 5 + 5;
502             else
503                 buf_index += 5;
504
505         } else {
506             if (!s->is_mpeg2)
507                 buf_index++;
508         }
509     
510         if (stream->id < 0xc0) {
511             /* AC3/LPCM private data header */
512             buf_index += 4;
513             if (stream->id >= 0xa0) {
514                 int n;
515                 buf_index += 3;
516                 /* NOTE: we round the payload size to an integer number of
517                    LPCM samples */
518                 n = (s->packet_size - buf_index) % stream->lpcm_align;
519                 if (n)
520                     buf_index += (stream->lpcm_align - n);
521             }
522         }
523
524         if (s->is_vcd && stream->id == AUDIO_ID)
525             /* The VCD standard demands that 20 zero bytes follow
526                each audio packet (see standard p. IV-8).*/
527             buf_index+=20;
528     }
529     return s->packet_size - buf_index; 
530 }
531
532 /* Write an MPEG padding packet header. */
533 static int put_padding_header(AVFormatContext *ctx,uint8_t* buf, int full_padding_size)
534 {
535     MpegMuxContext *s = ctx->priv_data;
536     int size = full_padding_size - 6;    /* subtract header length */
537
538     buf[0] = (uint8_t)(PADDING_STREAM >> 24);
539     buf[1] = (uint8_t)(PADDING_STREAM >> 16);
540     buf[2] = (uint8_t)(PADDING_STREAM >> 8);
541     buf[3] = (uint8_t)(PADDING_STREAM);
542     buf[4] = (uint8_t)(size >> 8);
543     buf[5] = (uint8_t)(size & 0xff);
544
545     if (!s->is_mpeg2) {
546         buf[6] = 0x0f;
547         return 7;
548     } else
549         return 6;
550 }
551
552 static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
553 {
554     uint8_t buffer[7];
555     int size, i;
556     
557     size = put_padding_header(ctx,buffer, packet_bytes);
558     put_buffer(pb, buffer, size);
559     packet_bytes -= size;
560
561     for(i=0;i<packet_bytes;i++)
562         put_byte(pb, 0xff);
563 }
564
565
566 /* flush the packet on stream stream_index */
567 static void flush_packet(AVFormatContext *ctx, int stream_index, 
568                          int64_t pts, int64_t dts, int64_t scr)
569 {
570     MpegMuxContext *s = ctx->priv_data;
571     StreamInfo *stream = ctx->streams[stream_index]->priv_data;
572     uint8_t *buf_ptr;
573     int size, payload_size, startcode, id, stuffing_size, i, header_len;
574     int packet_size;
575     uint8_t buffer[128];
576     int zero_trail_bytes = 0;
577     int pad_packet_bytes = 0;
578     int pes_flags;
579     int general_pack = 0;  /*"general" pack without data specific to one stream?*/
580     
581     id = stream->id;
582     
583 #if 0
584     printf("packet ID=%2x PTS=%0.3f\n", 
585            id, pts / 90000.0);
586 #endif
587
588     buf_ptr = buffer;
589
590     if (((s->packet_number % s->pack_header_freq) == 0)) {
591         /* output pack and systems header if needed */
592         size = put_pack_header(ctx, buf_ptr, scr);
593         buf_ptr += size;
594
595         if (s->is_vcd) {
596             /* there is exactly one system header for each stream in a VCD MPEG,
597                One in the very first video packet and one in the very first
598                audio packet (see VCD standard p. IV-7 and IV-8).*/
599             
600             if (stream->packet_number==0) {
601                 size = put_system_header(ctx, buf_ptr, id);
602                 buf_ptr += size;
603             }
604         } else {
605             if ((s->packet_number % s->system_header_freq) == 0) {
606                 size = put_system_header(ctx, buf_ptr, 0);
607                 buf_ptr += size;
608             }
609         }
610     }
611     size = buf_ptr - buffer;
612     put_buffer(&ctx->pb, buffer, size);
613
614     packet_size = s->packet_size - size;
615
616     if (s->is_vcd && id == AUDIO_ID)
617         /* The VCD standard demands that 20 zero bytes follow
618            each audio pack (see standard p. IV-8).*/
619         zero_trail_bytes += 20;
620             
621     if ((s->is_vcd && stream->packet_number==0)
622         || (s->is_svcd && s->packet_number==0)) {
623         /* for VCD the first pack of each stream contains only the pack header,
624            the system header and lots of padding (see VCD standard p. IV-6).
625            In the case of an audio pack, 20 zero bytes are also added at
626            the end.*/
627         /* For SVCD we fill the very first pack to increase compatibility with
628            some DVD players. Not mandated by the standard.*/
629         if (s->is_svcd)
630             general_pack = 1;    /* the system header refers to both streams and no stream data*/
631         pad_packet_bytes = packet_size - zero_trail_bytes;
632     }
633
634     packet_size -= pad_packet_bytes + zero_trail_bytes;
635
636     if (packet_size > 0) {
637
638         /* packet header size */
639         packet_size -= 6;
640         
641         /* packet header */
642         if (s->is_mpeg2) {
643             header_len = 3;
644             if (stream->packet_number==0)
645                 header_len += 3; /* PES extension */
646             header_len += 1; /* obligatory stuffing byte */
647         } else {
648             header_len = 0;
649         }
650         if (pts != AV_NOPTS_VALUE) {
651             if (dts != pts)
652                 header_len += 5 + 5;
653             else
654                 header_len += 5;
655         } else {
656             if (!s->is_mpeg2)
657                 header_len++;
658         }
659
660         payload_size = packet_size - header_len;
661         if (id < 0xc0) {
662             startcode = PRIVATE_STREAM_1;
663             payload_size -= 4;
664             if (id >= 0xa0)
665                 payload_size -= 3;
666         } else {
667             startcode = 0x100 + id;
668         }
669
670         stuffing_size = payload_size - stream->buffer_ptr;
671         if (stuffing_size < 0)
672             stuffing_size = 0;
673         if (stuffing_size > 16) {    /*<=16 for MPEG-1, <=32 for MPEG-2*/
674             pad_packet_bytes += stuffing_size;
675             packet_size -= stuffing_size;
676             payload_size -= stuffing_size;
677             stuffing_size = 0;
678         }
679
680         put_be32(&ctx->pb, startcode);
681
682         put_be16(&ctx->pb, packet_size);
683         
684         if (!s->is_mpeg2)
685             for(i=0;i<stuffing_size;i++)
686                 put_byte(&ctx->pb, 0xff);
687
688         if (s->is_mpeg2) {
689             put_byte(&ctx->pb, 0x80); /* mpeg2 id */
690
691             pes_flags=0;
692
693             if (pts != AV_NOPTS_VALUE) {
694                 pes_flags |= 0x80;
695                 if (dts != pts)
696                     pes_flags |= 0x40;
697             }
698
699             /* Both the MPEG-2 and the SVCD standards demand that the
700                P-STD_buffer_size field be included in the first packet of
701                every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
702                and MPEG-2 standard 2.7.7) */
703             if (stream->packet_number == 0)
704                 pes_flags |= 0x01;
705
706             put_byte(&ctx->pb, pes_flags); /* flags */
707             put_byte(&ctx->pb, header_len - 3 + stuffing_size);
708
709             if (pes_flags & 0x80)  /*write pts*/
710                 put_timestamp(&ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
711             if (pes_flags & 0x40)  /*write dts*/
712                 put_timestamp(&ctx->pb, 0x01, dts);
713             
714             if (pes_flags & 0x01) {  /*write pes extension*/
715                 put_byte(&ctx->pb, 0x10); /* flags */
716
717                 /* P-STD buffer info */                
718                 if (id == AUDIO_ID)
719                     put_be16(&ctx->pb, 0x4000 | stream->max_buffer_size/128);
720                 else
721                     put_be16(&ctx->pb, 0x6000 | stream->max_buffer_size/1024);
722             }
723
724         } else {
725             if (pts != AV_NOPTS_VALUE) {
726                 if (dts != pts) {
727                     put_timestamp(&ctx->pb, 0x03, pts);
728                     put_timestamp(&ctx->pb, 0x01, dts);
729                 } else {
730                     put_timestamp(&ctx->pb, 0x02, pts);
731                 }
732             } else {
733                 put_byte(&ctx->pb, 0x0f);
734             }
735         }
736
737         if (s->is_mpeg2) {
738             /* special stuffing byte that is always written
739                to prevent accidental generation of start codes. */
740             put_byte(&ctx->pb, 0xff);
741
742             for(i=0;i<stuffing_size;i++)
743                 put_byte(&ctx->pb, 0xff);
744         }
745
746         if (startcode == PRIVATE_STREAM_1) {
747             put_byte(&ctx->pb, id);
748             if (id >= 0xa0) {
749                 /* LPCM (XXX: check nb_frames) */
750                 put_byte(&ctx->pb, 7);
751                 put_be16(&ctx->pb, 4); /* skip 3 header bytes */
752                 put_byte(&ctx->pb, stream->lpcm_header[0]);
753                 put_byte(&ctx->pb, stream->lpcm_header[1]);
754                 put_byte(&ctx->pb, stream->lpcm_header[2]);
755             } else {
756                 /* AC3 */
757                 put_byte(&ctx->pb, stream->nb_frames);
758                 put_be16(&ctx->pb, stream->frame_start_offset);
759             }
760         }
761
762         /* output data */
763         put_buffer(&ctx->pb, stream->buffer, payload_size - stuffing_size);
764     }
765
766     if (pad_packet_bytes > 0)
767         put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);    
768
769     for(i=0;i<zero_trail_bytes;i++)
770         put_byte(&ctx->pb, 0x00);
771         
772     put_flush_packet(&ctx->pb);
773     
774     s->packet_number++;
775
776     /* only increase the stream packet number if this pack actually contains
777        something that is specific to this stream! I.e. a dedicated header
778        or some data.*/
779     if (!general_pack)
780         stream->packet_number++;
781     stream->nb_frames = 0;
782     stream->frame_start_offset = 0;
783 }
784
785 static void put_vcd_padding_sector(AVFormatContext *ctx)
786 {
787     /* There are two ways to do this padding: writing a sector/pack
788        of 0 values, or writing an MPEG padding pack. Both seem to
789        work with most decoders, BUT the VCD standard only allows a 0-sector
790        (see standard p. IV-4, IV-5).
791        So a 0-sector it is...*/
792
793     MpegMuxContext *s = ctx->priv_data;
794     int i;
795
796     for(i=0;i<s->packet_size;i++)
797         put_byte(&ctx->pb, 0);
798
799     s->vcd_padding_bytes_written += s->packet_size;
800         
801     put_flush_packet(&ctx->pb);
802     
803     /* increasing the packet number is correct. The SCR of the following packs
804        is calculated from the packet_number and it has to include the padding
805        sector (it represents the sector index, not the MPEG pack index)
806        (see VCD standard p. IV-6)*/
807     s->packet_number++;
808 }
809
810 static int64_t update_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
811 {
812     MpegMuxContext *s = ctx->priv_data;
813     int64_t scr;
814     StreamInfo *stream;
815     int i;
816
817     if (s->is_vcd) {
818         /* Since the data delivery rate is constant, SCR is computed
819            using the formula C + i * 1200 where C is the start constant
820            and i is the pack index.
821            It is recommended that SCR 0 is at the beginning of the VCD front
822            margin (a sequence of empty Form 2 sectors on the CD).
823            It is recommended that the front margin is 30 sectors long, so
824            we use C = 30*1200 = 36000
825            (Note that even if the front margin is not 30 sectors the file
826            will still be correct according to the standard. It just won't have
827            the "recommended" value).*/
828         scr = 36000 + s->packet_number * 1200;
829
830
831 #if 0
832         for(i=0;i<ctx->nb_streams;i++) {
833             stream = ctx->streams[i]->priv_data;
834             
835             if(scr > stream->start_pts && stream->start_pts!=AV_NOPTS_VALUE) {
836                 av_log(ctx, AV_LOG_DEBUG, "mpeg vcd: SCR above PTS (scr=%0.3f, stream index=%d, stream_pts=%0.3f).\n", scr/90000.0, i, stream->start_pts / 90000.0);                 
837             }
838         }
839 #endif
840     }
841     else {
842         
843         
844         /* XXX I believe this calculation of SCR is wrong. SCR
845            specifies at which time the data should enter the decoder.
846            Two packs cannot enter the decoder at the same time. */
847
848         /* XXX: system clock should be computed precisely, especially for
849         CBR case. The current mode gives at least something coherent */
850         if (stream_index == s->scr_stream_index
851             && pts != AV_NOPTS_VALUE)
852             scr = pts;
853         else
854             scr = s->last_scr;
855
856         /* "Sanity hack": make sure that the SCR does not overtake the pts of
857            buffered data that is still waiting to be written.*/
858         for(i=0;i<ctx->nb_streams;i++) {
859             stream = ctx->streams[i]->priv_data;
860             
861             if(scr > stream->start_pts && stream->start_pts!=AV_NOPTS_VALUE) {
862                 /* av_log(ctx, AV_LOG_DEBUG, "mpeg: restricting scr to stream pts (scr=%0.3f, stream index=%d, stream_pts=%0.3f).\n", scr/90000.0, i, stream->start_pts / 90000.0); */
863                 scr = stream->start_pts;
864             }
865         }
866     }
867
868     s->last_scr=scr;
869
870     return scr;
871 }    
872
873
874 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
875 {
876     MpegMuxContext *s = ctx->priv_data;
877     int stream_index= pkt->stream_index;
878     int size= pkt->size;
879     uint8_t *buf= pkt->data;
880     AVStream *st = ctx->streams[stream_index];
881     StreamInfo *stream = st->priv_data;
882     int64_t pts, dts, new_start_pts, new_start_dts;
883     int len, avail_size;
884     
885     pts= pkt->pts;
886     dts= pkt->dts;
887
888     if(s->is_svcd) {
889         /* offset pts and dts slightly into the future to be able
890            to do the compatibility fix below.*/
891         pts = (pts + 2) & ((1LL << 33) - 1);
892         dts = (dts + 2) & ((1LL << 33) - 1);
893
894         if (stream->packet_number == 0 && dts == pts)
895             /* For the very first packet we want to force the DTS to be included.
896                This increases compatibility with lots of DVD players.
897                Since the MPEG-2 standard mandates that DTS is only written when
898                it is different from PTS we have to move it slightly into the past.*/
899             dts = (dts - 2) & ((1LL << 33) - 1);
900     }
901     if(s->is_vcd) {
902         /* We have to offset the PTS, so that it is consistent with the SCR.
903            SCR starts at 36000, but the first two packs contain only padding
904            and the first pack from the other stream, respectively, may also have
905            been written before.
906            So the real data starts at SCR 36000+3*1200. */
907         pts = (pts + 36000 + 3600) & ((1LL << 33) - 1);
908         dts = (dts + 36000 + 3600) & ((1LL << 33) - 1);
909     }
910     
911 #if 0
912     update_scr(ctx,stream_index,pts);
913
914     printf("%d: pts=%0.3f dts=%0.3f scr=%0.3f\n", 
915            stream_index, 
916            pts / 90000.0, 
917            dts / 90000.0, 
918            s->last_scr / 90000.0);
919 #endif
920     
921     /* we assume here that pts != AV_NOPTS_VALUE */
922     new_start_pts = stream->start_pts;
923     new_start_dts = stream->start_dts;
924     
925     if (stream->start_pts == AV_NOPTS_VALUE) {
926         new_start_pts = pts;
927         new_start_dts = dts;
928     }
929     avail_size = get_packet_payload_size(ctx, stream_index,
930                                          new_start_pts, 
931                                          new_start_dts);
932     if (stream->buffer_ptr >= avail_size) {
933
934         update_scr(ctx,stream_index,stream->start_pts);
935
936         /* unlikely case: outputing the pts or dts increase the packet
937            size so that we cannot write the start of the next
938            packet. In this case, we must flush the current packet with
939            padding.
940            Note: this always happens for the first audio and video packet
941            in a VCD file, since they do not carry any data.*/
942         flush_packet(ctx, stream_index,
943                      stream->start_pts, stream->start_dts, s->last_scr);
944         stream->buffer_ptr = 0;
945     }
946     stream->start_pts = new_start_pts;
947     stream->start_dts = new_start_dts;
948     stream->nb_frames++;
949     if (stream->frame_start_offset == 0)
950         stream->frame_start_offset = stream->buffer_ptr + 1;
951     while (size > 0) {
952         avail_size = get_packet_payload_size(ctx, stream_index,
953                                              stream->start_pts, 
954                                              stream->start_dts);
955         len = avail_size - stream->buffer_ptr;
956         if (len > size)
957             len = size;
958         memcpy(stream->buffer + stream->buffer_ptr, buf, len);
959         stream->buffer_ptr += len;
960         buf += len;
961         size -= len;
962         if (stream->buffer_ptr >= avail_size) {
963
964             update_scr(ctx,stream_index,stream->start_pts);
965
966             /* if packet full, we send it now */
967             flush_packet(ctx, stream_index,
968                          stream->start_pts, stream->start_dts, s->last_scr);
969             stream->buffer_ptr = 0;
970
971             if (s->is_vcd) {
972                 /* Write one or more padding sectors, if necessary, to reach
973                    the constant overall bitrate.*/
974                 int vcd_pad_bytes;
975             
976                 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->start_pts) ) >= s->packet_size)
977                     put_vcd_padding_sector(ctx);
978             }
979
980             /* Make sure only the FIRST pes packet for this frame has
981                a timestamp */
982             stream->start_pts = AV_NOPTS_VALUE;
983             stream->start_dts = AV_NOPTS_VALUE;
984         }
985     }
986
987     return 0;
988 }
989
990 static int mpeg_mux_end(AVFormatContext *ctx)
991 {
992     MpegMuxContext *s = ctx->priv_data;
993     StreamInfo *stream;
994     int i;
995
996     /* flush each packet */
997     for(i=0;i<ctx->nb_streams;i++) {
998         stream = ctx->streams[i]->priv_data;
999         if (stream->buffer_ptr > 0) {
1000             update_scr(ctx,i,stream->start_pts);
1001
1002             /* NOTE: we can always write the remaining data as it was
1003                tested before in mpeg_mux_write_packet() */
1004             flush_packet(ctx, i, stream->start_pts, stream->start_dts, 
1005                          s->last_scr);
1006         }
1007     }
1008
1009     /* End header according to MPEG1 systems standard. We do not write
1010        it as it is usually not needed by decoders and because it
1011        complicates MPEG stream concatenation. */
1012     //put_be32(&ctx->pb, ISO_11172_END_CODE);
1013     //put_flush_packet(&ctx->pb);
1014
1015     for(i=0;i<ctx->nb_streams;i++)
1016         av_freep(&ctx->streams[i]->priv_data);
1017
1018     return 0;
1019 }
1020 #endif //CONFIG_ENCODERS
1021
1022 /*********************************************/
1023 /* demux code */
1024
1025 #define MAX_SYNC_SIZE 100000
1026
1027 static int mpegps_probe(AVProbeData *p)
1028 {
1029     int code, c, i;
1030
1031     code = 0xff;
1032     /* we search the first start code. If it is a packet start code,
1033        then we decide it is mpeg ps. We do not send highest value to
1034        give a chance to mpegts */
1035     /* NOTE: the search range was restricted to avoid too many false
1036        detections */
1037
1038     if (p->buf_size < 6)
1039         return 0;
1040
1041     for (i = 0; i < 20; i++) {
1042         c = p->buf[i];
1043         code = (code << 8) | c;
1044         if ((code & 0xffffff00) == 0x100) {
1045             if (code == PACK_START_CODE ||
1046                 code == SYSTEM_HEADER_START_CODE ||
1047                 (code >= 0x1e0 && code <= 0x1ef) ||
1048                 (code >= 0x1c0 && code <= 0x1df) ||
1049                 code == PRIVATE_STREAM_2 ||
1050                 code == PROGRAM_STREAM_MAP ||
1051                 code == PRIVATE_STREAM_1 ||
1052                 code == PADDING_STREAM)
1053                 return AVPROBE_SCORE_MAX - 2;
1054             else
1055                 return 0;
1056         }
1057     }
1058     return 0;
1059 }
1060
1061
1062 typedef struct MpegDemuxContext {
1063     int header_state;
1064 } MpegDemuxContext;
1065
1066 static int mpegps_read_header(AVFormatContext *s,
1067                               AVFormatParameters *ap)
1068 {
1069     MpegDemuxContext *m = s->priv_data;
1070     m->header_state = 0xff;
1071     s->ctx_flags |= AVFMTCTX_NOHEADER;
1072
1073     /* no need to do more */
1074     return 0;
1075 }
1076
1077 static int64_t get_pts(ByteIOContext *pb, int c)
1078 {
1079     int64_t pts;
1080     int val;
1081
1082     if (c < 0)
1083         c = get_byte(pb);
1084     pts = (int64_t)((c >> 1) & 0x07) << 30;
1085     val = get_be16(pb);
1086     pts |= (int64_t)(val >> 1) << 15;
1087     val = get_be16(pb);
1088     pts |= (int64_t)(val >> 1);
1089     return pts;
1090 }
1091
1092 static int find_next_start_code(ByteIOContext *pb, int *size_ptr, 
1093                                 uint32_t *header_state)
1094 {
1095     unsigned int state, v;
1096     int val, n;
1097
1098     state = *header_state;
1099     n = *size_ptr;
1100     while (n > 0) {
1101         if (url_feof(pb))
1102             break;
1103         v = get_byte(pb);
1104         n--;
1105         if (state == 0x000001) {
1106             state = ((state << 8) | v) & 0xffffff;
1107             val = state;
1108             goto found;
1109         }
1110         state = ((state << 8) | v) & 0xffffff;
1111     }
1112     val = -1;
1113  found:
1114     *header_state = state;
1115     *size_ptr = n;
1116     return val;
1117 }
1118
1119 /* XXX: optimize */
1120 static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
1121 {
1122     int64_t pos, pos_start;
1123     int max_size, start_code;
1124
1125     max_size = *size_ptr;
1126     pos_start = url_ftell(pb);
1127
1128     /* in order to go faster, we fill the buffer */
1129     pos = pos_start - 16386;
1130     if (pos < 0)
1131         pos = 0;
1132     url_fseek(pb, pos, SEEK_SET);
1133     get_byte(pb);
1134
1135     pos = pos_start;
1136     for(;;) {
1137         pos--;
1138         if (pos < 0 || (pos_start - pos) >= max_size) {
1139             start_code = -1;
1140             goto the_end;
1141         }
1142         url_fseek(pb, pos, SEEK_SET);
1143         start_code = get_be32(pb);
1144         if ((start_code & 0xffffff00) == 0x100)
1145             break;
1146     }
1147  the_end:
1148     *size_ptr = pos_start - pos;
1149     return start_code;
1150 }
1151
1152 /* read the next PES header. Return its position in ppos 
1153    (if not NULL), and its start code, pts and dts.
1154  */
1155 static int mpegps_read_pes_header(AVFormatContext *s,
1156                                   int64_t *ppos, int *pstart_code, 
1157                                   int64_t *ppts, int64_t *pdts)
1158 {
1159     MpegDemuxContext *m = s->priv_data;
1160     int len, size, startcode, c, flags, header_len;
1161     int64_t pts, dts, last_pos;
1162
1163     last_pos = -1;
1164  redo:
1165         /* next start code (should be immediately after) */
1166         m->header_state = 0xff;
1167         size = MAX_SYNC_SIZE;
1168         startcode = find_next_start_code(&s->pb, &size, &m->header_state);
1169     //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
1170     if (startcode < 0)
1171         return AVERROR_IO;
1172     if (startcode == PACK_START_CODE)
1173         goto redo;
1174     if (startcode == SYSTEM_HEADER_START_CODE)
1175         goto redo;
1176     if (startcode == PADDING_STREAM ||
1177         startcode == PRIVATE_STREAM_2) {
1178         /* skip them */
1179         len = get_be16(&s->pb);
1180         url_fskip(&s->pb, len);
1181         goto redo;
1182     }
1183     /* find matching stream */
1184     if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
1185           (startcode >= 0x1e0 && startcode <= 0x1ef) ||
1186           (startcode == 0x1bd)))
1187         goto redo;
1188     if (ppos) {
1189         *ppos = url_ftell(&s->pb) - 4;
1190     }
1191     len = get_be16(&s->pb);
1192     pts = AV_NOPTS_VALUE;
1193     dts = AV_NOPTS_VALUE;
1194     /* stuffing */
1195     for(;;) {
1196         if (len < 1)
1197             goto redo;
1198         c = get_byte(&s->pb);
1199         len--;
1200         /* XXX: for mpeg1, should test only bit 7 */
1201         if (c != 0xff) 
1202             break;
1203     }
1204     if ((c & 0xc0) == 0x40) {
1205         /* buffer scale & size */
1206         if (len < 2)
1207             goto redo;
1208         get_byte(&s->pb);
1209         c = get_byte(&s->pb);
1210         len -= 2;
1211     }
1212     if ((c & 0xf0) == 0x20) {
1213         if (len < 4)
1214             goto redo;
1215         dts = pts = get_pts(&s->pb, c);
1216         len -= 4;
1217     } else if ((c & 0xf0) == 0x30) {
1218         if (len < 9)
1219             goto redo;
1220         pts = get_pts(&s->pb, c);
1221         dts = get_pts(&s->pb, -1);
1222         len -= 9;
1223     } else if ((c & 0xc0) == 0x80) {
1224         /* mpeg 2 PES */
1225         if ((c & 0x30) != 0) {
1226             /* Encrypted multiplex not handled */
1227             goto redo;
1228         }
1229         flags = get_byte(&s->pb);
1230         header_len = get_byte(&s->pb);
1231         len -= 2;
1232         if (header_len > len)
1233             goto redo;
1234         if ((flags & 0xc0) == 0x80) {
1235             dts = pts = get_pts(&s->pb, -1);
1236             if (header_len < 5)
1237                 goto redo;
1238             header_len -= 5;
1239             len -= 5;
1240         } if ((flags & 0xc0) == 0xc0) {
1241             pts = get_pts(&s->pb, -1);
1242             dts = get_pts(&s->pb, -1);
1243             if (header_len < 10)
1244                 goto redo;
1245             header_len -= 10;
1246             len -= 10;
1247         }
1248         len -= header_len;
1249         while (header_len > 0) {
1250             get_byte(&s->pb);
1251             header_len--;
1252         }
1253     }
1254     else if( c!= 0xf )
1255         goto redo;
1256
1257     if (startcode == 0x1bd) {
1258         if (len < 1)
1259             goto redo;
1260         startcode = get_byte(&s->pb);
1261         len--;
1262         if (startcode >= 0x80 && startcode <= 0xbf) {
1263             /* audio: skip header */
1264             if (len < 3)
1265                 goto redo;
1266             get_byte(&s->pb);
1267             get_byte(&s->pb);
1268             get_byte(&s->pb);
1269             len -= 3;
1270         }
1271     }
1272     if(dts != AV_NOPTS_VALUE && ppos){
1273         int i;
1274         for(i=0; i<s->nb_streams; i++){
1275             if(startcode == s->streams[i]->id) {
1276                 av_add_index_entry(s->streams[i], *ppos, dts, 0, 0 /* FIXME keyframe? */);
1277             }
1278         }
1279     }
1280     
1281     *pstart_code = startcode;
1282     *ppts = pts;
1283     *pdts = dts;
1284     return len;
1285 }
1286
1287 static int mpegps_read_packet(AVFormatContext *s,
1288                               AVPacket *pkt)
1289 {
1290     AVStream *st;
1291     int len, startcode, i, type, codec_id = 0;
1292     int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
1293
1294  redo:
1295     len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
1296     if (len < 0)
1297         return len;
1298     
1299     /* now find stream */
1300     for(i=0;i<s->nb_streams;i++) {
1301         st = s->streams[i];
1302         if (st->id == startcode)
1303             goto found;
1304     }
1305     if (startcode >= 0x1e0 && startcode <= 0x1ef) {
1306         type = CODEC_TYPE_VIDEO;
1307         codec_id = CODEC_ID_MPEG2VIDEO;
1308     } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
1309         type = CODEC_TYPE_AUDIO;
1310         codec_id = CODEC_ID_MP2;
1311     } else if (startcode >= 0x80 && startcode <= 0x89) {
1312         type = CODEC_TYPE_AUDIO;
1313         codec_id = CODEC_ID_AC3;
1314     } else if (startcode >= 0x8a && startcode <= 0x9f) {
1315         type = CODEC_TYPE_AUDIO;
1316         codec_id = CODEC_ID_DTS;
1317     } else if (startcode >= 0xa0 && startcode <= 0xbf) {
1318         type = CODEC_TYPE_AUDIO;
1319         codec_id = CODEC_ID_PCM_S16BE;
1320     } else {
1321     skip:
1322         /* skip packet */
1323         url_fskip(&s->pb, len);
1324         goto redo;
1325     }
1326     /* no stream found: add a new stream */
1327     st = av_new_stream(s, startcode);
1328     if (!st) 
1329         goto skip;
1330     st->codec.codec_type = type;
1331     st->codec.codec_id = codec_id;
1332     if (codec_id != CODEC_ID_PCM_S16BE)
1333         st->need_parsing = 1;
1334  found:
1335     if (startcode >= 0xa0 && startcode <= 0xbf) {
1336         int b1, freq;
1337
1338         /* for LPCM, we just skip the header and consider it is raw
1339            audio data */
1340         if (len <= 3)
1341             goto skip;
1342         get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
1343         b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
1344         get_byte(&s->pb); /* dynamic range control (0x80 = off) */
1345         len -= 3;
1346         freq = (b1 >> 4) & 3;
1347         st->codec.sample_rate = lpcm_freq_tab[freq];
1348         st->codec.channels = 1 + (b1 & 7);
1349         st->codec.bit_rate = st->codec.channels * st->codec.sample_rate * 2;
1350     }
1351     av_new_packet(pkt, len);
1352     get_buffer(&s->pb, pkt->data, pkt->size);
1353     pkt->pts = pts;
1354     pkt->dts = dts;
1355     pkt->stream_index = st->index;
1356 #if 0
1357     av_log(s, AV_LOG_DEBUG, "%d: pts=%0.3f dts=%0.3f\n",
1358            pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0);
1359 #endif
1360
1361     return 0;
1362 }
1363
1364 static int mpegps_read_close(AVFormatContext *s)
1365 {
1366     return 0;
1367 }
1368
1369 static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index, 
1370                                int64_t *ppos, int64_t pos_limit)
1371 {
1372     int len, startcode;
1373     int64_t pos, pts, dts;
1374
1375     pos = *ppos;
1376 #ifdef DEBUG_SEEK
1377     printf("read_dts: pos=0x%llx next=%d -> ", pos, find_next);
1378 #endif
1379     url_fseek(&s->pb, pos, SEEK_SET);
1380     for(;;) {
1381         len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
1382         if (len < 0) {
1383 #ifdef DEBUG_SEEK
1384             printf("none (ret=%d)\n", len);
1385 #endif
1386             return AV_NOPTS_VALUE;
1387         }
1388         if (startcode == s->streams[stream_index]->id && 
1389             dts != AV_NOPTS_VALUE) {
1390             break;
1391         }
1392         url_fskip(&s->pb, len);
1393     }
1394 #ifdef DEBUG_SEEK
1395     printf("pos=0x%llx dts=0x%llx %0.3f\n", pos, dts, dts / 90000.0);
1396 #endif
1397     *ppos = pos;
1398     return dts;
1399 }
1400
1401 #ifdef CONFIG_ENCODERS
1402 static AVOutputFormat mpeg1system_mux = {
1403     "mpeg",
1404     "MPEG1 System format",
1405     "video/mpeg",
1406     "mpg,mpeg",
1407     sizeof(MpegMuxContext),
1408     CODEC_ID_MP2,
1409     CODEC_ID_MPEG1VIDEO,
1410     mpeg_mux_init,
1411     mpeg_mux_write_packet,
1412     mpeg_mux_end,
1413 };
1414
1415 static AVOutputFormat mpeg1vcd_mux = {
1416     "vcd",
1417     "MPEG1 System format (VCD)",
1418     "video/mpeg",
1419     NULL,
1420     sizeof(MpegMuxContext),
1421     CODEC_ID_MP2,
1422     CODEC_ID_MPEG1VIDEO,
1423     mpeg_mux_init,
1424     mpeg_mux_write_packet,
1425     mpeg_mux_end,
1426 };
1427
1428 static AVOutputFormat mpeg2vob_mux = {
1429     "vob",
1430     "MPEG2 PS format (VOB)",
1431     "video/mpeg",
1432     "vob",
1433     sizeof(MpegMuxContext),
1434     CODEC_ID_MP2,
1435     CODEC_ID_MPEG2VIDEO,
1436     mpeg_mux_init,
1437     mpeg_mux_write_packet,
1438     mpeg_mux_end,
1439 };
1440
1441 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1442 static AVOutputFormat mpeg2svcd_mux = {
1443     "svcd",
1444     "MPEG2 PS format (VOB)",
1445     "video/mpeg",
1446     "vob",
1447     sizeof(MpegMuxContext),
1448     CODEC_ID_MP2,
1449     CODEC_ID_MPEG2VIDEO,
1450     mpeg_mux_init,
1451     mpeg_mux_write_packet,
1452     mpeg_mux_end,
1453 };
1454
1455
1456
1457 #endif //CONFIG_ENCODERS
1458
1459 AVInputFormat mpegps_demux = {
1460     "mpeg",
1461     "MPEG PS format",
1462     sizeof(MpegDemuxContext),
1463     mpegps_probe,
1464     mpegps_read_header,
1465     mpegps_read_packet,
1466     mpegps_read_close,
1467     NULL, //mpegps_read_seek,
1468     mpegps_read_dts,
1469 };
1470
1471 int mpegps_init(void)
1472 {
1473 #ifdef CONFIG_ENCODERS
1474     av_register_output_format(&mpeg1system_mux);
1475     av_register_output_format(&mpeg1vcd_mux);
1476     av_register_output_format(&mpeg2vob_mux);
1477     av_register_output_format(&mpeg2svcd_mux);
1478 #endif //CONFIG_ENCODERS
1479     av_register_input_format(&mpegps_demux);
1480     return 0;
1481 }