keyframe & non keyframe index fixes
[libav.git] / libavformat / mpeg.c
CommitLineData
de6d9b64 1/*
fb7566d0 2 * MPEG1/2 mux/demux
19720f15 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
de6d9b64 4 *
19720f15
FB
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.
de6d9b64 9 *
19720f15 10 * This library is distributed in the hope that it will be useful,
de6d9b64 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
de6d9b64 14 *
19720f15
FB
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
de6d9b64 18 */
de6d9b64 19#include "avformat.h"
2de7795a 20#include "bitstream.h"
de6d9b64
FB
21
22#define MAX_PAYLOAD_SIZE 4096
27f388aa 23//#define DEBUG_SEEK
de6d9b64 24
b754978a
MN
25#undef NDEBUG
26#include <assert.h>
27
7000a175
MN
28typedef 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
de6d9b64 37typedef struct {
7000a175 38 FifoBuffer fifo;
0c1a9eda 39 uint8_t id;
de6d9b64 40 int max_buffer_size; /* in bytes */
7000a175
MN
41 int buffer_index;
42 PacketDesc *predecode_packet;
43 PacketDesc *premux_packet;
44 PacketDesc **next_packet;
de6d9b64 45 int packet_number;
044007c2
FB
46 uint8_t lpcm_header[3];
47 int lpcm_align;
cbb6e405
MN
48 uint8_t *fifo_iframe_ptr;
49 int align_iframe;
7be806f3 50 int64_t vobu_start_pts;
de6d9b64
FB
51} StreamInfo;
52
53typedef struct {
54 int packet_size; /* required packet size */
de6d9b64
FB
55 int packet_number;
56 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
57 int system_header_freq;
0dbb48d9 58 int system_header_size;
de6d9b64
FB
59 int mux_rate; /* bitrate in units of 50 bytes/s */
60 /* stream info */
61 int audio_bound;
62 int video_bound;
fb7566d0
FB
63 int is_mpeg2;
64 int is_vcd;
24515926 65 int is_svcd;
78a0efb4 66 int is_dvd;
27a206e0 67 int64_t last_scr; /* current system clock */
24515926 68
d8b5abfa 69 double vcd_padding_bitrate; //FIXME floats
24515926
HD
70 int64_t vcd_padding_bytes_written;
71
de6d9b64
FB
72} MpegMuxContext;
73
74#define PACK_START_CODE ((unsigned int)0x000001ba)
75#define SYSTEM_HEADER_START_CODE ((unsigned int)0x000001bb)
92b3e125 76#define SEQUENCE_END_CODE ((unsigned int)0x000001b7)
de6d9b64
FB
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
044007c2 90#define AC3_ID 0x80
23c99253 91#define DTS_ID 0x8a
044007c2 92#define LPCM_ID 0xa0
de6d9b64 93
8a05bca4
MN
94static const int lpcm_freq_tab[4] = { 48000, 96000, 44100, 32000 };
95
764ef400 96#ifdef CONFIG_ENCODERS
7906085f
FH
97static AVOutputFormat mpeg1system_mux;
98static AVOutputFormat mpeg1vcd_mux;
99static AVOutputFormat mpeg2vob_mux;
100static AVOutputFormat mpeg2svcd_mux;
78a0efb4 101static AVOutputFormat mpeg2dvd_mux;
fb7566d0 102
de6d9b64 103static int put_pack_header(AVFormatContext *ctx,
0c1a9eda 104 uint8_t *buf, int64_t timestamp)
de6d9b64
FB
105{
106 MpegMuxContext *s = ctx->priv_data;
107 PutBitContext pb;
108
117a5490 109 init_put_bits(&pb, buf, 128);
de6d9b64
FB
110
111 put_bits(&pb, 32, PACK_START_CODE);
b2cac184 112 if (s->is_mpeg2) {
8683e4a0 113 put_bits(&pb, 2, 0x1);
b2cac184
FB
114 } else {
115 put_bits(&pb, 4, 0x2);
116 }
0c1a9eda 117 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
de6d9b64 118 put_bits(&pb, 1, 1);
0c1a9eda 119 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
de6d9b64 120 put_bits(&pb, 1, 1);
0c1a9eda 121 put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
de6d9b64 122 put_bits(&pb, 1, 1);
b2cac184
FB
123 if (s->is_mpeg2) {
124 /* clock extension */
125 put_bits(&pb, 9, 0);
b2cac184 126 }
de6d9b64
FB
127 put_bits(&pb, 1, 1);
128 put_bits(&pb, 22, s->mux_rate);
129 put_bits(&pb, 1, 1);
b2cac184 130 if (s->is_mpeg2) {
4aa533be 131 put_bits(&pb, 1, 1);
b2cac184
FB
132 put_bits(&pb, 5, 0x1f); /* reserved */
133 put_bits(&pb, 3, 0); /* stuffing length */
134 }
de6d9b64 135 flush_put_bits(&pb);
17592475 136 return pbBufPtr(&pb) - pb.buf;
de6d9b64
FB
137}
138
24515926 139static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
de6d9b64
FB
140{
141 MpegMuxContext *s = ctx->priv_data;
7000a175 142 int size, i, private_stream_coded, id;
de6d9b64
FB
143 PutBitContext pb;
144
117a5490 145 init_put_bits(&pb, buf, 128);
de6d9b64
FB
146
147 put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
148 put_bits(&pb, 16, 0);
149 put_bits(&pb, 1, 1);
150
7000a175 151 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
de6d9b64 152 put_bits(&pb, 1, 1); /* marker */
24515926
HD
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);
de6d9b64 158
22494489
HD
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 }
de6d9b64 167
cbb6e405 168 if (s->is_vcd || s->is_dvd) {
24515926
HD
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
de6d9b64
FB
177 put_bits(&pb, 1, 1); /* marker */
178
24515926
HD
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);
de6d9b64 184
cbb6e405
MN
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;
24515926 201
cbb6e405
MN
202 for(i=0;i<ctx->nb_streams;i++) {
203 StreamInfo *stream = ctx->streams[i]->priv_data;
24515926
HD
204
205 id = stream->id;
cbb6e405
MN
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;
24515926 212 }
cbb6e405
MN
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 }
24515926 273 }
de6d9b64
FB
274 }
275 }
cbb6e405 276
de6d9b64 277 flush_put_bits(&pb);
17592475 278 size = pbBufPtr(&pb) - pb.buf;
de6d9b64
FB
279 /* patch packet size */
280 buf[4] = (size - 6) >> 8;
281 buf[5] = (size - 6) & 0xff;
282
283 return size;
284}
285
0dbb48d9
FB
286static int get_system_header_size(AVFormatContext *ctx)
287{
288 int buf_index, i, private_stream_coded;
289 StreamInfo *stream;
cbb6e405
MN
290 MpegMuxContext *s = ctx->priv_data;
291
292 if (s->is_dvd)
293 return 18; // DVD-Video system headers are 18 bytes fixed length.
0dbb48d9
FB
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
de6d9b64
FB
309static int mpeg_mux_init(AVFormatContext *ctx)
310{
db7f1f95 311 MpegMuxContext *s = ctx->priv_data;
23c99253 312 int bitrate, i, mpa_id, mpv_id, ac3_id, dts_id, lpcm_id, j;
de6d9b64
FB
313 AVStream *st;
314 StreamInfo *stream;
24515926
HD
315 int audio_bitrate;
316 int video_bitrate;
de6d9b64 317
de6d9b64 318 s->packet_number = 0;
fb7566d0 319 s->is_vcd = (ctx->oformat == &mpeg1vcd_mux);
24515926 320 s->is_svcd = (ctx->oformat == &mpeg2svcd_mux);
78a0efb4
PC
321 s->is_mpeg2 = (ctx->oformat == &mpeg2vob_mux || ctx->oformat == &mpeg2svcd_mux || ctx->oformat == &mpeg2dvd_mux);
322 s->is_dvd = (ctx->oformat == &mpeg2dvd_mux);
fb7566d0 323
2db3c638
MN
324 if(ctx->packet_size)
325 s->packet_size = ctx->packet_size;
92b3e125
J
326 else
327 s->packet_size = 2048;
2db3c638 328
24515926
HD
329 s->vcd_padding_bytes_written = 0;
330 s->vcd_padding_bitrate=0;
92b3e125 331
de6d9b64
FB
332 s->audio_bound = 0;
333 s->video_bound = 0;
334 mpa_id = AUDIO_ID;
044007c2 335 ac3_id = AC3_ID;
23c99253 336 dts_id = DTS_ID;
de6d9b64 337 mpv_id = VIDEO_ID;
044007c2 338 lpcm_id = LPCM_ID;
de6d9b64
FB
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
2031ba1b
MN
346 av_set_pts_info(st, 64, 1, 90000);
347
de6d9b64
FB
348 switch(st->codec.codec_type) {
349 case CODEC_TYPE_AUDIO:
044007c2 350 if (st->codec.codec_id == CODEC_ID_AC3) {
de6d9b64 351 stream->id = ac3_id++;
23c99253
MN
352 } else if (st->codec.codec_id == CODEC_ID_DTS) {
353 stream->id = dts_id++;
044007c2
FB
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 {
de6d9b64 369 stream->id = mpa_id++;
044007c2 370 }
22494489
HD
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.*/
de6d9b64
FB
374 stream->max_buffer_size = 4 * 1024;
375 s->audio_bound++;
376 break;
377 case CODEC_TYPE_VIDEO:
378 stream->id = mpv_id++;
7e051558
MN
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
22494489
HD
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;
7e051558 390#endif
de6d9b64
FB
391 s->video_bound++;
392 break;
ac5e6a5b 393 default:
71c32f19 394 return -1;
de6d9b64 395 }
0d712409 396 fifo_init(&stream->fifo, 16);
7000a175 397 stream->next_packet= &stream->premux_packet;
de6d9b64 398 }
24515926
HD
399 bitrate = 0;
400 audio_bitrate = 0;
401 video_bitrate = 0;
de6d9b64 402 for(i=0;i<ctx->nb_streams;i++) {
7000a175 403 int codec_rate;
de6d9b64 404 st = ctx->streams[i];
24515926 405 stream = (StreamInfo*) st->priv_data;
7000a175
MN
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;
24515926
HD
416
417 if (stream->id==AUDIO_ID)
7000a175 418 audio_bitrate += codec_rate;
24515926 419 else if (stream->id==VIDEO_ID)
7000a175 420 video_bitrate += codec_rate;
24515926 421 }
2db3c638
MN
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 }
24515926
HD
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.*/
2db3c638 443// s->mux_rate=2352 * 75 / 50; /* = 3528*/
24515926
HD
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);
de6d9b64 460 }
92b3e125 461
fb7566d0 462 if (s->is_vcd || s->is_mpeg2)
92b3e125
J
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;
b623bbcb
MN
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;
92b3e125 472
b2cac184
FB
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)
24515926
HD
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;
92b3e125 481 else
92b3e125
J
482 s->system_header_freq = s->pack_header_freq * 5;
483
de6d9b64
FB
484 for(i=0;i<ctx->nb_streams;i++) {
485 stream = ctx->streams[i]->priv_data;
de6d9b64 486 stream->packet_number = 0;
de6d9b64 487 }
0dbb48d9 488 s->system_header_size = get_system_header_size(ctx);
27a206e0 489 s->last_scr = 0;
de6d9b64
FB
490 return 0;
491 fail:
492 for(i=0;i<ctx->nb_streams;i++) {
1ea4f593 493 av_free(ctx->streams[i]->priv_data);
de6d9b64 494 }
de6d9b64
FB
495 return -ENOMEM;
496}
497
27a206e0
MB
498static 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
0dbb48d9 508
24515926
HD
509/* return the number of padding bytes that should be inserted into
510 the multiplexed stream.*/
511static 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
7000a175 520 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
24515926
HD
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
88730be6 533#if 0 /* unused, remove? */
0dbb48d9
FB
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. */
537static 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
24515926
HD
544 stream = ctx->streams[stream_index]->priv_data;
545
0dbb48d9
FB
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;
24515926
HD
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 }
0dbb48d9
FB
568 }
569
22494489
HD
570 if ((s->is_vcd && stream->packet_number==0)
571 || (s->is_svcd && s->packet_number==0))
24515926
HD
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;
22494489 579 if (s->is_mpeg2) {
044007c2 580 buf_index += 3;
22494489
HD
581 if (stream->packet_number==0)
582 buf_index += 3; /* PES extension */
583 buf_index += 1; /* obligatory stuffing byte */
584 }
24515926
HD
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 }
044007c2 608 }
24515926
HD
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;
0dbb48d9
FB
614 }
615 return s->packet_size - buf_index;
616}
88730be6 617#endif
0dbb48d9 618
24515926 619/* Write an MPEG padding packet header. */
d8b5abfa 620static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
24515926
HD
621{
622 MpegMuxContext *s = ctx->priv_data;
d8b5abfa
MN
623 int i;
624
625 put_be32(pb, PADDING_STREAM);
626 put_be16(pb, packet_bytes - 6);
24515926 627 if (!s->is_mpeg2) {
d8b5abfa
MN
628 put_byte(pb, 0x0f);
629 packet_bytes -= 7;
24515926 630 } else
d8b5abfa 631 packet_bytes -= 6;
24515926
HD
632
633 for(i=0;i<packet_bytes;i++)
634 put_byte(pb, 0xff);
635}
636
7000a175
MN
637static 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}
24515926 650
de6d9b64 651/* flush the packet on stream stream_index */
7000a175
MN
652static int flush_packet(AVFormatContext *ctx, int stream_index,
653 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
de6d9b64
FB
654{
655 MpegMuxContext *s = ctx->priv_data;
656 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
0c1a9eda 657 uint8_t *buf_ptr;
0dbb48d9
FB
658 int size, payload_size, startcode, id, stuffing_size, i, header_len;
659 int packet_size;
0c1a9eda 660 uint8_t buffer[128];
24515926
HD
661 int zero_trail_bytes = 0;
662 int pad_packet_bytes = 0;
22494489
HD
663 int pes_flags;
664 int general_pack = 0; /*"general" pack without data specific to one stream?*/
7000a175 665 int nb_frames;
92b3e125 666
de6d9b64 667 id = stream->id;
27a206e0 668
de6d9b64
FB
669#if 0
670 printf("packet ID=%2x PTS=%0.3f\n",
27a206e0 671 id, pts / 90000.0);
de6d9b64
FB
672#endif
673
674 buf_ptr = buffer;
24515926 675
7000a175 676 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
de6d9b64 677 /* output pack and systems header if needed */
27a206e0 678 size = put_pack_header(ctx, buf_ptr, scr);
de6d9b64 679 buf_ptr += size;
7000a175 680 s->last_scr= scr;
24515926
HD
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 }
7e0fda0a
C
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 }
24515926
HD
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 }
de6d9b64
FB
745 }
746 }
747 size = buf_ptr - buffer;
748 put_buffer(&ctx->pb, buffer, size);
749
24515926
HD
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
22494489
HD
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,
24515926
HD
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.*/
22494489
HD
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*/
24515926 767 pad_packet_bytes = packet_size - zero_trail_bytes;
27a206e0
MB
768 }
769
24515926 770 packet_size -= pad_packet_bytes + zero_trail_bytes;
0dbb48d9 771
24515926 772 if (packet_size > 0) {
de6d9b64 773
24515926
HD
774 /* packet header size */
775 packet_size -= 6;
776
777 /* packet header */
778 if (s->is_mpeg2) {
779 header_len = 3;
22494489
HD
780 if (stream->packet_number==0)
781 header_len += 3; /* PES extension */
782 header_len += 1; /* obligatory stuffing byte */
24515926
HD
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 }
4aa533be 795
24515926
HD
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 }
fb7566d0 805
7000a175
MN
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;
7e0fda0a
C
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 }
7000a175
MN
823 stuffing_size += timestamp_len;
824 if(payload_size > trailer_size)
825 stuffing_size += payload_size - trailer_size;
826 }
827
7e0fda0a
C
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
24515926
HD
839 if (stuffing_size < 0)
840 stuffing_size = 0;
22494489
HD
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 }
7000a175
MN
847
848 nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
22494489 849
24515926 850 put_be32(&ctx->pb, startcode);
27a206e0 851
24515926
HD
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
22494489
HD
861 pes_flags=0;
862
24515926 863 if (pts != AV_NOPTS_VALUE) {
22494489
HD
864 pes_flags |= 0x80;
865 if (dts != pts)
866 pes_flags |= 0x40;
27a206e0 867 }
22494489
HD
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
27a206e0 894 } else {
24515926
HD
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 }
27a206e0 902 } else {
24515926 903 put_byte(&ctx->pb, 0x0f);
27a206e0 904 }
27a206e0 905 }
de6d9b64 906
9e9080b6
SI
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
24515926
HD
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 */
7000a175
MN
927 put_byte(&ctx->pb, nb_frames);
928 put_be16(&ctx->pb, trailer_size+1);
24515926 929 }
de6d9b64 930 }
24515926 931
24515926 932 /* output data */
7000a175
MN
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;
de6d9b64
FB
938 }
939
24515926
HD
940 if (pad_packet_bytes > 0)
941 put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);
4aa533be 942
24515926
HD
943 for(i=0;i<zero_trail_bytes;i++)
944 put_byte(&ctx->pb, 0x00);
945
de6d9b64
FB
946 put_flush_packet(&ctx->pb);
947
de6d9b64 948 s->packet_number++;
22494489
HD
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++;
7000a175
MN
955
956 return payload_size - stuffing_size;
de6d9b64
FB
957}
958
24515926
HD
959static 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
88730be6 984#if 0 /* unused, remove? */
92050933 985static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
24515926
HD
986{
987 MpegMuxContext *s = ctx->priv_data;
988 int64_t scr;
989
24515926
HD
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;
22494489 1001
24515926
HD
1002 return scr;
1003}
88730be6 1004#endif
24515926 1005
7000a175
MN
1006static 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
1031static 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;
bc3429e3 1040 PacketDesc *timestamp_packet;
17c88cb0 1041 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
7000a175
MN
1042
1043retry:
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;
17c88cb0 1050 PacketDesc *next_pkt= stream->premux_packet;
7000a175
MN
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
17c88cb0
MN
1061 if(next_pkt && next_pkt->dts - scr > max_delay)
1062 continue;
1063
7000a175
MN
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
bc3429e3
MN
1108 timestamp_packet= stream->premux_packet;
1109 if(timestamp_packet->unwritten_size == timestamp_packet->size){
7000a175 1110 trailer_size= 0;
bc3429e3
MN
1111 }else{
1112 trailer_size= timestamp_packet->unwritten_size;
1113 timestamp_packet= timestamp_packet->next;
1114 }
7000a175 1115
bc3429e3 1116 if(timestamp_packet){
2db3c638 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);
bc3429e3
MN
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 }
7000a175
MN
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
92050933 1129 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
7000a175
MN
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}
24515926 1150
e928649b 1151static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
de6d9b64
FB
1152{
1153 MpegMuxContext *s = ctx->priv_data;
e928649b
MN
1154 int stream_index= pkt->stream_index;
1155 int size= pkt->size;
1156 uint8_t *buf= pkt->data;
de6d9b64
FB
1157 AVStream *st = ctx->streams[stream_index];
1158 StreamInfo *stream = st->priv_data;
92050933 1159 int64_t pts, dts;
7000a175 1160 PacketDesc *pkt_desc;
17c88cb0 1161 const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
cbb6e405 1162 const int is_iframe = st->codec.codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
24515926 1163
e928649b
MN
1164 pts= pkt->pts;
1165 dts= pkt->dts;
e45f1943 1166
17c88cb0
MN
1167 if(pts != AV_NOPTS_VALUE) pts += preload;
1168 if(dts != AV_NOPTS_VALUE) dts += preload;
1169
6c55b27f 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);
7000a175
MN
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
20b02bc6
C
1181 fifo_realloc(&stream->fifo, fifo_size(&stream->fifo, NULL) + size + 1);
1182
cbb6e405 1183 if (s->is_dvd){
7be806f3 1184 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
cbb6e405
MN
1185 stream->fifo_iframe_ptr = stream->fifo.wptr;
1186 stream->align_iframe = 1;
7be806f3 1187 stream->vobu_start_pts = pts;
cbb6e405
MN
1188 } else {
1189 stream->align_iframe = 0;
1190 }
1191 }
1192
7000a175 1193 fifo_write(&stream->fifo, buf, size, &stream->fifo.wptr);
24515926 1194
7000a175
MN
1195 for(;;){
1196 int ret= output_packet(ctx, 0);
92050933 1197 if(ret<=0)
7000a175 1198 return ret;
0dbb48d9 1199 }
de6d9b64
FB
1200}
1201
1202static int mpeg_mux_end(AVFormatContext *ctx)
1203{
7000a175 1204// MpegMuxContext *s = ctx->priv_data;
de6d9b64
FB
1205 StreamInfo *stream;
1206 int i;
7000a175
MN
1207
1208 for(;;){
1209 int ret= output_packet(ctx, 1);
1210 if(ret<0)
1211 return ret;
1212 else if(ret==0)
1213 break;
de6d9b64
FB
1214 }
1215
fa0f62c3
FB
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. */
92b3e125
J
1219 //put_be32(&ctx->pb, ISO_11172_END_CODE);
1220 //put_flush_packet(&ctx->pb);
9d90c37f 1221
7000a175
MN
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 }
de6d9b64
FB
1228 return 0;
1229}
764ef400 1230#endif //CONFIG_ENCODERS
de6d9b64
FB
1231
1232/*********************************************/
1233/* demux code */
1234
1235#define MAX_SYNC_SIZE 100000
1236
db7f1f95
FB
1237static int mpegps_probe(AVProbeData *p)
1238{
95f97de1
MN
1239 int i;
1240 int size= FFMIN(20, p->buf_size);
1241 uint32_t code=0xFF;
db7f1f95
FB
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 */
fa777321
FB
1246 /* NOTE: the search range was restricted to avoid too many false
1247 detections */
1248
95f97de1
MN
1249 for (i = 0; i < size; i++) {
1250 code = (code << 8) | p->buf[i];
ec23a472
IR
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)
149f7c02 1260 return AVPROBE_SCORE_MAX - 2;
ec23a472
IR
1261 else
1262 return 0;
1263 }
db7f1f95
FB
1264 }
1265 return 0;
1266}
1267
1268
de6d9b64
FB
1269typedef struct MpegDemuxContext {
1270 int header_state;
de6d9b64
FB
1271} MpegDemuxContext;
1272
27f388aa
FB
1273static 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
1284static 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
1299static int find_next_start_code(ByteIOContext *pb, int *size_ptr,
1300 uint32_t *header_state)
de6d9b64
FB
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
88730be6 1326#if 0 /* unused, remove? */
27f388aa
FB
1327/* XXX: optimize */
1328static int find_prev_start_code(ByteIOContext *pb, int *size_ptr)
de6d9b64 1329{
27f388aa
FB
1330 int64_t pos, pos_start;
1331 int max_size, start_code;
da24c5e3 1332
27f388aa
FB
1333 max_size = *size_ptr;
1334 pos_start = url_ftell(pb);
de6d9b64 1335
27f388aa
FB
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);
de6d9b64 1342
27f388aa
FB
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;
de6d9b64 1358}
88730be6 1359#endif
de6d9b64 1360
8d14a25c 1361/* read the next PES header. Return its position in ppos
27f388aa
FB
1362 (if not NULL), and its start code, pts and dts.
1363 */
1364static int mpegps_read_pes_header(AVFormatContext *s,
1365 int64_t *ppos, int *pstart_code,
8d14a25c 1366 int64_t *ppts, int64_t *pdts)
de6d9b64
FB
1367{
1368 MpegDemuxContext *m = s->priv_data;
27f388aa
FB
1369 int len, size, startcode, c, flags, header_len;
1370 int64_t pts, dts, last_pos;
de6d9b64 1371
27f388aa 1372 last_pos = -1;
de6d9b64 1373 redo:
27f388aa
FB
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);
001e3f55 1378 //printf("startcode=%x pos=0x%Lx\n", startcode, url_ftell(&s->pb));
de6d9b64 1379 if (startcode < 0)
0bd586c5 1380 return AVERROR_IO;
de6d9b64
FB
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;
27f388aa
FB
1397 if (ppos) {
1398 *ppos = url_ftell(&s->pb) - 4;
1399 }
de6d9b64 1400 len = get_be16(&s->pb);
b2cac184
FB
1401 pts = AV_NOPTS_VALUE;
1402 dts = AV_NOPTS_VALUE;
de6d9b64
FB
1403 /* stuffing */
1404 for(;;) {
27f388aa
FB
1405 if (len < 1)
1406 goto redo;
de6d9b64
FB
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 */
27f388aa
FB
1415 if (len < 2)
1416 goto redo;
de6d9b64
FB
1417 get_byte(&s->pb);
1418 c = get_byte(&s->pb);
1419 len -= 2;
1420 }
1421 if ((c & 0xf0) == 0x20) {
27f388aa
FB
1422 if (len < 4)
1423 goto redo;
1424 dts = pts = get_pts(&s->pb, c);
de6d9b64 1425 len -= 4;
de6d9b64 1426 } else if ((c & 0xf0) == 0x30) {
27f388aa
FB
1427 if (len < 9)
1428 goto redo;
de6d9b64
FB
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) {
27f388aa
FB
1435 /* Encrypted multiplex not handled */
1436 goto redo;
de6d9b64
FB
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;
1e5c667c 1443 if ((flags & 0xc0) == 0x80) {
27f388aa
FB
1444 dts = pts = get_pts(&s->pb, -1);
1445 if (header_len < 5)
1446 goto redo;
de6d9b64
FB
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);
27f388aa
FB
1452 if (header_len < 10)
1453 goto redo;
de6d9b64
FB
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 }
df70de1f
DB
1463 else if( c!= 0xf )
1464 goto redo;
1465
de6d9b64 1466 if (startcode == 0x1bd) {
27f388aa
FB
1467 if (len < 1)
1468 goto redo;
de6d9b64
FB
1469 startcode = get_byte(&s->pb);
1470 len--;
1471 if (startcode >= 0x80 && startcode <= 0xbf) {
1472 /* audio: skip header */
27f388aa
FB
1473 if (len < 3)
1474 goto redo;
de6d9b64
FB
1475 get_byte(&s->pb);
1476 get_byte(&s->pb);
1477 get_byte(&s->pb);
1478 len -= 3;
1479 }
1480 }
b754978a
MN
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) {
27a5fe5f 1485 av_add_index_entry(s->streams[i], *ppos, dts, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
b754978a
MN
1486 }
1487 }
1488 }
1489
27f388aa
FB
1490 *pstart_code = startcode;
1491 *ppts = pts;
1492 *pdts = dts;
1493 return len;
1494}
1495
1496static int mpegps_read_packet(AVFormatContext *s,
1497 AVPacket *pkt)
1498{
1499 AVStream *st;
0bd586c5 1500 int len, startcode, i, type, codec_id = 0;
b754978a 1501 int64_t pts, dts, dummy_pos; //dummy_pos is needed for the index building to work
27f388aa
FB
1502
1503 redo:
8d14a25c 1504 len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
27f388aa
FB
1505 if (len < 0)
1506 return len;
27a206e0 1507
de6d9b64
FB
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 }
db7f1f95
FB
1514 if (startcode >= 0x1e0 && startcode <= 0x1ef) {
1515 type = CODEC_TYPE_VIDEO;
0dbb48d9 1516 codec_id = CODEC_ID_MPEG2VIDEO;
db7f1f95
FB
1517 } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
1518 type = CODEC_TYPE_AUDIO;
1519 codec_id = CODEC_ID_MP2;
23c99253 1520 } else if (startcode >= 0x80 && startcode <= 0x89) {
db7f1f95
FB
1521 type = CODEC_TYPE_AUDIO;
1522 codec_id = CODEC_ID_AC3;
23c99253
MN
1523 } else if (startcode >= 0x8a && startcode <= 0x9f) {
1524 type = CODEC_TYPE_AUDIO;
1525 codec_id = CODEC_ID_DTS;
9ec05e36
FB
1526 } else if (startcode >= 0xa0 && startcode <= 0xbf) {
1527 type = CODEC_TYPE_AUDIO;
1528 codec_id = CODEC_ID_PCM_S16BE;
db7f1f95
FB
1529 } else {
1530 skip:
1531 /* skip packet */
1532 url_fskip(&s->pb, len);
1533 goto redo;
1534 }
1e5c667c
FB
1535 /* no stream found: add a new stream */
1536 st = av_new_stream(s, startcode);
1537 if (!st)
1538 goto skip;
db7f1f95
FB
1539 st->codec.codec_type = type;
1540 st->codec.codec_id = codec_id;
27f388aa
FB
1541 if (codec_id != CODEC_ID_PCM_S16BE)
1542 st->need_parsing = 1;
de6d9b64 1543 found:
b9866ebc
MN
1544 if(st->discard)
1545 goto skip;
9ec05e36
FB
1546 if (startcode >= 0xa0 && startcode <= 0xbf) {
1547 int b1, freq;
9ec05e36
FB
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 }
de6d9b64
FB
1562 av_new_packet(pkt, len);
1563 get_buffer(&s->pb, pkt->data, pkt->size);
1564 pkt->pts = pts;
27f388aa 1565 pkt->dts = dts;
db7f1f95 1566 pkt->stream_index = st->index;
27a206e0 1567#if 0
b9866ebc
MN
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);
27a206e0 1570#endif
0bd586c5 1571
de6d9b64
FB
1572 return 0;
1573}
1574
db7f1f95 1575static int mpegps_read_close(AVFormatContext *s)
de6d9b64 1576{
de6d9b64
FB
1577 return 0;
1578}
1579
27f388aa 1580static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
8d14a25c 1581 int64_t *ppos, int64_t pos_limit)
27f388aa
FB
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(;;) {
8d14a25c 1592 len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
27f388aa
FB
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 }
8d14a25c 1603 url_fskip(&s->pb, len);
27f388aa
FB
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;
cdd5034f 1609 return dts;
27f388aa
FB
1610}
1611
764ef400 1612#ifdef CONFIG_ENCODERS
fb7566d0 1613static AVOutputFormat mpeg1system_mux = {
de6d9b64 1614 "mpeg",
fb7566d0 1615 "MPEG1 System format",
c6c11cb6 1616 "video/mpeg",
fb7566d0
FB
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
1626static AVOutputFormat mpeg1vcd_mux = {
1627 "vcd",
1628 "MPEG1 System format (VCD)",
c6c11cb6 1629 "video/mpeg",
fb7566d0
FB
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
1639static AVOutputFormat mpeg2vob_mux = {
1640 "vob",
1641 "MPEG2 PS format (VOB)",
c6c11cb6 1642 "video/mpeg",
fb7566d0 1643 "vob",
db7f1f95 1644 sizeof(MpegMuxContext),
de6d9b64 1645 CODEC_ID_MP2,
0dbb48d9 1646 CODEC_ID_MPEG2VIDEO,
de6d9b64
FB
1647 mpeg_mux_init,
1648 mpeg_mux_write_packet,
1649 mpeg_mux_end,
db7f1f95 1650};
24515926
HD
1651
1652/* Same as mpeg2vob_mux except that the pack size is 2324 */
1653static 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
78a0efb4
PC
1666/* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1667static 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};
24515926 1679
764ef400 1680#endif //CONFIG_ENCODERS
de6d9b64 1681
32f38cb4 1682AVInputFormat mpegps_demux = {
db7f1f95
FB
1683 "mpeg",
1684 "MPEG PS format",
1685 sizeof(MpegDemuxContext),
1686 mpegps_probe,
1687 mpegps_read_header,
1688 mpegps_read_packet,
1689 mpegps_read_close,
8d14a25c
MN
1690 NULL, //mpegps_read_seek,
1691 mpegps_read_dts,
de6d9b64 1692};
db7f1f95
FB
1693
1694int mpegps_init(void)
1695{
764ef400 1696#ifdef CONFIG_ENCODERS
fb7566d0
FB
1697 av_register_output_format(&mpeg1system_mux);
1698 av_register_output_format(&mpeg1vcd_mux);
1699 av_register_output_format(&mpeg2vob_mux);
24515926 1700 av_register_output_format(&mpeg2svcd_mux);
78a0efb4 1701 av_register_output_format(&mpeg2dvd_mux);
764ef400 1702#endif //CONFIG_ENCODERS
db7f1f95
FB
1703 av_register_input_format(&mpegps_demux);
1704 return 0;
1705}