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