Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpeg.c @ 95f97de1

History | View | Annotate | Download (45.4 KB)

1
/*
2
 * MPEG1/2 mux/demux
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#include "avformat.h"
20

    
21
#define MAX_PAYLOAD_SIZE 4096
22
//#define DEBUG_SEEK
23

    
24
#undef NDEBUG
25
#include <assert.h>
26

    
27
typedef struct {
28
    uint8_t buffer[MAX_PAYLOAD_SIZE];
29
    int buffer_ptr;
30
    int nb_frames;    /* number of starting frame encountered (AC3) */
31
    int frame_start_offset; /* starting offset of the frame + 1 (0 if none) */
32
    uint8_t id;
33
    int max_buffer_size; /* in bytes */
34
    int packet_number;
35
    int64_t start_pts;
36
    int64_t start_dts;
37
    uint8_t lpcm_header[3];
38
    int lpcm_align;
39
} StreamInfo;
40

    
41
typedef struct {
42
    int packet_size; /* required packet size */
43
    int packet_number;
44
    int pack_header_freq;     /* frequency (in packets^-1) at which we send pack headers */
45
    int system_header_freq;
46
    int system_header_size;
47
    int mux_rate; /* bitrate in units of 50 bytes/s */
48
    /* stream info */
49
    int audio_bound;
50
    int video_bound;
51
    int is_mpeg2;
52
    int is_vcd;
53
    int is_svcd;
54
    int scr_stream_index; /* stream from which the system clock is
55
                             computed (VBR case) */
56
    int64_t last_scr; /* current system clock */
57

    
58
    double vcd_padding_bitrate;
59
    int64_t vcd_padding_bytes_written;
60

    
61
} MpegMuxContext;
62

    
63
#define PACK_START_CODE             ((unsigned int)0x000001ba)
64
#define SYSTEM_HEADER_START_CODE    ((unsigned int)0x000001bb)
65
#define SEQUENCE_END_CODE           ((unsigned int)0x000001b7)
66
#define PACKET_START_CODE_MASK      ((unsigned int)0xffffff00)
67
#define PACKET_START_CODE_PREFIX    ((unsigned int)0x00000100)
68
#define ISO_11172_END_CODE          ((unsigned int)0x000001b9)
69
  
70
/* mpeg2 */
71
#define PROGRAM_STREAM_MAP 0x1bc
72
#define PRIVATE_STREAM_1   0x1bd
73
#define PADDING_STREAM     0x1be
74
#define PRIVATE_STREAM_2   0x1bf
75

    
76

    
77
#define AUDIO_ID 0xc0
78
#define VIDEO_ID 0xe0
79
#define AC3_ID   0x80
80
#define DTS_ID   0x8a
81
#define LPCM_ID  0xa0
82

    
83
static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
84

    
85
#ifdef CONFIG_ENCODERS
86
static AVOutputFormat mpeg1system_mux;
87
static AVOutputFormat mpeg1vcd_mux;
88
static AVOutputFormat mpeg2vob_mux;
89
static AVOutputFormat mpeg2svcd_mux;
90

    
91
static int put_pack_header(AVFormatContext *ctx, 
92
                           uint8_t *buf, int64_t timestamp)
93
{
94
    MpegMuxContext *s = ctx->priv_data;
95
    PutBitContext pb;
96
    
97
    init_put_bits(&pb, buf, 128);
98

    
99
    put_bits(&pb, 32, PACK_START_CODE);
100
    if (s->is_mpeg2) {
101
        put_bits(&pb, 2, 0x1);
102
    } else {
103
        put_bits(&pb, 4, 0x2);
104
    }
105
    put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
106
    put_bits(&pb, 1, 1);
107
    put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
108
    put_bits(&pb, 1, 1);
109
    put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
110
    put_bits(&pb, 1, 1);
111
    if (s->is_mpeg2) {
112
        /* clock extension */
113
        put_bits(&pb, 9, 0);
114
    }
115
    put_bits(&pb, 1, 1);
116
    put_bits(&pb, 22, s->mux_rate);
117
    put_bits(&pb, 1, 1);
118
    if (s->is_mpeg2) {
119
        put_bits(&pb, 1, 1);
120
        put_bits(&pb, 5, 0x1f); /* reserved */
121
        put_bits(&pb, 3, 0); /* stuffing length */
122
    }
123
    flush_put_bits(&pb);
124
    return pbBufPtr(&pb) - pb.buf;
125
}
126

    
127
static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
128
{
129
    MpegMuxContext *s = ctx->priv_data;
130
    int size, rate_bound, i, private_stream_coded, id;
131
    PutBitContext pb;
132

    
133
    init_put_bits(&pb, buf, 128);
134

    
135
    put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
136
    put_bits(&pb, 16, 0);
137
    put_bits(&pb, 1, 1);
138
    
139
    rate_bound = s->mux_rate; /* maximum bit rate of the multiplexed stream */
140
    put_bits(&pb, 22, rate_bound);
141
    put_bits(&pb, 1, 1); /* marker */
142
    if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
143
        /* This header applies only to the video stream (see VCD standard p. IV-7)*/
144
        put_bits(&pb, 6, 0);
145
    } else
146
        put_bits(&pb, 6, s->audio_bound);
147

    
148
    if (s->is_vcd) {
149
        /* see VCD standard, p. IV-7*/
150
        put_bits(&pb, 1, 0); 
151
        put_bits(&pb, 1, 1);
152
    } else {
153
        put_bits(&pb, 1, 0); /* variable bitrate*/
154
        put_bits(&pb, 1, 0); /* non constrainted bit stream */
155
    }
156
    
157
    if (s->is_vcd) {
158
        /* see VCD standard p IV-7 */
159
        put_bits(&pb, 1, 1); /* audio locked */
160
        put_bits(&pb, 1, 1); /* video locked */
161
    } else {
162
        put_bits(&pb, 1, 0); /* audio locked */
163
        put_bits(&pb, 1, 0); /* video locked */
164
    }
165

    
166
    put_bits(&pb, 1, 1); /* marker */
167

    
168
    if (s->is_vcd && only_for_stream_id==AUDIO_ID) {
169
        /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
170
        put_bits(&pb, 5, 0);
171
    } else
172
        put_bits(&pb, 5, s->video_bound);
173

    
174
    put_bits(&pb, 8, 0xff); /* reserved byte */
175
    
176
    /* audio stream info */
177
    private_stream_coded = 0;
178
    for(i=0;i<ctx->nb_streams;i++) {
179
        StreamInfo *stream = ctx->streams[i]->priv_data;
180
        
181
        /* For VCDs, only include the stream info for the stream
182
           that the pack which contains this system belongs to.
183
           (see VCD standard p. IV-7) */
184
        if ( !s->is_vcd || stream->id==only_for_stream_id
185
            || only_for_stream_id==0) {
186

    
187
            id = stream->id;
188
            if (id < 0xc0) {
189
                /* special case for private streams (AC3 use that) */
190
                if (private_stream_coded)
191
                    continue;
192
                private_stream_coded = 1;
193
                id = 0xbd;
194
            }
195
            put_bits(&pb, 8, id); /* stream ID */
196
            put_bits(&pb, 2, 3);
197
            if (id < 0xe0) {
198
                /* audio */
199
                put_bits(&pb, 1, 0);
200
                put_bits(&pb, 13, stream->max_buffer_size / 128);
201
            } else {
202
                /* video */
203
                put_bits(&pb, 1, 1);
204
                put_bits(&pb, 13, stream->max_buffer_size / 1024);
205
            }
206
        }
207
    }
208
    flush_put_bits(&pb);
209
    size = pbBufPtr(&pb) - pb.buf;
210
    /* patch packet size */
211
    buf[4] = (size - 6) >> 8;
212
    buf[5] = (size - 6) & 0xff;
213

    
214
    return size;
215
}
216

    
217
static int get_system_header_size(AVFormatContext *ctx)
218
{
219
    int buf_index, i, private_stream_coded;
220
    StreamInfo *stream;
221

    
222
    buf_index = 12;
223
    private_stream_coded = 0;
224
    for(i=0;i<ctx->nb_streams;i++) {
225
        stream = ctx->streams[i]->priv_data;
226
        if (stream->id < 0xc0) {
227
            if (private_stream_coded)
228
                continue;
229
            private_stream_coded = 1;
230
        }
231
        buf_index += 3;
232
    }
233
    return buf_index;
234
}
235

    
236
static int mpeg_mux_init(AVFormatContext *ctx)
237
{
238
    MpegMuxContext *s = ctx->priv_data;
239
    int bitrate, i, mpa_id, mpv_id, ac3_id, dts_id, lpcm_id, j;
240
    AVStream *st;
241
    StreamInfo *stream;
242
    int audio_bitrate;
243
    int video_bitrate;
244

    
245
    s->packet_number = 0;
246
    s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
247
    s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
248
    s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux);
249
    
250
    if (s->is_vcd || s->is_svcd)
251
        s->packet_size = 2324; /* VCD/SVCD packet size */
252
    else
253
        s->packet_size = 2048;
254

    
255
    s->vcd_padding_bytes_written = 0;
256
    s->vcd_padding_bitrate=0;
257
        
258
    s->audio_bound = 0;
259
    s->video_bound = 0;
260
    mpa_id = AUDIO_ID;
261
    ac3_id = AC3_ID;
262
    dts_id = DTS_ID;
263
    mpv_id = VIDEO_ID;
264
    lpcm_id = LPCM_ID;
265
    s->scr_stream_index = -1;
266
    for(i=0;i<ctx->nb_streams;i++) {
267
        st = ctx->streams[i];
268
        stream = av_mallocz(sizeof(StreamInfo));
269
        if (!stream)
270
            goto fail;
271
        st->priv_data = stream;
272

    
273
        switch(st->codec.codec_type) {
274
        case CODEC_TYPE_AUDIO:
275
            if (st->codec.codec_id == CODEC_ID_AC3) {
276
                stream->id = ac3_id++;
277
            } else if (st->codec.codec_id == CODEC_ID_DTS) {
278
                stream->id = dts_id++;
279
            } else if (st->codec.codec_id == CODEC_ID_PCM_S16BE) {
280
                stream->id = lpcm_id++;
281
                for(j = 0; j < 4; j++) {
282
                    if (lpcm_freq_tab[j] == st->codec.sample_rate)
283
                        break;
284
                }
285
                if (j == 4)
286
                    goto fail;
287
                if (st->codec.channels > 8)
288
                    return -1;
289
                stream->lpcm_header[0] = 0x0c;
290
                stream->lpcm_header[1] = (st->codec.channels - 1) | (j << 4);
291
                stream->lpcm_header[2] = 0x80;
292
                stream->lpcm_align = st->codec.channels * 2;
293
            } else {
294
                stream->id = mpa_id++;
295
            }
296

    
297
            /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
298
               Right now it is also used for everything else.*/
299
            stream->max_buffer_size = 4 * 1024; 
300
            s->audio_bound++;
301
            break;
302
        case CODEC_TYPE_VIDEO:
303
            /* by default, video is used for the SCR computation */
304
            if (s->scr_stream_index == -1)
305
                s->scr_stream_index = i;
306
            stream->id = mpv_id++;
307
            if (s->is_vcd)
308
                /* see VCD standard, p. IV-7*/
309
                stream->max_buffer_size = 46 * 1024; 
310
            else
311
                /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
312
                   Right now it is also used for everything else.*/
313
                stream->max_buffer_size = 230 * 1024; 
314
            s->video_bound++;
315
            break;
316
        default:
317
            return -1;
318
        }
319
    }
320
    /* if no SCR, use first stream (audio) */
321
    if (s->scr_stream_index == -1)
322
        s->scr_stream_index = 0;
323

    
324
    bitrate = 0;
325
    audio_bitrate = 0;
326
    video_bitrate = 0;
327
    for(i=0;i<ctx->nb_streams;i++) {
328
        st = ctx->streams[i];
329
        stream = (StreamInfo*) st->priv_data;
330
        
331
        bitrate += st->codec.bit_rate;
332

    
333
        if (stream->id==AUDIO_ID)
334
            audio_bitrate += st->codec.bit_rate;
335
        else if (stream->id==VIDEO_ID)
336
            video_bitrate += st->codec.bit_rate;
337
    }
338

    
339
    if (s->is_vcd) {
340
        double overhead_rate;
341

    
342
        /* The VCD standard mandates that the mux_rate field is 3528
343
           (see standard p. IV-6).
344
           The value is actually "wrong", i.e. if you calculate
345
           it using the normal formula and the 75 sectors per second transfer
346
           rate you get a different value because the real pack size is 2324,
347
           not 2352. But the standard explicitly specifies that the mux_rate
348
           field in the header must have this value.*/
349
        s->mux_rate=2352 * 75 / 50;    /* = 3528*/
350

    
351
        /* The VCD standard states that the muxed stream must be
352
           exactly 75 packs / second (the data rate of a single speed cdrom).
353
           Since the video bitrate (probably 1150000 bits/sec) will be below
354
           the theoretical maximum we have to add some padding packets
355
           to make up for the lower data rate.
356
           (cf. VCD standard p. IV-6 )*/
357

    
358
        /* Add the header overhead to the data rate.
359
           2279 data bytes per audio pack, 2294 data bytes per video pack*/
360
        overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
361
        overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
362
        overhead_rate *= 8;
363
        
364
        /* Add padding so that the full bitrate is 2324*75 bytes/sec */
365
        s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
366

    
367
    } else {
368
        /* we increase slightly the bitrate to take into account the
369
           headers. XXX: compute it exactly */
370
        bitrate += 2000;
371
        s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
372
    }
373
    
374
    if (s->is_vcd || s->is_mpeg2)
375
        /* every packet */
376
        s->pack_header_freq = 1;
377
    else
378
        /* every 2 seconds */
379
        s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
380

    
381
    /* the above seems to make pack_header_freq zero sometimes */
382
    if (s->pack_header_freq == 0)
383
       s->pack_header_freq = 1;
384
    
385
    if (s->is_mpeg2)
386
        /* every 200 packets. Need to look at the spec.  */
387
        s->system_header_freq = s->pack_header_freq * 40;
388
    else if (s->is_vcd)
389
        /* the standard mandates that there are only two system headers
390
           in the whole file: one in the first packet of each stream.
391
           (see standard p. IV-7 and IV-8) */
392
        s->system_header_freq = 0x7fffffff;
393
    else
394
        s->system_header_freq = s->pack_header_freq * 5;
395
    
396
    for(i=0;i<ctx->nb_streams;i++) {
397
        stream = ctx->streams[i]->priv_data;
398
        stream->buffer_ptr = 0;
399
        stream->packet_number = 0;
400
        stream->start_pts = AV_NOPTS_VALUE;
401
        stream->start_dts = AV_NOPTS_VALUE;
402
    }
403
    s->system_header_size = get_system_header_size(ctx);
404
    s->last_scr = 0;
405
    return 0;
406
 fail:
407
    for(i=0;i<ctx->nb_streams;i++) {
408
        av_free(ctx->streams[i]->priv_data);
409
    }
410
    return -ENOMEM;
411
}
412

    
413
static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
414
{
415
    put_byte(pb, 
416
             (id << 4) | 
417
             (((timestamp >> 30) & 0x07) << 1) | 
418
             1);
419
    put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
420
    put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
421
}
422

    
423

    
424
/* return the number of padding bytes that should be inserted into
425
   the multiplexed stream.*/
426
static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
427
{
428
    MpegMuxContext *s = ctx->priv_data;
429
    int pad_bytes = 0;
430

    
431
    if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
432
    {
433
        int64_t full_pad_bytes;
434
        
435
        full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0);
436
        pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
437

    
438
        if (pad_bytes<0)
439
            /* might happen if we have already padded to a later timestamp. This
440
               can occur if another stream has already advanced further.*/
441
            pad_bytes=0;
442
    }
443

    
444
    return pad_bytes;
445
}
446

    
447

    
448
/* return the exact available payload size for the next packet for
449
   stream 'stream_index'. 'pts' and 'dts' are only used to know if
450
   timestamps are needed in the packet header. */
451
static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
452
                                   int64_t pts, int64_t dts)
453
{
454
    MpegMuxContext *s = ctx->priv_data;
455
    int buf_index;
456
    StreamInfo *stream;
457

    
458
    stream = ctx->streams[stream_index]->priv_data;
459

    
460
    buf_index = 0;
461
    if (((s->packet_number % s->pack_header_freq) == 0)) {
462
        /* pack header size */
463
        if (s->is_mpeg2) 
464
            buf_index += 14;
465
        else
466
            buf_index += 12;
467
        
468
        if (s->is_vcd) {
469
            /* there is exactly one system header for each stream in a VCD MPEG,
470
               One in the very first video packet and one in the very first
471
               audio packet (see VCD standard p. IV-7 and IV-8).*/
472
            
473
            if (stream->packet_number==0)
474
                /* The system headers refer only to the stream they occur in,
475
                   so they have a constant size.*/
476
                buf_index += 15;
477

    
478
        } else {            
479
            if ((s->packet_number % s->system_header_freq) == 0)
480
                buf_index += s->system_header_size;
481
        }
482
    }
483

    
484
    if ((s->is_vcd && stream->packet_number==0)
485
        || (s->is_svcd && s->packet_number==0))
486
        /* the first pack of each stream contains only the pack header,
487
           the system header and some padding (see VCD standard p. IV-6) 
488
           Add the padding size, so that the actual payload becomes 0.*/
489
        buf_index += s->packet_size - buf_index;
490
    else {
491
        /* packet header size */
492
        buf_index += 6;
493
        if (s->is_mpeg2) {
494
            buf_index += 3;
495
            if (stream->packet_number==0)
496
                buf_index += 3; /* PES extension */
497
            buf_index += 1;    /* obligatory stuffing byte */
498
        }
499
        if (pts != AV_NOPTS_VALUE) {
500
            if (dts != pts)
501
                buf_index += 5 + 5;
502
            else
503
                buf_index += 5;
504

    
505
        } else {
506
            if (!s->is_mpeg2)
507
                buf_index++;
508
        }
509
    
510
        if (stream->id < 0xc0) {
511
            /* AC3/LPCM private data header */
512
            buf_index += 4;
513
            if (stream->id >= 0xa0) {
514
                int n;
515
                buf_index += 3;
516
                /* NOTE: we round the payload size to an integer number of
517
                   LPCM samples */
518
                n = (s->packet_size - buf_index) % stream->lpcm_align;
519
                if (n)
520
                    buf_index += (stream->lpcm_align - n);
521
            }
522
        }
523

    
524
        if (s->is_vcd && stream->id == AUDIO_ID)
525
            /* The VCD standard demands that 20 zero bytes follow
526
               each audio packet (see standard p. IV-8).*/
527
            buf_index+=20;
528
    }
529
    return s->packet_size - buf_index; 
530
}
531

    
532
/* Write an MPEG padding packet header. */
533
static int put_padding_header(AVFormatContext *ctx,uint8_t* buf, int full_padding_size)
534
{
535
    MpegMuxContext *s = ctx->priv_data;
536
    int size = full_padding_size - 6;    /* subtract header length */
537

    
538
    buf[0] = (uint8_t)(PADDING_STREAM >> 24);
539
    buf[1] = (uint8_t)(PADDING_STREAM >> 16);
540
    buf[2] = (uint8_t)(PADDING_STREAM >> 8);
541
    buf[3] = (uint8_t)(PADDING_STREAM);
542
    buf[4] = (uint8_t)(size >> 8);
543
    buf[5] = (uint8_t)(size & 0xff);
544

    
545
    if (!s->is_mpeg2) {
546
        buf[6] = 0x0f;
547
        return 7;
548
    } else
549
        return 6;
550
}
551

    
552
static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
553
{
554
    uint8_t buffer[7];
555
    int size, i;
556
    
557
    size = put_padding_header(ctx,buffer, packet_bytes);
558
    put_buffer(pb, buffer, size);
559
    packet_bytes -= size;
560

    
561
    for(i=0;i<packet_bytes;i++)
562
        put_byte(pb, 0xff);
563
}
564

    
565

    
566
/* flush the packet on stream stream_index */
567
static void flush_packet(AVFormatContext *ctx, int stream_index, 
568
                         int64_t pts, int64_t dts, int64_t scr)
569
{
570
    MpegMuxContext *s = ctx->priv_data;
571
    StreamInfo *stream = ctx->streams[stream_index]->priv_data;
572
    uint8_t *buf_ptr;
573
    int size, payload_size, startcode, id, stuffing_size, i, header_len;
574
    int packet_size;
575
    uint8_t buffer[128];
576
    int zero_trail_bytes = 0;
577
    int pad_packet_bytes = 0;
578
    int pes_flags;
579
    int general_pack = 0;  /*"general" pack without data specific to one stream?*/
580
    
581
    id = stream->id;
582
    
583
#if 0
584
    printf("packet ID=%2x PTS=%0.3f\n", 
585
           id, pts / 90000.0);
586
#endif
587

    
588
    buf_ptr = buffer;
589

    
590
    if (((s->packet_number % s->pack_header_freq) == 0)) {
591
        /* output pack and systems header if needed */
592
        size = put_pack_header(ctx, buf_ptr, scr);
593
        buf_ptr += size;
594

    
595
        if (s->is_vcd) {
596
            /* there is exactly one system header for each stream in a VCD MPEG,
597
               One in the very first video packet and one in the very first
598
               audio packet (see VCD standard p. IV-7 and IV-8).*/
599
            
600
            if (stream->packet_number==0) {
601
                size = put_system_header(ctx, buf_ptr, id);
602
                buf_ptr += size;
603
            }
604
        } else {
605
            if ((s->packet_number % s->system_header_freq) == 0) {
606
                size = put_system_header(ctx, buf_ptr, 0);
607
                buf_ptr += size;
608
            }
609
        }
610
    }
611
    size = buf_ptr - buffer;
612
    put_buffer(&ctx->pb, buffer, size);
613

    
614
    packet_size = s->packet_size - size;
615

    
616
    if (s->is_vcd && id == AUDIO_ID)
617
        /* The VCD standard demands that 20 zero bytes follow
618
           each audio pack (see standard p. IV-8).*/
619
        zero_trail_bytes += 20;
620
            
621
    if ((s->is_vcd && stream->packet_number==0)
622
        || (s->is_svcd && s->packet_number==0)) {
623
        /* for VCD the first pack of each stream contains only the pack header,
624
           the system header and lots of padding (see VCD standard p. IV-6).
625
           In the case of an audio pack, 20 zero bytes are also added at
626
           the end.*/
627
        /* For SVCD we fill the very first pack to increase compatibility with
628
           some DVD players. Not mandated by the standard.*/
629
        if (s->is_svcd)
630
            general_pack = 1;    /* the system header refers to both streams and no stream data*/
631
        pad_packet_bytes = packet_size - zero_trail_bytes;
632
    }
633

    
634
    packet_size -= pad_packet_bytes + zero_trail_bytes;
635

    
636
    if (packet_size > 0) {
637

    
638
        /* packet header size */
639
        packet_size -= 6;
640
        
641
        /* packet header */
642
        if (s->is_mpeg2) {
643
            header_len = 3;
644
            if (stream->packet_number==0)
645
                header_len += 3; /* PES extension */
646
            header_len += 1; /* obligatory stuffing byte */
647
        } else {
648
            header_len = 0;
649
        }
650
        if (pts != AV_NOPTS_VALUE) {
651
            if (dts != pts)
652
                header_len += 5 + 5;
653
            else
654
                header_len += 5;
655
        } else {
656
            if (!s->is_mpeg2)
657
                header_len++;
658
        }
659

    
660
        payload_size = packet_size - header_len;
661
        if (id < 0xc0) {
662
            startcode = PRIVATE_STREAM_1;
663
            payload_size -= 4;
664
            if (id >= 0xa0)
665
                payload_size -= 3;
666
        } else {
667
            startcode = 0x100 + id;
668
        }
669

    
670
        stuffing_size = payload_size - stream->buffer_ptr;
671
        if (stuffing_size < 0)
672
            stuffing_size = 0;
673
        if (stuffing_size > 16) {    /*<=16 for MPEG-1, <=32 for MPEG-2*/
674
            pad_packet_bytes += stuffing_size;
675
            packet_size -= stuffing_size;
676
            payload_size -= stuffing_size;
677
            stuffing_size = 0;
678
        }
679

    
680
        put_be32(&ctx->pb, startcode);
681

    
682
        put_be16(&ctx->pb, packet_size);
683
        
684
        if (!s->is_mpeg2)
685
            for(i=0;i<stuffing_size;i++)
686
                put_byte(&ctx->pb, 0xff);
687

    
688
        if (s->is_mpeg2) {
689
            put_byte(&ctx->pb, 0x80); /* mpeg2 id */
690

    
691
            pes_flags=0;
692

    
693
            if (pts != AV_NOPTS_VALUE) {
694
                pes_flags |= 0x80;
695
                if (dts != pts)
696
                    pes_flags |= 0x40;
697
            }
698

    
699
            /* Both the MPEG-2 and the SVCD standards demand that the
700
               P-STD_buffer_size field be included in the first packet of
701
               every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
702
               and MPEG-2 standard 2.7.7) */
703
            if (stream->packet_number == 0)
704
                pes_flags |= 0x01;
705

    
706
            put_byte(&ctx->pb, pes_flags); /* flags */
707
            put_byte(&ctx->pb, header_len - 3 + stuffing_size);
708

    
709
            if (pes_flags & 0x80)  /*write pts*/
710
                put_timestamp(&ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
711
            if (pes_flags & 0x40)  /*write dts*/
712
                put_timestamp(&ctx->pb, 0x01, dts);
713
            
714
            if (pes_flags & 0x01) {  /*write pes extension*/
715
                put_byte(&ctx->pb, 0x10); /* flags */
716

    
717
                /* P-STD buffer info */                
718
                if (id == AUDIO_ID)
719
                    put_be16(&ctx->pb, 0x4000 | stream->max_buffer_size/128);
720
                else
721
                    put_be16(&ctx->pb, 0x6000 | stream->max_buffer_size/1024);
722
            }
723

    
724
        } else {
725
            if (pts != AV_NOPTS_VALUE) {
726
                if (dts != pts) {
727
                    put_timestamp(&ctx->pb, 0x03, pts);
728
                    put_timestamp(&ctx->pb, 0x01, dts);
729
                } else {
730
                    put_timestamp(&ctx->pb, 0x02, pts);
731
                }
732
            } else {
733
                put_byte(&ctx->pb, 0x0f);
734
            }
735
        }
736

    
737
        if (s->is_mpeg2) {
738
            /* special stuffing byte that is always written
739
               to prevent accidental generation of start codes. */
740
            put_byte(&ctx->pb, 0xff);
741

    
742
            for(i=0;i<stuffing_size;i++)
743
                put_byte(&ctx->pb, 0xff);
744
        }
745

    
746
        if (startcode == PRIVATE_STREAM_1) {
747
            put_byte(&ctx->pb, id);
748
            if (id >= 0xa0) {
749
                /* LPCM (XXX: check nb_frames) */
750
                put_byte(&ctx->pb, 7);
751
                put_be16(&ctx->pb, 4); /* skip 3 header bytes */
752
                put_byte(&ctx->pb, stream->lpcm_header[0]);
753
                put_byte(&ctx->pb, stream->lpcm_header[1]);
754
                put_byte(&ctx->pb, stream->lpcm_header[2]);
755
            } else {
756
                /* AC3 */
757
                put_byte(&ctx->pb, stream->nb_frames);
758
                put_be16(&ctx->pb, stream->frame_start_offset);
759
            }
760
        }
761

    
762
        /* output data */
763
        put_buffer(&ctx->pb, stream->buffer, payload_size - stuffing_size);
764
    }
765

    
766
    if (pad_packet_bytes > 0)
767
        put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);    
768

    
769
    for(i=0;i<zero_trail_bytes;i++)
770
        put_byte(&ctx->pb, 0x00);
771
        
772
    put_flush_packet(&ctx->pb);
773
    
774
    s->packet_number++;
775

    
776
    /* only increase the stream packet number if this pack actually contains
777
       something that is specific to this stream! I.e. a dedicated header
778
       or some data.*/
779
    if (!general_pack)
780
        stream->packet_number++;
781
    stream->nb_frames = 0;
782
    stream->frame_start_offset = 0;
783
}
784

    
785
static void put_vcd_padding_sector(AVFormatContext *ctx)
786
{
787
    /* There are two ways to do this padding: writing a sector/pack
788
       of 0 values, or writing an MPEG padding pack. Both seem to
789
       work with most decoders, BUT the VCD standard only allows a 0-sector
790
       (see standard p. IV-4, IV-5).
791
       So a 0-sector it is...*/
792

    
793
    MpegMuxContext *s = ctx->priv_data;
794
    int i;
795

    
796
    for(i=0;i<s->packet_size;i++)
797
        put_byte(&ctx->pb, 0);
798

    
799
    s->vcd_padding_bytes_written += s->packet_size;
800
        
801
    put_flush_packet(&ctx->pb);
802
    
803
    /* increasing the packet number is correct. The SCR of the following packs
804
       is calculated from the packet_number and it has to include the padding
805
       sector (it represents the sector index, not the MPEG pack index)
806
       (see VCD standard p. IV-6)*/
807
    s->packet_number++;
808
}
809

    
810
static int64_t update_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
811
{
812
    MpegMuxContext *s = ctx->priv_data;
813
    int64_t scr;
814
    StreamInfo *stream;
815
    int i;
816

    
817
    if (s->is_vcd) {
818
        /* Since the data delivery rate is constant, SCR is computed
819
           using the formula C + i * 1200 where C is the start constant
820
           and i is the pack index.
821
           It is recommended that SCR 0 is at the beginning of the VCD front
822
           margin (a sequence of empty Form 2 sectors on the CD).
823
           It is recommended that the front margin is 30 sectors long, so
824
           we use C = 30*1200 = 36000
825
           (Note that even if the front margin is not 30 sectors the file
826
           will still be correct according to the standard. It just won't have
827
           the "recommended" value).*/
828
        scr = 36000 + s->packet_number * 1200;
829

    
830

    
831
#if 0
832
        for(i=0;i<ctx->nb_streams;i++) {
833
            stream = ctx->streams[i]->priv_data;
834
            
835
            if(scr > stream->start_pts && stream->start_pts!=AV_NOPTS_VALUE) {
836
                av_log(ctx, AV_LOG_DEBUG, "mpeg vcd: SCR above PTS (scr=%0.3f, stream index=%d, stream_pts=%0.3f).\n", scr/90000.0, i, stream->start_pts / 90000.0);                 
837
            }
838
        }
839
#endif
840
    }
841
    else {
842
        
843
        
844
        /* XXX I believe this calculation of SCR is wrong. SCR
845
           specifies at which time the data should enter the decoder.
846
           Two packs cannot enter the decoder at the same time. */
847

    
848
        /* XXX: system clock should be computed precisely, especially for
849
        CBR case. The current mode gives at least something coherent */
850
        if (stream_index == s->scr_stream_index
851
            && pts != AV_NOPTS_VALUE)
852
            scr = pts;
853
        else
854
            scr = s->last_scr;
855

    
856
        /* "Sanity hack": make sure that the SCR does not overtake the pts of
857
           buffered data that is still waiting to be written.*/
858
        for(i=0;i<ctx->nb_streams;i++) {
859
            stream = ctx->streams[i]->priv_data;
860
            
861
            if(scr > stream->start_pts && stream->start_pts!=AV_NOPTS_VALUE) {
862
                /* av_log(ctx, AV_LOG_DEBUG, "mpeg: restricting scr to stream pts (scr=%0.3f, stream index=%d, stream_pts=%0.3f).\n", scr/90000.0, i, stream->start_pts / 90000.0); */
863
                scr = stream->start_pts;
864
            }
865
        }
866
    }
867

    
868
    s->last_scr=scr;
869

    
870
    return scr;
871
}    
872

    
873

    
874
static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
875
{
876
    MpegMuxContext *s = ctx->priv_data;
877
    int stream_index= pkt->stream_index;
878
    int size= pkt->size;
879
    uint8_t *buf= pkt->data;
880
    AVStream *st = ctx->streams[stream_index];
881
    StreamInfo *stream = st->priv_data;
882
    int64_t pts, dts, new_start_pts, new_start_dts;
883
    int len, avail_size;
884
    
885
    pts= pkt->pts;
886
    dts= pkt->dts;
887

    
888
    if(s->is_svcd) {
889
        /* offset pts and dts slightly into the future to be able
890
           to do the compatibility fix below.*/
891
        pts = (pts + 2) & ((1LL << 33) - 1);
892
        dts = (dts + 2) & ((1LL << 33) - 1);
893

    
894
        if (stream->packet_number == 0 && dts == pts)
895
            /* For the very first packet we want to force the DTS to be included.
896
               This increases compatibility with lots of DVD players.
897
               Since the MPEG-2 standard mandates that DTS is only written when
898
               it is different from PTS we have to move it slightly into the past.*/
899
            dts = (dts - 2) & ((1LL << 33) - 1);
900
    }
901
    if(s->is_vcd) {
902
        /* We have to offset the PTS, so that it is consistent with the SCR.
903
           SCR starts at 36000, but the first two packs contain only padding
904
           and the first pack from the other stream, respectively, may also have
905
           been written before.
906
           So the real data starts at SCR 36000+3*1200. */
907
        pts = (pts + 36000 + 3600) & ((1LL << 33) - 1);
908
        dts = (dts + 36000 + 3600) & ((1LL << 33) - 1);
909
    }
910
    
911
#if 0
912
    update_scr(ctx,stream_index,pts);
913

914
    printf("%d: pts=%0.3f dts=%0.3f scr=%0.3f\n", 
915
           stream_index, 
916
           pts / 90000.0, 
917
           dts / 90000.0, 
918
           s->last_scr / 90000.0);
919
#endif
920
    
921
    /* we assume here that pts != AV_NOPTS_VALUE */
922
    new_start_pts = stream->start_pts;
923
    new_start_dts = stream->start_dts;
924
    
925
    if (stream->start_pts == AV_NOPTS_VALUE) {
926
        new_start_pts = pts;
927
        new_start_dts = dts;
928
    }
929
    avail_size = get_packet_payload_size(ctx, stream_index,
930
                                         new_start_pts, 
931
                                         new_start_dts);
932
    if (stream->buffer_ptr >= avail_size) {
933

    
934
        update_scr(ctx,stream_index,stream->start_pts);
935

    
936
        /* unlikely case: outputing the pts or dts increase the packet
937
           size so that we cannot write the start of the next
938
           packet. In this case, we must flush the current packet with
939
           padding.
940
           Note: this always happens for the first audio and video packet
941
           in a VCD file, since they do not carry any data.*/
942
        flush_packet(ctx, stream_index,
943
                     stream->start_pts, stream->start_dts, s->last_scr);
944
        stream->buffer_ptr = 0;
945
    }
946
    stream->start_pts = new_start_pts;
947
    stream->start_dts = new_start_dts;
948
    stream->nb_frames++;
949
    if (stream->frame_start_offset == 0)
950
        stream->frame_start_offset = stream->buffer_ptr + 1;
951
    while (size > 0) {
952
        avail_size = get_packet_payload_size(ctx, stream_index,
953
                                             stream->start_pts, 
954
                                             stream->start_dts);
955
        len = avail_size - stream->buffer_ptr;
956
        if (len > size)
957
            len = size;
958
        memcpy(stream->buffer + stream->buffer_ptr, buf, len);
959
        stream->buffer_ptr += len;
960
        buf += len;
961
        size -= len;
962
        if (stream->buffer_ptr >= avail_size) {
963

    
964
            update_scr(ctx,stream_index,stream->start_pts);
965

    
966
            /* if packet full, we send it now */
967
            flush_packet(ctx, stream_index,
968
                         stream->start_pts, stream->start_dts, s->last_scr);
969
            stream->buffer_ptr = 0;
970

    
971
            if (s->is_vcd) {
972
                /* Write one or more padding sectors, if necessary, to reach
973
                   the constant overall bitrate.*/
974
                int vcd_pad_bytes;
975
            
976
                while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->start_pts) ) >= s->packet_size)
977
                    put_vcd_padding_sector(ctx);
978
            }
979

    
980
            /* Make sure only the FIRST pes packet for this frame has
981
               a timestamp */
982
            stream->start_pts = AV_NOPTS_VALUE;
983
            stream->start_dts = AV_NOPTS_VALUE;
984
        }
985
    }
986

    
987
    return 0;
988
}
989

    
990
static int mpeg_mux_end(AVFormatContext *ctx)
991
{
992
    MpegMuxContext *s = ctx->priv_data;
993
    StreamInfo *stream;
994
    int i;
995

    
996
    /* flush each packet */
997
    for(i=0;i<ctx->nb_streams;i++) {
998
        stream = ctx->streams[i]->priv_data;
999
        if (stream->buffer_ptr > 0) {
1000
            update_scr(ctx,i,stream->start_pts);
1001

    
1002
            /* NOTE: we can always write the remaining data as it was
1003
               tested before in mpeg_mux_write_packet() */
1004
            flush_packet(ctx, i, stream->start_pts, stream->start_dts, 
1005
                         s->last_scr);
1006
        }
1007
    }
1008

    
1009
    /* End header according to MPEG1 systems standard. We do not write
1010
       it as it is usually not needed by decoders and because it
1011
       complicates MPEG stream concatenation. */
1012
    //put_be32(&ctx->pb, ISO_11172_END_CODE);
1013
    //put_flush_packet(&ctx->pb);
1014

    
1015
    for(i=0;i<ctx->nb_streams;i++)
1016
        av_freep(&ctx->streams[i]->priv_data);
1017

    
1018
    return 0;
1019
}
1020
#endif //CONFIG_ENCODERS
1021

    
1022
/*********************************************/
1023
/* demux code */
1024

    
1025
#define MAX_SYNC_SIZE 100000
1026

    
1027
static int mpegps_probe(AVProbeData *p)
1028
{
1029
    int i;
1030
    int size= FFMIN(20, p->buf_size);
1031
    uint32_t code=0xFF;
1032

    
1033
    /* we search the first start code. If it is a packet start code,
1034
       then we decide it is mpeg ps. We do not send highest value to
1035
       give a chance to mpegts */
1036
    /* NOTE: the search range was restricted to avoid too many false
1037
       detections */
1038

    
1039
    for (i = 0; i < size; i++) {
1040
        code = (code << 8) | p->buf[i];
1041
        if ((code & 0xffffff00) == 0x100) {
1042
            if (code == PACK_START_CODE ||
1043
                code == SYSTEM_HEADER_START_CODE ||
1044
                (code >= 0x1e0 && code <= 0x1ef) ||
1045
                (code >= 0x1c0 && code <= 0x1df) ||
1046
                code == PRIVATE_STREAM_2 ||
1047
                code == PROGRAM_STREAM_MAP ||
1048
                code == PRIVATE_STREAM_1 ||
1049
                code == PADDING_STREAM)
1050
                return AVPROBE_SCORE_MAX - 2;
1051
            else
1052
                return 0;
1053
        }
1054
    }
1055
    return 0;
1056
}
1057

    
1058

    
1059
typedef struct MpegDemuxContext {
1060
    int header_state;
1061
} MpegDemuxContext;
1062

    
1063
static int mpegps_read_header(AVFormatContext *s,
1064
                              AVFormatParameters *ap)
1065
{
1066
    MpegDemuxContext *m = s->priv_data;
1067
    m->header_state = 0xff;
1068
    s->ctx_flags |= AVFMTCTX_NOHEADER;
1069

    
1070
    /* no need to do more */
1071
    return 0;
1072
}
1073

    
1074
static int64_t get_pts(ByteIOContext *pb, int c)
1075
{
1076
    int64_t pts;
1077
    int val;
1078

    
1079
    if (c < 0)
1080
        c = get_byte(pb);
1081
    pts = (int64_t)((c >> 1) & 0x07) << 30;
1082
    val = get_be16(pb);
1083
    pts |= (int64_t)(val >> 1) << 15;
1084
    val = get_be16(pb);
1085
    pts |= (int64_t)(val >> 1);
1086
    return pts;
1087
}
1088

    
1089
static int find_next_start_code(ByteIOContext *pb, int *size_ptr, 
1090
                                uint32_t *header_state)
1091
{
1092
    unsigned int state, v;
1093
    int val, n;
1094

    
1095
    state = *header_state;
1096
    n = *size_ptr;
1097
    while (n > 0) {
1098
        if (url_feof(pb))
1099
            break;
1100
        v = get_byte(pb);
1101
        n--;
1102
        if (state == 0x000001) {
1103
            state = ((state << 8) | v) & 0xffffff;
1104
            val = state;
1105
            goto found;
1106
        }
1107
        state = ((state << 8) | v) & 0xffffff;
1108
    }
1109
    val = -1;
1110
 found:
1111
    *header_state = state;
1112
    *size_ptr = n;
1113
    return val;
1114
}
1115

    
1116
/* XXX: optimize */
1117
static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
1118
{
1119
    int64_t pos, pos_start;
1120
    int max_size, start_code;
1121

    
1122
    max_size = *size_ptr;
1123
    pos_start = url_ftell(pb);
1124

    
1125
    /* in order to go faster, we fill the buffer */
1126
    pos = pos_start - 16386;
1127
    if (pos < 0)
1128
        pos = 0;
1129
    url_fseek(pb, pos, SEEK_SET);
1130
    get_byte(pb);
1131

    
1132
    pos = pos_start;
1133
    for(;;) {
1134
        pos--;
1135
        if (pos < 0 || (pos_start - pos) >= max_size) {
1136
            start_code = -1;
1137
            goto the_end;
1138
        }
1139
        url_fseek(pb, pos, SEEK_SET);
1140
        start_code = get_be32(pb);
1141
        if ((start_code & 0xffffff00) == 0x100)
1142
            break;
1143
    }
1144
 the_end:
1145
    *size_ptr = pos_start - pos;
1146
    return start_code;
1147
}
1148

    
1149
/* read the next PES header. Return its position in ppos 
1150
   (if not NULL), and its start code, pts and dts.
1151
 */
1152
static int mpegps_read_pes_header(AVFormatContext *s,
1153
                                  int64_t *ppos, int *pstart_code, 
1154
                                  int64_t *ppts, int64_t *pdts)
1155
{
1156
    MpegDemuxContext *m = s->priv_data;
1157
    int len, size, startcode, c, flags, header_len;
1158
    int64_t pts, dts, last_pos;
1159

    
1160
    last_pos = -1;
1161
 redo:
1162
        /* next start code (should be immediately after) */
1163
        m->header_state = 0xff;
1164
        size = MAX_SYNC_SIZE;
1165
        startcode = find_next_start_code(&s->pb, &size, &m->header_state);
1166
    //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
1167
    if (startcode < 0)
1168
        return AVERROR_IO;
1169
    if (startcode == PACK_START_CODE)
1170
        goto redo;
1171
    if (startcode == SYSTEM_HEADER_START_CODE)
1172
        goto redo;
1173
    if (startcode == PADDING_STREAM ||
1174
        startcode == PRIVATE_STREAM_2) {
1175
        /* skip them */
1176
        len = get_be16(&s->pb);
1177
        url_fskip(&s->pb, len);
1178
        goto redo;
1179
    }
1180
    /* find matching stream */
1181
    if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
1182
          (startcode >= 0x1e0 && startcode <= 0x1ef) ||
1183
          (startcode == 0x1bd)))
1184
        goto redo;
1185
    if (ppos) {
1186
        *ppos = url_ftell(&s->pb) - 4;
1187
    }
1188
    len = get_be16(&s->pb);
1189
    pts = AV_NOPTS_VALUE;
1190
    dts = AV_NOPTS_VALUE;
1191
    /* stuffing */
1192
    for(;;) {
1193
        if (len < 1)
1194
            goto redo;
1195
        c = get_byte(&s->pb);
1196
        len--;
1197
        /* XXX: for mpeg1, should test only bit 7 */
1198
        if (c != 0xff) 
1199
            break;
1200
    }
1201
    if ((c & 0xc0) == 0x40) {
1202
        /* buffer scale & size */
1203
        if (len < 2)
1204
            goto redo;
1205
        get_byte(&s->pb);
1206
        c = get_byte(&s->pb);
1207
        len -= 2;
1208
    }
1209
    if ((c & 0xf0) == 0x20) {
1210
        if (len < 4)
1211
            goto redo;
1212
        dts = pts = get_pts(&s->pb, c);
1213
        len -= 4;
1214
    } else if ((c & 0xf0) == 0x30) {
1215
        if (len < 9)
1216
            goto redo;
1217
        pts = get_pts(&s->pb, c);
1218
        dts = get_pts(&s->pb, -1);
1219
        len -= 9;
1220
    } else if ((c & 0xc0) == 0x80) {
1221
        /* mpeg 2 PES */
1222
        if ((c & 0x30) != 0) {
1223
            /* Encrypted multiplex not handled */
1224
            goto redo;
1225
        }
1226
        flags = get_byte(&s->pb);
1227
        header_len = get_byte(&s->pb);
1228
        len -= 2;
1229
        if (header_len > len)
1230
            goto redo;
1231
        if ((flags & 0xc0) == 0x80) {
1232
            dts = pts = get_pts(&s->pb, -1);
1233
            if (header_len < 5)
1234
                goto redo;
1235
            header_len -= 5;
1236
            len -= 5;
1237
        } if ((flags & 0xc0) == 0xc0) {
1238
            pts = get_pts(&s->pb, -1);
1239
            dts = get_pts(&s->pb, -1);
1240
            if (header_len < 10)
1241
                goto redo;
1242
            header_len -= 10;
1243
            len -= 10;
1244
        }
1245
        len -= header_len;
1246
        while (header_len > 0) {
1247
            get_byte(&s->pb);
1248
            header_len--;
1249
        }
1250
    }
1251
    else if( c!= 0xf )
1252
        goto redo;
1253

    
1254
    if (startcode == 0x1bd) {
1255
        if (len < 1)
1256
            goto redo;
1257
        startcode = get_byte(&s->pb);
1258
        len--;
1259
        if (startcode >= 0x80 && startcode <= 0xbf) {
1260
            /* audio: skip header */
1261
            if (len < 3)
1262
                goto redo;
1263
            get_byte(&s->pb);
1264
            get_byte(&s->pb);
1265
            get_byte(&s->pb);
1266
            len -= 3;
1267
        }
1268
    }
1269
    if(dts != AV_NOPTS_VALUE && ppos){
1270
        int i;
1271
        for(i=0; i<s->nb_streams; i++){
1272
            if(startcode == s->streams[i]->id) {
1273
                av_add_index_entry(s->streams[i], *ppos, dts, 0, 0 /* FIXME keyframe? */);
1274
            }
1275
        }
1276
    }
1277
    
1278
    *pstart_code = startcode;
1279
    *ppts = pts;
1280
    *pdts = dts;
1281
    return len;
1282
}
1283

    
1284
static int mpegps_read_packet(AVFormatContext *s,
1285
                              AVPacket *pkt)
1286
{
1287
    AVStream *st;
1288
    int len, startcode, i, type, codec_id = 0;
1289
    int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
1290

    
1291
 redo:
1292
    len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
1293
    if (len < 0)
1294
        return len;
1295
    
1296
    /* now find stream */
1297
    for(i=0;i<s->nb_streams;i++) {
1298
        st = s->streams[i];
1299
        if (st->id == startcode)
1300
            goto found;
1301
    }
1302
    if (startcode >= 0x1e0 && startcode <= 0x1ef) {
1303
        type = CODEC_TYPE_VIDEO;
1304
        codec_id = CODEC_ID_MPEG2VIDEO;
1305
    } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
1306
        type = CODEC_TYPE_AUDIO;
1307
        codec_id = CODEC_ID_MP2;
1308
    } else if (startcode >= 0x80 && startcode <= 0x89) {
1309
        type = CODEC_TYPE_AUDIO;
1310
        codec_id = CODEC_ID_AC3;
1311
    } else if (startcode >= 0x8a && startcode <= 0x9f) {
1312
        type = CODEC_TYPE_AUDIO;
1313
        codec_id = CODEC_ID_DTS;
1314
    } else if (startcode >= 0xa0 && startcode <= 0xbf) {
1315
        type = CODEC_TYPE_AUDIO;
1316
        codec_id = CODEC_ID_PCM_S16BE;
1317
    } else {
1318
    skip:
1319
        /* skip packet */
1320
        url_fskip(&s->pb, len);
1321
        goto redo;
1322
    }
1323
    /* no stream found: add a new stream */
1324
    st = av_new_stream(s, startcode);
1325
    if (!st) 
1326
        goto skip;
1327
    st->codec.codec_type = type;
1328
    st->codec.codec_id = codec_id;
1329
    if (codec_id != CODEC_ID_PCM_S16BE)
1330
        st->need_parsing = 1;
1331
 found:
1332
    if (startcode >= 0xa0 && startcode <= 0xbf) {
1333
        int b1, freq;
1334

    
1335
        /* for LPCM, we just skip the header and consider it is raw
1336
           audio data */
1337
        if (len <= 3)
1338
            goto skip;
1339
        get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
1340
        b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
1341
        get_byte(&s->pb); /* dynamic range control (0x80 = off) */
1342
        len -= 3;
1343
        freq = (b1 >> 4) & 3;
1344
        st->codec.sample_rate = lpcm_freq_tab[freq];
1345
        st->codec.channels = 1 + (b1 & 7);
1346
        st->codec.bit_rate = st->codec.channels * st->codec.sample_rate * 2;
1347
    }
1348
    av_new_packet(pkt, len);
1349
    get_buffer(&s->pb, pkt->data, pkt->size);
1350
    pkt->pts = pts;
1351
    pkt->dts = dts;
1352
    pkt->stream_index = st->index;
1353
#if 0
1354
    av_log(s, AV_LOG_DEBUG, "%d: pts=%0.3f dts=%0.3f\n",
1355
           pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0);
1356
#endif
1357

    
1358
    return 0;
1359
}
1360

    
1361
static int mpegps_read_close(AVFormatContext *s)
1362
{
1363
    return 0;
1364
}
1365

    
1366
static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index, 
1367
                               int64_t *ppos, int64_t pos_limit)
1368
{
1369
    int len, startcode;
1370
    int64_t pos, pts, dts;
1371

    
1372
    pos = *ppos;
1373
#ifdef DEBUG_SEEK
1374
    printf("read_dts: pos=0x%llx next=%d -> ", pos, find_next);
1375
#endif
1376
    url_fseek(&s->pb, pos, SEEK_SET);
1377
    for(;;) {
1378
        len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
1379
        if (len < 0) {
1380
#ifdef DEBUG_SEEK
1381
            printf("none (ret=%d)\n", len);
1382
#endif
1383
            return AV_NOPTS_VALUE;
1384
        }
1385
        if (startcode == s->streams[stream_index]->id && 
1386
            dts != AV_NOPTS_VALUE) {
1387
            break;
1388
        }
1389
        url_fskip(&s->pb, len);
1390
    }
1391
#ifdef DEBUG_SEEK
1392
    printf("pos=0x%llx dts=0x%llx %0.3f\n", pos, dts, dts / 90000.0);
1393
#endif
1394
    *ppos = pos;
1395
    return dts;
1396
}
1397

    
1398
#ifdef CONFIG_ENCODERS
1399
static AVOutputFormat mpeg1system_mux = {
1400
    "mpeg",
1401
    "MPEG1 System format",
1402
    "video/mpeg",
1403
    "mpg,mpeg",
1404
    sizeof(MpegMuxContext),
1405
    CODEC_ID_MP2,
1406
    CODEC_ID_MPEG1VIDEO,
1407
    mpeg_mux_init,
1408
    mpeg_mux_write_packet,
1409
    mpeg_mux_end,
1410
};
1411

    
1412
static AVOutputFormat mpeg1vcd_mux = {
1413
    "vcd",
1414
    "MPEG1 System format (VCD)",
1415
    "video/mpeg",
1416
    NULL,
1417
    sizeof(MpegMuxContext),
1418
    CODEC_ID_MP2,
1419
    CODEC_ID_MPEG1VIDEO,
1420
    mpeg_mux_init,
1421
    mpeg_mux_write_packet,
1422
    mpeg_mux_end,
1423
};
1424

    
1425
static AVOutputFormat mpeg2vob_mux = {
1426
    "vob",
1427
    "MPEG2 PS format (VOB)",
1428
    "video/mpeg",
1429
    "vob",
1430
    sizeof(MpegMuxContext),
1431
    CODEC_ID_MP2,
1432
    CODEC_ID_MPEG2VIDEO,
1433
    mpeg_mux_init,
1434
    mpeg_mux_write_packet,
1435
    mpeg_mux_end,
1436
};
1437

    
1438
/* Same as mpeg2vob_mux except that the pack size is 2324 */
1439
static AVOutputFormat mpeg2svcd_mux = {
1440
    "svcd",
1441
    "MPEG2 PS format (VOB)",
1442
    "video/mpeg",
1443
    "vob",
1444
    sizeof(MpegMuxContext),
1445
    CODEC_ID_MP2,
1446
    CODEC_ID_MPEG2VIDEO,
1447
    mpeg_mux_init,
1448
    mpeg_mux_write_packet,
1449
    mpeg_mux_end,
1450
};
1451

    
1452

    
1453

    
1454
#endif //CONFIG_ENCODERS
1455

    
1456
AVInputFormat mpegps_demux = {
1457
    "mpeg",
1458
    "MPEG PS format",
1459
    sizeof(MpegDemuxContext),
1460
    mpegps_probe,
1461
    mpegps_read_header,
1462
    mpegps_read_packet,
1463
    mpegps_read_close,
1464
    NULL, //mpegps_read_seek,
1465
    mpegps_read_dts,
1466
};
1467

    
1468
int mpegps_init(void)
1469
{
1470
#ifdef CONFIG_ENCODERS
1471
    av_register_output_format(&mpeg1system_mux);
1472
    av_register_output_format(&mpeg1vcd_mux);
1473
    av_register_output_format(&mpeg2vob_mux);
1474
    av_register_output_format(&mpeg2svcd_mux);
1475
#endif //CONFIG_ENCODERS
1476
    av_register_input_format(&mpegps_demux);
1477
    return 0;
1478
}