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