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  buf[4] = (size - 6) >> 8;
269  buf[5] = (size - 6) & 0xff;
270 
271  return size;
272 }
273 
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 
298 {
299  MpegMuxContext *s = ctx->priv_data;
300  int bitrate, i, mpa_id, mpv_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 = 0;
325 
327  s->vcd_padding_bitrate=0;
328 
329  s->audio_bound = 0;
330  s->video_bound = 0;
331  mpa_id = AUDIO_ID;
332  ac3_id = AC3_ID;
333  dts_id = DTS_ID;
334  mpv_id = VIDEO_ID;
335  mps_id = SUB_ID;
336  lpcm_id = LPCM_ID;
337  for(i=0;i<ctx->nb_streams;i++) {
338  st = ctx->streams[i];
339  stream = av_mallocz(sizeof(StreamInfo));
340  if (!stream)
341  goto fail;
342  st->priv_data = stream;
343 
344  avpriv_set_pts_info(st, 64, 1, 90000);
345 
346  switch(st->codec->codec_type) {
347  case AVMEDIA_TYPE_AUDIO:
348  if (st->codec->codec_id == AV_CODEC_ID_AC3) {
349  stream->id = ac3_id++;
350  } else if (st->codec->codec_id == AV_CODEC_ID_DTS) {
351  stream->id = dts_id++;
352  } else if (st->codec->codec_id == AV_CODEC_ID_PCM_S16BE) {
353  stream->id = lpcm_id++;
354  for(j = 0; j < 4; j++) {
355  if (lpcm_freq_tab[j] == st->codec->sample_rate)
356  break;
357  }
358  if (j == 4)
359  goto fail;
360  if (st->codec->channels > 8)
361  return -1;
362  stream->lpcm_header[0] = 0x0c;
363  stream->lpcm_header[1] = (st->codec->channels - 1) | (j << 4);
364  stream->lpcm_header[2] = 0x80;
365  stream->lpcm_align = st->codec->channels * 2;
366  } else {
367  stream->id = mpa_id++;
368  }
369 
370  /* This value HAS to be used for VCD (see VCD standard, p. IV-7).
371  Right now it is also used for everything else.*/
372  stream->max_buffer_size = 4 * 1024;
373  s->audio_bound++;
374  break;
375  case AVMEDIA_TYPE_VIDEO:
376  stream->id = mpv_id++;
377  if (st->codec->rc_buffer_size)
378  stream->max_buffer_size = 6*1024 + st->codec->rc_buffer_size/8;
379  else {
380  av_log(ctx, AV_LOG_WARNING, "VBV buffer size not set, muxing may fail\n");
381  stream->max_buffer_size = 230*1024; //FIXME this is probably too small as default
382  }
383  s->video_bound++;
384  break;
386  stream->id = mps_id++;
387  stream->max_buffer_size = 16 * 1024;
388  break;
389  default:
390  return -1;
391  }
392  stream->fifo= av_fifo_alloc(16);
393  if (!stream->fifo)
394  goto fail;
395  }
396  bitrate = 0;
397  audio_bitrate = 0;
398  video_bitrate = 0;
399  for(i=0;i<ctx->nb_streams;i++) {
400  int codec_rate;
401  st = ctx->streams[i];
402  stream = (StreamInfo*) st->priv_data;
403 
404  if(st->codec->rc_max_rate || stream->id==VIDEO_ID)
405  codec_rate= st->codec->rc_max_rate;
406  else
407  codec_rate= st->codec->bit_rate;
408 
409  if(!codec_rate)
410  codec_rate= (1<<21)*8*50/ctx->nb_streams;
411 
412  bitrate += codec_rate;
413 
414  if ((stream->id & 0xe0) == AUDIO_ID)
415  audio_bitrate += codec_rate;
416  else if (stream->id==VIDEO_ID)
417  video_bitrate += codec_rate;
418  }
419 
420  if (s->user_mux_rate) {
421  s->mux_rate = (s->user_mux_rate + (8 * 50) - 1) / (8 * 50);
422  } else {
423  /* we increase slightly the bitrate to take into account the
424  headers. XXX: compute it exactly */
425  bitrate += bitrate / 20;
426  bitrate += 10000;
427  s->mux_rate = (bitrate + (8 * 50) - 1) / (8 * 50);
428  }
429 
430  if (s->is_vcd) {
431  double overhead_rate;
432 
433  /* The VCD standard mandates that the mux_rate field is 3528
434  (see standard p. IV-6).
435  The value is actually "wrong", i.e. if you calculate
436  it using the normal formula and the 75 sectors per second transfer
437  rate you get a different value because the real pack size is 2324,
438  not 2352. But the standard explicitly specifies that the mux_rate
439  field in the header must have this value.*/
440 // s->mux_rate=2352 * 75 / 50; /* = 3528*/
441 
442  /* The VCD standard states that the muxed stream must be
443  exactly 75 packs / second (the data rate of a single speed cdrom).
444  Since the video bitrate (probably 1150000 bits/sec) will be below
445  the theoretical maximum we have to add some padding packets
446  to make up for the lower data rate.
447  (cf. VCD standard p. IV-6 )*/
448 
449  /* Add the header overhead to the data rate.
450  2279 data bytes per audio pack, 2294 data bytes per video pack*/
451  overhead_rate = ((audio_bitrate / 8.0) / 2279) * (2324 - 2279);
452  overhead_rate += ((video_bitrate / 8.0) / 2294) * (2324 - 2294);
453  overhead_rate *= 8;
454 
455  /* Add padding so that the full bitrate is 2324*75 bytes/sec */
456  s->vcd_padding_bitrate = 2324 * 75 * 8 - (bitrate + overhead_rate);
457  }
458 
459  if (s->is_vcd || s->is_mpeg2)
460  /* every packet */
461  s->pack_header_freq = 1;
462  else
463  /* every 2 seconds */
464  s->pack_header_freq = 2 * bitrate / s->packet_size / 8;
465 
466  /* the above seems to make pack_header_freq zero sometimes */
467  if (s->pack_header_freq == 0)
468  s->pack_header_freq = 1;
469 
470  if (s->is_mpeg2)
471  /* every 200 packets. Need to look at the spec. */
473  else if (s->is_vcd)
474  /* the standard mandates that there are only two system headers
475  in the whole file: one in the first packet of each stream.
476  (see standard p. IV-7 and IV-8) */
477  s->system_header_freq = 0x7fffffff;
478  else
480 
481  for(i=0;i<ctx->nb_streams;i++) {
482  stream = ctx->streams[i]->priv_data;
483  stream->packet_number = 0;
484  }
487  return 0;
488  fail:
489  for(i=0;i<ctx->nb_streams;i++) {
490  av_free(ctx->streams[i]->priv_data);
491  }
492  return AVERROR(ENOMEM);
493 }
494 
495 static inline void put_timestamp(AVIOContext *pb, int id, int64_t timestamp)
496 {
497  avio_w8(pb,
498  (id << 4) |
499  (((timestamp >> 30) & 0x07) << 1) |
500  1);
501  avio_wb16(pb, (uint16_t)((((timestamp >> 15) & 0x7fff) << 1) | 1));
502  avio_wb16(pb, (uint16_t)((((timestamp ) & 0x7fff) << 1) | 1));
503 }
504 
505 
506 /* return the number of padding bytes that should be inserted into
507  the multiplexed stream.*/
508 static int get_vcd_padding_size(AVFormatContext *ctx, int64_t pts)
509 {
510  MpegMuxContext *s = ctx->priv_data;
511  int pad_bytes = 0;
512 
513  if (s->vcd_padding_bitrate > 0 && pts!=AV_NOPTS_VALUE)
514  {
515  int64_t full_pad_bytes;
516 
517  full_pad_bytes = (int64_t)((s->vcd_padding_bitrate * (pts / 90000.0)) / 8.0); //FIXME this is wrong
518  pad_bytes = (int) (full_pad_bytes - s->vcd_padding_bytes_written);
519 
520  if (pad_bytes<0)
521  /* might happen if we have already padded to a later timestamp. This
522  can occur if another stream has already advanced further.*/
523  pad_bytes=0;
524  }
525 
526  return pad_bytes;
527 }
528 
529 
530 /* Write an MPEG padding packet header. */
531 static void put_padding_packet(AVFormatContext *ctx, AVIOContext *pb,int packet_bytes)
532 {
533  MpegMuxContext *s = ctx->priv_data;
534  int i;
535 
537  avio_wb16(pb, packet_bytes - 6);
538  if (!s->is_mpeg2) {
539  avio_w8(pb, 0x0f);
540  packet_bytes -= 7;
541  } else
542  packet_bytes -= 6;
543 
544  for(i=0;i<packet_bytes;i++)
545  avio_w8(pb, 0xff);
546 }
547 
548 static int get_nb_frames(AVFormatContext *ctx, StreamInfo *stream, int len){
549  int nb_frames=0;
550  PacketDesc *pkt_desc= stream->premux_packet;
551 
552  while(len>0){
553  if(pkt_desc->size == pkt_desc->unwritten_size)
554  nb_frames++;
555  len -= pkt_desc->unwritten_size;
556  pkt_desc= pkt_desc->next;
557  }
558 
559  return nb_frames;
560 }
561 
562 /* flush the packet on stream stream_index */
563 static int flush_packet(AVFormatContext *ctx, int stream_index,
564  int64_t pts, int64_t dts, int64_t scr, int trailer_size)
565 {
566  MpegMuxContext *s = ctx->priv_data;
567  StreamInfo *stream = ctx->streams[stream_index]->priv_data;
568  uint8_t *buf_ptr;
569  int size, payload_size, startcode, id, stuffing_size, i, header_len;
570  int packet_size;
571  uint8_t buffer[128];
572  int zero_trail_bytes = 0;
573  int pad_packet_bytes = 0;
574  int pes_flags;
575  int general_pack = 0; /*"general" pack without data specific to one stream?*/
576  int nb_frames;
577 
578  id = stream->id;
579 
580  av_dlog(ctx, "packet ID=%2x PTS=%0.3f\n", id, pts / 90000.0);
581 
582  buf_ptr = buffer;
583 
584  if ((s->packet_number % s->pack_header_freq) == 0 || s->last_scr != scr) {
585  /* output pack and systems header if needed */
586  size = put_pack_header(ctx, buf_ptr, scr);
587  buf_ptr += size;
588  s->last_scr= scr;
589 
590  if (s->is_vcd) {
591  /* there is exactly one system header for each stream in a VCD MPEG,
592  One in the very first video packet and one in the very first
593  audio packet (see VCD standard p. IV-7 and IV-8).*/
594 
595  if (stream->packet_number==0) {
596  size = put_system_header(ctx, buf_ptr, id);
597  buf_ptr += size;
598  }
599  } else if (s->is_dvd) {
600  if (stream->align_iframe || s->packet_number == 0){
601  int PES_bytes_to_fill = s->packet_size - size - 10;
602 
603  if (pts != AV_NOPTS_VALUE) {
604  if (dts != pts)
605  PES_bytes_to_fill -= 5 + 5;
606  else
607  PES_bytes_to_fill -= 5;
608  }
609 
610  if (stream->bytes_to_iframe == 0 || s->packet_number == 0) {
611  size = put_system_header(ctx, buf_ptr, 0);
612  buf_ptr += size;
613  size = buf_ptr - buffer;
614  avio_write(ctx->pb, buffer, size);
615 
617  avio_wb16(ctx->pb, 0x03d4); // length
618  avio_w8(ctx->pb, 0x00); // substream ID, 00=PCI
619  for (i = 0; i < 979; i++)
620  avio_w8(ctx->pb, 0x00);
621 
623  avio_wb16(ctx->pb, 0x03fa); // length
624  avio_w8(ctx->pb, 0x01); // substream ID, 01=DSI
625  for (i = 0; i < 1017; i++)
626  avio_w8(ctx->pb, 0x00);
627 
628  memset(buffer, 0, 128);
629  buf_ptr = buffer;
630  s->packet_number++;
631  stream->align_iframe = 0;
632  scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
633  size = put_pack_header(ctx, buf_ptr, scr);
634  s->last_scr= scr;
635  buf_ptr += size;
636  /* GOP Start */
637  } else if (stream->bytes_to_iframe < PES_bytes_to_fill) {
638  pad_packet_bytes = PES_bytes_to_fill - stream->bytes_to_iframe;
639  }
640  }
641  } else {
642  if ((s->packet_number % s->system_header_freq) == 0) {
643  size = put_system_header(ctx, buf_ptr, 0);
644  buf_ptr += size;
645  }
646  }
647  }
648  size = buf_ptr - buffer;
649  avio_write(ctx->pb, buffer, size);
650 
651  packet_size = s->packet_size - size;
652 
653  if (s->is_vcd && (id & 0xe0) == AUDIO_ID)
654  /* The VCD standard demands that 20 zero bytes follow
655  each audio pack (see standard p. IV-8).*/
656  zero_trail_bytes += 20;
657 
658  if ((s->is_vcd && stream->packet_number==0)
659  || (s->is_svcd && s->packet_number==0)) {
660  /* for VCD the first pack of each stream contains only the pack header,
661  the system header and lots of padding (see VCD standard p. IV-6).
662  In the case of an audio pack, 20 zero bytes are also added at
663  the end.*/
664  /* For SVCD we fill the very first pack to increase compatibility with
665  some DVD players. Not mandated by the standard.*/
666  if (s->is_svcd)
667  general_pack = 1; /* the system header refers to both streams and no stream data*/
668  pad_packet_bytes = packet_size - zero_trail_bytes;
669  }
670 
671  packet_size -= pad_packet_bytes + zero_trail_bytes;
672 
673  if (packet_size > 0) {
674 
675  /* packet header size */
676  packet_size -= 6;
677 
678  /* packet header */
679  if (s->is_mpeg2) {
680  header_len = 3;
681  if (stream->packet_number==0)
682  header_len += 3; /* PES extension */
683  header_len += 1; /* obligatory stuffing byte */
684  } else {
685  header_len = 0;
686  }
687  if (pts != AV_NOPTS_VALUE) {
688  if (dts != pts)
689  header_len += 5 + 5;
690  else
691  header_len += 5;
692  } else {
693  if (!s->is_mpeg2)
694  header_len++;
695  }
696 
697  payload_size = packet_size - header_len;
698  if (id < 0xc0) {
699  startcode = PRIVATE_STREAM_1;
700  payload_size -= 1;
701  if (id >= 0x40) {
702  payload_size -= 3;
703  if (id >= 0xa0)
704  payload_size -= 3;
705  }
706  } else {
707  startcode = 0x100 + id;
708  }
709 
710  stuffing_size = payload_size - av_fifo_size(stream->fifo);
711 
712  // first byte does not fit -> reset pts/dts + stuffing
713  if(payload_size <= trailer_size && pts != AV_NOPTS_VALUE){
714  int timestamp_len=0;
715  if(dts != pts)
716  timestamp_len += 5;
717  if(pts != AV_NOPTS_VALUE)
718  timestamp_len += s->is_mpeg2 ? 5 : 4;
719  pts=dts= AV_NOPTS_VALUE;
720  header_len -= timestamp_len;
721  if (s->is_dvd && stream->align_iframe) {
722  pad_packet_bytes += timestamp_len;
723  packet_size -= timestamp_len;
724  } else {
725  payload_size += timestamp_len;
726  }
727  stuffing_size += timestamp_len;
728  if(payload_size > trailer_size)
729  stuffing_size += payload_size - trailer_size;
730  }
731 
732  if (pad_packet_bytes > 0 && pad_packet_bytes <= 7) { // can't use padding, so use stuffing
733  packet_size += pad_packet_bytes;
734  payload_size += pad_packet_bytes; // undo the previous adjustment
735  if (stuffing_size < 0) {
736  stuffing_size = pad_packet_bytes;
737  } else {
738  stuffing_size += pad_packet_bytes;
739  }
740  pad_packet_bytes = 0;
741  }
742 
743  if (stuffing_size < 0)
744  stuffing_size = 0;
745 
746  if (startcode == PRIVATE_STREAM_1 && id >= 0xa0) {
747  if (payload_size < av_fifo_size(stream->fifo))
748  stuffing_size += payload_size % stream->lpcm_align;
749  }
750 
751  if (stuffing_size > 16) { /*<=16 for MPEG-1, <=32 for MPEG-2*/
752  pad_packet_bytes += stuffing_size;
753  packet_size -= stuffing_size;
754  payload_size -= stuffing_size;
755  stuffing_size = 0;
756  }
757 
758  nb_frames= get_nb_frames(ctx, stream, payload_size - stuffing_size);
759 
760  avio_wb32(ctx->pb, startcode);
761 
762  avio_wb16(ctx->pb, packet_size);
763 
764  if (!s->is_mpeg2)
765  for(i=0;i<stuffing_size;i++)
766  avio_w8(ctx->pb, 0xff);
767 
768  if (s->is_mpeg2) {
769  avio_w8(ctx->pb, 0x80); /* mpeg2 id */
770 
771  pes_flags=0;
772 
773  if (pts != AV_NOPTS_VALUE) {
774  pes_flags |= 0x80;
775  if (dts != pts)
776  pes_flags |= 0x40;
777  }
778 
779  /* Both the MPEG-2 and the SVCD standards demand that the
780  P-STD_buffer_size field be included in the first packet of
781  every stream. (see SVCD standard p. 26 V.2.3.1 and V.2.3.2
782  and MPEG-2 standard 2.7.7) */
783  if (stream->packet_number == 0)
784  pes_flags |= 0x01;
785 
786  avio_w8(ctx->pb, pes_flags); /* flags */
787  avio_w8(ctx->pb, header_len - 3 + stuffing_size);
788 
789  if (pes_flags & 0x80) /*write pts*/
790  put_timestamp(ctx->pb, (pes_flags & 0x40) ? 0x03 : 0x02, pts);
791  if (pes_flags & 0x40) /*write dts*/
792  put_timestamp(ctx->pb, 0x01, dts);
793 
794  if (pes_flags & 0x01) { /*write pes extension*/
795  avio_w8(ctx->pb, 0x10); /* flags */
796 
797  /* P-STD buffer info */
798  if ((id & 0xe0) == AUDIO_ID)
799  avio_wb16(ctx->pb, 0x4000 | stream->max_buffer_size/ 128);
800  else
801  avio_wb16(ctx->pb, 0x6000 | stream->max_buffer_size/1024);
802  }
803 
804  } else {
805  if (pts != AV_NOPTS_VALUE) {
806  if (dts != pts) {
807  put_timestamp(ctx->pb, 0x03, pts);
808  put_timestamp(ctx->pb, 0x01, dts);
809  } else {
810  put_timestamp(ctx->pb, 0x02, pts);
811  }
812  } else {
813  avio_w8(ctx->pb, 0x0f);
814  }
815  }
816 
817  if (s->is_mpeg2) {
818  /* special stuffing byte that is always written
819  to prevent accidental generation of start codes. */
820  avio_w8(ctx->pb, 0xff);
821 
822  for(i=0;i<stuffing_size;i++)
823  avio_w8(ctx->pb, 0xff);
824  }
825 
826  if (startcode == PRIVATE_STREAM_1) {
827  avio_w8(ctx->pb, id);
828  if (id >= 0xa0) {
829  /* LPCM (XXX: check nb_frames) */
830  avio_w8(ctx->pb, 7);
831  avio_wb16(ctx->pb, 4); /* skip 3 header bytes */
832  avio_w8(ctx->pb, stream->lpcm_header[0]);
833  avio_w8(ctx->pb, stream->lpcm_header[1]);
834  avio_w8(ctx->pb, stream->lpcm_header[2]);
835  } else if (id >= 0x40) {
836  /* AC-3 */
837  avio_w8(ctx->pb, nb_frames);
838  avio_wb16(ctx->pb, trailer_size+1);
839  }
840  }
841 
842  /* output data */
843  assert(payload_size - stuffing_size <= av_fifo_size(stream->fifo));
844  av_fifo_generic_read(stream->fifo, ctx->pb, payload_size - stuffing_size, (void*)avio_write);
845  stream->bytes_to_iframe -= payload_size - stuffing_size;
846  }else{
847  payload_size=
848  stuffing_size= 0;
849  }
850 
851  if (pad_packet_bytes > 0)
852  put_padding_packet(ctx,ctx->pb, pad_packet_bytes);
853 
854  for(i=0;i<zero_trail_bytes;i++)
855  avio_w8(ctx->pb, 0x00);
856 
857  avio_flush(ctx->pb);
858 
859  s->packet_number++;
860 
861  /* only increase the stream packet number if this pack actually contains
862  something that is specific to this stream! I.e. a dedicated header
863  or some data.*/
864  if (!general_pack)
865  stream->packet_number++;
866 
867  return payload_size - stuffing_size;
868 }
869 
871 {
872  /* There are two ways to do this padding: writing a sector/pack
873  of 0 values, or writing an MPEG padding pack. Both seem to
874  work with most decoders, BUT the VCD standard only allows a 0-sector
875  (see standard p. IV-4, IV-5).
876  So a 0-sector it is...*/
877 
878  MpegMuxContext *s = ctx->priv_data;
879  int i;
880 
881  for(i=0;i<s->packet_size;i++)
882  avio_w8(ctx->pb, 0);
883 
885 
886  avio_flush(ctx->pb);
887 
888  /* increasing the packet number is correct. The SCR of the following packs
889  is calculated from the packet_number and it has to include the padding
890  sector (it represents the sector index, not the MPEG pack index)
891  (see VCD standard p. IV-6)*/
892  s->packet_number++;
893 }
894 
895 static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){
896 // MpegMuxContext *s = ctx->priv_data;
897  int i;
898 
899  for(i=0; i<ctx->nb_streams; i++){
900  AVStream *st = ctx->streams[i];
901  StreamInfo *stream = st->priv_data;
902  PacketDesc *pkt_desc;
903 
904  while((pkt_desc= stream->predecode_packet)
905  && scr > pkt_desc->dts){ //FIXME > vs >=
906  if(stream->buffer_index < pkt_desc->size ||
907  stream->predecode_packet == stream->premux_packet){
908  av_log(ctx, AV_LOG_ERROR,
909  "buffer underflow i=%d bufi=%d size=%d\n",
910  i, stream->buffer_index, pkt_desc->size);
911  break;
912  }
913  stream->buffer_index -= pkt_desc->size;
914 
915  stream->predecode_packet= pkt_desc->next;
916  av_freep(&pkt_desc);
917  }
918  }
919 
920  return 0;
921 }
922 
923 static int output_packet(AVFormatContext *ctx, int flush){
924  MpegMuxContext *s = ctx->priv_data;
925  AVStream *st;
926  StreamInfo *stream;
927  int i, avail_space=0, es_size, trailer_size;
928  int best_i= -1;
929  int best_score= INT_MIN;
930  int ignore_constraints=0;
931  int64_t scr= s->last_scr;
932  PacketDesc *timestamp_packet;
933  const int64_t max_delay= av_rescale(ctx->max_delay, 90000, AV_TIME_BASE);
934 
935 retry:
936  for(i=0; i<ctx->nb_streams; i++){
937  AVStream *st = ctx->streams[i];
938  StreamInfo *stream = st->priv_data;
939  const int avail_data= av_fifo_size(stream->fifo);
940  const int space= stream->max_buffer_size - stream->buffer_index;
941  int rel_space= 1024LL*space / stream->max_buffer_size;
942  PacketDesc *next_pkt= stream->premux_packet;
943 
944  /* for subtitle, a single PES packet must be generated,
945  so we flush after every single subtitle packet */
946  if(s->packet_size > avail_data && !flush
948  return 0;
949  if(avail_data==0)
950  continue;
951  assert(avail_data>0);
952 
953  if(space < s->packet_size && !ignore_constraints)
954  continue;
955 
956  if(next_pkt && next_pkt->dts - scr > max_delay)
957  continue;
958 
959  if(rel_space > best_score){
960  best_score= rel_space;
961  best_i = i;
962  avail_space= space;
963  }
964  }
965 
966  if(best_i < 0){
967  int64_t best_dts= INT64_MAX;
968 
969  for(i=0; i<ctx->nb_streams; i++){
970  AVStream *st = ctx->streams[i];
971  StreamInfo *stream = st->priv_data;
972  PacketDesc *pkt_desc= stream->predecode_packet;
973  if(pkt_desc && pkt_desc->dts < best_dts)
974  best_dts= pkt_desc->dts;
975  }
976 
977  av_dlog(ctx, "bumping scr, scr:%f, dts:%f\n",
978  scr / 90000.0, best_dts / 90000.0);
979  if(best_dts == INT64_MAX)
980  return 0;
981 
982  if(scr >= best_dts+1 && !ignore_constraints){
983  av_log(ctx, AV_LOG_ERROR, "packet too large, ignoring buffer limits to mux it\n");
984  ignore_constraints= 1;
985  }
986  scr= FFMAX(best_dts+1, scr);
987  if(remove_decoded_packets(ctx, scr) < 0)
988  return -1;
989  goto retry;
990  }
991 
992  assert(best_i >= 0);
993 
994  st = ctx->streams[best_i];
995  stream = st->priv_data;
996 
997  assert(av_fifo_size(stream->fifo) > 0);
998 
999  assert(avail_space >= s->packet_size || ignore_constraints);
1000 
1001  timestamp_packet= stream->premux_packet;
1002  if(timestamp_packet->unwritten_size == timestamp_packet->size){
1003  trailer_size= 0;
1004  }else{
1005  trailer_size= timestamp_packet->unwritten_size;
1006  timestamp_packet= timestamp_packet->next;
1007  }
1008 
1009  if(timestamp_packet){
1010  av_dlog(ctx, "dts:%f pts:%f scr:%f stream:%d\n",
1011  timestamp_packet->dts / 90000.0,
1012  timestamp_packet->pts / 90000.0,
1013  scr / 90000.0, best_i);
1014  es_size= flush_packet(ctx, best_i, timestamp_packet->pts, timestamp_packet->dts, scr, trailer_size);
1015  }else{
1016  assert(av_fifo_size(stream->fifo) == trailer_size);
1017  es_size= flush_packet(ctx, best_i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, scr, trailer_size);
1018  }
1019 
1020  if (s->is_vcd) {
1021  /* Write one or more padding sectors, if necessary, to reach
1022  the constant overall bitrate.*/
1023  int vcd_pad_bytes;
1024 
1025  while((vcd_pad_bytes = get_vcd_padding_size(ctx,stream->premux_packet->pts) ) >= s->packet_size){ //FIXME pts cannot be correct here
1027  s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1028  }
1029  }
1030 
1031  stream->buffer_index += es_size;
1032  s->last_scr += s->packet_size*90000LL / (s->mux_rate*50LL); //FIXME rounding and first few bytes of each packet
1033 
1034  while(stream->premux_packet && stream->premux_packet->unwritten_size <= es_size){
1035  es_size -= stream->premux_packet->unwritten_size;
1036  stream->premux_packet= stream->premux_packet->next;
1037  }
1038  if(es_size)
1039  stream->premux_packet->unwritten_size -= es_size;
1040 
1041  if(remove_decoded_packets(ctx, s->last_scr) < 0)
1042  return -1;
1043 
1044  return 1;
1045 }
1046 
1048 {
1049  MpegMuxContext *s = ctx->priv_data;
1050  int stream_index= pkt->stream_index;
1051  int size= pkt->size;
1052  uint8_t *buf= pkt->data;
1053  AVStream *st = ctx->streams[stream_index];
1054  StreamInfo *stream = st->priv_data;
1055  int64_t pts, dts;
1056  PacketDesc *pkt_desc;
1057  int preload;
1058  const int is_iframe = st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (pkt->flags & AV_PKT_FLAG_KEY);
1059 
1060  preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1061 
1062  pts= pkt->pts;
1063  dts= pkt->dts;
1064 
1065  if (s->last_scr == AV_NOPTS_VALUE) {
1066  if (dts == AV_NOPTS_VALUE || (dts < preload && ctx->avoid_negative_ts) || s->is_dvd) {
1067  if (dts != AV_NOPTS_VALUE)
1068  s->preload += av_rescale(-dts, AV_TIME_BASE, 90000);
1069  s->last_scr = 0;
1070  } else {
1071  s->last_scr = dts - preload;
1072  s->preload = 0;
1073  }
1074  preload = av_rescale(s->preload, 90000, AV_TIME_BASE);
1075  av_log(ctx, AV_LOG_DEBUG, "First SCR: %"PRId64" First DTS: %"PRId64"\n", s->last_scr, dts + preload);
1076  }
1077 
1078  if (dts != AV_NOPTS_VALUE) dts += preload;
1079  if (pts != AV_NOPTS_VALUE) pts += preload;
1080 
1081  av_dlog(ctx, "dts:%f pts:%f flags:%d stream:%d nopts:%d\n",
1082  dts / 90000.0, pts / 90000.0, pkt->flags,
1083  pkt->stream_index, pts != AV_NOPTS_VALUE);
1084  if (!stream->premux_packet)
1085  stream->next_packet = &stream->premux_packet;
1086  *stream->next_packet=
1087  pkt_desc= av_mallocz(sizeof(PacketDesc));
1088  pkt_desc->pts= pts;
1089  pkt_desc->dts= dts;
1090  pkt_desc->unwritten_size=
1091  pkt_desc->size= size;
1092  if(!stream->predecode_packet)
1093  stream->predecode_packet= pkt_desc;
1094  stream->next_packet= &pkt_desc->next;
1095 
1096  if (av_fifo_realloc2(stream->fifo, av_fifo_size(stream->fifo) + size) < 0)
1097  return -1;
1098 
1099  if (s->is_dvd){
1100  if (is_iframe && (s->packet_number == 0 || (pts - stream->vobu_start_pts >= 36000))) { // min VOBU length 0.4 seconds (mpucoder)
1101  stream->bytes_to_iframe = av_fifo_size(stream->fifo);
1102  stream->align_iframe = 1;
1103  stream->vobu_start_pts = pts;
1104  }
1105  }
1106 
1107  av_fifo_generic_write(stream->fifo, buf, size, NULL);
1108 
1109  for(;;){
1110  int ret= output_packet(ctx, 0);
1111  if(ret<=0)
1112  return ret;
1113  }
1114 }
1115 
1117 {
1118 // MpegMuxContext *s = ctx->priv_data;
1119  StreamInfo *stream;
1120  int i;
1121 
1122  for(;;){
1123  int ret= output_packet(ctx, 1);
1124  if(ret<0)
1125  return ret;
1126  else if(ret==0)
1127  break;
1128  }
1129 
1130  /* End header according to MPEG1 systems standard. We do not write
1131  it as it is usually not needed by decoders and because it
1132  complicates MPEG stream concatenation. */
1133  //avio_wb32(ctx->pb, ISO_11172_END_CODE);
1134  //avio_flush(ctx->pb);
1135 
1136  for(i=0;i<ctx->nb_streams;i++) {
1137  stream = ctx->streams[i]->priv_data;
1138 
1139  assert(av_fifo_size(stream->fifo) == 0);
1140  av_fifo_free(stream->fifo);
1141  }
1142  return 0;
1143 }
1144 
1145 #define OFFSET(x) offsetof(MpegMuxContext, x)
1146 #define E AV_OPT_FLAG_ENCODING_PARAM
1147 static const AVOption options[] = {
1148  { "muxrate", NULL, OFFSET(user_mux_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
1149  { "preload", "Initial demux-decode delay in microseconds.", OFFSET(preload), AV_OPT_TYPE_INT, {.i64 = 500000}, 0, INT_MAX, E},
1150  { NULL },
1151 };
1152 
1153 #define MPEGENC_CLASS(flavor)\
1154 static const AVClass flavor ## _class = {\
1155  .class_name = #flavor " muxer",\
1156  .item_name = av_default_item_name,\
1157  .version = LIBAVUTIL_VERSION_INT,\
1158  .option = options,\
1159 };
1160 
1161 #if CONFIG_MPEG1SYSTEM_MUXER
1162 MPEGENC_CLASS(mpeg)
1163 AVOutputFormat ff_mpeg1system_muxer = {
1164  .name = "mpeg",
1165  .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream"),
1166  .mime_type = "video/mpeg",
1167  .extensions = "mpg,mpeg",
1168  .priv_data_size = sizeof(MpegMuxContext),
1169  .audio_codec = AV_CODEC_ID_MP2,
1170  .video_codec = AV_CODEC_ID_MPEG1VIDEO,
1174  .priv_class = &mpeg_class,
1175 };
1176 #endif
1177 #if CONFIG_MPEG1VCD_MUXER
1178 MPEGENC_CLASS(vcd)
1179 AVOutputFormat ff_mpeg1vcd_muxer = {
1180  .name = "vcd",
1181  .long_name = NULL_IF_CONFIG_SMALL("MPEG-1 Systems / MPEG program stream (VCD)"),
1182  .mime_type = "video/mpeg",
1183  .priv_data_size = sizeof(MpegMuxContext),
1184  .audio_codec = AV_CODEC_ID_MP2,
1185  .video_codec = AV_CODEC_ID_MPEG1VIDEO,
1189  .priv_class = &vcd_class,
1190 };
1191 #endif
1192 #if CONFIG_MPEG2VOB_MUXER
1193 MPEGENC_CLASS(vob)
1194 AVOutputFormat ff_mpeg2vob_muxer = {
1195  .name = "vob",
1196  .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (VOB)"),
1197  .mime_type = "video/mpeg",
1198  .extensions = "vob",
1199  .priv_data_size = sizeof(MpegMuxContext),
1200  .audio_codec = AV_CODEC_ID_MP2,
1201  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1205  .priv_class = &vob_class,
1206 };
1207 #endif
1208 
1209 /* Same as mpeg2vob_mux except that the pack size is 2324 */
1210 #if CONFIG_MPEG2SVCD_MUXER
1211 MPEGENC_CLASS(svcd)
1212 AVOutputFormat ff_mpeg2svcd_muxer = {
1213  .name = "svcd",
1214  .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (SVCD)"),
1215  .mime_type = "video/mpeg",
1216  .extensions = "vob",
1217  .priv_data_size = sizeof(MpegMuxContext),
1218  .audio_codec = AV_CODEC_ID_MP2,
1219  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1223  .priv_class = &svcd_class,
1224 };
1225 #endif
1226 
1227 /* Same as mpeg2vob_mux except the 'is_dvd' flag is set to produce NAV pkts */
1228 #if CONFIG_MPEG2DVD_MUXER
1229 MPEGENC_CLASS(dvd)
1230 AVOutputFormat ff_mpeg2dvd_muxer = {
1231  .name = "dvd",
1232  .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 PS (DVD VOB)"),
1233  .mime_type = "video/mpeg",
1234  .extensions = "dvd",
1235  .priv_data_size = sizeof(MpegMuxContext),
1236  .audio_codec = AV_CODEC_ID_MP2,
1237  .video_codec = AV_CODEC_ID_MPEG2VIDEO,
1241  .priv_class = &dvd_class,
1242 };
1243 #endif