Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpeg.c @ f3356e9c

History | View | Annotate | Download (52.8 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
#include "bitstream.h"
21

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

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

    
28
typedef struct PacketDesc {
29
    int64_t pts;
30
    int64_t dts;
31
    int size;
32
    int unwritten_size;
33
    int flags;
34
    struct PacketDesc *next;
35
} PacketDesc;
36

    
37
typedef struct {
38
    FifoBuffer fifo;
39
    uint8_t id;
40
    int max_buffer_size; /* in bytes */
41
    int buffer_index;
42
    PacketDesc *predecode_packet;
43
    PacketDesc *premux_packet;
44
    PacketDesc **next_packet;
45
    int packet_number;
46
    uint8_t lpcm_header[3];
47
    int lpcm_align;
48
    uint8_t *fifo_iframe_ptr;
49
    int align_iframe;
50
    int64_t vobu_start_pts;
51
} StreamInfo;
52

    
53
typedef struct {
54
    int packet_size; /* required packet size */
55
    int packet_number;
56
    int pack_header_freq;     /* frequency (in packets^-1) at which we send pack headers */
57
    int system_header_freq;
58
    int system_header_size;
59
    int mux_rate; /* bitrate in units of 50 bytes/s */
60
    /* stream info */
61
    int audio_bound;
62
    int video_bound;
63
    int is_mpeg2;
64
    int is_vcd;
65
    int is_svcd;
66
    int is_dvd;
67
    int64_t last_scr; /* current system clock */
68

    
69
    double vcd_padding_bitrate; //FIXME floats
70
    int64_t vcd_padding_bytes_written;
71

    
72
} MpegMuxContext;
73

    
74
#define PACK_START_CODE             ((unsigned int)0x000001ba)
75
#define SYSTEM_HEADER_START_CODE    ((unsigned int)0x000001bb)
76
#define SEQUENCE_END_CODE           ((unsigned int)0x000001b7)
77
#define PACKET_START_CODE_MASK      ((unsigned int)0xffffff00)
78
#define PACKET_START_CODE_PREFIX    ((unsigned int)0x00000100)
79
#define ISO_11172_END_CODE          ((unsigned int)0x000001b9)
80
  
81
/* mpeg2 */
82
#define PROGRAM_STREAM_MAP 0x1bc
83
#define PRIVATE_STREAM_1   0x1bd
84
#define PADDING_STREAM     0x1be
85
#define PRIVATE_STREAM_2   0x1bf
86

    
87

    
88
#define AUDIO_ID 0xc0
89
#define VIDEO_ID 0xe0
90
#define AC3_ID   0x80
91
#define DTS_ID   0x8a
92
#define LPCM_ID  0xa0
93

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

    
96
#ifdef CONFIG_ENCODERS
97
static AVOutputFormat mpeg1system_mux;
98
static AVOutputFormat mpeg1vcd_mux;
99
static AVOutputFormat mpeg2vob_mux;
100
static AVOutputFormat mpeg2svcd_mux;
101
static AVOutputFormat mpeg2dvd_mux;
102

    
103
static int put_pack_header(AVFormatContext *ctx, 
104
                           uint8_t *buf, int64_t timestamp)
105
{
106
    MpegMuxContext *s = ctx->priv_data;
107
    PutBitContext pb;
108
    
109
    init_put_bits(&pb, buf, 128);
110

    
111
    put_bits(&pb, 32, PACK_START_CODE);
112
    if (s->is_mpeg2) {
113
        put_bits(&pb, 2, 0x1);
114
    } else {
115
        put_bits(&pb, 4, 0x2);
116
    }
117
    put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
118
    put_bits(&pb, 1, 1);
119
    put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
120
    put_bits(&pb, 1, 1);
121
    put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
122
    put_bits(&pb, 1, 1);
123
    if (s->is_mpeg2) {
124
        /* clock extension */
125
        put_bits(&pb, 9, 0);
126
    }
127
    put_bits(&pb, 1, 1);
128
    put_bits(&pb, 22, s->mux_rate);
129
    put_bits(&pb, 1, 1);
130
    if (s->is_mpeg2) {
131
        put_bits(&pb, 1, 1);
132
        put_bits(&pb, 5, 0x1f); /* reserved */
133
        put_bits(&pb, 3, 0); /* stuffing length */
134
    }
135
    flush_put_bits(&pb);
136
    return pbBufPtr(&pb) - pb.buf;
137
}
138

    
139
static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
140
{
141
    MpegMuxContext *s = ctx->priv_data;
142
    int size, i, private_stream_coded, id;
143
    PutBitContext pb;
144

    
145
    init_put_bits(&pb, buf, 128);
146

    
147
    put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
148
    put_bits(&pb, 16, 0);
149
    put_bits(&pb, 1, 1);
150
    
151
    put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
152
    put_bits(&pb, 1, 1); /* marker */
153
    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

    
159
    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
    
168
    if (s->is_vcd || s->is_dvd) {
169
        /* 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
    put_bits(&pb, 1, 1); /* marker */
178

    
179
    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
    
185
    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
        
202
        for(i=0;i<ctx->nb_streams;i++) {
203
            StreamInfo *stream = ctx->streams[i]->priv_data;
204

    
205
            id = stream->id;
206
            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
            }
213
        }
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
            }
274
        }
275
    }
276

    
277
    flush_put_bits(&pb);
278
    size = pbBufPtr(&pb) - pb.buf;
279
    /* patch packet size */
280
    buf[4] = (size - 6) >> 8;
281
    buf[5] = (size - 6) & 0xff;
282

    
283
    return size;
284
}
285

    
286
static int get_system_header_size(AVFormatContext *ctx)
287
{
288
    int buf_index, i, private_stream_coded;
289
    StreamInfo *stream;
290
    MpegMuxContext *s = ctx->priv_data;
291

    
292
    if (s->is_dvd)
293
       return 18; // DVD-Video system headers are 18 bytes fixed length.
294

    
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
static int mpeg_mux_init(AVFormatContext *ctx)
310
{
311
    MpegMuxContext *s = ctx->priv_data;
312
    int bitrate, i, mpa_id, mpv_id, ac3_id, dts_id, lpcm_id, j;
313
    AVStream *st;
314
    StreamInfo *stream;
315
    int audio_bitrate;
316
    int video_bitrate;
317

    
318
    s->packet_number = 0;
319
    s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
320
    s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
321
    s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux || ctx->oformat == &mpeg2dvd_mux);
322
    s->is_dvd = (ctx->oformat == &mpeg2dvd_mux);
323
    
324
    if(ctx->packet_size)
325
        s->packet_size = ctx->packet_size;
326
    else
327
        s->packet_size = 2048;
328
       
329
    s->vcd_padding_bytes_written = 0;
330
    s->vcd_padding_bitrate=0;
331
        
332
    s->audio_bound = 0;
333
    s->video_bound = 0;
334
    mpa_id = AUDIO_ID;
335
    ac3_id = AC3_ID;
336
    dts_id = DTS_ID;
337
    mpv_id = VIDEO_ID;
338
    lpcm_id = LPCM_ID;
339
    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
        av_set_pts_info(st, 64, 1, 90000);
347

    
348
        switch(st->codec.codec_type) {
349
        case CODEC_TYPE_AUDIO:
350
            if (st->codec.codec_id == CODEC_ID_AC3) {
351
                stream->id = ac3_id++;
352
            } else if (st->codec.codec_id == CODEC_ID_DTS) {
353
                stream->id = dts_id++;
354
            } 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
                stream->id = mpa_id++;
370
            }
371

    
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
            stream->max_buffer_size = 4 * 1024; 
375
            s->audio_bound++;
376
            break;
377
        case CODEC_TYPE_VIDEO:
378
            stream->id = mpv_id++;
379
            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
                /* 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
#endif
391
            s->video_bound++;
392
            break;
393
        default:
394
            return -1;
395
        }
396
        fifo_init(&stream->fifo, 16);
397
        stream->next_packet= &stream->premux_packet;
398
    }
399
    bitrate = 0;
400
    audio_bitrate = 0;
401
    video_bitrate = 0;
402
    for(i=0;i<ctx->nb_streams;i++) {
403
        int codec_rate;
404
        st = ctx->streams[i];
405
        stream = (StreamInfo*) st->priv_data;
406

    
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

    
417
        if (stream->id==AUDIO_ID)
418
            audio_bitrate += codec_rate;
419
        else if (stream->id==VIDEO_ID)
420
            video_bitrate += codec_rate;
421
    }
422
    
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

    
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
//        s->mux_rate=2352 * 75 / 50;    /* = 3528*/
444

    
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
    }
461
    
462
    if (s->is_vcd || s->is_mpeg2)
463
        /* 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

    
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
    
473
    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
        /* 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
    else
482
        s->system_header_freq = s->pack_header_freq * 5;
483
    
484
    for(i=0;i<ctx->nb_streams;i++) {
485
        stream = ctx->streams[i]->priv_data;
486
        stream->packet_number = 0;
487
    }
488
    s->system_header_size = get_system_header_size(ctx);
489
    s->last_scr = 0;
490
    return 0;
491
 fail:
492
    for(i=0;i<ctx->nb_streams;i++) {
493
        av_free(ctx->streams[i]->priv_data);
494
    }
495
    return -ENOMEM;
496
}
497

    
498
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

    
509
/* 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
        full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
521
        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
#if 0 /* unused, remove? */
534
/* return the exact available payload size for the next packet for
535
   stream 'stream_index'. 'pts' and 'dts' are only used to know if
536
   timestamps are needed in the packet header. */
537
static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
538
                                   int64_t pts, int64_t dts)
539
{
540
    MpegMuxContext *s = ctx->priv_data;
541
    int buf_index;
542
    StreamInfo *stream;
543

544
    stream = ctx->streams[stream_index]->priv_data;
545

546
    buf_index = 0;
547
    if (((s->packet_number % s->pack_header_freq) == 0)) {
548
        /* pack header size */
549
        if (s->is_mpeg2) 
550
            buf_index += 14;
551
        else
552
            buf_index += 12;
553
        
554
        if (s->is_vcd) {
555
            /* there is exactly one system header for each stream in a VCD MPEG,
556
               One in the very first video packet and one in the very first
557
               audio packet (see VCD standard p. IV-7 and IV-8).*/
558
            
559
            if (stream->packet_number==0)
560
                /* The system headers refer only to the stream they occur in,
561
                   so they have a constant size.*/
562
                buf_index += 15;
563

564
        } else {            
565
            if ((s->packet_number % s->system_header_freq) == 0)
566
                buf_index += s->system_header_size;
567
        }
568
    }
569

570
    if ((s->is_vcd && stream->packet_number==0)
571
        || (s->is_svcd && s->packet_number==0))
572
        /* the first pack of each stream contains only the pack header,
573
           the system header and some padding (see VCD standard p. IV-6) 
574
           Add the padding size, so that the actual payload becomes 0.*/
575
        buf_index += s->packet_size - buf_index;
576
    else {
577
        /* packet header size */
578
        buf_index += 6;
579
        if (s->is_mpeg2) {
580
            buf_index += 3;
581
            if (stream->packet_number==0)
582
                buf_index += 3; /* PES extension */
583
            buf_index += 1;    /* obligatory stuffing byte */
584
        }
585
        if (pts != AV_NOPTS_VALUE) {
586
            if (dts != pts)
587
                buf_index += 5 + 5;
588
            else
589
                buf_index += 5;
590

591
        } else {
592
            if (!s->is_mpeg2)
593
                buf_index++;
594
        }
595
    
596
        if (stream->id < 0xc0) {
597
            /* AC3/LPCM private data header */
598
            buf_index += 4;
599
            if (stream->id >= 0xa0) {
600
                int n;
601
                buf_index += 3;
602
                /* NOTE: we round the payload size to an integer number of
603
                   LPCM samples */
604
                n = (s->packet_size - buf_index) % stream->lpcm_align;
605
                if (n)
606
                    buf_index += (stream->lpcm_align - n);
607
            }
608
        }
609

610
        if (s->is_vcd && stream->id == AUDIO_ID)
611
            /* The VCD standard demands that 20 zero bytes follow
612
               each audio packet (see standard p. IV-8).*/
613
            buf_index+=20;
614
    }
615
    return s->packet_size - buf_index; 
616
}
617
#endif
618

    
619
/* Write an MPEG padding packet header. */
620
static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
621
{
622
    MpegMuxContext *s = ctx->priv_data;
623
    int i;
624
    
625
    put_be32(pb, PADDING_STREAM);
626
    put_be16(pb, packet_bytes - 6);
627
    if (!s->is_mpeg2) {
628
        put_byte(pb, 0x0f);
629
        packet_bytes -= 7;
630
    } else
631
        packet_bytes -= 6;
632

    
633
    for(i=0;i<packet_bytes;i++)
634
        put_byte(pb, 0xff);
635
}
636

    
637
static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
638
    int nb_frames=0;
639
    PacketDesc *pkt_desc= stream->premux_packet;
640

    
641
    while(len>0){ 
642
        if(pkt_desc->size == pkt_desc->unwritten_size)
643
            nb_frames++;
644
        len -= pkt_desc->unwritten_size;
645
        pkt_desc= pkt_desc->next;
646
    }
647

    
648
    return nb_frames;
649
}
650

    
651
/* flush the packet on stream stream_index */
652
static int flush_packet(AVFormatContext *ctx, int stream_index, 
653
                         int64_t pts, int64_t dts, int64_t scr, int trailer_size)
654
{
655
    MpegMuxContext *s = ctx->priv_data;
656
    StreamInfo *stream = ctx->streams[stream_index]->priv_data;
657
    uint8_t *buf_ptr;
658
    int size, payload_size, startcode, id, stuffing_size, i, header_len;
659
    int packet_size;
660
    uint8_t buffer[128];
661
    int zero_trail_bytes = 0;
662
    int pad_packet_bytes = 0;
663
    int pes_flags;
664
    int general_pack = 0;  /*"general" pack without data specific to one stream?*/
665
    int nb_frames;
666
    
667
    id = stream->id;
668
    
669
#if 0
670
    printf("packet ID=%2x PTS=%0.3f\n", 
671
           id, pts / 90000.0);
672
#endif
673

    
674
    buf_ptr = buffer;
675

    
676
    if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
677
        /* output pack and systems header if needed */
678
        size = put_pack_header(ctx, buf_ptr, scr);
679
        buf_ptr += size;
680
        s->last_scr= scr;
681

    
682
        if (s->is_vcd) {
683
            /* there is exactly one system header for each stream in a VCD MPEG,
684
               One in the very first video packet and one in the very first
685
               audio packet (see VCD standard p. IV-7 and IV-8).*/
686
            
687
            if (stream->packet_number==0) {
688
                size = put_system_header(ctx, buf_ptr, id);
689
                buf_ptr += size;
690
            }
691
        } else if (s->is_dvd) {
692
            if (stream->align_iframe || s->packet_number == 0){
693
                int bytes_to_iframe;
694
                int PES_bytes_to_fill;
695
                if (stream->fifo_iframe_ptr >= stream->fifo.rptr) {
696
                    bytes_to_iframe = stream->fifo_iframe_ptr - stream->fifo.rptr;
697
                } else {
698
                    bytes_to_iframe = (stream->fifo.end - stream->fifo.rptr) + (stream->fifo_iframe_ptr - stream->fifo.buffer);
699
                }
700
                PES_bytes_to_fill = s->packet_size - size - 10;
701

    
702
                if (pts != AV_NOPTS_VALUE) {
703
                    if (dts != pts)
704
                        PES_bytes_to_fill -= 5 + 5;
705
                    else
706
                        PES_bytes_to_fill -= 5;
707
                }
708

    
709
                if (bytes_to_iframe == 0 || s->packet_number == 0) {
710
                    size = put_system_header(ctx, buf_ptr, 0);
711
                    buf_ptr += size;
712
                    size = buf_ptr - buffer;
713
                    put_buffer(&ctx->pb, buffer, size);
714

    
715
                    put_be32(&ctx->pb, PRIVATE_STREAM_2);
716
                    put_be16(&ctx->pb, 0x03d4);         // length
717
                    put_byte(&ctx->pb, 0x00);           // substream ID, 00=PCI
718
                    for (i = 0; i < 979; i++)
719
                        put_byte(&ctx->pb, 0x00);
720

    
721
                    put_be32(&ctx->pb, PRIVATE_STREAM_2);
722
                    put_be16(&ctx->pb, 0x03fa);         // length
723
                    put_byte(&ctx->pb, 0x01);           // substream ID, 01=DSI
724
                    for (i = 0; i < 1017; i++)
725
                        put_byte(&ctx->pb, 0x00);
726

    
727
                    memset(buffer, 0, 128);
728
                    buf_ptr = buffer;
729
                    s->packet_number++;
730
                    stream->align_iframe = 0;
731
                    scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
732
                    size = put_pack_header(ctx, buf_ptr, scr);
733
                    s->last_scr= scr;
734
                    buf_ptr += size;
735
                    /* GOP Start */
736
                } else if (bytes_to_iframe < PES_bytes_to_fill) {
737
                    pad_packet_bytes = PES_bytes_to_fill - bytes_to_iframe;
738
                }
739
            }
740
        } else {
741
            if ((s->packet_number % s->system_header_freq) == 0) {
742
                size = put_system_header(ctx, buf_ptr, 0);
743
                buf_ptr += size;
744
            }
745
        }
746
    }
747
    size = buf_ptr - buffer;
748
    put_buffer(&ctx->pb, buffer, size);
749

    
750
    packet_size = s->packet_size - size;
751

    
752
    if (s->is_vcd && id == AUDIO_ID)
753
        /* The VCD standard demands that 20 zero bytes follow
754
           each audio pack (see standard p. IV-8).*/
755
        zero_trail_bytes += 20;
756
            
757
    if ((s->is_vcd && stream->packet_number==0)
758
        || (s->is_svcd && s->packet_number==0)) {
759
        /* for VCD the first pack of each stream contains only the pack header,
760
           the system header and lots of padding (see VCD standard p. IV-6).
761
           In the case of an audio pack, 20 zero bytes are also added at
762
           the end.*/
763
        /* For SVCD we fill the very first pack to increase compatibility with
764
           some DVD players. Not mandated by the standard.*/
765
        if (s->is_svcd)
766
            general_pack = 1;    /* the system header refers to both streams and no stream data*/
767
        pad_packet_bytes = packet_size - zero_trail_bytes;
768
    }
769

    
770
    packet_size -= pad_packet_bytes + zero_trail_bytes;
771

    
772
    if (packet_size > 0) {
773

    
774
        /* packet header size */
775
        packet_size -= 6;
776
        
777
        /* packet header */
778
        if (s->is_mpeg2) {
779
            header_len = 3;
780
            if (stream->packet_number==0)
781
                header_len += 3; /* PES extension */
782
            header_len += 1; /* obligatory stuffing byte */
783
        } else {
784
            header_len = 0;
785
        }
786
        if (pts != AV_NOPTS_VALUE) {
787
            if (dts != pts)
788
                header_len += 5 + 5;
789
            else
790
                header_len += 5;
791
        } else {
792
            if (!s->is_mpeg2)
793
                header_len++;
794
        }
795

    
796
        payload_size = packet_size - header_len;
797
        if (id < 0xc0) {
798
            startcode = PRIVATE_STREAM_1;
799
            payload_size -= 4;
800
            if (id >= 0xa0)
801
                payload_size -= 3;
802
        } else {
803
            startcode = 0x100 + id;
804
        }
805

    
806
        stuffing_size = payload_size - fifo_size(&stream->fifo, stream->fifo.rptr);
807

    
808
        // first byte doesnt fit -> reset pts/dts + stuffing
809
        if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
810
            int timestamp_len=0;
811
            if(dts != pts) 
812
                timestamp_len += 5;
813
            if(pts != AV_NOPTS_VALUE)
814
                timestamp_len += s->is_mpeg2 ? 5 : 4;
815
            pts=dts= AV_NOPTS_VALUE;
816
            header_len -= timestamp_len;
817
            if (s->is_dvd && stream->align_iframe) {
818
                pad_packet_bytes += timestamp_len;
819
                packet_size -= timestamp_len;
820
            } else {
821
                payload_size += timestamp_len;
822
            }
823
            stuffing_size += timestamp_len;
824
            if(payload_size > trailer_size)
825
                stuffing_size += payload_size - trailer_size;
826
        }
827

    
828
        if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
829
            packet_size += pad_packet_bytes;
830
            payload_size += pad_packet_bytes; // undo the previous adjustment
831
            if (stuffing_size < 0) {
832
                stuffing_size = pad_packet_bytes;
833
            } else {
834
                stuffing_size += pad_packet_bytes;
835
            }
836
            pad_packet_bytes = 0;
837
        }
838

    
839
        if (stuffing_size < 0)
840
            stuffing_size = 0;
841
        if (stuffing_size > 16) {    /*<=16 for MPEG-1, <=32 for MPEG-2*/
842
            pad_packet_bytes += stuffing_size;
843
            packet_size -= stuffing_size;
844
            payload_size -= stuffing_size;
845
            stuffing_size = 0;
846
        }
847
        
848
        nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
849

    
850
        put_be32(&ctx->pb, startcode);
851

    
852
        put_be16(&ctx->pb, packet_size);
853
        
854
        if (!s->is_mpeg2)
855
            for(i=0;i<stuffing_size;i++)
856
                put_byte(&ctx->pb, 0xff);
857

    
858
        if (s->is_mpeg2) {
859
            put_byte(&ctx->pb, 0x80); /* mpeg2 id */
860

    
861
            pes_flags=0;
862

    
863
            if (pts != AV_NOPTS_VALUE) {
864
                pes_flags |= 0x80;
865
                if (dts != pts)
866
                    pes_flags |= 0x40;
867
            }
868

    
869
            /* Both the MPEG-2 and the SVCD standards demand that the
870
               P-STD_buffer_size field be included in the first packet of
871
               every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
872
               and MPEG-2 standard 2.7.7) */
873
            if (stream->packet_number == 0)
874
                pes_flags |= 0x01;
875

    
876
            put_byte(&ctx->pb, pes_flags); /* flags */
877
            put_byte(&ctx->pb, header_len - 3 + stuffing_size);
878

    
879
            if (pes_flags & 0x80)  /*write pts*/
880
                put_timestamp(&ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
881
            if (pes_flags & 0x40)  /*write dts*/
882
                put_timestamp(&ctx->pb, 0x01, dts);
883
            
884
            if (pes_flags & 0x01) {  /*write pes extension*/
885
                put_byte(&ctx->pb, 0x10); /* flags */
886

    
887
                /* P-STD buffer info */                
888
                if (id == AUDIO_ID)
889
                    put_be16(&ctx->pb, 0x4000 | stream->max_buffer_size/128);
890
                else
891
                    put_be16(&ctx->pb, 0x6000 | stream->max_buffer_size/1024);
892
            }
893

    
894
        } else {
895
            if (pts != AV_NOPTS_VALUE) {
896
                if (dts != pts) {
897
                    put_timestamp(&ctx->pb, 0x03, pts);
898
                    put_timestamp(&ctx->pb, 0x01, dts);
899
                } else {
900
                    put_timestamp(&ctx->pb, 0x02, pts);
901
                }
902
            } else {
903
                put_byte(&ctx->pb, 0x0f);
904
            }
905
        }
906

    
907
        if (s->is_mpeg2) {
908
            /* special stuffing byte that is always written
909
               to prevent accidental generation of start codes. */
910
            put_byte(&ctx->pb, 0xff);
911

    
912
            for(i=0;i<stuffing_size;i++)
913
                put_byte(&ctx->pb, 0xff);
914
        }
915

    
916
        if (startcode == PRIVATE_STREAM_1) {
917
            put_byte(&ctx->pb, id);
918
            if (id >= 0xa0) {
919
                /* LPCM (XXX: check nb_frames) */
920
                put_byte(&ctx->pb, 7);
921
                put_be16(&ctx->pb, 4); /* skip 3 header bytes */
922
                put_byte(&ctx->pb, stream->lpcm_header[0]);
923
                put_byte(&ctx->pb, stream->lpcm_header[1]);
924
                put_byte(&ctx->pb, stream->lpcm_header[2]);
925
            } else {
926
                /* AC3 */
927
                put_byte(&ctx->pb, nb_frames);
928
                put_be16(&ctx->pb, trailer_size+1);
929
            }
930
        }
931

    
932
        /* output data */
933
        if(put_fifo(&ctx->pb, &stream->fifo, payload_size - stuffing_size, &stream->fifo.rptr) < 0)
934
            return -1;
935
    }else{
936
        payload_size=
937
        stuffing_size= 0;
938
    }
939

    
940
    if (pad_packet_bytes > 0)
941
        put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);    
942

    
943
    for(i=0;i<zero_trail_bytes;i++)
944
        put_byte(&ctx->pb, 0x00);
945
        
946
    put_flush_packet(&ctx->pb);
947
    
948
    s->packet_number++;
949

    
950
    /* only increase the stream packet number if this pack actually contains
951
       something that is specific to this stream! I.e. a dedicated header
952
       or some data.*/
953
    if (!general_pack)
954
        stream->packet_number++;
955
    
956
    return payload_size - stuffing_size;
957
}
958

    
959
static void put_vcd_padding_sector(AVFormatContext *ctx)
960
{
961
    /* There are two ways to do this padding: writing a sector/pack
962
       of 0 values, or writing an MPEG padding pack. Both seem to
963
       work with most decoders, BUT the VCD standard only allows a 0-sector
964
       (see standard p. IV-4, IV-5).
965
       So a 0-sector it is...*/
966

    
967
    MpegMuxContext *s = ctx->priv_data;
968
    int i;
969

    
970
    for(i=0;i<s->packet_size;i++)
971
        put_byte(&ctx->pb, 0);
972

    
973
    s->vcd_padding_bytes_written += s->packet_size;
974
        
975
    put_flush_packet(&ctx->pb);
976
    
977
    /* increasing the packet number is correct. The SCR of the following packs
978
       is calculated from the packet_number and it has to include the padding
979
       sector (it represents the sector index, not the MPEG pack index)
980
       (see VCD standard p. IV-6)*/
981
    s->packet_number++;
982
}
983

    
984
#if 0 /* unused, remove? */
985
static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
986
{
987
    MpegMuxContext *s = ctx->priv_data;
988
    int64_t scr;
989

990
        /* Since the data delivery rate is constant, SCR is computed
991
           using the formula C + i * 1200 where C is the start constant
992
           and i is the pack index.
993
           It is recommended that SCR 0 is at the beginning of the VCD front
994
           margin (a sequence of empty Form 2 sectors on the CD).
995
           It is recommended that the front margin is 30 sectors long, so
996
           we use C = 30*1200 = 36000
997
           (Note that even if the front margin is not 30 sectors the file
998
           will still be correct according to the standard. It just won't have
999
           the "recommended" value).*/
1000
        scr = 36000 + s->packet_number * 1200;
1001

1002
    return scr;
1003
}    
1004
#endif
1005

    
1006
static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
1007
//    MpegMuxContext *s = ctx->priv_data;
1008
    int i;
1009

    
1010
    for(i=0; i<ctx->nb_streams; i++){
1011
        AVStream *st = ctx->streams[i];
1012
        StreamInfo *stream = st->priv_data;
1013
        PacketDesc *pkt_desc= stream->predecode_packet;
1014
        
1015
        while(pkt_desc && scr > pkt_desc->dts){ //FIXME > vs >=
1016
            if(stream->buffer_index < pkt_desc->size || 
1017
               stream->predecode_packet == stream->premux_packet){
1018
                av_log(ctx, AV_LOG_ERROR, "buffer underflow\n");
1019
                break;
1020
            }
1021
            stream->buffer_index -= pkt_desc->size;
1022

    
1023
            stream->predecode_packet= pkt_desc->next;
1024
            av_freep(&pkt_desc);
1025
        }
1026
    }
1027
    
1028
    return 0;
1029
}
1030

    
1031
static int output_packet(AVFormatContext *ctx, int flush){
1032
    MpegMuxContext *s = ctx->priv_data;
1033
    AVStream *st;
1034
    StreamInfo *stream;
1035
    int i, avail_space, es_size, trailer_size;
1036
    int best_i= -1;
1037
    int best_score= INT_MIN;
1038
    int ignore_constraints=0;
1039
    int64_t scr= s->last_scr;
1040
    PacketDesc *timestamp_packet;
1041
    const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1042

    
1043
retry:
1044
    for(i=0; i<ctx->nb_streams; i++){
1045
        AVStream *st = ctx->streams[i];
1046
        StreamInfo *stream = st->priv_data;
1047
        const int avail_data=  fifo_size(&stream->fifo, stream->fifo.rptr);
1048
        const int space= stream->max_buffer_size - stream->buffer_index;
1049
        int rel_space= 1024*space / stream->max_buffer_size;
1050
        PacketDesc *next_pkt= stream->premux_packet;
1051

    
1052
        if(s->packet_size > avail_data && !flush)
1053
            return 0;
1054
        if(avail_data==0)
1055
            continue;
1056
        assert(avail_data>0);
1057

    
1058
        if(space < s->packet_size && !ignore_constraints)
1059
            continue;
1060
            
1061
        if(next_pkt && next_pkt->dts - scr > max_delay)
1062
            continue;
1063
            
1064
        if(rel_space > best_score){
1065
            best_score= rel_space;
1066
            best_i = i;
1067
            avail_space= space;
1068
        }
1069
    }
1070
    
1071
    if(best_i < 0){
1072
        int64_t best_dts= INT64_MAX;
1073

    
1074
        for(i=0; i<ctx->nb_streams; i++){
1075
            AVStream *st = ctx->streams[i];
1076
            StreamInfo *stream = st->priv_data;
1077
            PacketDesc *pkt_desc= stream->predecode_packet;
1078
            if(pkt_desc && pkt_desc->dts < best_dts)
1079
                best_dts= pkt_desc->dts;
1080
        }
1081

    
1082
#if 0
1083
        av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n", 
1084
               scr/90000.0, best_dts/90000.0);
1085
#endif
1086
        if(best_dts == INT64_MAX)
1087
            return 0;
1088

    
1089
        if(scr >= best_dts+1 && !ignore_constraints){
1090
            av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1091
            ignore_constraints= 1;
1092
        }
1093
        scr= FFMAX(best_dts+1, scr);
1094
        if(remove_decoded_packets(ctx, scr) < 0)
1095
            return -1;
1096
        goto retry;
1097
    }
1098

    
1099
    assert(best_i >= 0);
1100
    
1101
    st = ctx->streams[best_i];
1102
    stream = st->priv_data;
1103
    
1104
    assert(fifo_size(&stream->fifo, stream->fifo.rptr) > 0);
1105

    
1106
    assert(avail_space >= s->packet_size || ignore_constraints);
1107
    
1108
    timestamp_packet= stream->premux_packet;
1109
    if(timestamp_packet->unwritten_size == timestamp_packet->size){
1110
        trailer_size= 0;
1111
    }else{
1112
        trailer_size= timestamp_packet->unwritten_size;
1113
        timestamp_packet= timestamp_packet->next;
1114
    }
1115

    
1116
    if(timestamp_packet){
1117
//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);
1118
        es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1119
    }else{
1120
        assert(fifo_size(&stream->fifo, stream->fifo.rptr) == trailer_size);
1121
        es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1122
    }
1123

    
1124
    if (s->is_vcd) {
1125
        /* Write one or more padding sectors, if necessary, to reach
1126
           the constant overall bitrate.*/
1127
        int vcd_pad_bytes;
1128

    
1129
        while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1130
            put_vcd_padding_sector(ctx);
1131
            s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1132
        }
1133
    }
1134
    
1135
    stream->buffer_index += es_size;
1136
    s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1137
    
1138
    while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1139
        es_size -= stream->premux_packet->unwritten_size;
1140
        stream->premux_packet= stream->premux_packet->next;
1141
    }
1142
    if(es_size)
1143
        stream->premux_packet->unwritten_size -= es_size;
1144
    
1145
    if(remove_decoded_packets(ctx, s->last_scr) < 0)
1146
        return -1;
1147

    
1148
    return 1;
1149
}
1150

    
1151
static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1152
{
1153
    MpegMuxContext *s = ctx->priv_data;
1154
    int stream_index= pkt->stream_index;
1155
    int size= pkt->size;
1156
    uint8_t *buf= pkt->data;
1157
    AVStream *st = ctx->streams[stream_index];
1158
    StreamInfo *stream = st->priv_data;
1159
    int64_t pts, dts;
1160
    PacketDesc *pkt_desc;
1161
    const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
1162
    const int is_iframe = st->codec.codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
1163
    
1164
    pts= pkt->pts;
1165
    dts= pkt->dts;
1166

    
1167
    if(pts != AV_NOPTS_VALUE) pts += preload;
1168
    if(dts != AV_NOPTS_VALUE) dts += preload;
1169

    
1170
//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);
1171
    *stream->next_packet=
1172
    pkt_desc= av_mallocz(sizeof(PacketDesc));
1173
    pkt_desc->pts= pts;
1174
    pkt_desc->dts= dts;
1175
    pkt_desc->unwritten_size=
1176
    pkt_desc->size= size;
1177
    if(!stream->predecode_packet)
1178
        stream->predecode_packet= pkt_desc;
1179
    stream->next_packet= &pkt_desc->next;
1180

    
1181
    fifo_realloc(&stream->fifo, fifo_size(&stream->fifo, NULL) + size + 1);
1182

    
1183
    if (s->is_dvd){
1184
        if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1185
            stream->fifo_iframe_ptr = stream->fifo.wptr;
1186
            stream->align_iframe = 1;
1187
            stream->vobu_start_pts = pts;
1188
        } else {
1189
            stream->align_iframe = 0;
1190
        }
1191
    }
1192

    
1193
    fifo_write(&stream->fifo, buf, size, &stream->fifo.wptr);
1194

    
1195
    for(;;){
1196
        int ret= output_packet(ctx, 0);
1197
        if(ret<=0) 
1198
            return ret;
1199
    }
1200
}
1201

    
1202
static int mpeg_mux_end(AVFormatContext *ctx)
1203
{
1204
//    MpegMuxContext *s = ctx->priv_data;
1205
    StreamInfo *stream;
1206
    int i;
1207
    
1208
    for(;;){
1209
        int ret= output_packet(ctx, 1);
1210
        if(ret<0) 
1211
            return ret;
1212
        else if(ret==0)
1213
            break;
1214
    }
1215

    
1216
    /* End header according to MPEG1 systems standard. We do not write
1217
       it as it is usually not needed by decoders and because it
1218
       complicates MPEG stream concatenation. */
1219
    //put_be32(&ctx->pb, ISO_11172_END_CODE);
1220
    //put_flush_packet(&ctx->pb);
1221

    
1222
    for(i=0;i<ctx->nb_streams;i++) {
1223
        stream = ctx->streams[i]->priv_data;
1224

    
1225
        assert(fifo_size(&stream->fifo, stream->fifo.rptr) == 0);
1226
        fifo_free(&stream->fifo);
1227
    }
1228
    return 0;
1229
}
1230
#endif //CONFIG_ENCODERS
1231

    
1232
/*********************************************/
1233
/* demux code */
1234

    
1235
#define MAX_SYNC_SIZE 100000
1236

    
1237
static int mpegps_probe(AVProbeData *p)
1238
{
1239
    int i;
1240
    int size= FFMIN(20, p->buf_size);
1241
    uint32_t code=0xFF;
1242

    
1243
    /* we search the first start code. If it is a packet start code,
1244
       then we decide it is mpeg ps. We do not send highest value to
1245
       give a chance to mpegts */
1246
    /* NOTE: the search range was restricted to avoid too many false
1247
       detections */
1248

    
1249
    for (i = 0; i < size; i++) {
1250
        code = (code << 8) | p->buf[i];
1251
        if ((code & 0xffffff00) == 0x100) {
1252
            if (code == PACK_START_CODE ||
1253
                code == SYSTEM_HEADER_START_CODE ||
1254
                (code >= 0x1e0 && code <= 0x1ef) ||
1255
                (code >= 0x1c0 && code <= 0x1df) ||
1256
                code == PRIVATE_STREAM_2 ||
1257
                code == PROGRAM_STREAM_MAP ||
1258
                code == PRIVATE_STREAM_1 ||
1259
                code == PADDING_STREAM)
1260
                return AVPROBE_SCORE_MAX - 2;
1261
            else
1262
                return 0;
1263
        }
1264
    }
1265
    return 0;
1266
}
1267

    
1268

    
1269
typedef struct MpegDemuxContext {
1270
    int header_state;
1271
} MpegDemuxContext;
1272

    
1273
static int mpegps_read_header(AVFormatContext *s,
1274
                              AVFormatParameters *ap)
1275
{
1276
    MpegDemuxContext *m = s->priv_data;
1277
    m->header_state = 0xff;
1278
    s->ctx_flags |= AVFMTCTX_NOHEADER;
1279

    
1280
    /* no need to do more */
1281
    return 0;
1282
}
1283

    
1284
static int64_t get_pts(ByteIOContext *pb, int c)
1285
{
1286
    int64_t pts;
1287
    int val;
1288

    
1289
    if (c < 0)
1290
        c = get_byte(pb);
1291
    pts = (int64_t)((c >> 1) & 0x07) << 30;
1292
    val = get_be16(pb);
1293
    pts |= (int64_t)(val >> 1) << 15;
1294
    val = get_be16(pb);
1295
    pts |= (int64_t)(val >> 1);
1296
    return pts;
1297
}
1298

    
1299
static int find_next_start_code(ByteIOContext *pb, int *size_ptr, 
1300
                                uint32_t *header_state)
1301
{
1302
    unsigned int state, v;
1303
    int val, n;
1304

    
1305
    state = *header_state;
1306
    n = *size_ptr;
1307
    while (n > 0) {
1308
        if (url_feof(pb))
1309
            break;
1310
        v = get_byte(pb);
1311
        n--;
1312
        if (state == 0x000001) {
1313
            state = ((state << 8) | v) & 0xffffff;
1314
            val = state;
1315
            goto found;
1316
        }
1317
        state = ((state << 8) | v) & 0xffffff;
1318
    }
1319
    val = -1;
1320
 found:
1321
    *header_state = state;
1322
    *size_ptr = n;
1323
    return val;
1324
}
1325

    
1326
#if 0 /* unused, remove? */
1327
/* XXX: optimize */
1328
static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
1329
{
1330
    int64_t pos, pos_start;
1331
    int max_size, start_code;
1332

1333
    max_size = *size_ptr;
1334
    pos_start = url_ftell(pb);
1335

1336
    /* in order to go faster, we fill the buffer */
1337
    pos = pos_start - 16386;
1338
    if (pos < 0)
1339
        pos = 0;
1340
    url_fseek(pb, pos, SEEK_SET);
1341
    get_byte(pb);
1342

1343
    pos = pos_start;
1344
    for(;;) {
1345
        pos--;
1346
        if (pos < 0 || (pos_start - pos) >= max_size) {
1347
            start_code = -1;
1348
            goto the_end;
1349
        }
1350
        url_fseek(pb, pos, SEEK_SET);
1351
        start_code = get_be32(pb);
1352
        if ((start_code & 0xffffff00) == 0x100)
1353
            break;
1354
    }
1355
 the_end:
1356
    *size_ptr = pos_start - pos;
1357
    return start_code;
1358
}
1359
#endif
1360

    
1361
/* read the next PES header. Return its position in ppos 
1362
   (if not NULL), and its start code, pts and dts.
1363
 */
1364
static int mpegps_read_pes_header(AVFormatContext *s,
1365
                                  int64_t *ppos, int *pstart_code, 
1366
                                  int64_t *ppts, int64_t *pdts)
1367
{
1368
    MpegDemuxContext *m = s->priv_data;
1369
    int len, size, startcode, c, flags, header_len;
1370
    int64_t pts, dts, last_pos;
1371

    
1372
    last_pos = -1;
1373
 redo:
1374
        /* next start code (should be immediately after) */
1375
        m->header_state = 0xff;
1376
        size = MAX_SYNC_SIZE;
1377
        startcode = find_next_start_code(&s->pb, &size, &m->header_state);
1378
    //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
1379
    if (startcode < 0)
1380
        return AVERROR_IO;
1381
    if (startcode == PACK_START_CODE)
1382
        goto redo;
1383
    if (startcode == SYSTEM_HEADER_START_CODE)
1384
        goto redo;
1385
    if (startcode == PADDING_STREAM ||
1386
        startcode == PRIVATE_STREAM_2) {
1387
        /* skip them */
1388
        len = get_be16(&s->pb);
1389
        url_fskip(&s->pb, len);
1390
        goto redo;
1391
    }
1392
    /* find matching stream */
1393
    if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
1394
          (startcode >= 0x1e0 && startcode <= 0x1ef) ||
1395
          (startcode == 0x1bd)))
1396
        goto redo;
1397
    if (ppos) {
1398
        *ppos = url_ftell(&s->pb) - 4;
1399
    }
1400
    len = get_be16(&s->pb);
1401
    pts = AV_NOPTS_VALUE;
1402
    dts = AV_NOPTS_VALUE;
1403
    /* stuffing */
1404
    for(;;) {
1405
        if (len < 1)
1406
            goto redo;
1407
        c = get_byte(&s->pb);
1408
        len--;
1409
        /* XXX: for mpeg1, should test only bit 7 */
1410
        if (c != 0xff) 
1411
            break;
1412
    }
1413
    if ((c & 0xc0) == 0x40) {
1414
        /* buffer scale & size */
1415
        if (len < 2)
1416
            goto redo;
1417
        get_byte(&s->pb);
1418
        c = get_byte(&s->pb);
1419
        len -= 2;
1420
    }
1421
    if ((c & 0xf0) == 0x20) {
1422
        if (len < 4)
1423
            goto redo;
1424
        dts = pts = get_pts(&s->pb, c);
1425
        len -= 4;
1426
    } else if ((c & 0xf0) == 0x30) {
1427
        if (len < 9)
1428
            goto redo;
1429
        pts = get_pts(&s->pb, c);
1430
        dts = get_pts(&s->pb, -1);
1431
        len -= 9;
1432
    } else if ((c & 0xc0) == 0x80) {
1433
        /* mpeg 2 PES */
1434
        if ((c & 0x30) != 0) {
1435
            /* Encrypted multiplex not handled */
1436
            goto redo;
1437
        }
1438
        flags = get_byte(&s->pb);
1439
        header_len = get_byte(&s->pb);
1440
        len -= 2;
1441
        if (header_len > len)
1442
            goto redo;
1443
        if ((flags & 0xc0) == 0x80) {
1444
            dts = pts = get_pts(&s->pb, -1);
1445
            if (header_len < 5)
1446
                goto redo;
1447
            header_len -= 5;
1448
            len -= 5;
1449
        } if ((flags & 0xc0) == 0xc0) {
1450
            pts = get_pts(&s->pb, -1);
1451
            dts = get_pts(&s->pb, -1);
1452
            if (header_len < 10)
1453
                goto redo;
1454
            header_len -= 10;
1455
            len -= 10;
1456
        }
1457
        len -= header_len;
1458
        while (header_len > 0) {
1459
            get_byte(&s->pb);
1460
            header_len--;
1461
        }
1462
    }
1463
    else if( c!= 0xf )
1464
        goto redo;
1465

    
1466
    if (startcode == 0x1bd) {
1467
        if (len < 1)
1468
            goto redo;
1469
        startcode = get_byte(&s->pb);
1470
        len--;
1471
        if (startcode >= 0x80 && startcode <= 0xbf) {
1472
            /* audio: skip header */
1473
            if (len < 3)
1474
                goto redo;
1475
            get_byte(&s->pb);
1476
            get_byte(&s->pb);
1477
            get_byte(&s->pb);
1478
            len -= 3;
1479
        }
1480
    }
1481
    if(dts != AV_NOPTS_VALUE && ppos){
1482
        int i;
1483
        for(i=0; i<s->nb_streams; i++){
1484
            if(startcode == s->streams[i]->id) {
1485
                av_add_index_entry(s->streams[i], *ppos, dts, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
1486
            }
1487
        }
1488
    }
1489
    
1490
    *pstart_code = startcode;
1491
    *ppts = pts;
1492
    *pdts = dts;
1493
    return len;
1494
}
1495

    
1496
static int mpegps_read_packet(AVFormatContext *s,
1497
                              AVPacket *pkt)
1498
{
1499
    AVStream *st;
1500
    int len, startcode, i, type, codec_id = 0;
1501
    int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
1502

    
1503
 redo:
1504
    len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
1505
    if (len < 0)
1506
        return len;
1507
    
1508
    /* now find stream */
1509
    for(i=0;i<s->nb_streams;i++) {
1510
        st = s->streams[i];
1511
        if (st->id == startcode)
1512
            goto found;
1513
    }
1514
    if (startcode >= 0x1e0 && startcode <= 0x1ef) {
1515
        type = CODEC_TYPE_VIDEO;
1516
        codec_id = CODEC_ID_MPEG2VIDEO;
1517
    } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
1518
        type = CODEC_TYPE_AUDIO;
1519
        codec_id = CODEC_ID_MP2;
1520
    } else if (startcode >= 0x80 && startcode <= 0x89) {
1521
        type = CODEC_TYPE_AUDIO;
1522
        codec_id = CODEC_ID_AC3;
1523
    } else if (startcode >= 0x8a && startcode <= 0x9f) {
1524
        type = CODEC_TYPE_AUDIO;
1525
        codec_id = CODEC_ID_DTS;
1526
    } else if (startcode >= 0xa0 && startcode <= 0xbf) {
1527
        type = CODEC_TYPE_AUDIO;
1528
        codec_id = CODEC_ID_PCM_S16BE;
1529
    } else {
1530
    skip:
1531
        /* skip packet */
1532
        url_fskip(&s->pb, len);
1533
        goto redo;
1534
    }
1535
    /* no stream found: add a new stream */
1536
    st = av_new_stream(s, startcode);
1537
    if (!st) 
1538
        goto skip;
1539
    st->codec.codec_type = type;
1540
    st->codec.codec_id = codec_id;
1541
    if (codec_id != CODEC_ID_PCM_S16BE)
1542
        st->need_parsing = 1;
1543
 found:
1544
    if(st->discard >= AVDISCARD_ALL)
1545
        goto skip;
1546
    if (startcode >= 0xa0 && startcode <= 0xbf) {
1547
        int b1, freq;
1548

    
1549
        /* for LPCM, we just skip the header and consider it is raw
1550
           audio data */
1551
        if (len <= 3)
1552
            goto skip;
1553
        get_byte(&s->pb); /* emphasis (1), muse(1), reserved(1), frame number(5) */
1554
        b1 = get_byte(&s->pb); /* quant (2), freq(2), reserved(1), channels(3) */
1555
        get_byte(&s->pb); /* dynamic range control (0x80 = off) */
1556
        len -= 3;
1557
        freq = (b1 >> 4) & 3;
1558
        st->codec.sample_rate = lpcm_freq_tab[freq];
1559
        st->codec.channels = 1 + (b1 & 7);
1560
        st->codec.bit_rate = st->codec.channels * st->codec.sample_rate * 2;
1561
    }
1562
    av_new_packet(pkt, len);
1563
    get_buffer(&s->pb, pkt->data, pkt->size);
1564
    pkt->pts = pts;
1565
    pkt->dts = dts;
1566
    pkt->stream_index = st->index;
1567
#if 0
1568
    av_log(s, AV_LOG_DEBUG, "%d: pts=%0.3f dts=%0.3f size=%d\n",
1569
           pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0, pkt->size);
1570
#endif
1571

    
1572
    return 0;
1573
}
1574

    
1575
static int mpegps_read_close(AVFormatContext *s)
1576
{
1577
    return 0;
1578
}
1579

    
1580
static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index, 
1581
                               int64_t *ppos, int64_t pos_limit)
1582
{
1583
    int len, startcode;
1584
    int64_t pos, pts, dts;
1585

    
1586
    pos = *ppos;
1587
#ifdef DEBUG_SEEK
1588
    printf("read_dts: pos=0x%llx next=%d -> ", pos, find_next);
1589
#endif
1590
    url_fseek(&s->pb, pos, SEEK_SET);
1591
    for(;;) {
1592
        len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
1593
        if (len < 0) {
1594
#ifdef DEBUG_SEEK
1595
            printf("none (ret=%d)\n", len);
1596
#endif
1597
            return AV_NOPTS_VALUE;
1598
        }
1599
        if (startcode == s->streams[stream_index]->id && 
1600
            dts != AV_NOPTS_VALUE) {
1601
            break;
1602
        }
1603
        url_fskip(&s->pb, len);
1604
    }
1605
#ifdef DEBUG_SEEK
1606
    printf("pos=0x%llx dts=0x%llx %0.3f\n", pos, dts, dts / 90000.0);
1607
#endif
1608
    *ppos = pos;
1609
    return dts;
1610
}
1611

    
1612
#ifdef CONFIG_ENCODERS
1613
static AVOutputFormat mpeg1system_mux = {
1614
    "mpeg",
1615
    "MPEG1 System format",
1616
    "video/mpeg",
1617
    "mpg,mpeg",
1618
    sizeof(MpegMuxContext),
1619
    CODEC_ID_MP2,
1620
    CODEC_ID_MPEG1VIDEO,
1621
    mpeg_mux_init,
1622
    mpeg_mux_write_packet,
1623
    mpeg_mux_end,
1624
};
1625

    
1626
static AVOutputFormat mpeg1vcd_mux = {
1627
    "vcd",
1628
    "MPEG1 System format (VCD)",
1629
    "video/mpeg",
1630
    NULL,
1631
    sizeof(MpegMuxContext),
1632
    CODEC_ID_MP2,
1633
    CODEC_ID_MPEG1VIDEO,
1634
    mpeg_mux_init,
1635
    mpeg_mux_write_packet,
1636
    mpeg_mux_end,
1637
};
1638

    
1639
static AVOutputFormat mpeg2vob_mux = {
1640
    "vob",
1641
    "MPEG2 PS format (VOB)",
1642
    "video/mpeg",
1643
    "vob",
1644
    sizeof(MpegMuxContext),
1645
    CODEC_ID_MP2,
1646
    CODEC_ID_MPEG2VIDEO,
1647
    mpeg_mux_init,
1648
    mpeg_mux_write_packet,
1649
    mpeg_mux_end,
1650
};
1651

    
1652
/* Same as mpeg2vob_mux except that the pack size is 2324 */
1653
static AVOutputFormat mpeg2svcd_mux = {
1654
    "svcd",
1655
    "MPEG2 PS format (VOB)",
1656
    "video/mpeg",
1657
    "vob",
1658
    sizeof(MpegMuxContext),
1659
    CODEC_ID_MP2,
1660
    CODEC_ID_MPEG2VIDEO,
1661
    mpeg_mux_init,
1662
    mpeg_mux_write_packet,
1663
    mpeg_mux_end,
1664
};
1665

    
1666
/*  Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1667
static AVOutputFormat mpeg2dvd_mux = {
1668
    "dvd",
1669
    "MPEG2 PS format (DVD VOB)",
1670
    "video/mpeg",
1671
    "dvd",
1672
    sizeof(MpegMuxContext),
1673
    CODEC_ID_MP2,
1674
    CODEC_ID_MPEG2VIDEO,
1675
    mpeg_mux_init,
1676
    mpeg_mux_write_packet,
1677
    mpeg_mux_end,
1678
};
1679

    
1680
#endif //CONFIG_ENCODERS
1681

    
1682
AVInputFormat mpegps_demux = {
1683
    "mpeg",
1684
    "MPEG PS format",
1685
    sizeof(MpegDemuxContext),
1686
    mpegps_probe,
1687
    mpegps_read_header,
1688
    mpegps_read_packet,
1689
    mpegps_read_close,
1690
    NULL, //mpegps_read_seek,
1691
    mpegps_read_dts,
1692
};
1693

    
1694
int mpegps_init(void)
1695
{
1696
#ifdef CONFIG_ENCODERS
1697
    av_register_output_format(&mpeg1system_mux);
1698
    av_register_output_format(&mpeg1vcd_mux);
1699
    av_register_output_format(&mpeg2vob_mux);
1700
    av_register_output_format(&mpeg2svcd_mux);
1701
    av_register_output_format(&mpeg2dvd_mux);
1702
#endif //CONFIG_ENCODERS
1703
    av_register_input_format(&mpegps_demux);
1704
    return 0;
1705
}