]> git.sesse.net Git - ffmpeg/blob - libavformat/mpeg.c
3 lines while -> 1 line for loop
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 #include "avformat.h"
20 #include "bitstream.h"
21
22 #define MAX_PAYLOAD_SIZE 4096
23 //#define DEBUG_SEEK
24
25 #undef NDEBUG
26 #include <assert.h>
27
28 typedef struct PacketDesc {
29     int64_t pts;
30     int64_t dts;
31     int size;
32     int unwritten_size;
33     int flags;
34     struct PacketDesc *next;
35 } PacketDesc;
36
37 typedef struct {
38     FifoBuffer fifo;
39     uint8_t id;
40     int max_buffer_size; /* in bytes */
41     int buffer_index;
42     PacketDesc *predecode_packet;
43     PacketDesc *premux_packet;
44     PacketDesc **next_packet;
45     int packet_number;
46     uint8_t lpcm_header[3];
47     int lpcm_align;
48     uint8_t *fifo_iframe_ptr;
49     int align_iframe;
50     int64_t vobu_start_pts;
51 } StreamInfo;
52
53 typedef struct {
54     int packet_size; /* required packet size */
55     int packet_number;
56     int pack_header_freq;     /* frequency (in packets^-1) at which we send pack headers */
57     int system_header_freq;
58     int system_header_size;
59     int mux_rate; /* bitrate in units of 50 bytes/s */
60     /* stream info */
61     int audio_bound;
62     int video_bound;
63     int is_mpeg2;
64     int is_vcd;
65     int is_svcd;
66     int is_dvd;
67     int64_t last_scr; /* current system clock */
68
69     double vcd_padding_bitrate; //FIXME floats
70     int64_t vcd_padding_bytes_written;
71
72 } MpegMuxContext;
73
74 #define PACK_START_CODE             ((unsigned int)0x000001ba)
75 #define SYSTEM_HEADER_START_CODE    ((unsigned int)0x000001bb)
76 #define SEQUENCE_END_CODE           ((unsigned int)0x000001b7)
77 #define PACKET_START_CODE_MASK      ((unsigned int)0xffffff00)
78 #define PACKET_START_CODE_PREFIX    ((unsigned int)0x00000100)
79 #define ISO_11172_END_CODE          ((unsigned int)0x000001b9)
80
81 /* mpeg2 */
82 #define PROGRAM_STREAM_MAP 0x1bc
83 #define PRIVATE_STREAM_1   0x1bd
84 #define PADDING_STREAM     0x1be
85 #define PRIVATE_STREAM_2   0x1bf
86
87
88 #define AUDIO_ID 0xc0
89 #define VIDEO_ID 0xe0
90 #define AC3_ID   0x80
91 #define DTS_ID   0x8a
92 #define LPCM_ID  0xa0
93 #define SUB_ID   0x20
94
95 #define STREAM_TYPE_VIDEO_MPEG1     0x01
96 #define STREAM_TYPE_VIDEO_MPEG2     0x02
97 #define STREAM_TYPE_AUDIO_MPEG1     0x03
98 #define STREAM_TYPE_AUDIO_MPEG2     0x04
99 #define STREAM_TYPE_PRIVATE_SECTION 0x05
100 #define STREAM_TYPE_PRIVATE_DATA    0x06
101 #define STREAM_TYPE_AUDIO_AAC       0x0f
102 #define STREAM_TYPE_VIDEO_MPEG4     0x10
103 #define STREAM_TYPE_VIDEO_H264      0x1b
104
105 #define STREAM_TYPE_AUDIO_AC3       0x81
106 #define STREAM_TYPE_AUDIO_DTS       0x8a
107
108 static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
109
110 #ifdef CONFIG_MUXERS
111 static AVOutputFormat mpeg1system_mux;
112 static AVOutputFormat mpeg1vcd_mux;
113 static AVOutputFormat mpeg2vob_mux;
114 static AVOutputFormat mpeg2svcd_mux;
115 static AVOutputFormat mpeg2dvd_mux;
116
117 static int put_pack_header(AVFormatContext *ctx,
118                            uint8_t *buf, int64_t timestamp)
119 {
120     MpegMuxContext *s = ctx->priv_data;
121     PutBitContext pb;
122
123     init_put_bits(&pb, buf, 128);
124
125     put_bits(&pb, 32, PACK_START_CODE);
126     if (s->is_mpeg2) {
127         put_bits(&pb, 2, 0x1);
128     } else {
129         put_bits(&pb, 4, 0x2);
130     }
131     put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
132     put_bits(&pb, 1, 1);
133     put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
134     put_bits(&pb, 1, 1);
135     put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
136     put_bits(&pb, 1, 1);
137     if (s->is_mpeg2) {
138         /* clock extension */
139         put_bits(&pb, 9, 0);
140     }
141     put_bits(&pb, 1, 1);
142     put_bits(&pb, 22, s->mux_rate);
143     put_bits(&pb, 1, 1);
144     if (s->is_mpeg2) {
145         put_bits(&pb, 1, 1);
146         put_bits(&pb, 5, 0x1f); /* reserved */
147         put_bits(&pb, 3, 0); /* stuffing length */
148     }
149     flush_put_bits(&pb);
150     return pbBufPtr(&pb) - pb.buf;
151 }
152
153 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
154 {
155     MpegMuxContext *s = ctx->priv_data;
156     int size, i, private_stream_coded, id;
157     PutBitContext pb;
158
159     init_put_bits(&pb, buf, 128);
160
161     put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
162     put_bits(&pb, 16, 0);
163     put_bits(&pb, 1, 1);
164
165     put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
166     put_bits(&pb, 1, 1); /* marker */
167     if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
168         /* This header applies only to the video stream (see VCD standard p. IV-7)*/
169         put_bits(&pb, 6, 0);
170     } else
171         put_bits(&pb, 6, s->audio_bound);
172
173     if (s->is_vcd) {
174         /* see VCD standard, p. IV-7*/
175         put_bits(&pb, 1, 0);
176         put_bits(&pb, 1, 1);
177     } else {
178         put_bits(&pb, 1, 0); /* variable bitrate*/
179         put_bits(&pb, 1, 0); /* non constrainted bit stream */
180     }
181
182     if (s->is_vcd || s->is_dvd) {
183         /* see VCD standard p IV-7 */
184         put_bits(&pb, 1, 1); /* audio locked */
185         put_bits(&pb, 1, 1); /* video locked */
186     } else {
187         put_bits(&pb, 1, 0); /* audio locked */
188         put_bits(&pb, 1, 0); /* video locked */
189     }
190
191     put_bits(&pb, 1, 1); /* marker */
192
193     if (s->is_vcd && only_for_stream_id==AUDIO_ID) {
194         /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
195         put_bits(&pb, 5, 0);
196     } else
197         put_bits(&pb, 5, s->video_bound);
198
199     if (s->is_dvd) {
200         put_bits(&pb, 1, 0);    /* packet_rate_restriction_flag */
201         put_bits(&pb, 7, 0x7f); /* reserved byte */
202     } else
203         put_bits(&pb, 8, 0xff); /* reserved byte */
204
205     /* DVD-Video Stream_bound entries
206     id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
207     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)
208     id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
209     id (0xBF) private stream 2, NAV packs, set to 2x1024. */
210     if (s->is_dvd) {
211
212         int P_STD_max_video = 0;
213         int P_STD_max_mpeg_audio = 0;
214         int P_STD_max_mpeg_PS1 = 0;
215
216         for(i=0;i<ctx->nb_streams;i++) {
217             StreamInfo *stream = ctx->streams[i]->priv_data;
218
219             id = stream->id;
220             if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
221                 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
222             } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
223                 P_STD_max_mpeg_audio = stream->max_buffer_size;
224             } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
225                 P_STD_max_video = stream->max_buffer_size;
226             }
227         }
228
229         /* video */
230         put_bits(&pb, 8, 0xb9); /* stream ID */
231         put_bits(&pb, 2, 3);
232         put_bits(&pb, 1, 1);
233         put_bits(&pb, 13, P_STD_max_video / 1024);
234
235         /* audio */
236         if (P_STD_max_mpeg_audio == 0)
237             P_STD_max_mpeg_audio = 4096;
238         put_bits(&pb, 8, 0xb8); /* stream ID */
239         put_bits(&pb, 2, 3);
240         put_bits(&pb, 1, 0);
241         put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
242
243         /* private stream 1 */
244         put_bits(&pb, 8, 0xbd); /* stream ID */
245         put_bits(&pb, 2, 3);
246         put_bits(&pb, 1, 0);
247         put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
248
249         /* private stream 2 */
250         put_bits(&pb, 8, 0xbf); /* stream ID */
251         put_bits(&pb, 2, 3);
252         put_bits(&pb, 1, 1);
253         put_bits(&pb, 13, 2);
254     }
255     else {
256         /* audio stream info */
257         private_stream_coded = 0;
258         for(i=0;i<ctx->nb_streams;i++) {
259             StreamInfo *stream = ctx->streams[i]->priv_data;
260
261
262             /* For VCDs, only include the stream info for the stream
263             that the pack which contains this system belongs to.
264             (see VCD standard p. IV-7) */
265             if ( !s->is_vcd || stream->id==only_for_stream_id
266                 || only_for_stream_id==0) {
267
268                 id = stream->id;
269                 if (id < 0xc0) {
270                     /* special case for private streams (AC3 use that) */
271                     if (private_stream_coded)
272                         continue;
273                     private_stream_coded = 1;
274                     id = 0xbd;
275                 }
276                 put_bits(&pb, 8, id); /* stream ID */
277                 put_bits(&pb, 2, 3);
278                 if (id < 0xe0) {
279                     /* audio */
280                     put_bits(&pb, 1, 0);
281                     put_bits(&pb, 13, stream->max_buffer_size / 128);
282                 } else {
283                     /* video */
284                     put_bits(&pb, 1, 1);
285                     put_bits(&pb, 13, stream->max_buffer_size / 1024);
286                 }
287             }
288         }
289     }
290
291     flush_put_bits(&pb);
292     size = pbBufPtr(&pb) - pb.buf;
293     /* patch packet size */
294     buf[4] = (size - 6) >> 8;
295     buf[5] = (size - 6) & 0xff;
296
297     return size;
298 }
299
300 static int get_system_header_size(AVFormatContext *ctx)
301 {
302     int buf_index, i, private_stream_coded;
303     StreamInfo *stream;
304     MpegMuxContext *s = ctx->priv_data;
305
306     if (s->is_dvd)
307        return 18; // DVD-Video system headers are 18 bytes fixed length.
308
309     buf_index = 12;
310     private_stream_coded = 0;
311     for(i=0;i<ctx->nb_streams;i++) {
312         stream = ctx->streams[i]->priv_data;
313         if (stream->id < 0xc0) {
314             if (private_stream_coded)
315                 continue;
316             private_stream_coded = 1;
317         }
318         buf_index += 3;
319     }
320     return buf_index;
321 }
322
323 static int mpeg_mux_init(AVFormatContext *ctx)
324 {
325     MpegMuxContext *s = ctx->priv_data;
326     int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
327     AVStream *st;
328     StreamInfo *stream;
329     int audio_bitrate;
330     int video_bitrate;
331
332     s->packet_number = 0;
333     s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
334     s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
335     s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux || ctx->oformat == &mpeg2dvd_mux);
336     s->is_dvd = (ctx->oformat == &mpeg2dvd_mux);
337
338     if(ctx->packet_size)
339         s->packet_size = ctx->packet_size;
340     else
341         s->packet_size = 2048;
342
343     s->vcd_padding_bytes_written = 0;
344     s->vcd_padding_bitrate=0;
345
346     s->audio_bound = 0;
347     s->video_bound = 0;
348     mpa_id = AUDIO_ID;
349     ac3_id = AC3_ID;
350     dts_id = DTS_ID;
351     mpv_id = VIDEO_ID;
352     mps_id = SUB_ID;
353     lpcm_id = LPCM_ID;
354     for(i=0;i<ctx->nb_streams;i++) {
355         st = ctx->streams[i];
356         stream = av_mallocz(sizeof(StreamInfo));
357         if (!stream)
358             goto fail;
359         st->priv_data = stream;
360
361         av_set_pts_info(st, 64, 1, 90000);
362
363         switch(st->codec->codec_type) {
364         case CODEC_TYPE_AUDIO:
365             if (st->codec->codec_id == CODEC_ID_AC3) {
366                 stream->id = ac3_id++;
367             } else if (st->codec->codec_id == CODEC_ID_DTS) {
368                 stream->id = dts_id++;
369             } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
370                 stream->id = lpcm_id++;
371                 for(j = 0; j < 4; j++) {
372                     if (lpcm_freq_tab[j] == st->codec->sample_rate)
373                         break;
374                 }
375                 if (j == 4)
376                     goto fail;
377                 if (st->codec->channels > 8)
378                     return -1;
379                 stream->lpcm_header[0] = 0x0c;
380                 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
381                 stream->lpcm_header[2] = 0x80;
382                 stream->lpcm_align = st->codec->channels * 2;
383             } else {
384                 stream->id = mpa_id++;
385             }
386
387             /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
388                Right now it is also used for everything else.*/
389             stream->max_buffer_size = 4 * 1024;
390             s->audio_bound++;
391             break;
392         case CODEC_TYPE_VIDEO:
393             stream->id = mpv_id++;
394             if (st->codec->rc_buffer_size)
395                 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
396             else
397                 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
398 #if 0
399                 /* see VCD standard, p. IV-7*/
400                 stream->max_buffer_size = 46 * 1024;
401             else
402                 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
403                    Right now it is also used for everything else.*/
404                 stream->max_buffer_size = 230 * 1024;
405 #endif
406             s->video_bound++;
407             break;
408         case CODEC_TYPE_SUBTITLE:
409             stream->id = mps_id++;
410             stream->max_buffer_size = 16 * 1024;
411             break;
412         default:
413             return -1;
414         }
415         fifo_init(&stream->fifo, 16);
416     }
417     bitrate = 0;
418     audio_bitrate = 0;
419     video_bitrate = 0;
420     for(i=0;i<ctx->nb_streams;i++) {
421         int codec_rate;
422         st = ctx->streams[i];
423         stream = (StreamInfo*) st->priv_data;
424
425         if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
426             codec_rate= st->codec->rc_max_rate;
427         else
428             codec_rate= st->codec->bit_rate;
429
430         if(!codec_rate)
431             codec_rate= (1<<21)*8*50/ctx->nb_streams;
432
433         bitrate += codec_rate;
434
435         if (stream->id==AUDIO_ID)
436             audio_bitrate += codec_rate;
437         else if (stream->id==VIDEO_ID)
438             video_bitrate += codec_rate;
439     }
440
441     if(ctx->mux_rate){
442         s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
443     } else {
444         /* we increase slightly the bitrate to take into account the
445            headers. XXX: compute it exactly */
446         bitrate += bitrate*5/100;
447         bitrate += 10000;
448         s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
449     }
450
451     if (s->is_vcd) {
452         double overhead_rate;
453
454         /* The VCD standard mandates that the mux_rate field is 3528
455            (see standard p. IV-6).
456            The value is actually "wrong", i.e. if you calculate
457            it using the normal formula and the 75 sectors per second transfer
458            rate you get a different value because the real pack size is 2324,
459            not 2352. But the standard explicitly specifies that the mux_rate
460            field in the header must have this value.*/
461 //        s->mux_rate=2352 * 75 / 50;    /* = 3528*/
462
463         /* The VCD standard states that the muxed stream must be
464            exactly 75 packs / second (the data rate of a single speed cdrom).
465            Since the video bitrate (probably 1150000 bits/sec) will be below
466            the theoretical maximum we have to add some padding packets
467            to make up for the lower data rate.
468            (cf. VCD standard p. IV-6 )*/
469
470         /* Add the header overhead to the data rate.
471            2279 data bytes per audio pack, 2294 data bytes per video pack*/
472         overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
473         overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
474         overhead_rate *= 8;
475
476         /* Add padding so that the full bitrate is 2324*75 bytes/sec */
477         s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
478     }
479
480     if (s->is_vcd || s->is_mpeg2)
481         /* every packet */
482         s->pack_header_freq = 1;
483     else
484         /* every 2 seconds */
485         s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
486
487     /* the above seems to make pack_header_freq zero sometimes */
488     if (s->pack_header_freq == 0)
489        s->pack_header_freq = 1;
490
491     if (s->is_mpeg2)
492         /* every 200 packets. Need to look at the spec.  */
493         s->system_header_freq = s->pack_header_freq * 40;
494     else if (s->is_vcd)
495         /* the standard mandates that there are only two system headers
496            in the whole file: one in the first packet of each stream.
497            (see standard p. IV-7 and IV-8) */
498         s->system_header_freq = 0x7fffffff;
499     else
500         s->system_header_freq = s->pack_header_freq * 5;
501
502     for(i=0;i<ctx->nb_streams;i++) {
503         stream = ctx->streams[i]->priv_data;
504         stream->packet_number = 0;
505     }
506     s->system_header_size = get_system_header_size(ctx);
507     s->last_scr = 0;
508     return 0;
509  fail:
510     for(i=0;i<ctx->nb_streams;i++) {
511         av_free(ctx->streams[i]->priv_data);
512     }
513     return -ENOMEM;
514 }
515
516 static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
517 {
518     put_byte(pb,
519              (id << 4) |
520              (((timestamp >> 30) & 0x07) << 1) |
521              1);
522     put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
523     put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
524 }
525
526
527 /* return the number of padding bytes that should be inserted into
528    the multiplexed stream.*/
529 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
530 {
531     MpegMuxContext *s = ctx->priv_data;
532     int pad_bytes = 0;
533
534     if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
535     {
536         int64_t full_pad_bytes;
537
538         full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
539         pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
540
541         if (pad_bytes<0)
542             /* might happen if we have already padded to a later timestamp. This
543                can occur if another stream has already advanced further.*/
544             pad_bytes=0;
545     }
546
547     return pad_bytes;
548 }
549
550
551 #if 0 /* unused, remove? */
552 /* return the exact available payload size for the next packet for
553    stream 'stream_index'. 'pts' and 'dts' are only used to know if
554    timestamps are needed in the packet header. */
555 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
556                                    int64_t pts, int64_t dts)
557 {
558     MpegMuxContext *s = ctx->priv_data;
559     int buf_index;
560     StreamInfo *stream;
561
562     stream = ctx->streams[stream_index]->priv_data;
563
564     buf_index = 0;
565     if (((s->packet_number % s->pack_header_freq) == 0)) {
566         /* pack header size */
567         if (s->is_mpeg2)
568             buf_index += 14;
569         else
570             buf_index += 12;
571
572         if (s->is_vcd) {
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).*/
576
577             if (stream->packet_number==0)
578                 /* The system headers refer only to the stream they occur in,
579                    so they have a constant size.*/
580                 buf_index += 15;
581
582         } else {
583             if ((s->packet_number % s->system_header_freq) == 0)
584                 buf_index += s->system_header_size;
585         }
586     }
587
588     if ((s->is_vcd && stream->packet_number==0)
589         || (s->is_svcd && s->packet_number==0))
590         /* the first pack of each stream contains only the pack header,
591            the system header and some padding (see VCD standard p. IV-6)
592            Add the padding size, so that the actual payload becomes 0.*/
593         buf_index += s->packet_size - buf_index;
594     else {
595         /* packet header size */
596         buf_index += 6;
597         if (s->is_mpeg2) {
598             buf_index += 3;
599             if (stream->packet_number==0)
600                 buf_index += 3; /* PES extension */
601             buf_index += 1;    /* obligatory stuffing byte */
602         }
603         if (pts != AV_NOPTS_VALUE) {
604             if (dts != pts)
605                 buf_index += 5 + 5;
606             else
607                 buf_index += 5;
608
609         } else {
610             if (!s->is_mpeg2)
611                 buf_index++;
612         }
613
614         if (stream->id < 0xc0) {
615             /* AC3/LPCM private data header */
616             buf_index += 4;
617             if (stream->id >= 0xa0) {
618                 int n;
619                 buf_index += 3;
620                 /* NOTE: we round the payload size to an integer number of
621                    LPCM samples */
622                 n = (s->packet_size - buf_index) % stream->lpcm_align;
623                 if (n)
624                     buf_index += (stream->lpcm_align - n);
625             }
626         }
627
628         if (s->is_vcd && stream->id == AUDIO_ID)
629             /* The VCD standard demands that 20 zero bytes follow
630                each audio packet (see standard p. IV-8).*/
631             buf_index+=20;
632     }
633     return s->packet_size - buf_index;
634 }
635 #endif
636
637 /* Write an MPEG padding packet header. */
638 static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
639 {
640     MpegMuxContext *s = ctx->priv_data;
641     int i;
642
643     put_be32(pb, PADDING_STREAM);
644     put_be16(pb, packet_bytes - 6);
645     if (!s->is_mpeg2) {
646         put_byte(pb, 0x0f);
647         packet_bytes -= 7;
648     } else
649         packet_bytes -= 6;
650
651     for(i=0;i<packet_bytes;i++)
652         put_byte(pb, 0xff);
653 }
654
655 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
656     int nb_frames=0;
657     PacketDesc *pkt_desc= stream->premux_packet;
658
659     while(len>0){
660         if(pkt_desc->size == pkt_desc->unwritten_size)
661             nb_frames++;
662         len -= pkt_desc->unwritten_size;
663         pkt_desc= pkt_desc->next;
664     }
665
666     return nb_frames;
667 }
668
669 /* flush the packet on stream stream_index */
670 static int flush_packet(AVFormatContext *ctx, int stream_index,
671                          int64_t pts, int64_t dts, int64_t scr, int trailer_size)
672 {
673     MpegMuxContext *s = ctx->priv_data;
674     StreamInfo *stream = ctx->streams[stream_index]->priv_data;
675     uint8_t *buf_ptr;
676     int size, payload_size, startcode, id, stuffing_size, i, header_len;
677     int packet_size;
678     uint8_t buffer[128];
679     int zero_trail_bytes = 0;
680     int pad_packet_bytes = 0;
681     int pes_flags;
682     int general_pack = 0;  /*"general" pack without data specific to one stream?*/
683     int nb_frames;
684
685     id = stream->id;
686
687 #if 0
688     printf("packet ID=%2x PTS=%0.3f\n",
689            id, pts / 90000.0);
690 #endif
691
692     buf_ptr = buffer;
693
694     if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
695         /* output pack and systems header if needed */
696         size = put_pack_header(ctx, buf_ptr, scr);
697         buf_ptr += size;
698         s->last_scr= scr;
699
700         if (s->is_vcd) {
701             /* there is exactly one system header for each stream in a VCD MPEG,
702                One in the very first video packet and one in the very first
703                audio packet (see VCD standard p. IV-7 and IV-8).*/
704
705             if (stream->packet_number==0) {
706                 size = put_system_header(ctx, buf_ptr, id);
707                 buf_ptr += size;
708             }
709         } else if (s->is_dvd) {
710             if (stream->align_iframe || s->packet_number == 0){
711                 int bytes_to_iframe;
712                 int PES_bytes_to_fill;
713                 if (stream->fifo_iframe_ptr >= stream->fifo.rptr) {
714                     bytes_to_iframe = stream->fifo_iframe_ptr - stream->fifo.rptr;
715                 } else {
716                     bytes_to_iframe = (stream->fifo.end - stream->fifo.rptr) + (stream->fifo_iframe_ptr - stream->fifo.buffer);
717                 }
718                 PES_bytes_to_fill = s->packet_size - size - 10;
719
720                 if (pts != AV_NOPTS_VALUE) {
721                     if (dts != pts)
722                         PES_bytes_to_fill -= 5 + 5;
723                     else
724                         PES_bytes_to_fill -= 5;
725                 }
726
727                 if (bytes_to_iframe == 0 || s->packet_number == 0) {
728                     size = put_system_header(ctx, buf_ptr, 0);
729                     buf_ptr += size;
730                     size = buf_ptr - buffer;
731                     put_buffer(&ctx->pb, buffer, size);
732
733                     put_be32(&ctx->pb, PRIVATE_STREAM_2);
734                     put_be16(&ctx->pb, 0x03d4);         // length
735                     put_byte(&ctx->pb, 0x00);           // substream ID, 00=PCI
736                     for (i = 0; i < 979; i++)
737                         put_byte(&ctx->pb, 0x00);
738
739                     put_be32(&ctx->pb, PRIVATE_STREAM_2);
740                     put_be16(&ctx->pb, 0x03fa);         // length
741                     put_byte(&ctx->pb, 0x01);           // substream ID, 01=DSI
742                     for (i = 0; i < 1017; i++)
743                         put_byte(&ctx->pb, 0x00);
744
745                     memset(buffer, 0, 128);
746                     buf_ptr = buffer;
747                     s->packet_number++;
748                     stream->align_iframe = 0;
749                     scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
750                     size = put_pack_header(ctx, buf_ptr, scr);
751                     s->last_scr= scr;
752                     buf_ptr += size;
753                     /* GOP Start */
754                 } else if (bytes_to_iframe < PES_bytes_to_fill) {
755                     pad_packet_bytes = PES_bytes_to_fill - bytes_to_iframe;
756                 }
757             }
758         } else {
759             if ((s->packet_number % s->system_header_freq) == 0) {
760                 size = put_system_header(ctx, buf_ptr, 0);
761                 buf_ptr += size;
762             }
763         }
764     }
765     size = buf_ptr - buffer;
766     put_buffer(&ctx->pb, buffer, size);
767
768     packet_size = s->packet_size - size;
769
770     if (s->is_vcd && id == AUDIO_ID)
771         /* The VCD standard demands that 20 zero bytes follow
772            each audio pack (see standard p. IV-8).*/
773         zero_trail_bytes += 20;
774
775     if ((s->is_vcd && stream->packet_number==0)
776         || (s->is_svcd && s->packet_number==0)) {
777         /* for VCD the first pack of each stream contains only the pack header,
778            the system header and lots of padding (see VCD standard p. IV-6).
779            In the case of an audio pack, 20 zero bytes are also added at
780            the end.*/
781         /* For SVCD we fill the very first pack to increase compatibility with
782            some DVD players. Not mandated by the standard.*/
783         if (s->is_svcd)
784             general_pack = 1;    /* the system header refers to both streams and no stream data*/
785         pad_packet_bytes = packet_size - zero_trail_bytes;
786     }
787
788     packet_size -= pad_packet_bytes + zero_trail_bytes;
789
790     if (packet_size > 0) {
791
792         /* packet header size */
793         packet_size -= 6;
794
795         /* packet header */
796         if (s->is_mpeg2) {
797             header_len = 3;
798             if (stream->packet_number==0)
799                 header_len += 3; /* PES extension */
800             header_len += 1; /* obligatory stuffing byte */
801         } else {
802             header_len = 0;
803         }
804         if (pts != AV_NOPTS_VALUE) {
805             if (dts != pts)
806                 header_len += 5 + 5;
807             else
808                 header_len += 5;
809         } else {
810             if (!s->is_mpeg2)
811                 header_len++;
812         }
813
814         payload_size = packet_size - header_len;
815         if (id < 0xc0) {
816             startcode = PRIVATE_STREAM_1;
817             payload_size -= 1;
818             if (id >= 0x40) {
819                 payload_size -= 3;
820                 if (id >= 0xa0)
821                     payload_size -= 3;
822             }
823         } else {
824             startcode = 0x100 + id;
825         }
826
827         stuffing_size = payload_size - fifo_size(&stream->fifo, stream->fifo.rptr);
828
829         // first byte doesnt fit -> reset pts/dts + stuffing
830         if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
831             int timestamp_len=0;
832             if(dts != pts)
833                 timestamp_len += 5;
834             if(pts != AV_NOPTS_VALUE)
835                 timestamp_len += s->is_mpeg2 ? 5 : 4;
836             pts=dts= AV_NOPTS_VALUE;
837             header_len -= timestamp_len;
838             if (s->is_dvd && stream->align_iframe) {
839                 pad_packet_bytes += timestamp_len;
840                 packet_size -= timestamp_len;
841             } else {
842                 payload_size += timestamp_len;
843             }
844             stuffing_size += timestamp_len;
845             if(payload_size > trailer_size)
846                 stuffing_size += payload_size - trailer_size;
847         }
848
849         if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
850             packet_size += pad_packet_bytes;
851             payload_size += pad_packet_bytes; // undo the previous adjustment
852             if (stuffing_size < 0) {
853                 stuffing_size = pad_packet_bytes;
854             } else {
855                 stuffing_size += pad_packet_bytes;
856             }
857             pad_packet_bytes = 0;
858         }
859
860         if (stuffing_size < 0)
861             stuffing_size = 0;
862         if (stuffing_size > 16) {    /*<=16 for MPEG-1, <=32 for MPEG-2*/
863             pad_packet_bytes += stuffing_size;
864             packet_size -= stuffing_size;
865             payload_size -= stuffing_size;
866             stuffing_size = 0;
867         }
868
869         nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
870
871         put_be32(&ctx->pb, startcode);
872
873         put_be16(&ctx->pb, packet_size);
874
875         if (!s->is_mpeg2)
876             for(i=0;i<stuffing_size;i++)
877                 put_byte(&ctx->pb, 0xff);
878
879         if (s->is_mpeg2) {
880             put_byte(&ctx->pb, 0x80); /* mpeg2 id */
881
882             pes_flags=0;
883
884             if (pts != AV_NOPTS_VALUE) {
885                 pes_flags |= 0x80;
886                 if (dts != pts)
887                     pes_flags |= 0x40;
888             }
889
890             /* Both the MPEG-2 and the SVCD standards demand that the
891                P-STD_buffer_size field be included in the first packet of
892                every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
893                and MPEG-2 standard 2.7.7) */
894             if (stream->packet_number == 0)
895                 pes_flags |= 0x01;
896
897             put_byte(&ctx->pb, pes_flags); /* flags */
898             put_byte(&ctx->pb, header_len - 3 + stuffing_size);
899
900             if (pes_flags & 0x80)  /*write pts*/
901                 put_timestamp(&ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
902             if (pes_flags & 0x40)  /*write dts*/
903                 put_timestamp(&ctx->pb, 0x01, dts);
904
905             if (pes_flags & 0x01) {  /*write pes extension*/
906                 put_byte(&ctx->pb, 0x10); /* flags */
907
908                 /* P-STD buffer info */
909                 if (id == AUDIO_ID)
910                     put_be16(&ctx->pb, 0x4000 | stream->max_buffer_size/128);
911                 else
912                     put_be16(&ctx->pb, 0x6000 | stream->max_buffer_size/1024);
913             }
914
915         } else {
916             if (pts != AV_NOPTS_VALUE) {
917                 if (dts != pts) {
918                     put_timestamp(&ctx->pb, 0x03, pts);
919                     put_timestamp(&ctx->pb, 0x01, dts);
920                 } else {
921                     put_timestamp(&ctx->pb, 0x02, pts);
922                 }
923             } else {
924                 put_byte(&ctx->pb, 0x0f);
925             }
926         }
927
928         if (s->is_mpeg2) {
929             /* special stuffing byte that is always written
930                to prevent accidental generation of start codes. */
931             put_byte(&ctx->pb, 0xff);
932
933             for(i=0;i<stuffing_size;i++)
934                 put_byte(&ctx->pb, 0xff);
935         }
936
937         if (startcode == PRIVATE_STREAM_1) {
938             put_byte(&ctx->pb, id);
939             if (id >= 0xa0) {
940                 /* LPCM (XXX: check nb_frames) */
941                 put_byte(&ctx->pb, 7);
942                 put_be16(&ctx->pb, 4); /* skip 3 header bytes */
943                 put_byte(&ctx->pb, stream->lpcm_header[0]);
944                 put_byte(&ctx->pb, stream->lpcm_header[1]);
945                 put_byte(&ctx->pb, stream->lpcm_header[2]);
946             } else if (id >= 0x40) {
947                 /* AC3 */
948                 put_byte(&ctx->pb, nb_frames);
949                 put_be16(&ctx->pb, trailer_size+1);
950             }
951         }
952
953         /* output data */
954         if(put_fifo(&ctx->pb, &stream->fifo, payload_size - stuffing_size, &stream->fifo.rptr) < 0)
955             return -1;
956     }else{
957         payload_size=
958         stuffing_size= 0;
959     }
960
961     if (pad_packet_bytes > 0)
962         put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);
963
964     for(i=0;i<zero_trail_bytes;i++)
965         put_byte(&ctx->pb, 0x00);
966
967     put_flush_packet(&ctx->pb);
968
969     s->packet_number++;
970
971     /* only increase the stream packet number if this pack actually contains
972        something that is specific to this stream! I.e. a dedicated header
973        or some data.*/
974     if (!general_pack)
975         stream->packet_number++;
976
977     return payload_size - stuffing_size;
978 }
979
980 static void put_vcd_padding_sector(AVFormatContext *ctx)
981 {
982     /* There are two ways to do this padding: writing a sector/pack
983        of 0 values, or writing an MPEG padding pack. Both seem to
984        work with most decoders, BUT the VCD standard only allows a 0-sector
985        (see standard p. IV-4, IV-5).
986        So a 0-sector it is...*/
987
988     MpegMuxContext *s = ctx->priv_data;
989     int i;
990
991     for(i=0;i<s->packet_size;i++)
992         put_byte(&ctx->pb, 0);
993
994     s->vcd_padding_bytes_written += s->packet_size;
995
996     put_flush_packet(&ctx->pb);
997
998     /* increasing the packet number is correct. The SCR of the following packs
999        is calculated from the packet_number and it has to include the padding
1000        sector (it represents the sector index, not the MPEG pack index)
1001        (see VCD standard p. IV-6)*/
1002     s->packet_number++;
1003 }
1004
1005 #if 0 /* unused, remove? */
1006 static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
1007 {
1008     MpegMuxContext *s = ctx->priv_data;
1009     int64_t scr;
1010
1011         /* Since the data delivery rate is constant, SCR is computed
1012            using the formula C + i * 1200 where C is the start constant
1013            and i is the pack index.
1014            It is recommended that SCR 0 is at the beginning of the VCD front
1015            margin (a sequence of empty Form 2 sectors on the CD).
1016            It is recommended that the front margin is 30 sectors long, so
1017            we use C = 30*1200 = 36000
1018            (Note that even if the front margin is not 30 sectors the file
1019            will still be correct according to the standard. It just won't have
1020            the "recommended" value).*/
1021         scr = 36000 + s->packet_number * 1200;
1022
1023     return scr;
1024 }
1025 #endif
1026
1027 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
1028 //    MpegMuxContext *s = ctx->priv_data;
1029     int i;
1030
1031     for(i=0; i<ctx->nb_streams; i++){
1032         AVStream *st = ctx->streams[i];
1033         StreamInfo *stream = st->priv_data;
1034         PacketDesc *pkt_desc= stream->predecode_packet;
1035
1036         while(pkt_desc && scr > pkt_desc->dts){ //FIXME > vs >=
1037             if(stream->buffer_index < pkt_desc->size ||
1038                stream->predecode_packet == stream->premux_packet){
1039                 av_log(ctx, AV_LOG_ERROR, "buffer underflow\n");
1040                 break;
1041             }
1042             stream->buffer_index -= pkt_desc->size;
1043
1044             stream->predecode_packet= pkt_desc->next;
1045             av_freep(&pkt_desc);
1046         }
1047     }
1048
1049     return 0;
1050 }
1051
1052 static int output_packet(AVFormatContext *ctx, int flush){
1053     MpegMuxContext *s = ctx->priv_data;
1054     AVStream *st;
1055     StreamInfo *stream;
1056     int i, avail_space, es_size, trailer_size;
1057     int best_i= -1;
1058     int best_score= INT_MIN;
1059     int ignore_constraints=0;
1060     int64_t scr= s->last_scr;
1061     PacketDesc *timestamp_packet;
1062     const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1063
1064 retry:
1065     for(i=0; i<ctx->nb_streams; i++){
1066         AVStream *st = ctx->streams[i];
1067         StreamInfo *stream = st->priv_data;
1068         const int avail_data=  fifo_size(&stream->fifo, stream->fifo.rptr);
1069         const int space= stream->max_buffer_size - stream->buffer_index;
1070         int rel_space= 1024*space / stream->max_buffer_size;
1071         PacketDesc *next_pkt= stream->premux_packet;
1072
1073         /* for subtitle, a single PES packet must be generated,
1074            so we flush after every single subtitle packet */
1075         if(s->packet_size > avail_data && !flush
1076            && st->codec->codec_type != CODEC_TYPE_SUBTITLE)
1077             return 0;
1078         if(avail_data==0)
1079             continue;
1080         assert(avail_data>0);
1081
1082         if(space < s->packet_size && !ignore_constraints)
1083             continue;
1084
1085         if(next_pkt && next_pkt->dts - scr > max_delay)
1086             continue;
1087
1088         if(rel_space > best_score){
1089             best_score= rel_space;
1090             best_i = i;
1091             avail_space= space;
1092         }
1093     }
1094
1095     if(best_i < 0){
1096         int64_t best_dts= INT64_MAX;
1097
1098         for(i=0; i<ctx->nb_streams; i++){
1099             AVStream *st = ctx->streams[i];
1100             StreamInfo *stream = st->priv_data;
1101             PacketDesc *pkt_desc= stream->predecode_packet;
1102             if(pkt_desc && pkt_desc->dts < best_dts)
1103                 best_dts= pkt_desc->dts;
1104         }
1105
1106 #if 0
1107         av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n",
1108                scr/90000.0, best_dts/90000.0);
1109 #endif
1110         if(best_dts == INT64_MAX)
1111             return 0;
1112
1113         if(scr >= best_dts+1 && !ignore_constraints){
1114             av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1115             ignore_constraints= 1;
1116         }
1117         scr= FFMAX(best_dts+1, scr);
1118         if(remove_decoded_packets(ctx, scr) < 0)
1119             return -1;
1120         goto retry;
1121     }
1122
1123     assert(best_i >= 0);
1124
1125     st = ctx->streams[best_i];
1126     stream = st->priv_data;
1127
1128     assert(fifo_size(&stream->fifo, stream->fifo.rptr) > 0);
1129
1130     assert(avail_space >= s->packet_size || ignore_constraints);
1131
1132     timestamp_packet= stream->premux_packet;
1133     if(timestamp_packet->unwritten_size == timestamp_packet->size){
1134         trailer_size= 0;
1135     }else{
1136         trailer_size= timestamp_packet->unwritten_size;
1137         timestamp_packet= timestamp_packet->next;
1138     }
1139
1140     if(timestamp_packet){
1141 //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);
1142         es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1143     }else{
1144         assert(fifo_size(&stream->fifo, stream->fifo.rptr) == trailer_size);
1145         es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1146     }
1147
1148     if (s->is_vcd) {
1149         /* Write one or more padding sectors, if necessary, to reach
1150            the constant overall bitrate.*/
1151         int vcd_pad_bytes;
1152
1153         while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1154             put_vcd_padding_sector(ctx);
1155             s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1156         }
1157     }
1158
1159     stream->buffer_index += es_size;
1160     s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1161
1162     while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1163         es_size -= stream->premux_packet->unwritten_size;
1164         stream->premux_packet= stream->premux_packet->next;
1165     }
1166     if(es_size)
1167         stream->premux_packet->unwritten_size -= es_size;
1168
1169     if(remove_decoded_packets(ctx, s->last_scr) < 0)
1170         return -1;
1171
1172     return 1;
1173 }
1174
1175 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1176 {
1177     MpegMuxContext *s = ctx->priv_data;
1178     int stream_index= pkt->stream_index;
1179     int size= pkt->size;
1180     uint8_t *buf= pkt->data;
1181     AVStream *st = ctx->streams[stream_index];
1182     StreamInfo *stream = st->priv_data;
1183     int64_t pts, dts;
1184     PacketDesc *pkt_desc;
1185     const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
1186     const int is_iframe = st->codec->codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
1187
1188     pts= pkt->pts;
1189     dts= pkt->dts;
1190
1191     if(pts != AV_NOPTS_VALUE) pts += preload;
1192     if(dts != AV_NOPTS_VALUE) dts += preload;
1193
1194 //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);
1195     if (!stream->premux_packet)
1196         stream->next_packet = &stream->premux_packet;
1197     *stream->next_packet=
1198     pkt_desc= av_mallocz(sizeof(PacketDesc));
1199     pkt_desc->pts= pts;
1200     pkt_desc->dts= dts;
1201     pkt_desc->unwritten_size=
1202     pkt_desc->size= size;
1203     if(!stream->predecode_packet)
1204         stream->predecode_packet= pkt_desc;
1205     stream->next_packet= &pkt_desc->next;
1206
1207     fifo_realloc(&stream->fifo, fifo_size(&stream->fifo, NULL) + size + 1);
1208
1209     if (s->is_dvd){
1210         if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1211             stream->fifo_iframe_ptr = stream->fifo.wptr;
1212             stream->align_iframe = 1;
1213             stream->vobu_start_pts = pts;
1214         } else {
1215             stream->align_iframe = 0;
1216         }
1217     }
1218
1219     fifo_write(&stream->fifo, buf, size, &stream->fifo.wptr);
1220
1221     for(;;){
1222         int ret= output_packet(ctx, 0);
1223         if(ret<=0)
1224             return ret;
1225     }
1226 }
1227
1228 static int mpeg_mux_end(AVFormatContext *ctx)
1229 {
1230 //    MpegMuxContext *s = ctx->priv_data;
1231     StreamInfo *stream;
1232     int i;
1233
1234     for(;;){
1235         int ret= output_packet(ctx, 1);
1236         if(ret<0)
1237             return ret;
1238         else if(ret==0)
1239             break;
1240     }
1241
1242     /* End header according to MPEG1 systems standard. We do not write
1243        it as it is usually not needed by decoders and because it
1244        complicates MPEG stream concatenation. */
1245     //put_be32(&ctx->pb, ISO_11172_END_CODE);
1246     //put_flush_packet(&ctx->pb);
1247
1248     for(i=0;i<ctx->nb_streams;i++) {
1249         stream = ctx->streams[i]->priv_data;
1250
1251         assert(fifo_size(&stream->fifo, stream->fifo.rptr) == 0);
1252         fifo_free(&stream->fifo);
1253     }
1254     return 0;
1255 }
1256 #endif //CONFIG_MUXERS
1257
1258 /*********************************************/
1259 /* demux code */
1260
1261 #define MAX_SYNC_SIZE 100000
1262
1263 static int mpegps_probe(AVProbeData *p)
1264 {
1265     uint32_t code= -1;
1266     int sys=0, pspack=0, priv1=0, vid=0, audio=0;
1267     int i;
1268
1269     for(i=0; i<p->buf_size; i++){
1270         code = (code<<8) + p->buf[i];
1271         if ((code & 0xffffff00) == 0x100) {
1272             if(code == SYSTEM_HEADER_START_CODE) sys++;
1273             else if(code == PRIVATE_STREAM_1)    priv1++;
1274             else if(code == PACK_START_CODE)     pspack++;
1275             else if((code & 0xf0) == VIDEO_ID)   vid++;
1276             else if((code & 0xe0) == AUDIO_ID)   audio++;
1277         }
1278     }
1279     if(sys && sys*9 <= pspack*10)
1280         return AVPROBE_SCORE_MAX/2+2; // +1 for .mpg
1281     if((priv1 || vid || audio) && (priv1+vid+audio)*9 <= pspack*10)
1282         return AVPROBE_SCORE_MAX/2+2; // +1 for .mpg
1283     if((!!vid ^ !!audio) && !sys && !pspack) /* PES stream */
1284         return AVPROBE_SCORE_MAX/2+2;
1285     if(vid || audio)            /* invalid VDR files */
1286         return AVPROBE_SCORE_MAX/2+2;
1287     return 0;
1288 }
1289
1290
1291 typedef struct MpegDemuxContext {
1292     int header_state;
1293     unsigned char psm_es_type[256];
1294 } MpegDemuxContext;
1295
1296 static int mpegps_read_header(AVFormatContext *s,
1297                               AVFormatParameters *ap)
1298 {
1299     MpegDemuxContext *m = s->priv_data;
1300     m->header_state = 0xff;
1301     s->ctx_flags |= AVFMTCTX_NOHEADER;
1302
1303     /* no need to do more */
1304     return 0;
1305 }
1306
1307 static int64_t get_pts(ByteIOContext *pb, int c)
1308 {
1309     int64_t pts;
1310     int val;
1311
1312     if (c < 0)
1313         c = get_byte(pb);
1314     pts = (int64_t)((c >> 1) & 0x07) << 30;
1315     val = get_be16(pb);
1316     pts |= (int64_t)(val >> 1) << 15;
1317     val = get_be16(pb);
1318     pts |= (int64_t)(val >> 1);
1319     return pts;
1320 }
1321
1322 static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
1323                                 uint32_t *header_state)
1324 {
1325     unsigned int state, v;
1326     int val, n;
1327
1328     state = *header_state;
1329     n = *size_ptr;
1330     while (n > 0) {
1331         if (url_feof(pb))
1332             break;
1333         v = get_byte(pb);
1334         n--;
1335         if (state == 0x000001) {
1336             state = ((state << 8) | v) & 0xffffff;
1337             val = state;
1338             goto found;
1339         }
1340         state = ((state << 8) | v) & 0xffffff;
1341     }
1342     val = -1;
1343  found:
1344     *header_state = state;
1345     *size_ptr = n;
1346     return val;
1347 }
1348
1349 #if 0 /* unused, remove? */
1350 /* XXX: optimize */
1351 static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
1352 {
1353     int64_t pos, pos_start;
1354     int max_size, start_code;
1355
1356     max_size = *size_ptr;
1357     pos_start = url_ftell(pb);
1358
1359     /* in order to go faster, we fill the buffer */
1360     pos = pos_start - 16386;
1361     if (pos < 0)
1362         pos = 0;
1363     url_fseek(pb, pos, SEEK_SET);
1364     get_byte(pb);
1365
1366     pos = pos_start;
1367     for(;;) {
1368         pos--;
1369         if (pos < 0 || (pos_start - pos) >= max_size) {
1370             start_code = -1;
1371             goto the_end;
1372         }
1373         url_fseek(pb, pos, SEEK_SET);
1374         start_code = get_be32(pb);
1375         if ((start_code & 0xffffff00) == 0x100)
1376             break;
1377     }
1378  the_end:
1379     *size_ptr = pos_start - pos;
1380     return start_code;
1381 }
1382 #endif
1383
1384 /**
1385  * Extracts stream types from a program stream map
1386  * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
1387  *
1388  * @return number of bytes occupied by PSM in the bitstream
1389  */
1390 static long mpegps_psm_parse(MpegDemuxContext *m, ByteIOContext *pb)
1391 {
1392     int psm_length, ps_info_length, es_map_length;
1393
1394     psm_length = get_be16(pb);
1395     get_byte(pb);
1396     get_byte(pb);
1397     ps_info_length = get_be16(pb);
1398
1399     /* skip program_stream_info */
1400     url_fskip(pb, ps_info_length);
1401     es_map_length = get_be16(pb);
1402
1403     /* at least one es available? */
1404     while (es_map_length >= 4){
1405         unsigned char type = get_byte(pb);
1406         unsigned char es_id = get_byte(pb);
1407         uint16_t es_info_length = get_be16(pb);
1408         /* remember mapping from stream id to stream type */
1409         m->psm_es_type[es_id] = type;
1410         /* skip program_stream_info */
1411         url_fskip(pb, es_info_length);
1412         es_map_length -= 4 + es_info_length;
1413     }
1414     get_be32(pb); /* crc32 */
1415     return 2 + psm_length;
1416 }
1417
1418 /* read the next PES header. Return its position in ppos
1419    (if not NULL), and its start code, pts and dts.
1420  */
1421 static int mpegps_read_pes_header(AVFormatContext *s,
1422                                   int64_t *ppos, int *pstart_code,
1423                                   int64_t *ppts, int64_t *pdts)
1424 {
1425     MpegDemuxContext *m = s->priv_data;
1426     int len, size, startcode, c, flags, header_len;
1427     int64_t pts, dts, last_pos;
1428
1429     last_pos = -1;
1430  redo:
1431         /* next start code (should be immediately after) */
1432         m->header_state = 0xff;
1433         size = MAX_SYNC_SIZE;
1434         startcode = find_next_start_code(&s->pb, &size, &m->header_state);
1435     //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
1436     if (startcode < 0)
1437         return AVERROR_IO;
1438     if (startcode == PACK_START_CODE)
1439         goto redo;
1440     if (startcode == SYSTEM_HEADER_START_CODE)
1441         goto redo;
1442     if (startcode == PADDING_STREAM ||
1443         startcode == PRIVATE_STREAM_2) {
1444         /* skip them */
1445         len = get_be16(&s->pb);
1446         url_fskip(&s->pb, len);
1447         goto redo;
1448     }
1449     if (startcode == PROGRAM_STREAM_MAP) {
1450         mpegps_psm_parse(m, &s->pb);
1451         goto redo;
1452     }
1453
1454     /* find matching stream */
1455     if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
1456           (startcode >= 0x1e0 && startcode <= 0x1ef) ||
1457           (startcode == 0x1bd)))
1458         goto redo;
1459     if (ppos) {
1460         *ppos = url_ftell(&s->pb) - 4;
1461     }
1462     len = get_be16(&s->pb);
1463     pts = AV_NOPTS_VALUE;
1464     dts = AV_NOPTS_VALUE;
1465     /* stuffing */
1466     for(;;) {
1467         if (len < 1)
1468             goto redo;
1469         c = get_byte(&s->pb);
1470         len--;
1471         /* XXX: for mpeg1, should test only bit 7 */
1472         if (c != 0xff)
1473             break;
1474     }
1475     if ((c & 0xc0) == 0x40) {
1476         /* buffer scale & size */
1477         if (len < 2)
1478             goto redo;
1479         get_byte(&s->pb);
1480         c = get_byte(&s->pb);
1481         len -= 2;
1482     }
1483     if ((c & 0xf0) == 0x20) {
1484         if (len < 4)
1485             goto redo;
1486         dts = pts = get_pts(&s->pb, c);
1487         len -= 4;
1488     } else if ((c & 0xf0) == 0x30) {
1489         if (len < 9)
1490             goto redo;
1491         pts = get_pts(&s->pb, c);
1492         dts = get_pts(&s->pb, -1);
1493         len -= 9;
1494     } else if ((c & 0xc0) == 0x80) {
1495         /* mpeg 2 PES */
1496 #if 0 /* some streams have this field set for no apparent reason */
1497         if ((c & 0x30) != 0) {
1498             /* Encrypted multiplex not handled */
1499             goto redo;
1500         }
1501 #endif
1502         flags = get_byte(&s->pb);
1503         header_len = get_byte(&s->pb);
1504         len -= 2;
1505         if (header_len > len)
1506             goto redo;
1507         if ((flags & 0xc0) == 0x80) {
1508             dts = pts = get_pts(&s->pb, -1);
1509             if (header_len < 5)
1510                 goto redo;
1511             header_len -= 5;
1512             len -= 5;
1513         } if ((flags & 0xc0) == 0xc0) {
1514             pts = get_pts(&s->pb, -1);
1515             dts = get_pts(&s->pb, -1);
1516             if (header_len < 10)
1517                 goto redo;
1518             header_len -= 10;
1519             len -= 10;
1520         }
1521         len -= header_len;
1522         while (header_len > 0) {
1523             get_byte(&s->pb);
1524             header_len--;
1525         }
1526     }
1527     else if( c!= 0xf )
1528         goto redo;
1529
1530     if (startcode == PRIVATE_STREAM_1 && !m->psm_es_type[startcode & 0xff]) {
1531         if (len < 1)
1532             goto redo;
1533         startcode = get_byte(&s->pb);
1534         len--;
1535         if (startcode >= 0x80 && startcode <= 0xbf) {
1536             /* audio: skip header */
1537             if (len < 3)
1538                 goto redo;
1539             get_byte(&s->pb);
1540             get_byte(&s->pb);
1541             get_byte(&s->pb);
1542             len -= 3;
1543         }
1544     }
1545     if(dts != AV_NOPTS_VALUE && ppos){
1546         int i;
1547         for(i=0; i<s->nb_streams; i++){
1548             if(startcode == s->streams[i]->id) {
1549                 av_add_index_entry(s->streams[i], *ppos, dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
1550             }
1551         }
1552     }
1553
1554     *pstart_code = startcode;
1555     *ppts = pts;
1556     *pdts = dts;
1557     return len;
1558 }
1559
1560 static int mpegps_read_packet(AVFormatContext *s,
1561                               AVPacket *pkt)
1562 {
1563     MpegDemuxContext *m = s->priv_data;
1564     AVStream *st;
1565     int len, startcode, i, type, codec_id = 0, es_type;
1566     int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
1567
1568  redo:
1569     len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
1570     if (len < 0)
1571         return len;
1572
1573     /* now find stream */
1574     for(i=0;i<s->nb_streams;i++) {
1575         st = s->streams[i];
1576         if (st->id == startcode)
1577             goto found;
1578     }
1579
1580     es_type = m->psm_es_type[startcode & 0xff];
1581     if(es_type > 0){
1582         if(es_type == STREAM_TYPE_VIDEO_MPEG1){
1583             codec_id = CODEC_ID_MPEG2VIDEO;
1584             type = CODEC_TYPE_VIDEO;
1585         } else if(es_type == STREAM_TYPE_VIDEO_MPEG2){
1586             codec_id = CODEC_ID_MPEG2VIDEO;
1587             type = CODEC_TYPE_VIDEO;
1588         } else if(es_type == STREAM_TYPE_AUDIO_MPEG1 ||
1589                   es_type == STREAM_TYPE_AUDIO_MPEG2){
1590             codec_id = CODEC_ID_MP3;
1591             type = CODEC_TYPE_AUDIO;
1592         } else if(es_type == STREAM_TYPE_AUDIO_AAC){
1593             codec_id = CODEC_ID_AAC;
1594             type = CODEC_TYPE_AUDIO;
1595         } else if(es_type == STREAM_TYPE_VIDEO_MPEG4){
1596             codec_id = CODEC_ID_MPEG4;
1597             type = CODEC_TYPE_VIDEO;
1598         } else if(es_type == STREAM_TYPE_VIDEO_H264){
1599             codec_id = CODEC_ID_H264;
1600             type = CODEC_TYPE_VIDEO;
1601         } else if(es_type == STREAM_TYPE_AUDIO_AC3){
1602             codec_id = CODEC_ID_AC3;
1603             type = CODEC_TYPE_AUDIO;
1604         } else {
1605             goto skip;
1606         }
1607     } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
1608         type = CODEC_TYPE_VIDEO;
1609         codec_id = CODEC_ID_MPEG2VIDEO;
1610     } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
1611         type = CODEC_TYPE_AUDIO;
1612         codec_id = CODEC_ID_MP2;
1613     } else if (startcode >= 0x80 && startcode <= 0x87) {
1614         type = CODEC_TYPE_AUDIO;
1615         codec_id = CODEC_ID_AC3;
1616     } else if (startcode >= 0x88 && startcode <= 0x9f) {
1617         type = CODEC_TYPE_AUDIO;
1618         codec_id = CODEC_ID_DTS;
1619     } else if (startcode >= 0xa0 && startcode <= 0xbf) {
1620         type = CODEC_TYPE_AUDIO;
1621         codec_id = CODEC_ID_PCM_S16BE;
1622     } else if (startcode >= 0x20 && startcode <= 0x3f) {
1623         type = CODEC_TYPE_SUBTITLE;
1624         codec_id = CODEC_ID_DVD_SUBTITLE;
1625     } else {
1626     skip:
1627         /* skip packet */
1628         url_fskip(&s->pb, len);
1629         goto redo;
1630     }
1631     /* no stream found: add a new stream */
1632     st = av_new_stream(s, startcode);
1633     if (!st)
1634         goto skip;
1635     st->codec->codec_type = type;
1636     st->codec->codec_id = codec_id;
1637     if (codec_id != CODEC_ID_PCM_S16BE)
1638         st->need_parsing = 1;
1639  found:
1640     if(st->discard >= AVDISCARD_ALL)
1641         goto skip;
1642     if (startcode >= 0xa0 && startcode <= 0xbf) {
1643         int b1, freq;
1644
1645         /* for LPCM, we just skip the header and consider it is raw
1646            audio data */
1647         if (len <= 3)
1648             goto skip;
1649         get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
1650         b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
1651         get_byte(&s->pb); /* dynamic range control (0x80 = off) */
1652         len -= 3;
1653         freq = (b1 >> 4) & 3;
1654         st->codec->sample_rate = lpcm_freq_tab[freq];
1655         st->codec->channels = 1 + (b1 & 7);
1656         st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * 2;
1657     }
1658     av_new_packet(pkt, len);
1659     get_buffer(&s->pb, pkt->data, pkt->size);
1660     pkt->pts = pts;
1661     pkt->dts = dts;
1662     pkt->stream_index = st->index;
1663 #if 0
1664     av_log(s, AV_LOG_DEBUG, "%d: pts=%0.3f dts=%0.3f size=%d\n",
1665            pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0, pkt->size);
1666 #endif
1667
1668     return 0;
1669 }
1670
1671 static int mpegps_read_close(AVFormatContext *s)
1672 {
1673     return 0;
1674 }
1675
1676 static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
1677                                int64_t *ppos, int64_t pos_limit)
1678 {
1679     int len, startcode;
1680     int64_t pos, pts, dts;
1681
1682     pos = *ppos;
1683 #ifdef DEBUG_SEEK
1684     printf("read_dts: pos=0x%llx next=%d -> ", pos, find_next);
1685 #endif
1686     url_fseek(&s->pb, pos, SEEK_SET);
1687     for(;;) {
1688         len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
1689         if (len < 0) {
1690 #ifdef DEBUG_SEEK
1691             printf("none (ret=%d)\n", len);
1692 #endif
1693             return AV_NOPTS_VALUE;
1694         }
1695         if (startcode == s->streams[stream_index]->id &&
1696             dts != AV_NOPTS_VALUE) {
1697             break;
1698         }
1699         url_fskip(&s->pb, len);
1700     }
1701 #ifdef DEBUG_SEEK
1702     printf("pos=0x%llx dts=0x%llx %0.3f\n", pos, dts, dts / 90000.0);
1703 #endif
1704     *ppos = pos;
1705     return dts;
1706 }
1707
1708 #ifdef CONFIG_MUXERS
1709 static AVOutputFormat mpeg1system_mux = {
1710     "mpeg",
1711     "MPEG1 System format",
1712     "video/mpeg",
1713     "mpg,mpeg",
1714     sizeof(MpegMuxContext),
1715     CODEC_ID_MP2,
1716     CODEC_ID_MPEG1VIDEO,
1717     mpeg_mux_init,
1718     mpeg_mux_write_packet,
1719     mpeg_mux_end,
1720 };
1721
1722 static AVOutputFormat mpeg1vcd_mux = {
1723     "vcd",
1724     "MPEG1 System format (VCD)",
1725     "video/mpeg",
1726     NULL,
1727     sizeof(MpegMuxContext),
1728     CODEC_ID_MP2,
1729     CODEC_ID_MPEG1VIDEO,
1730     mpeg_mux_init,
1731     mpeg_mux_write_packet,
1732     mpeg_mux_end,
1733 };
1734
1735 static AVOutputFormat mpeg2vob_mux = {
1736     "vob",
1737     "MPEG2 PS format (VOB)",
1738     "video/mpeg",
1739     "vob",
1740     sizeof(MpegMuxContext),
1741     CODEC_ID_MP2,
1742     CODEC_ID_MPEG2VIDEO,
1743     mpeg_mux_init,
1744     mpeg_mux_write_packet,
1745     mpeg_mux_end,
1746 };
1747
1748 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1749 static AVOutputFormat mpeg2svcd_mux = {
1750     "svcd",
1751     "MPEG2 PS format (VOB)",
1752     "video/mpeg",
1753     "vob",
1754     sizeof(MpegMuxContext),
1755     CODEC_ID_MP2,
1756     CODEC_ID_MPEG2VIDEO,
1757     mpeg_mux_init,
1758     mpeg_mux_write_packet,
1759     mpeg_mux_end,
1760 };
1761
1762 /*  Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1763 static AVOutputFormat mpeg2dvd_mux = {
1764     "dvd",
1765     "MPEG2 PS format (DVD VOB)",
1766     "video/mpeg",
1767     "dvd",
1768     sizeof(MpegMuxContext),
1769     CODEC_ID_MP2,
1770     CODEC_ID_MPEG2VIDEO,
1771     mpeg_mux_init,
1772     mpeg_mux_write_packet,
1773     mpeg_mux_end,
1774 };
1775
1776 #endif //CONFIG_MUXERS
1777
1778 AVInputFormat mpegps_demux = {
1779     "mpeg",
1780     "MPEG PS format",
1781     sizeof(MpegDemuxContext),
1782     mpegps_probe,
1783     mpegps_read_header,
1784     mpegps_read_packet,
1785     mpegps_read_close,
1786     NULL, //mpegps_read_seek,
1787     mpegps_read_dts,
1788     .flags = AVFMT_SHOW_IDS,
1789 };
1790
1791 int mpegps_init(void)
1792 {
1793 #ifdef CONFIG_MUXERS
1794     av_register_output_format(&mpeg1system_mux);
1795     av_register_output_format(&mpeg1vcd_mux);
1796     av_register_output_format(&mpeg2vob_mux);
1797     av_register_output_format(&mpeg2svcd_mux);
1798     av_register_output_format(&mpeg2dvd_mux);
1799 #endif //CONFIG_MUXERS
1800     av_register_input_format(&mpegps_demux);
1801     return 0;
1802 }