use allformats.h
[libav.git] / libavformat / mpegenc.c
1 /*
2 * MPEG1/2 muxer
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "avformat.h"
23 #include "allformats.h"
24 #include "bitstream.h"
25 #include "fifo.h"
26 #include "mpeg.h"
27
28 #define MAX_PAYLOAD_SIZE 4096
29 //#define DEBUG_SEEK
30
31 #undef NDEBUG
32 #include <assert.h>
33
34 typedef struct PacketDesc {
35 int64_t pts;
36 int64_t dts;
37 int size;
38 int unwritten_size;
39 int flags;
40 struct PacketDesc *next;
41 } PacketDesc;
42
43 typedef struct {
44 AVFifoBuffer fifo;
45 uint8_t id;
46 int max_buffer_size; /* in bytes */
47 int buffer_index;
48 PacketDesc *predecode_packet;
49 PacketDesc *premux_packet;
50 PacketDesc **next_packet;
51 int packet_number;
52 uint8_t lpcm_header[3];
53 int lpcm_align;
54 int bytes_to_iframe;
55 int align_iframe;
56 int64_t vobu_start_pts;
57 } StreamInfo;
58
59 typedef struct {
60 int packet_size; /* required packet size */
61 int packet_number;
62 int pack_header_freq; /* frequency (in packets^-1) at which we send pack headers */
63 int system_header_freq;
64 int system_header_size;
65 int mux_rate; /* bitrate in units of 50 bytes/s */
66 /* stream info */
67 int audio_bound;
68 int video_bound;
69 int is_mpeg2;
70 int is_vcd;
71 int is_svcd;
72 int is_dvd;
73 int64_t last_scr; /* current system clock */
74
75 double vcd_padding_bitrate; //FIXME floats
76 int64_t vcd_padding_bytes_written;
77
78 } MpegMuxContext;
79
80 static int put_pack_header(AVFormatContext *ctx,
81 uint8_t *buf, int64_t timestamp)
82 {
83 MpegMuxContext *s = ctx->priv_data;
84 PutBitContext pb;
85
86 init_put_bits(&pb, buf, 128);
87
88 put_bits(&pb, 32, PACK_START_CODE);
89 if (s->is_mpeg2) {
90 put_bits(&pb, 2, 0x1);
91 } else {
92 put_bits(&pb, 4, 0x2);
93 }
94 put_bits(&pb, 3, (uint32_t)((timestamp >> 30) & 0x07));
95 put_bits(&pb, 1, 1);
96 put_bits(&pb, 15, (uint32_t)((timestamp >> 15) & 0x7fff));
97 put_bits(&pb, 1, 1);
98 put_bits(&pb, 15, (uint32_t)((timestamp) & 0x7fff));
99 put_bits(&pb, 1, 1);
100 if (s->is_mpeg2) {
101 /* clock extension */
102 put_bits(&pb, 9, 0);
103 }
104 put_bits(&pb, 1, 1);
105 put_bits(&pb, 22, s->mux_rate);
106 put_bits(&pb, 1, 1);
107 if (s->is_mpeg2) {
108 put_bits(&pb, 1, 1);
109 put_bits(&pb, 5, 0x1f); /* reserved */
110 put_bits(&pb, 3, 0); /* stuffing length */
111 }
112 flush_put_bits(&pb);
113 return pbBufPtr(&pb) - pb.buf;
114 }
115
116 static int put_system_header(AVFormatContext *ctx, uint8_t *buf,int only_for_stream_id)
117 {
118 MpegMuxContext *s = ctx->priv_data;
119 int size, i, private_stream_coded, id;
120 PutBitContext pb;
121
122 init_put_bits(&pb, buf, 128);
123
124 put_bits(&pb, 32, SYSTEM_HEADER_START_CODE);
125 put_bits(&pb, 16, 0);
126 put_bits(&pb, 1, 1);
127
128 put_bits(&pb, 22, s->mux_rate); /* maximum bit rate of the multiplexed stream */
129 put_bits(&pb, 1, 1); /* marker */
130 if (s->is_vcd && only_for_stream_id==VIDEO_ID) {
131 /* This header applies only to the video stream (see VCD standard p. IV-7)*/
132 put_bits(&pb, 6, 0);
133 } else
134 put_bits(&pb, 6, s->audio_bound);
135
136 if (s->is_vcd) {
137 /* see VCD standard, p. IV-7*/
138 put_bits(&pb, 1, 0);
139 put_bits(&pb, 1, 1);
140 } else {
141 put_bits(&pb, 1, 0); /* variable bitrate*/
142 put_bits(&pb, 1, 0); /* non constrainted bit stream */
143 }
144
145 if (s->is_vcd || s->is_dvd) {
146 /* see VCD standard p IV-7 */
147 put_bits(&pb, 1, 1); /* audio locked */
148 put_bits(&pb, 1, 1); /* video locked */
149 } else {
150 put_bits(&pb, 1, 0); /* audio locked */
151 put_bits(&pb, 1, 0); /* video locked */
152 }
153
154 put_bits(&pb, 1, 1); /* marker */
155
156 if (s->is_vcd && only_for_stream_id==AUDIO_ID) {
157 /* This header applies only to the audio stream (see VCD standard p. IV-7)*/
158 put_bits(&pb, 5, 0);
159 } else
160 put_bits(&pb, 5, s->video_bound);
161
162 if (s->is_dvd) {
163 put_bits(&pb, 1, 0); /* packet_rate_restriction_flag */
164 put_bits(&pb, 7, 0x7f); /* reserved byte */
165 } else
166 put_bits(&pb, 8, 0xff); /* reserved byte */
167
168 /* DVD-Video Stream_bound entries
169 id (0xB9) video, maximum P-STD for stream 0xE0. (P-STD_buffer_bound_scale = 1)
170 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)
171 id (0xBD) private stream 1 (audio other than MPEG and subpictures). (P-STD_buffer_bound_scale = 1)
172 id (0xBF) private stream 2, NAV packs, set to 2x1024. */
173 if (s->is_dvd) {
174
175 int P_STD_max_video = 0;
176 int P_STD_max_mpeg_audio = 0;
177 int P_STD_max_mpeg_PS1 = 0;
178
179 for(i=0;i<ctx->nb_streams;i++) {
180 StreamInfo *stream = ctx->streams[i]->priv_data;
181
182 id = stream->id;
183 if (id == 0xbd && stream->max_buffer_size > P_STD_max_mpeg_PS1) {
184 P_STD_max_mpeg_PS1 = stream->max_buffer_size;
185 } else if (id >= 0xc0 && id <= 0xc7 && stream->max_buffer_size > P_STD_max_mpeg_audio) {
186 P_STD_max_mpeg_audio = stream->max_buffer_size;
187 } else if (id == 0xe0 && stream->max_buffer_size > P_STD_max_video) {
188 P_STD_max_video = stream->max_buffer_size;
189 }
190 }
191
192 /* video */
193 put_bits(&pb, 8, 0xb9); /* stream ID */
194 put_bits(&pb, 2, 3);
195 put_bits(&pb, 1, 1);
196 put_bits(&pb, 13, P_STD_max_video / 1024);
197
198 /* audio */
199 if (P_STD_max_mpeg_audio == 0)
200 P_STD_max_mpeg_audio = 4096;
201 put_bits(&pb, 8, 0xb8); /* stream ID */
202 put_bits(&pb, 2, 3);
203 put_bits(&pb, 1, 0);
204 put_bits(&pb, 13, P_STD_max_mpeg_audio / 128);
205
206 /* private stream 1 */
207 put_bits(&pb, 8, 0xbd); /* stream ID */
208 put_bits(&pb, 2, 3);
209 put_bits(&pb, 1, 0);
210 put_bits(&pb, 13, P_STD_max_mpeg_PS1 / 128);
211
212 /* private stream 2 */
213 put_bits(&pb, 8, 0xbf); /* stream ID */
214 put_bits(&pb, 2, 3);
215 put_bits(&pb, 1, 1);
216 put_bits(&pb, 13, 2);
217 }
218 else {
219 /* audio stream info */
220 private_stream_coded = 0;
221 for(i=0;i<ctx->nb_streams;i++) {
222 StreamInfo *stream = ctx->streams[i]->priv_data;
223
224
225 /* For VCDs, only include the stream info for the stream
226 that the pack which contains this system belongs to.
227 (see VCD standard p. IV-7) */
228 if ( !s->is_vcd || stream->id==only_for_stream_id
229 || only_for_stream_id==0) {
230
231 id = stream->id;
232 if (id < 0xc0) {
233 /* special case for private streams (AC3 use that) */
234 if (private_stream_coded)
235 continue;
236 private_stream_coded = 1;
237 id = 0xbd;
238 }
239 put_bits(&pb, 8, id); /* stream ID */
240 put_bits(&pb, 2, 3);
241 if (id < 0xe0) {
242 /* audio */
243 put_bits(&pb, 1, 0);
244 put_bits(&pb, 13, stream->max_buffer_size / 128);
245 } else {
246 /* video */
247 put_bits(&pb, 1, 1);
248 put_bits(&pb, 13, stream->max_buffer_size / 1024);
249 }
250 }
251 }
252 }
253
254 flush_put_bits(&pb);
255 size = pbBufPtr(&pb) - pb.buf;
256 /* patch packet size */
257 buf[4] = (size - 6) >> 8;
258 buf[5] = (size - 6) & 0xff;
259
260 return size;
261 }
262
263 static int get_system_header_size(AVFormatContext *ctx)
264 {
265 int buf_index, i, private_stream_coded;
266 StreamInfo *stream;
267 MpegMuxContext *s = ctx->priv_data;
268
269 if (s->is_dvd)
270 return 18; // DVD-Video system headers are 18 bytes fixed length.
271
272 buf_index = 12;
273 private_stream_coded = 0;
274 for(i=0;i<ctx->nb_streams;i++) {
275 stream = ctx->streams[i]->priv_data;
276 if (stream->id < 0xc0) {
277 if (private_stream_coded)
278 continue;
279 private_stream_coded = 1;
280 }
281 buf_index += 3;
282 }
283 return buf_index;
284 }
285
286 static int mpeg_mux_init(AVFormatContext *ctx)
287 {
288 MpegMuxContext *s = ctx->priv_data;
289 int bitrate, i, mpa_id, mpv_id, mps_id, ac3_id, dts_id, lpcm_id, j;
290 AVStream *st;
291 StreamInfo *stream;
292 int audio_bitrate;
293 int video_bitrate;
294
295 s->packet_number = 0;
296 s->is_vcd = (ctx->oformat == &mpeg1vcd_muxer);
297 s->is_svcd = (ctx->oformat == &mpeg2svcd_muxer);
298 s->is_mpeg2 = (ctx->oformat == &mpeg2vob_muxer || ctx->oformat == &mpeg2svcd_muxer || ctx->oformat == &mpeg2dvd_muxer);
299 s->is_dvd = (ctx->oformat == &mpeg2dvd_muxer);
300
301 if(ctx->packet_size)
302 s->packet_size = ctx->packet_size;
303 else
304 s->packet_size = 2048;
305
306 s->vcd_padding_bytes_written = 0;
307 s->vcd_padding_bitrate=0;
308
309 s->audio_bound = 0;
310 s->video_bound = 0;
311 mpa_id = AUDIO_ID;
312 ac3_id = AC3_ID;
313 dts_id = DTS_ID;
314 mpv_id = VIDEO_ID;
315 mps_id = SUB_ID;
316 lpcm_id = LPCM_ID;
317 for(i=0;i<ctx->nb_streams;i++) {
318 st = ctx->streams[i];
319 stream = av_mallocz(sizeof(StreamInfo));
320 if (!stream)
321 goto fail;
322 st->priv_data = stream;
323
324 av_set_pts_info(st, 64, 1, 90000);
325
326 switch(st->codec->codec_type) {
327 case CODEC_TYPE_AUDIO:
328 if (st->codec->codec_id == CODEC_ID_AC3) {
329 stream->id = ac3_id++;
330 } else if (st->codec->codec_id == CODEC_ID_DTS) {
331 stream->id = dts_id++;
332 } else if (st->codec->codec_id == CODEC_ID_PCM_S16BE) {
333 stream->id = lpcm_id++;
334 for(j = 0; j < 4; j++) {
335 if (lpcm_freq_tab[j] == st->codec->sample_rate)
336 break;
337 }
338 if (j == 4)
339 goto fail;
340 if (st->codec->channels > 8)
341 return -1;
342 stream->lpcm_header[0] = 0x0c;
343 stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
344 stream->lpcm_header[2] = 0x80;
345 stream->lpcm_align = st->codec->channels * 2;
346 } else {
347 stream->id = mpa_id++;
348 }
349
350 /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
351 Right now it is also used for everything else.*/
352 stream->max_buffer_size = 4 * 1024;
353 s->audio_bound++;
354 break;
355 case CODEC_TYPE_VIDEO:
356 stream->id = mpv_id++;
357 if (st->codec->rc_buffer_size)
358 stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
359 else
360 stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
361 #if 0
362 /* see VCD standard, p. IV-7*/
363 stream->max_buffer_size = 46 * 1024;
364 else
365 /* This value HAS to be used for SVCD (see SVCD standard, p. 26 V.2.3.2).
366 Right now it is also used for everything else.*/
367 stream->max_buffer_size = 230 * 1024;
368 #endif
369 s->video_bound++;
370 break;
371 case CODEC_TYPE_SUBTITLE:
372 stream->id = mps_id++;
373 stream->max_buffer_size = 16 * 1024;
374 break;
375 default:
376 return -1;
377 }
378 av_fifo_init(&stream->fifo, 16);
379 }
380 bitrate = 0;
381 audio_bitrate = 0;
382 video_bitrate = 0;
383 for(i=0;i<ctx->nb_streams;i++) {
384 int codec_rate;
385 st = ctx->streams[i];
386 stream = (StreamInfo*) st->priv_data;
387
388 if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
389 codec_rate= st->codec->rc_max_rate;
390 else
391 codec_rate= st->codec->bit_rate;
392
393 if(!codec_rate)
394 codec_rate= (1<<21)*8*50/ctx->nb_streams;
395
396 bitrate += codec_rate;
397
398 if (stream->id==AUDIO_ID)
399 audio_bitrate += codec_rate;
400 else if (stream->id==VIDEO_ID)
401 video_bitrate += codec_rate;
402 }
403
404 if(ctx->mux_rate){
405 s->mux_rate= (ctx->mux_rate + (8 * 50) - 1) / (8 * 50);
406 } else {
407 /* we increase slightly the bitrate to take into account the
408 headers. XXX: compute it exactly */
409 bitrate += bitrate*5/100;
410 bitrate += 10000;
411 s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
412 }
413
414 if (s->is_vcd) {
415 double overhead_rate;
416
417 /* The VCD standard mandates that the mux_rate field is 3528
418 (see standard p. IV-6).
419 The value is actually "wrong", i.e. if you calculate
420 it using the normal formula and the 75 sectors per second transfer
421 rate you get a different value because the real pack size is 2324,
422 not 2352. But the standard explicitly specifies that the mux_rate
423 field in the header must have this value.*/
424 // s->mux_rate=2352 * 75 / 50; /* = 3528*/
425
426 /* The VCD standard states that the muxed stream must be
427 exactly 75 packs / second (the data rate of a single speed cdrom).
428 Since the video bitrate (probably 1150000 bits/sec) will be below
429 the theoretical maximum we have to add some padding packets
430 to make up for the lower data rate.
431 (cf. VCD standard p. IV-6 )*/
432
433 /* Add the header overhead to the data rate.
434 2279 data bytes per audio pack, 2294 data bytes per video pack*/
435 overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
436 overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
437 overhead_rate *= 8;
438
439 /* Add padding so that the full bitrate is 2324*75 bytes/sec */
440 s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
441 }
442
443 if (s->is_vcd || s->is_mpeg2)
444 /* every packet */
445 s->pack_header_freq = 1;
446 else
447 /* every 2 seconds */
448 s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
449
450 /* the above seems to make pack_header_freq zero sometimes */
451 if (s->pack_header_freq == 0)
452 s->pack_header_freq = 1;
453
454 if (s->is_mpeg2)
455 /* every 200 packets. Need to look at the spec. */
456 s->system_header_freq = s->pack_header_freq * 40;
457 else if (s->is_vcd)
458 /* the standard mandates that there are only two system headers
459 in the whole file: one in the first packet of each stream.
460 (see standard p. IV-7 and IV-8) */
461 s->system_header_freq = 0x7fffffff;
462 else
463 s->system_header_freq = s->pack_header_freq * 5;
464
465 for(i=0;i<ctx->nb_streams;i++) {
466 stream = ctx->streams[i]->priv_data;
467 stream->packet_number = 0;
468 }
469 s->system_header_size = get_system_header_size(ctx);
470 s->last_scr = 0;
471 return 0;
472 fail:
473 for(i=0;i<ctx->nb_streams;i++) {
474 av_free(ctx->streams[i]->priv_data);
475 }
476 return AVERROR(ENOMEM);
477 }
478
479 static inline void put_timestamp(ByteIOContext *pb, int id, int64_t timestamp)
480 {
481 put_byte(pb,
482 (id << 4) |
483 (((timestamp >> 30) & 0x07) << 1) |
484 1);
485 put_be16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
486 put_be16(pb, (uint16_t)((((timestamp) & 0x7fff) << 1) | 1));
487 }
488
489
490 /* return the number of padding bytes that should be inserted into
491 the multiplexed stream.*/
492 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
493 {
494 MpegMuxContext *s = ctx->priv_data;
495 int pad_bytes = 0;
496
497 if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
498 {
499 int64_t full_pad_bytes;
500
501 full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
502 pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
503
504 if (pad_bytes<0)
505 /* might happen if we have already padded to a later timestamp. This
506 can occur if another stream has already advanced further.*/
507 pad_bytes=0;
508 }
509
510 return pad_bytes;
511 }
512
513
514 #if 0 /* unused, remove? */
515 /* return the exact available payload size for the next packet for
516 stream 'stream_index'. 'pts' and 'dts' are only used to know if
517 timestamps are needed in the packet header. */
518 static int get_packet_payload_size(AVFormatContext *ctx, int stream_index,
519 int64_t pts, int64_t dts)
520 {
521 MpegMuxContext *s = ctx->priv_data;
522 int buf_index;
523 StreamInfo *stream;
524
525 stream = ctx->streams[stream_index]->priv_data;
526
527 buf_index = 0;
528 if (((s->packet_number % s->pack_header_freq) == 0)) {
529 /* pack header size */
530 if (s->is_mpeg2)
531 buf_index += 14;
532 else
533 buf_index += 12;
534
535 if (s->is_vcd) {
536 /* there is exactly one system header for each stream in a VCD MPEG,
537 One in the very first video packet and one in the very first
538 audio packet (see VCD standard p. IV-7 and IV-8).*/
539
540 if (stream->packet_number==0)
541 /* The system headers refer only to the stream they occur in,
542 so they have a constant size.*/
543 buf_index += 15;
544
545 } else {
546 if ((s->packet_number % s->system_header_freq) == 0)
547 buf_index += s->system_header_size;
548 }
549 }
550
551 if ((s->is_vcd && stream->packet_number==0)
552 || (s->is_svcd && s->packet_number==0))
553 /* the first pack of each stream contains only the pack header,
554 the system header and some padding (see VCD standard p. IV-6)
555 Add the padding size, so that the actual payload becomes 0.*/
556 buf_index += s->packet_size - buf_index;
557 else {
558 /* packet header size */
559 buf_index += 6;
560 if (s->is_mpeg2) {
561 buf_index += 3;
562 if (stream->packet_number==0)
563 buf_index += 3; /* PES extension */
564 buf_index += 1; /* obligatory stuffing byte */
565 }
566 if (pts != AV_NOPTS_VALUE) {
567 if (dts != pts)
568 buf_index += 5 + 5;
569 else
570 buf_index += 5;
571
572 } else {
573 if (!s->is_mpeg2)
574 buf_index++;
575 }
576
577 if (stream->id < 0xc0) {
578 /* AC3/LPCM private data header */
579 buf_index += 4;
580 if (stream->id >= 0xa0) {
581 int n;
582 buf_index += 3;
583 /* NOTE: we round the payload size to an integer number of
584 LPCM samples */
585 n = (s->packet_size - buf_index) % stream->lpcm_align;
586 if (n)
587 buf_index += (stream->lpcm_align - n);
588 }
589 }
590
591 if (s->is_vcd && stream->id == AUDIO_ID)
592 /* The VCD standard demands that 20 zero bytes follow
593 each audio packet (see standard p. IV-8).*/
594 buf_index+=20;
595 }
596 return s->packet_size - buf_index;
597 }
598 #endif
599
600 /* Write an MPEG padding packet header. */
601 static void put_padding_packet(AVFormatContext *ctx, ByteIOContext *pb,int packet_bytes)
602 {
603 MpegMuxContext *s = ctx->priv_data;
604 int i;
605
606 put_be32(pb, PADDING_STREAM);
607 put_be16(pb, packet_bytes - 6);
608 if (!s->is_mpeg2) {
609 put_byte(pb, 0x0f);
610 packet_bytes -= 7;
611 } else
612 packet_bytes -= 6;
613
614 for(i=0;i<packet_bytes;i++)
615 put_byte(pb, 0xff);
616 }
617
618 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
619 int nb_frames=0;
620 PacketDesc *pkt_desc= stream->premux_packet;
621
622 while(len>0){
623 if(pkt_desc->size == pkt_desc->unwritten_size)
624 nb_frames++;
625 len -= pkt_desc->unwritten_size;
626 pkt_desc= pkt_desc->next;
627 }
628
629 return nb_frames;
630 }
631
632 /* flush the packet on stream stream_index */
633 static int flush_packet(AVFormatContext *ctx, int stream_index,
634 int64_t pts, int64_t dts, int64_t scr, int trailer_size)
635 {
636 MpegMuxContext *s = ctx->priv_data;
637 StreamInfo *stream = ctx->streams[stream_index]->priv_data;
638 uint8_t *buf_ptr;
639 int size, payload_size, startcode, id, stuffing_size, i, header_len;
640 int packet_size;
641 uint8_t buffer[128];
642 int zero_trail_bytes = 0;
643 int pad_packet_bytes = 0;
644 int pes_flags;
645 int general_pack = 0; /*"general" pack without data specific to one stream?*/
646 int nb_frames;
647
648 id = stream->id;
649
650 #if 0
651 printf("packet ID=%2x PTS=%0.3f\n",
652 id, pts / 90000.0);
653 #endif
654
655 buf_ptr = buffer;
656
657 if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
658 /* output pack and systems header if needed */
659 size = put_pack_header(ctx, buf_ptr, scr);
660 buf_ptr += size;
661 s->last_scr= scr;
662
663 if (s->is_vcd) {
664 /* there is exactly one system header for each stream in a VCD MPEG,
665 One in the very first video packet and one in the very first
666 audio packet (see VCD standard p. IV-7 and IV-8).*/
667
668 if (stream->packet_number==0) {
669 size = put_system_header(ctx, buf_ptr, id);
670 buf_ptr += size;
671 }
672 } else if (s->is_dvd) {
673 if (stream->align_iframe || s->packet_number == 0){
674 int PES_bytes_to_fill = s->packet_size - size - 10;
675
676 if (pts != AV_NOPTS_VALUE) {
677 if (dts != pts)
678 PES_bytes_to_fill -= 5 + 5;
679 else
680 PES_bytes_to_fill -= 5;
681 }
682
683 if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
684 size = put_system_header(ctx, buf_ptr, 0);
685 buf_ptr += size;
686 size = buf_ptr - buffer;
687 put_buffer(&ctx->pb, buffer, size);
688
689 put_be32(&ctx->pb, PRIVATE_STREAM_2);
690 put_be16(&ctx->pb, 0x03d4); // length
691 put_byte(&ctx->pb, 0x00); // substream ID, 00=PCI
692 for (i = 0; i < 979; i++)
693 put_byte(&ctx->pb, 0x00);
694
695 put_be32(&ctx->pb, PRIVATE_STREAM_2);
696 put_be16(&ctx->pb, 0x03fa); // length
697 put_byte(&ctx->pb, 0x01); // substream ID, 01=DSI
698 for (i = 0; i < 1017; i++)
699 put_byte(&ctx->pb, 0x00);
700
701 memset(buffer, 0, 128);
702 buf_ptr = buffer;
703 s->packet_number++;
704 stream->align_iframe = 0;
705 scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
706 size = put_pack_header(ctx, buf_ptr, scr);
707 s->last_scr= scr;
708 buf_ptr += size;
709 /* GOP Start */
710 } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
711 pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
712 }
713 }
714 } else {
715 if ((s->packet_number % s->system_header_freq) == 0) {
716 size = put_system_header(ctx, buf_ptr, 0);
717 buf_ptr += size;
718 }
719 }
720 }
721 size = buf_ptr - buffer;
722 put_buffer(&ctx->pb, buffer, size);
723
724 packet_size = s->packet_size - size;
725
726 if (s->is_vcd && id == AUDIO_ID)
727 /* The VCD standard demands that 20 zero bytes follow
728 each audio pack (see standard p. IV-8).*/
729 zero_trail_bytes += 20;
730
731 if ((s->is_vcd && stream->packet_number==0)
732 || (s->is_svcd && s->packet_number==0)) {
733 /* for VCD the first pack of each stream contains only the pack header,
734 the system header and lots of padding (see VCD standard p. IV-6).
735 In the case of an audio pack, 20 zero bytes are also added at
736 the end.*/
737 /* For SVCD we fill the very first pack to increase compatibility with
738 some DVD players. Not mandated by the standard.*/
739 if (s->is_svcd)
740 general_pack = 1; /* the system header refers to both streams and no stream data*/
741 pad_packet_bytes = packet_size - zero_trail_bytes;
742 }
743
744 packet_size -= pad_packet_bytes + zero_trail_bytes;
745
746 if (packet_size > 0) {
747
748 /* packet header size */
749 packet_size -= 6;
750
751 /* packet header */
752 if (s->is_mpeg2) {
753 header_len = 3;
754 if (stream->packet_number==0)
755 header_len += 3; /* PES extension */
756 header_len += 1; /* obligatory stuffing byte */
757 } else {
758 header_len = 0;
759 }
760 if (pts != AV_NOPTS_VALUE) {
761 if (dts != pts)
762 header_len += 5 + 5;
763 else
764 header_len += 5;
765 } else {
766 if (!s->is_mpeg2)
767 header_len++;
768 }
769
770 payload_size = packet_size - header_len;
771 if (id < 0xc0) {
772 startcode = PRIVATE_STREAM_1;
773 payload_size -= 1;
774 if (id >= 0x40) {
775 payload_size -= 3;
776 if (id >= 0xa0)
777 payload_size -= 3;
778 }
779 } else {
780 startcode = 0x100 + id;
781 }
782
783 stuffing_size = payload_size - av_fifo_size(&stream->fifo);
784
785 // first byte does not fit -> reset pts/dts + stuffing
786 if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
787 int timestamp_len=0;
788 if(dts != pts)
789 timestamp_len += 5;
790 if(pts != AV_NOPTS_VALUE)
791 timestamp_len += s->is_mpeg2 ? 5 : 4;
792 pts=dts= AV_NOPTS_VALUE;
793 header_len -= timestamp_len;
794 if (s->is_dvd && stream->align_iframe) {
795 pad_packet_bytes += timestamp_len;
796 packet_size -= timestamp_len;
797 } else {
798 payload_size += timestamp_len;
799 }
800 stuffing_size += timestamp_len;
801 if(payload_size > trailer_size)
802 stuffing_size += payload_size - trailer_size;
803 }
804
805 if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
806 packet_size += pad_packet_bytes;
807 payload_size += pad_packet_bytes; // undo the previous adjustment
808 if (stuffing_size < 0) {
809 stuffing_size = pad_packet_bytes;
810 } else {
811 stuffing_size += pad_packet_bytes;
812 }
813 pad_packet_bytes = 0;
814 }
815
816 if (stuffing_size < 0)
817 stuffing_size = 0;
818 if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
819 pad_packet_bytes += stuffing_size;
820 packet_size -= stuffing_size;
821 payload_size -= stuffing_size;
822 stuffing_size = 0;
823 }
824
825 nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
826
827 put_be32(&ctx->pb, startcode);
828
829 put_be16(&ctx->pb, packet_size);
830
831 if (!s->is_mpeg2)
832 for(i=0;i<stuffing_size;i++)
833 put_byte(&ctx->pb, 0xff);
834
835 if (s->is_mpeg2) {
836 put_byte(&ctx->pb, 0x80); /* mpeg2 id */
837
838 pes_flags=0;
839
840 if (pts != AV_NOPTS_VALUE) {
841 pes_flags |= 0x80;
842 if (dts != pts)
843 pes_flags |= 0x40;
844 }
845
846 /* Both the MPEG-2 and the SVCD standards demand that the
847 P-STD_buffer_size field be included in the first packet of
848 every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
849 and MPEG-2 standard 2.7.7) */
850 if (stream->packet_number == 0)
851 pes_flags |= 0x01;
852
853 put_byte(&ctx->pb, pes_flags); /* flags */
854 put_byte(&ctx->pb, header_len - 3 + stuffing_size);
855
856 if (pes_flags & 0x80) /*write pts*/
857 put_timestamp(&ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
858 if (pes_flags & 0x40) /*write dts*/
859 put_timestamp(&ctx->pb, 0x01, dts);
860
861 if (pes_flags & 0x01) { /*write pes extension*/
862 put_byte(&ctx->pb, 0x10); /* flags */
863
864 /* P-STD buffer info */
865 if (id == AUDIO_ID)
866 put_be16(&ctx->pb, 0x4000 | stream->max_buffer_size/128);
867 else
868 put_be16(&ctx->pb, 0x6000 | stream->max_buffer_size/1024);
869 }
870
871 } else {
872 if (pts != AV_NOPTS_VALUE) {
873 if (dts != pts) {
874 put_timestamp(&ctx->pb, 0x03, pts);
875 put_timestamp(&ctx->pb, 0x01, dts);
876 } else {
877 put_timestamp(&ctx->pb, 0x02, pts);
878 }
879 } else {
880 put_byte(&ctx->pb, 0x0f);
881 }
882 }
883
884 if (s->is_mpeg2) {
885 /* special stuffing byte that is always written
886 to prevent accidental generation of start codes. */
887 put_byte(&ctx->pb, 0xff);
888
889 for(i=0;i<stuffing_size;i++)
890 put_byte(&ctx->pb, 0xff);
891 }
892
893 if (startcode == PRIVATE_STREAM_1) {
894 put_byte(&ctx->pb, id);
895 if (id >= 0xa0) {
896 /* LPCM (XXX: check nb_frames) */
897 put_byte(&ctx->pb, 7);
898 put_be16(&ctx->pb, 4); /* skip 3 header bytes */
899 put_byte(&ctx->pb, stream->lpcm_header[0]);
900 put_byte(&ctx->pb, stream->lpcm_header[1]);
901 put_byte(&ctx->pb, stream->lpcm_header[2]);
902 } else if (id >= 0x40) {
903 /* AC3 */
904 put_byte(&ctx->pb, nb_frames);
905 put_be16(&ctx->pb, trailer_size+1);
906 }
907 }
908
909 /* output data */
910 if(av_fifo_generic_read(&stream->fifo, payload_size - stuffing_size, &put_buffer, &ctx->pb) < 0)
911 return -1;
912 stream->bytes_to_iframe -= payload_size - stuffing_size;
913 }else{
914 payload_size=
915 stuffing_size= 0;
916 }
917
918 if (pad_packet_bytes > 0)
919 put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);
920
921 for(i=0;i<zero_trail_bytes;i++)
922 put_byte(&ctx->pb, 0x00);
923
924 put_flush_packet(&ctx->pb);
925
926 s->packet_number++;
927
928 /* only increase the stream packet number if this pack actually contains
929 something that is specific to this stream! I.e. a dedicated header
930 or some data.*/
931 if (!general_pack)
932 stream->packet_number++;
933
934 return payload_size - stuffing_size;
935 }
936
937 static void put_vcd_padding_sector(AVFormatContext *ctx)
938 {
939 /* There are two ways to do this padding: writing a sector/pack
940 of 0 values, or writing an MPEG padding pack. Both seem to
941 work with most decoders, BUT the VCD standard only allows a 0-sector
942 (see standard p. IV-4, IV-5).
943 So a 0-sector it is...*/
944
945 MpegMuxContext *s = ctx->priv_data;
946 int i;
947
948 for(i=0;i<s->packet_size;i++)
949 put_byte(&ctx->pb, 0);
950
951 s->vcd_padding_bytes_written += s->packet_size;
952
953 put_flush_packet(&ctx->pb);
954
955 /* increasing the packet number is correct. The SCR of the following packs
956 is calculated from the packet_number and it has to include the padding
957 sector (it represents the sector index, not the MPEG pack index)
958 (see VCD standard p. IV-6)*/
959 s->packet_number++;
960 }
961
962 #if 0 /* unused, remove? */
963 static int64_t get_vcd_scr(AVFormatContext *ctx,int stream_index,int64_t pts)
964 {
965 MpegMuxContext *s = ctx->priv_data;
966 int64_t scr;
967
968 /* Since the data delivery rate is constant, SCR is computed
969 using the formula C + i * 1200 where C is the start constant
970 and i is the pack index.
971 It is recommended that SCR 0 is at the beginning of the VCD front
972 margin (a sequence of empty Form 2 sectors on the CD).
973 It is recommended that the front margin is 30 sectors long, so
974 we use C = 30*1200 = 36000
975 (Note that even if the front margin is not 30 sectors the file
976 will still be correct according to the standard. It just won't have
977 the "recommended" value).*/
978 scr = 36000 + s->packet_number * 1200;
979
980 return scr;
981 }
982 #endif
983
984 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
985 // MpegMuxContext *s = ctx->priv_data;
986 int i;
987
988 for(i=0; i<ctx->nb_streams; i++){
989 AVStream *st = ctx->streams[i];
990 StreamInfo *stream = st->priv_data;
991 PacketDesc *pkt_desc;
992
993 while((pkt_desc= stream->predecode_packet)
994 && scr > pkt_desc->dts){ //FIXME > vs >=
995 if(stream->buffer_index < pkt_desc->size ||
996 stream->predecode_packet == stream->premux_packet){
997 av_log(ctx, AV_LOG_ERROR,
998 "buffer underflow i=%d bufi=%d size=%d\n",
999 i, stream->buffer_index, pkt_desc->size);
1000 break;
1001 }
1002 stream->buffer_index -= pkt_desc->size;
1003
1004 stream->predecode_packet= pkt_desc->next;
1005 av_freep(&pkt_desc);
1006 }
1007 }
1008
1009 return 0;
1010 }
1011
1012 static int output_packet(AVFormatContext *ctx, int flush){
1013 MpegMuxContext *s = ctx->priv_data;
1014 AVStream *st;
1015 StreamInfo *stream;
1016 int i, avail_space, es_size, trailer_size;
1017 int best_i= -1;
1018 int best_score= INT_MIN;
1019 int ignore_constraints=0;
1020 int64_t scr= s->last_scr;
1021 PacketDesc *timestamp_packet;
1022 const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
1023
1024 retry:
1025 for(i=0; i<ctx->nb_streams; i++){
1026 AVStream *st = ctx->streams[i];
1027 StreamInfo *stream = st->priv_data;
1028 const int avail_data= av_fifo_size(&stream->fifo);
1029 const int space= stream->max_buffer_size - stream->buffer_index;
1030 int rel_space= 1024*space / stream->max_buffer_size;
1031 PacketDesc *next_pkt= stream->premux_packet;
1032
1033 /* for subtitle, a single PES packet must be generated,
1034 so we flush after every single subtitle packet */
1035 if(s->packet_size > avail_data && !flush
1036 && st->codec->codec_type != CODEC_TYPE_SUBTITLE)
1037 return 0;
1038 if(avail_data==0)
1039 continue;
1040 assert(avail_data>0);
1041
1042 if(space < s->packet_size && !ignore_constraints)
1043 continue;
1044
1045 if(next_pkt && next_pkt->dts - scr > max_delay)
1046 continue;
1047
1048 if(rel_space > best_score){
1049 best_score= rel_space;
1050 best_i = i;
1051 avail_space= space;
1052 }
1053 }
1054
1055 if(best_i < 0){
1056 int64_t best_dts= INT64_MAX;
1057
1058 for(i=0; i<ctx->nb_streams; i++){
1059 AVStream *st = ctx->streams[i];
1060 StreamInfo *stream = st->priv_data;
1061 PacketDesc *pkt_desc= stream->predecode_packet;
1062 if(pkt_desc && pkt_desc->dts < best_dts)
1063 best_dts= pkt_desc->dts;
1064 }
1065
1066 #if 0
1067 av_log(ctx, AV_LOG_DEBUG, "bumping scr, scr:%f, dts:%f\n",
1068 scr/90000.0, best_dts/90000.0);
1069 #endif
1070 if(best_dts == INT64_MAX)
1071 return 0;
1072
1073 if(scr >= best_dts+1 && !ignore_constraints){
1074 av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
1075 ignore_constraints= 1;
1076 }
1077 scr= FFMAX(best_dts+1, scr);
1078 if(remove_decoded_packets(ctx, scr) < 0)
1079 return -1;
1080 goto retry;
1081 }
1082
1083 assert(best_i >= 0);
1084
1085 st = ctx->streams[best_i];
1086 stream = st->priv_data;
1087
1088 assert(av_fifo_size(&stream->fifo) > 0);
1089
1090 assert(avail_space >= s->packet_size || ignore_constraints);
1091
1092 timestamp_packet= stream->premux_packet;
1093 if(timestamp_packet->unwritten_size == timestamp_packet->size){
1094 trailer_size= 0;
1095 }else{
1096 trailer_size= timestamp_packet->unwritten_size;
1097 timestamp_packet= timestamp_packet->next;
1098 }
1099
1100 if(timestamp_packet){
1101 //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);
1102 es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1103 }else{
1104 assert(av_fifo_size(&stream->fifo) == trailer_size);
1105 es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1106 }
1107
1108 if (s->is_vcd) {
1109 /* Write one or more padding sectors, if necessary, to reach
1110 the constant overall bitrate.*/
1111 int vcd_pad_bytes;
1112
1113 while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1114 put_vcd_padding_sector(ctx);
1115 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1116 }
1117 }
1118
1119 stream->buffer_index += es_size;
1120 s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1121
1122 while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1123 es_size -= stream->premux_packet->unwritten_size;
1124 stream->premux_packet= stream->premux_packet->next;
1125 }
1126 if(es_size)
1127 stream->premux_packet->unwritten_size -= es_size;
1128
1129 if(remove_decoded_packets(ctx, s->last_scr) < 0)
1130 return -1;
1131
1132 return 1;
1133 }
1134
1135 static int mpeg_mux_write_packet(AVFormatContext *ctx, AVPacket *pkt)
1136 {
1137 MpegMuxContext *s = ctx->priv_data;
1138 int stream_index= pkt->stream_index;
1139 int size= pkt->size;
1140 uint8_t *buf= pkt->data;
1141 AVStream *st = ctx->streams[stream_index];
1142 StreamInfo *stream = st->priv_data;
1143 int64_t pts, dts;
1144 PacketDesc *pkt_desc;
1145 const int preload= av_rescale(ctx->preload, 90000, AV_TIME_BASE);
1146 const int is_iframe = st->codec->codec_type == CODEC_TYPE_VIDEO && (pkt->flags & PKT_FLAG_KEY);
1147
1148 pts= pkt->pts;
1149 dts= pkt->dts;
1150
1151 if(pts != AV_NOPTS_VALUE) pts += preload;
1152 if(dts != AV_NOPTS_VALUE) dts += preload;
1153
1154 //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);
1155 if (!stream->premux_packet)
1156 stream->next_packet = &stream->premux_packet;
1157 *stream->next_packet=
1158 pkt_desc= av_mallocz(sizeof(PacketDesc));
1159 pkt_desc->pts= pts;
1160 pkt_desc->dts= dts;
1161 pkt_desc->unwritten_size=
1162 pkt_desc->size= size;
1163 if(!stream->predecode_packet)
1164 stream->predecode_packet= pkt_desc;
1165 stream->next_packet= &pkt_desc->next;
1166
1167 av_fifo_realloc(&stream->fifo, av_fifo_size(&stream->fifo) + size + 1);
1168
1169 if (s->is_dvd){
1170 if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1171 stream->bytes_to_iframe = av_fifo_size(&stream->fifo);
1172 stream->align_iframe = 1;
1173 stream->vobu_start_pts = pts;
1174 } else {
1175 stream->align_iframe = 0;
1176 }
1177 }
1178
1179 av_fifo_write(&stream->fifo, buf, size);
1180
1181 for(;;){
1182 int ret= output_packet(ctx, 0);
1183 if(ret<=0)
1184 return ret;
1185 }
1186 }
1187
1188 static int mpeg_mux_end(AVFormatContext *ctx)
1189 {
1190 // MpegMuxContext *s = ctx->priv_data;
1191 StreamInfo *stream;
1192 int i;
1193
1194 for(;;){
1195 int ret= output_packet(ctx, 1);
1196 if(ret<0)
1197 return ret;
1198 else if(ret==0)
1199 break;
1200 }
1201
1202 /* End header according to MPEG1 systems standard. We do not write
1203 it as it is usually not needed by decoders and because it
1204 complicates MPEG stream concatenation. */
1205 //put_be32(&ctx->pb, ISO_11172_END_CODE);
1206 //put_flush_packet(&ctx->pb);
1207
1208 for(i=0;i<ctx->nb_streams;i++) {
1209 stream = ctx->streams[i]->priv_data;
1210
1211 assert(av_fifo_size(&stream->fifo) == 0);
1212 av_fifo_free(&stream->fifo);
1213 }
1214 return 0;
1215 }
1216
1217 #ifdef CONFIG_MPEG1SYSTEM_MUXER
1218 AVOutputFormat mpeg1system_muxer = {
1219 "mpeg",
1220 "MPEG1 System format",
1221 "video/mpeg",
1222 "mpg,mpeg",
1223 sizeof(MpegMuxContext),
1224 CODEC_ID_MP2,
1225 CODEC_ID_MPEG1VIDEO,
1226 mpeg_mux_init,
1227 mpeg_mux_write_packet,
1228 mpeg_mux_end,
1229 };
1230 #endif
1231 #ifdef CONFIG_MPEG1VCD_MUXER
1232 AVOutputFormat mpeg1vcd_muxer = {
1233 "vcd",
1234 "MPEG1 System format (VCD)",
1235 "video/mpeg",
1236 NULL,
1237 sizeof(MpegMuxContext),
1238 CODEC_ID_MP2,
1239 CODEC_ID_MPEG1VIDEO,
1240 mpeg_mux_init,
1241 mpeg_mux_write_packet,
1242 mpeg_mux_end,
1243 };
1244 #endif
1245 #ifdef CONFIG_MPEG2VOB_MUXER
1246 AVOutputFormat mpeg2vob_muxer = {
1247 "vob",
1248 "MPEG2 PS format (VOB)",
1249 "video/mpeg",
1250 "vob",
1251 sizeof(MpegMuxContext),
1252 CODEC_ID_MP2,
1253 CODEC_ID_MPEG2VIDEO,
1254 mpeg_mux_init,
1255 mpeg_mux_write_packet,
1256 mpeg_mux_end,
1257 };
1258 #endif
1259
1260 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1261 #ifdef CONFIG_MPEG2SVCD_MUXER
1262 AVOutputFormat mpeg2svcd_muxer = {
1263 "svcd",
1264 "MPEG2 PS format (VOB)",
1265 "video/mpeg",
1266 "vob",
1267 sizeof(MpegMuxContext),
1268 CODEC_ID_MP2,
1269 CODEC_ID_MPEG2VIDEO,
1270 mpeg_mux_init,
1271 mpeg_mux_write_packet,
1272 mpeg_mux_end,
1273 };
1274 #endif
1275
1276 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1277 #ifdef CONFIG_MPEG2DVD_MUXER
1278 AVOutputFormat mpeg2dvd_muxer = {
1279 "dvd",
1280 "MPEG2 PS format (DVD VOB)",
1281 "video/mpeg",
1282 "dvd",
1283 sizeof(MpegMuxContext),
1284 CODEC_ID_MP2,
1285 CODEC_ID_MPEG2VIDEO,
1286 mpeg_mux_init,
1287 mpeg_mux_write_packet,
1288 mpeg_mux_end,
1289 };
1290 #endif