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