Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpeg.c @ 7be806f3

History | View | Annotate | Download (52.7 KB)

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