Statistics
| Branch: | Revision:

ffmpeg / libavformat / mpeg.c @ 7be806f3

History | View | Annotate | Download (52.7 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
/* return the exact available payload size for the next packet for
534
   stream 'stream_index'. 'pts' and 'dts' are only used to know if
535
   timestamps are needed in the packet header. */
536
static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
537
                                   int64_t pts, int64_t dts)
538
{
539
    MpegMuxContext *s = ctx->priv_data;
540
    int buf_index;
541
    StreamInfo *stream;
542

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

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

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

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

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

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

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

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

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

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

    
646
    return nb_frames;
647
}
648

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

    
672
    buf_ptr = buffer;
673

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

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

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

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

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

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

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

    
748
    packet_size = s->packet_size - size;
749

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

    
768
    packet_size -= pad_packet_bytes + zero_trail_bytes;
769

    
770
    if (packet_size > 0) {
771

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

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

    
804
        stuffing_size = payload_size - fifo_size(&stream->fifo, stream->fifo.rptr);
805

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

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

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

    
848
        put_be32(&ctx->pb, startcode);
849

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

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

    
859
            pes_flags=0;
860

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

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

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

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

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

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

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

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

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

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

    
938
    if (pad_packet_bytes > 0)
939
        put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);    
940

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

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

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

    
965
    MpegMuxContext *s = ctx->priv_data;
966
    int i;
967

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

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

    
982
static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
983
{
984
    MpegMuxContext *s = ctx->priv_data;
985
    int64_t scr;
986

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

    
999
    return scr;
1000
}    
1001

    
1002
static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
1003
//    MpegMuxContext *s = ctx->priv_data;
1004
    int i;
1005

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

    
1019
            stream->predecode_packet= pkt_desc->next;
1020
            av_freep(&pkt_desc);
1021
        }
1022
    }
1023
    
1024
    return 0;
1025
}
1026

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

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

    
1048
        if(s->packet_size > avail_data && !flush)
1049
            return 0;
1050
        if(avail_data==0)
1051
            continue;
1052
        assert(avail_data>0);
1053

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

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

    
1078
#if 0
1079
        av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n", 
1080
               scr/90000.0, best_dts/90000.0);
1081
#endif
1082
        if(best_dts == INT64_MAX)
1083
            return 0;
1084

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

    
1095
    assert(best_i >= 0);
1096
    
1097
    st = ctx->streams[best_i];
1098
    stream = st->priv_data;
1099
    
1100
    assert(fifo_size(&stream->fifo, stream->fifo.rptr) > 0);
1101

    
1102
    assert(avail_space >= s->packet_size || ignore_constraints);
1103
    
1104
    timestamp_packet= stream->premux_packet;
1105
    if(timestamp_packet->unwritten_size == timestamp_packet->size){
1106
        trailer_size= 0;
1107
    }else{
1108
        trailer_size= timestamp_packet->unwritten_size;
1109
        timestamp_packet= timestamp_packet->next;
1110
    }
1111

    
1112
    if(timestamp_packet){
1113
//av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f scr:%f stream:%d\n", timestamp_packet->dts/90000.0, timestamp_packet->pts/90000.0, scr/90000.0, best_i);
1114
        es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1115
    }else{
1116
        assert(fifo_size(&stream->fifo, stream->fifo.rptr) == trailer_size);
1117
        es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1118
    }
1119

    
1120
    if (s->is_vcd) {
1121
        /* Write one or more padding sectors, if necessary, to reach
1122
           the constant overall bitrate.*/
1123
        int vcd_pad_bytes;
1124

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

    
1144
    return 1;
1145
}
1146

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

    
1163
    if(pts != AV_NOPTS_VALUE) pts += preload;
1164
    if(dts != AV_NOPTS_VALUE) dts += preload;
1165

    
1166
//av_log(ctx, AV_LOG_DEBUG, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n", dts/90000.0, pts/90000.0, pkt->flags, pkt->stream_index, pts != AV_NOPTS_VALUE);
1167
    *stream->next_packet=
1168
    pkt_desc= av_mallocz(sizeof(PacketDesc));
1169
    pkt_desc->pts= pts;
1170
    pkt_desc->dts= dts;
1171
    pkt_desc->unwritten_size=
1172
    pkt_desc->size= size;
1173
    if(!stream->predecode_packet)
1174
        stream->predecode_packet= pkt_desc;
1175
    stream->next_packet= &pkt_desc->next;
1176

    
1177
    fifo_realloc(&stream->fifo, fifo_size(&stream->fifo, NULL) + size + 1);
1178

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

    
1189
    fifo_write(&stream->fifo, buf, size, &stream->fifo.wptr);
1190

    
1191
    for(;;){
1192
        int ret= output_packet(ctx, 0);
1193
        if(ret<=0) 
1194
            return ret;
1195
    }
1196
}
1197

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

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

    
1218
    for(i=0;i<ctx->nb_streams;i++) {
1219
        stream = ctx->streams[i]->priv_data;
1220

    
1221
        assert(fifo_size(&stream->fifo, stream->fifo.rptr) == 0);
1222
        fifo_free(&stream->fifo);
1223
    }
1224
    return 0;
1225
}
1226
#endif //CONFIG_ENCODERS
1227

    
1228
/*********************************************/
1229
/* demux code */
1230

    
1231
#define MAX_SYNC_SIZE 100000
1232

    
1233
static int mpegps_probe(AVProbeData *p)
1234
{
1235
    int i;
1236
    int size= FFMIN(20, p->buf_size);
1237
    uint32_t code=0xFF;
1238

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

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

    
1264

    
1265
typedef struct MpegDemuxContext {
1266
    int header_state;
1267
} MpegDemuxContext;
1268

    
1269
static int mpegps_read_header(AVFormatContext *s,
1270
                              AVFormatParameters *ap)
1271
{
1272
    MpegDemuxContext *m = s->priv_data;
1273
    m->header_state = 0xff;
1274
    s->ctx_flags |= AVFMTCTX_NOHEADER;
1275

    
1276
    /* no need to do more */
1277
    return 0;
1278
}
1279

    
1280
static int64_t get_pts(ByteIOContext *pb, int c)
1281
{
1282
    int64_t pts;
1283
    int val;
1284

    
1285
    if (c < 0)
1286
        c = get_byte(pb);
1287
    pts = (int64_t)((c >> 1) & 0x07) << 30;
1288
    val = get_be16(pb);
1289
    pts |= (int64_t)(val >> 1) << 15;
1290
    val = get_be16(pb);
1291
    pts |= (int64_t)(val >> 1);
1292
    return pts;
1293
}
1294

    
1295
static int find_next_start_code(ByteIOContext *pb, int *size_ptr, 
1296
                                uint32_t *header_state)
1297
{
1298
    unsigned int state, v;
1299
    int val, n;
1300

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

    
1322
/* XXX: optimize */
1323
static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
1324
{
1325
    int64_t pos, pos_start;
1326
    int max_size, start_code;
1327

    
1328
    max_size = *size_ptr;
1329
    pos_start = url_ftell(pb);
1330

    
1331
    /* in order to go faster, we fill the buffer */
1332
    pos = pos_start - 16386;
1333
    if (pos < 0)
1334
        pos = 0;
1335
    url_fseek(pb, pos, SEEK_SET);
1336
    get_byte(pb);
1337

    
1338
    pos = pos_start;
1339
    for(;;) {
1340
        pos--;
1341
        if (pos < 0 || (pos_start - pos) >= max_size) {
1342
            start_code = -1;
1343
            goto the_end;
1344
        }
1345
        url_fseek(pb, pos, SEEK_SET);
1346
        start_code = get_be32(pb);
1347
        if ((start_code & 0xffffff00) == 0x100)
1348
            break;
1349
    }
1350
 the_end:
1351
    *size_ptr = pos_start - pos;
1352
    return start_code;
1353
}
1354

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

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

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

    
1490
static int mpegps_read_packet(AVFormatContext *s,
1491
                              AVPacket *pkt)
1492
{
1493
    AVStream *st;
1494
    int len, startcode, i, type, codec_id = 0;
1495
    int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
1496

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

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

    
1566
    return 0;
1567
}
1568

    
1569
static int mpegps_read_close(AVFormatContext *s)
1570
{
1571
    return 0;
1572
}
1573

    
1574
static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index, 
1575
                               int64_t *ppos, int64_t pos_limit)
1576
{
1577
    int len, startcode;
1578
    int64_t pos, pts, dts;
1579

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

    
1606
#ifdef CONFIG_ENCODERS
1607
static AVOutputFormat mpeg1system_mux = {
1608
    "mpeg",
1609
    "MPEG1 System format",
1610
    "video/mpeg",
1611
    "mpg,mpeg",
1612
    sizeof(MpegMuxContext),
1613
    CODEC_ID_MP2,
1614
    CODEC_ID_MPEG1VIDEO,
1615
    mpeg_mux_init,
1616
    mpeg_mux_write_packet,
1617
    mpeg_mux_end,
1618
};
1619

    
1620
static AVOutputFormat mpeg1vcd_mux = {
1621
    "vcd",
1622
    "MPEG1 System format (VCD)",
1623
    "video/mpeg",
1624
    NULL,
1625
    sizeof(MpegMuxContext),
1626
    CODEC_ID_MP2,
1627
    CODEC_ID_MPEG1VIDEO,
1628
    mpeg_mux_init,
1629
    mpeg_mux_write_packet,
1630
    mpeg_mux_end,
1631
};
1632

    
1633
static AVOutputFormat mpeg2vob_mux = {
1634
    "vob",
1635
    "MPEG2 PS format (VOB)",
1636
    "video/mpeg",
1637
    "vob",
1638
    sizeof(MpegMuxContext),
1639
    CODEC_ID_MP2,
1640
    CODEC_ID_MPEG2VIDEO,
1641
    mpeg_mux_init,
1642
    mpeg_mux_write_packet,
1643
    mpeg_mux_end,
1644
};
1645

    
1646
/* Same as mpeg2vob_mux except that the pack size is 2324 */
1647
static AVOutputFormat mpeg2svcd_mux = {
1648
    "svcd",
1649
    "MPEG2 PS format (VOB)",
1650
    "video/mpeg",
1651
    "vob",
1652
    sizeof(MpegMuxContext),
1653
    CODEC_ID_MP2,
1654
    CODEC_ID_MPEG2VIDEO,
1655
    mpeg_mux_init,
1656
    mpeg_mux_write_packet,
1657
    mpeg_mux_end,
1658
};
1659

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

    
1674
#endif //CONFIG_ENCODERS
1675

    
1676
AVInputFormat mpegps_demux = {
1677
    "mpeg",
1678
    "MPEG PS format",
1679
    sizeof(MpegDemuxContext),
1680
    mpegps_probe,
1681
    mpegps_read_header,
1682
    mpegps_read_packet,
1683
    mpegps_read_close,
1684
    NULL, //mpegps_read_seek,
1685
    mpegps_read_dts,
1686
};
1687

    
1688
int mpegps_init(void)
1689
{
1690
#ifdef CONFIG_ENCODERS
1691
    av_register_output_format(&mpeg1system_mux);
1692
    av_register_output_format(&mpeg1vcd_mux);
1693
    av_register_output_format(&mpeg2vob_mux);
1694
    av_register_output_format(&mpeg2svcd_mux);
1695
    av_register_output_format(&mpeg2dvd_mux);
1696
#endif //CONFIG_ENCODERS
1697
    av_register_input_format(&mpegps_demux);
1698
    return 0;
1699
}