ts.c
上传用户:riyaled888
上传日期:2009-03-27
资源大小:7338k
文件大小:68k
源码类别:

多媒体

开发平台:

MultiPlatform

  1. /*****************************************************************************
  2.  * ts.c: MPEG-II TS Muxer
  3.  *****************************************************************************
  4.  * Copyright (C) 2001, 2002 VideoLAN
  5.  * $Id: ts.c 9132 2004-11-04 13:02:38Z zorglub $
  6.  *
  7.  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
  8.  *          Eric Petit <titer@videolan.org>
  9.  *
  10.  * This program is free software; you can redistribute it and/or modify
  11.  * it under the terms of the GNU General Public License as published by
  12.  * the Free Software Foundation; either version 2 of the License, or
  13.  * (at your option) any later version.
  14.  *
  15.  * This program is distributed in the hope that it will be useful,
  16.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18.  * GNU General Public License for more details.
  19.  *
  20.  * You should have received a copy of the GNU General Public License
  21.  * along with this program; if not, write to the Free Software
  22.  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
  23.  *****************************************************************************/
  24. /*****************************************************************************
  25.  * Preamble
  26.  *****************************************************************************/
  27. #include <stdlib.h>
  28. #include <vlc/vlc.h>
  29. #include <vlc/input.h>
  30. #include <vlc/sout.h>
  31. #include "iso_lang.h"
  32. #include "bits.h"
  33. #include "pes.h"
  34. #include "csa.h"
  35. #ifdef HAVE_DVBPSI_DR_H
  36. #   include <dvbpsi/dvbpsi.h>
  37. #   include <dvbpsi/descriptor.h>
  38. #   include <dvbpsi/pat.h>
  39. #   include <dvbpsi/pmt.h>
  40. #   include <dvbpsi/dr.h>
  41. #   include <dvbpsi/psi.h>
  42. #else
  43. #   include "dvbpsi.h"
  44. #   include "descriptor.h"
  45. #   include "tables/pat.h"
  46. #   include "tables/pmt.h"
  47. #   include "descriptors/dr.h"
  48. #   include "psi.h"
  49. #endif
  50. /*
  51.  * TODO:
  52.  *  - check PCR frequency requirement
  53.  *  - check PAT/PMT  "        "
  54.  *  - check PCR/PCR "soft"
  55.  *  - check if "registration" descriptor : "AC-3" should be a program
  56.  *    descriptor or an es one. (xine want an es one)
  57.  *
  58.  *  - remove creation of PAT/PMT without dvbpsi
  59.  *  - ?
  60.  * FIXME:
  61.  *  - subtitle support is far from perfect. I expect some subtitles drop
  62.  *    if they arrive a bit late
  63.  *    (We cannot rely on the fact that the fifo should be full)
  64.  */
  65. /*****************************************************************************
  66.  * Module descriptor
  67.  *****************************************************************************/
  68. static int     Open   ( vlc_object_t * );
  69. static void    Close  ( vlc_object_t * );
  70. #define VPID_TEXT N_("Video PID")
  71. #define VPID_LONGTEXT N_("Assigns a fixed PID to the video stream. The PCR " 
  72.   "PID will automatically be the video.")
  73. #define APID_TEXT N_("Audio PID")
  74. #define APID_LONGTEXT N_("Assigns a fixed PID to the audio stream.")
  75. #define SPUPID_TEXT N_("SPU PID")
  76. #define SPUPID_LONGTEXT N_("Assigns a fixed PID to the SPU.")
  77. #define PMTPID_TEXT N_("PMT PID")
  78. #define PMTPID_LONGTEXT N_("Assings a fixed PID to the PMT")
  79. #define TSID_TEXT N_("TS ID")
  80. #define TSID_LONGTEXT N_("Assigns a fixed Transport Stream ID.")
  81. #define SHAPING_TEXT N_("Shaping delay (ms)")
  82. #define SHAPING_LONGTEXT N_("If enabled, the TS muxer will cut the " 
  83.   "stream in slices of the given duration, and ensure a constant bitrate " 
  84.   "between the two boundaries. This avoids having huge bitrate peaks for " 
  85.   "reference frames, in particular.")
  86. #define KEYF_TEXT N_("Use keyframes")
  87. #define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " 
  88.   "the TS muxer will place the boundaries at the end of I pictures. In " 
  89.   "that case, the shaping duration given by the user is a worse case " 
  90.   "used when no reference frame is available. This enhances the efficiency " 
  91.   "of the shaping algorithm, since I frames are usually the biggest " 
  92.   "frames in the stream.")
  93. #define PCR_TEXT N_("PCR delay (ms)")
  94. #define PCR_LONGTEXT N_("This option allows you to set at which interval " 
  95.   "PCRs (Program Clock Reference) will be sent. " 
  96.   "This value should be below 100ms. (default is 30)")
  97. #define BMIN_TEXT N_( "Minimum B (deprecated)")
  98. #define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )
  99. #define BMAX_TEXT N_( "Maximum B (deprecated)")
  100. #define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")
  101. #define DTS_TEXT N_("DTS delay (ms)")
  102. #define DTS_LONGTEXT N_("This option will delay the DTS (decoding time " 
  103.   "stamps) and PTS (presentation timestamps) of the data in the " 
  104.   "stream, compared to the PCRs. This allows for some buffering inside " 
  105.   "the client decoder.")
  106. #define ACRYPT_TEXT N_("Crypt audio")
  107. #define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
  108. #define CK_TEXT N_("CSA Key")
  109. #define CK_LONGTEXT N_("Defines the CSA encryption key. This must be a " 
  110.   "16 char string (8 hexadecimal bytes).")
  111. #define SOUT_CFG_PREFIX "sout-ts-"
  112. vlc_module_begin();
  113.     set_description( _("TS muxer (libdvbpsi)") );
  114.     set_capability( "sout mux", 120 );
  115.     add_shortcut( "ts" );
  116.     add_integer( SOUT_CFG_PREFIX "pid-video", 0, NULL,VPID_TEXT, VPID_LONGTEXT,
  117.                                   VLC_TRUE );
  118.     add_integer( SOUT_CFG_PREFIX "pid-audio", 0, NULL, APID_TEXT,
  119.                  APID_LONGTEXT, VLC_TRUE );
  120.     add_integer( SOUT_CFG_PREFIX "pid-spu", 0, NULL, SPUPID_TEXT,
  121.                  SPUPID_LONGTEXT, VLC_TRUE );
  122.     add_integer( SOUT_CFG_PREFIX "pid-pmt", 0, NULL, PMTPID_TEXT,
  123.                  PMTPID_LONGTEXT, VLC_TRUE );
  124.     add_integer( SOUT_CFG_PREFIX "tsid", 0, NULL, TSID_TEXT,
  125.                  TSID_LONGTEXT, VLC_TRUE );
  126.     add_integer( SOUT_CFG_PREFIX "shaping", 200, NULL,SHAPING_TEXT,
  127.                  SHAPING_LONGTEXT, VLC_TRUE );
  128.     add_bool( SOUT_CFG_PREFIX "use-key-frames", VLC_FALSE, NULL, KEYF_TEXT,
  129.               KEYF_LONGTEXT, VLC_TRUE );
  130.     add_integer( SOUT_CFG_PREFIX "pcr", 30, NULL, PCR_TEXT, PCR_LONGTEXT,
  131.                  VLC_TRUE );
  132.     add_integer( SOUT_CFG_PREFIX "bmin", 0, NULL, BMIN_TEXT, BMIN_LONGTEXT,
  133.                  VLC_TRUE );
  134.     add_integer( SOUT_CFG_PREFIX "bmax", 0, NULL, BMAX_TEXT, BMAX_LONGTEXT,
  135.                  VLC_TRUE );
  136.     add_integer( SOUT_CFG_PREFIX "dts-delay", 200, NULL, DTS_TEXT,
  137.                  DTS_LONGTEXT, VLC_TRUE );
  138.     add_bool( SOUT_CFG_PREFIX "crypt-audio", VLC_TRUE, NULL, ACRYPT_TEXT,
  139.               ACRYPT_LONGTEXT, VLC_TRUE );
  140.     add_string( SOUT_CFG_PREFIX "csa-ck", NULL, NULL, CK_TEXT, CK_LONGTEXT,
  141.                 VLC_TRUE );
  142.     set_callbacks( Open, Close );
  143. vlc_module_end();
  144. /*****************************************************************************
  145.  * Local data structures
  146.  *****************************************************************************/
  147. static const char *ppsz_sout_options[] = {
  148.     "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid", "shaping", "pcr",
  149.     "bmin", "bmax", "use-key-frames", "dts-delay", "csa-ck", "crypt-audio",
  150.     NULL
  151. };
  152. #define SOUT_BUFFER_FLAGS_PRIVATE_PCR  ( 1 << BLOCK_FLAG_PRIVATE_SHIFT )
  153. #define SOUT_BUFFER_FLAGS_PRIVATE_CSA  ( 2 << BLOCK_FLAG_PRIVATE_SHIFT )
  154. typedef struct
  155. {
  156.     int     i_depth;
  157.     block_t *p_first;
  158.     block_t **pp_last;
  159. } sout_buffer_chain_t;
  160. static inline void BufferChainInit  ( sout_buffer_chain_t *c )
  161. {
  162.     c->i_depth = 0;
  163.     c->p_first = NULL;
  164.     c->pp_last = &c->p_first;
  165. }
  166. static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
  167. {
  168.     *c->pp_last = b;
  169.     c->i_depth++;
  170.     while( b->p_next )
  171.     {
  172.         b = b->p_next;
  173.         c->i_depth++;
  174.     }
  175.     c->pp_last = &b->p_next;
  176. }
  177. static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
  178. {
  179.     block_t *b = c->p_first;
  180.     if( b )
  181.     {
  182.         c->i_depth--;
  183.         c->p_first = b->p_next;
  184.         if( c->p_first == NULL )
  185.         {
  186.             c->pp_last = &c->p_first;
  187.         }
  188.         b->p_next = NULL;
  189.     }
  190.     return b;
  191. }
  192. static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
  193. {
  194.     block_t *b = c->p_first;
  195.     return b;
  196. }
  197. static inline void BufferChainClean( sout_instance_t *p_sout,
  198.                                      sout_buffer_chain_t *c )
  199. {
  200.     block_t *b;
  201.     while( ( b = BufferChainGet( c ) ) )
  202.     {
  203.         block_Release( b );
  204.     }
  205.     BufferChainInit( c );
  206. }
  207. typedef struct ts_stream_t
  208. {
  209.     int             i_pid;
  210.     vlc_fourcc_t    i_codec;
  211.     int             i_stream_type;
  212.     int             i_stream_id;
  213.     int             i_continuity_counter;
  214.     /* to be used for carriege of DIV3 */
  215.     vlc_fourcc_t    i_bih_codec;
  216.     int             i_bih_width, i_bih_height;
  217.     /* Specific to mpeg4 in mpeg2ts */
  218.     int             i_es_id;
  219.     int             i_decoder_specific_info;
  220.     uint8_t         *p_decoder_specific_info;
  221.     /* language is iso639-2T */
  222.     uint8_t         lang[3];
  223.     sout_buffer_chain_t chain_pes;
  224.     mtime_t             i_pes_dts;
  225.     mtime_t             i_pes_length;
  226.     int                 i_pes_used;
  227.     vlc_bool_t          b_key_frame;
  228. } ts_stream_t;
  229. struct sout_mux_sys_t
  230. {
  231.     int             i_pcr_pid;
  232.     sout_input_t    *p_pcr_input;
  233.     int             i_audio_bound;
  234.     int             i_video_bound;
  235.     int             i_pid_video;
  236.     int             i_pid_audio;
  237.     int             i_pid_spu;
  238.     int             i_pid_free; // first usable pid
  239.     int             i_tsid;
  240.     int             i_pat_version_number;
  241.     ts_stream_t     pat;
  242.     int             i_pmt_version_number;
  243.     ts_stream_t     pmt;        // Up to now only one program
  244.     int             i_mpeg4_streams;
  245.     int             i_null_continuity_counter;  /* Needed ? */
  246.     /* for TS building */
  247.     int64_t             i_bitrate_min;
  248.     int64_t             i_bitrate_max;
  249.     int64_t             i_shaping_delay;
  250.     int64_t             i_pcr_delay;
  251.     int64_t             i_dts_delay;
  252.     vlc_bool_t          b_use_key_frames;
  253.     mtime_t             i_pcr;  /* last PCR emited */
  254.     csa_t               *csa;
  255.     vlc_bool_t          b_crypt_audio;
  256. };
  257. /* Reserve a pid and return it */
  258. static int  AllocatePID( sout_mux_sys_t *p_sys, int i_cat )
  259. {
  260.     int i_pid;
  261.     if ( i_cat == VIDEO_ES && p_sys->i_pid_video )
  262.     {
  263.         i_pid = p_sys->i_pid_video;
  264.         p_sys->i_pid_video = 0;
  265.     }
  266.     else if ( i_cat == AUDIO_ES && p_sys->i_pid_audio )
  267.     {
  268.         i_pid = p_sys->i_pid_audio;
  269.         p_sys->i_pid_audio = 0;
  270.     }
  271.     else if ( i_cat == SPU_ES && p_sys->i_pid_spu )
  272.     {
  273.         i_pid = p_sys->i_pid_spu;
  274.         p_sys->i_pid_spu = 0;
  275.     }
  276.     else
  277.     {
  278.         i_pid = ++p_sys->i_pid_free;
  279.     }
  280.     return i_pid;
  281. }
  282. /*****************************************************************************
  283.  * Local prototypes
  284.  *****************************************************************************/
  285. static int Control  ( sout_mux_t *, int, va_list );
  286. static int AddStream( sout_mux_t *, sout_input_t * );
  287. static int DelStream( sout_mux_t *, sout_input_t * );
  288. static int Mux      ( sout_mux_t * );
  289. static void TSSchedule  ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
  290.                           mtime_t i_pcr_length, mtime_t i_pcr_dts );
  291. static void TSDate      ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
  292.                           mtime_t i_pcr_length, mtime_t i_pcr_dts );
  293. static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
  294. static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
  295. static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream, vlc_bool_t b_pcr );
  296. static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
  297. static void PEStoTS  ( sout_instance_t *, sout_buffer_chain_t *, block_t *, ts_stream_t * );
  298. /*****************************************************************************
  299.  * Open:
  300.  *****************************************************************************/
  301. static int Open( vlc_object_t *p_this )
  302. {
  303.     sout_mux_t          *p_mux =(sout_mux_t*)p_this;
  304.     sout_mux_sys_t      *p_sys;
  305.     vlc_value_t         val;
  306.     msg_Dbg( p_mux, "Open" );
  307.     sout_CfgParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
  308.     p_sys = malloc( sizeof( sout_mux_sys_t ) );
  309.     p_mux->pf_control   = Control;
  310.     p_mux->pf_addstream = AddStream;
  311.     p_mux->pf_delstream = DelStream;
  312.     p_mux->pf_mux       = Mux;
  313.     p_mux->p_sys        = p_sys;
  314.     srand( (uint32_t)mdate() );
  315.     p_sys->i_audio_bound = 0;
  316.     p_sys->i_video_bound = 0;
  317.     p_sys->i_pat_version_number = rand() % 32;
  318.     p_sys->pat.i_pid = 0;
  319.     p_sys->pat.i_continuity_counter = 0;
  320.     var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
  321.     if ( val.i_int )
  322.         p_sys->i_tsid = val.i_int;
  323.     else
  324.         p_sys->i_tsid = rand() % 65536;
  325.     p_sys->i_pmt_version_number = rand() % 32;
  326.     p_sys->pmt.i_continuity_counter = 0;
  327.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
  328.     if (val.i_int )
  329.     {
  330.         p_sys->pmt.i_pid = val.i_int;
  331.     }
  332.     else
  333.     {
  334.        p_sys->pmt.i_pid = 0x42;
  335.     }
  336.     p_sys->i_pid_free = p_sys->pmt.i_pid + 1;
  337.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
  338.     p_sys->i_pid_video = val.i_int;
  339.     if ( p_sys->i_pid_video > p_sys->i_pid_free )
  340.     {
  341.         p_sys->i_pid_free = p_sys->i_pid_video + 1;
  342.     }
  343.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
  344.     p_sys->i_pid_audio = val.i_int;
  345.     if ( p_sys->i_pid_audio > p_sys->i_pid_free )
  346.     {
  347.         p_sys->i_pid_free = p_sys->i_pid_audio + 1;
  348.     }
  349.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
  350.     p_sys->i_pid_spu = val.i_int;
  351.     if ( p_sys->i_pid_spu > p_sys->i_pid_free )
  352.     {
  353.         p_sys->i_pid_free = p_sys->i_pid_spu + 1;
  354.     }
  355.     p_sys->i_pcr_pid = 0x1fff;
  356.     p_sys->p_pcr_input = NULL;
  357.     p_sys->i_mpeg4_streams = 0;
  358.     p_sys->i_null_continuity_counter = 0;
  359.     /* Allow to create constrained stream */
  360.     var_Get( p_mux, SOUT_CFG_PREFIX "bmin", &val );
  361.     p_sys->i_bitrate_min = val.i_int;
  362.     var_Get( p_mux, SOUT_CFG_PREFIX "bmax", &val );
  363.     p_sys->i_bitrate_max = val.i_int;
  364.     if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
  365.         p_sys->i_bitrate_min > p_sys->i_bitrate_max )
  366.     {
  367.         msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
  368.                  "disabling bitrate control" );
  369.         p_sys->i_bitrate_min = 0;
  370.         p_sys->i_bitrate_max = 0;
  371.     }
  372.     if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
  373.     {
  374.         msg_Err( p_mux, "bmin and bmax no more supported "
  375.                  "(if you need them report it)" );
  376.     }
  377.     var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
  378.     p_sys->i_shaping_delay = (int64_t)val.i_int * 1000;
  379.     if( p_sys->i_shaping_delay <= 0 )
  380.     {
  381.         msg_Err( p_mux,
  382.                  "invalid shaping ("I64Fd"ms) resetting to 200ms",
  383.                  p_sys->i_shaping_delay / 1000 );
  384.         p_sys->i_shaping_delay = 200000;
  385.     }
  386.     var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
  387.     p_sys->i_pcr_delay = (int64_t)val.i_int * 1000;
  388.     if( p_sys->i_pcr_delay <= 0 ||
  389.         p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
  390.     {
  391.         msg_Err( p_mux,
  392.                  "invalid pcr delay ("I64Fd"ms) resetting to 30ms",
  393.                  p_sys->i_pcr_delay / 1000 );
  394.         p_sys->i_pcr_delay = 30000;
  395.     }
  396.     var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
  397.     p_sys->i_dts_delay = (int64_t)val.i_int * 1000;
  398.     msg_Dbg( p_mux, "shaping="I64Fd" pcr="I64Fd" dts_delay="I64Fd,
  399.              p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );
  400.     var_Get( p_mux, SOUT_CFG_PREFIX "use-key-frames", &val );
  401.     p_sys->b_use_key_frames = val.b_bool;
  402.     /* for TS generation */
  403.     p_sys->i_pcr    = 0;
  404.     p_sys->csa      = NULL;
  405.     var_Get( p_mux, SOUT_CFG_PREFIX "csa-ck", &val );
  406.     if( val.psz_string )
  407.     {
  408.         char *psz = val.psz_string;
  409.         /* skip 0x */
  410.         if( psz[0] == '0' && ( psz[1] == 'x' || psz[1] == 'X' ) )
  411.         {
  412.             psz += 2;
  413.         }
  414.         if( strlen( psz ) != 16 )
  415.         {
  416.             msg_Dbg( p_mux, "invalid csa ck (it must be 16 chars long)" );
  417.         }
  418.         else
  419.         {
  420.             uint64_t i_ck = strtoull( psz, NULL, 16 );
  421.             uint8_t  ck[8];
  422.             int      i;
  423.             for( i = 0; i < 8; i++ )
  424.             {
  425.                 ck[i] = ( i_ck >> ( 56 - 8*i) )&0xff;
  426.             }
  427.             msg_Dbg( p_mux, "using CSA scrambling with ck=%x:%x:%x:%x:%x:%x:%x:%x",
  428.                      ck[0], ck[1], ck[2], ck[3], ck[4], ck[5], ck[6], ck[7] );
  429.             p_sys->csa = csa_New();
  430.             csa_SetCW( p_sys->csa, ck, ck );
  431.         }
  432.     }
  433.     if( val.psz_string ) free( val.psz_string );
  434.     var_Get( p_mux, SOUT_CFG_PREFIX "crypt-audio", &val );
  435.     p_sys->b_crypt_audio = val.b_bool;
  436.     return VLC_SUCCESS;
  437. }
  438. /*****************************************************************************
  439.  * Close:
  440.  *****************************************************************************/
  441. static void Close( vlc_object_t * p_this )
  442. {
  443.     sout_mux_t          *p_mux = (sout_mux_t*)p_this;
  444.     sout_mux_sys_t      *p_sys = p_mux->p_sys;
  445.     msg_Dbg( p_mux, "Close" );
  446.     if( p_sys->csa )
  447.     {
  448.         csa_Delete( p_sys->csa );
  449.     }
  450.     free( p_sys );
  451. }
  452. /*****************************************************************************
  453.  * Control:
  454.  *****************************************************************************/
  455. static int Control( sout_mux_t *p_mux, int i_query, va_list args )
  456. {
  457.     vlc_bool_t *pb_bool;
  458.     char **ppsz;
  459.    switch( i_query )
  460.    {
  461.        case MUX_CAN_ADD_STREAM_WHILE_MUXING:
  462.            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
  463.            *pb_bool = VLC_TRUE;
  464.            return VLC_SUCCESS;
  465.        case MUX_GET_ADD_STREAM_WAIT:
  466.            pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t * );
  467.            *pb_bool = VLC_FALSE;
  468.            return VLC_SUCCESS;
  469.        case MUX_GET_MIME:
  470.            ppsz = (char**)va_arg( args, char ** );
  471.            *ppsz = strdup( "video/mpeg" );  /* FIXME not sure */
  472.            return VLC_SUCCESS;
  473.         default:
  474.             return VLC_EGENERIC;
  475.    }
  476. }
  477. /*****************************************************************************
  478.  * AddStream: called for each stream addition
  479.  *****************************************************************************/
  480. static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
  481. {
  482.     sout_mux_sys_t      *p_sys = p_mux->p_sys;
  483.     ts_stream_t         *p_stream;
  484.     p_input->p_sys = p_stream = malloc( sizeof( ts_stream_t ) );
  485.     /* Init this new stream */
  486.     p_stream->i_pid = AllocatePID( p_sys, p_input->p_fmt->i_cat );
  487.     p_stream->i_codec = p_input->p_fmt->i_codec;
  488.     p_stream->i_continuity_counter    = 0;
  489.     p_stream->i_decoder_specific_info = 0;
  490.     p_stream->p_decoder_specific_info = NULL;
  491.     msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
  492.              (char*)&p_input->p_fmt->i_codec, p_stream->i_pid );
  493.     /* All others fields depand on codec */
  494.     switch( p_input->p_fmt->i_cat )
  495.     {
  496.         case VIDEO_ES:
  497.             switch( p_input->p_fmt->i_codec )
  498.             {
  499.                 case VLC_FOURCC( 'm', 'p','g', 'v' ):
  500.                     /* TODO: do we need to check MPEG-I/II ? */
  501.                     p_stream->i_stream_type = 0x02;
  502.                     p_stream->i_stream_id = 0xe0;
  503.                     break;
  504.                 case VLC_FOURCC( 'm', 'p','4', 'v' ):
  505.                     p_stream->i_stream_type = 0x10;
  506.                     p_stream->i_stream_id = 0xfa;
  507.                     p_sys->i_mpeg4_streams++;
  508.                     p_stream->i_es_id = p_stream->i_pid;
  509.                     break;
  510.                 case VLC_FOURCC( 'h', '2','6', '4' ):
  511.                     p_stream->i_stream_type = 0x1b;
  512.                     p_stream->i_stream_id = 0xe0;
  513.                     break;
  514.                 /* XXX dirty dirty but somebody want that:
  515.                  *     using crapy MS-codec XXX */
  516.                 /* I didn't want to do that :P */
  517.                 case VLC_FOURCC( 'H', '2', '6', '3' ):
  518.                 case VLC_FOURCC( 'I', '2', '6', '3' ):
  519.                 case VLC_FOURCC( 'W', 'M', 'V', '3' ):
  520.                 case VLC_FOURCC( 'W', 'M', 'V', '2' ):
  521.                 case VLC_FOURCC( 'W', 'M', 'V', '1' ):
  522.                 case VLC_FOURCC( 'D', 'I', 'V', '3' ):
  523.                 case VLC_FOURCC( 'D', 'I', 'V', '2' ):
  524.                 case VLC_FOURCC( 'D', 'I', 'V', '1' ):
  525.                 case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
  526.                     p_stream->i_stream_type = 0xa0; // private
  527.                     p_stream->i_stream_id = 0xa0;   // beurk
  528.                     p_stream->i_bih_codec  = p_input->p_fmt->i_codec;
  529.                     p_stream->i_bih_width  = p_input->p_fmt->video.i_width;
  530.                     p_stream->i_bih_height = p_input->p_fmt->video.i_height;
  531.                     break;
  532.                 default:
  533.                     free( p_stream );
  534.                     return VLC_EGENERIC;
  535.             }
  536.             p_sys->i_video_bound++;
  537.             break;
  538.         case AUDIO_ES:
  539.             switch( p_input->p_fmt->i_codec )
  540.             {
  541.                 case VLC_FOURCC( 'm', 'p','g', 'a' ):
  542.                     p_stream->i_stream_type =
  543.                         p_input->p_fmt->audio.i_rate >= 32000 ? 0x03 : 0x04;
  544.                     p_stream->i_stream_id = 0xc0;
  545.                     break;
  546.                 case VLC_FOURCC( 'a', '5','2', ' ' ):
  547.                     p_stream->i_stream_type = 0x81;
  548.                     p_stream->i_stream_id = 0xbd;
  549.                     break;
  550.                 case VLC_FOURCC( 'l', 'p','c', 'm' ):
  551.                     p_stream->i_stream_type = 0x83;
  552.                     p_stream->i_stream_id = 0xbd;
  553.                     break;
  554.                 case VLC_FOURCC( 'd', 't','s', ' ' ):
  555.                     p_stream->i_stream_type = 0x06;
  556.                     p_stream->i_stream_id = 0xbd;
  557.                     break;
  558.                 case VLC_FOURCC( 'm', 'p','4', 'a' ):
  559.                     p_stream->i_stream_type = 0x11;
  560.                     p_stream->i_stream_id = 0xfa;
  561.                     p_sys->i_mpeg4_streams++;
  562.                     p_stream->i_es_id = p_stream->i_pid;
  563.                     break;
  564.                 default:
  565.                     free( p_stream );
  566.                     return VLC_EGENERIC;
  567.             }
  568.             p_sys->i_audio_bound++;
  569.             break;
  570.         case SPU_ES:
  571.             switch( p_input->p_fmt->i_codec )
  572.             {
  573.                 case VLC_FOURCC( 's', 'p','u', ' ' ):
  574.                     p_stream->i_stream_type = 0x82;
  575.                     p_stream->i_stream_id = 0xbd;
  576.                     break;
  577.                 case VLC_FOURCC( 's', 'u','b', 't' ):
  578.                     p_stream->i_stream_type = 0x12;
  579.                     p_stream->i_stream_id = 0xfa;
  580.                     p_sys->i_mpeg4_streams++;
  581.                     p_stream->i_es_id = p_stream->i_pid;
  582.                     break;
  583.                 case VLC_FOURCC('d','v','b','s'):
  584.                     p_stream->i_stream_type = 0x06;
  585.                     p_stream->i_es_id = p_input->p_fmt->subs.dvb.i_id;
  586.                     p_stream->i_stream_id = 0xbd;
  587.                     break;
  588.                 case VLC_FOURCC('t','e','l','x'):
  589.                     p_stream->i_stream_type = 0x06;
  590.                     p_stream->i_stream_id = 0xbd; /* FIXME */
  591.                     break;
  592.                 default:
  593.                     free( p_stream );
  594.                     return VLC_EGENERIC;
  595.             }
  596.             break;
  597.         default:
  598.             free( p_stream );
  599.             return VLC_EGENERIC;
  600.     }
  601.     p_stream->lang[0] =
  602.     p_stream->lang[1] =
  603.     p_stream->lang[2] = '';
  604.     if( p_input->p_fmt->psz_language )
  605.     {
  606.         char *psz = p_input->p_fmt->psz_language;
  607.         const iso639_lang_t *pl = NULL;
  608.         if( strlen( psz ) == 2 )
  609.         {
  610.             pl = GetLang_1( psz );
  611.         }
  612.         else if( strlen( psz ) == 3 )
  613.         {
  614.             pl = GetLang_2B( psz );
  615.             if( !strcmp( pl->psz_iso639_1, "??" ) )
  616.             {
  617.                 pl = GetLang_2T( psz );
  618.             }
  619.         }
  620.         if( pl && strcmp( pl->psz_iso639_1, "??" ) )
  621.         {
  622.             p_stream->lang[0] = pl->psz_iso639_2T[0];
  623.             p_stream->lang[1] = pl->psz_iso639_2T[1];
  624.             p_stream->lang[2] = pl->psz_iso639_2T[2];
  625.             msg_Dbg( p_mux, "    - lang=%c%c%c",
  626.                      p_stream->lang[0], p_stream->lang[1], p_stream->lang[2] );
  627.         }
  628.     }
  629.     /* Copy extra data (VOL for MPEG-4 and extra BitMapInfoHeader for VFW */
  630.     p_stream->i_decoder_specific_info = p_input->p_fmt->i_extra;
  631.     if( p_stream->i_decoder_specific_info > 0 )
  632.     {
  633.         p_stream->p_decoder_specific_info =
  634.             malloc( p_stream->i_decoder_specific_info );
  635.         memcpy( p_stream->p_decoder_specific_info,
  636.                 p_input->p_fmt->p_extra,
  637.                 p_input->p_fmt->i_extra );
  638.     }
  639.     /* Create decoder specific info for subt */
  640.     if( p_stream->i_codec == VLC_FOURCC( 's', 'u','b', 't' ) )
  641.     {
  642.         uint8_t *p;
  643.         p_stream->i_decoder_specific_info = 55;
  644.         p_stream->p_decoder_specific_info = p =
  645.             malloc( p_stream->i_decoder_specific_info );
  646.         p[0] = 0x10;    /* textFormat, 0x10 for 3GPP TS 26.245 */
  647.         p[1] = 0x00;    /* flags: 1b: associated video info flag
  648.                                   3b: reserved
  649.                                   1b: duration flag
  650.                                   3b: reserved */
  651.         p[2] = 52;      /* remaining size */
  652.         p += 3;
  653.         p[0] = p[1] = p[2] = p[3] = 0; p+=4;    /* display flags */
  654.         *p++ = 0;  /* horizontal justification (-1: left, 0 center, 1 right) */
  655.         *p++ = 1;  /* vertical   justification (-1: top, 0 center, 1 bottom) */
  656.         p[0] = p[1] = p[2] = 0x00; p+=3;/* background rgb */
  657.         *p++ = 0xff;                    /* background a */
  658.         p[0] = p[1] = 0; p += 2;        /* text box top */
  659.         p[0] = p[1] = 0; p += 2;        /* text box left */
  660.         p[0] = p[1] = 0; p += 2;        /* text box bottom */
  661.         p[0] = p[1] = 0; p += 2;        /* text box right */
  662.         p[0] = p[1] = 0; p += 2;        /* start char */
  663.         p[0] = p[1] = 0; p += 2;        /* end char */
  664.         p[0] = p[1] = 0; p += 2;        /* default font id */
  665.         *p++ = 0;                       /* font style flags */
  666.         *p++ = 12;                      /* font size */
  667.         p[0] = p[1] = p[2] = 0x00; p+=3;/* foreground rgb */
  668.         *p++ = 0x00;                    /* foreground a */
  669.         p[0] = p[1] = p[2] = 0; p[3] = 22; p += 4;
  670.         memcpy( p, "ftab", 4 ); p += 4;
  671.         *p++ = 0; *p++ = 1;             /* entry count */
  672.         p[0] = p[1] = 0; p += 2;        /* font id */
  673.         *p++ = 9;                       /* font name length */
  674.         memcpy( p, "Helvetica", 9 );    /* font name */
  675.     }
  676.     /* Init pes chain */
  677.     BufferChainInit( &p_stream->chain_pes );
  678.     p_stream->i_pes_dts    = 0;
  679.     p_stream->i_pes_length = 0;
  680.     p_stream->i_pes_used   = 0;
  681.     p_stream->b_key_frame  = 0;
  682.     /* We only change PMT version (PAT isn't changed) */
  683.     p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;
  684.     /* Update pcr_pid */
  685.     if( p_input->p_fmt->i_cat != SPU_ES &&
  686.         ( p_sys->i_pcr_pid == 0x1fff || p_input->p_fmt->i_cat == VIDEO_ES ) )
  687.     {
  688.         if( p_sys->p_pcr_input )
  689.         {
  690.             /* There was already a PCR stream, so clean context */
  691.             /* FIXME */
  692.         }
  693.         p_sys->i_pcr_pid   = p_stream->i_pid;
  694.         p_sys->p_pcr_input = p_input;
  695.         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
  696.     }
  697.     return VLC_SUCCESS;
  698. }
  699. /*****************************************************************************
  700.  * DelStream: called before a stream deletion
  701.  *****************************************************************************/
  702. static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
  703. {
  704.     sout_mux_sys_t  *p_sys = p_mux->p_sys;
  705.     ts_stream_t     *p_stream;
  706.     vlc_value_t     val;
  707.     p_stream = (ts_stream_t*)p_input->p_sys;
  708.     msg_Dbg( p_mux, "removing input pid=%d", p_stream->i_pid );
  709.     if( p_sys->i_pcr_pid == p_stream->i_pid )
  710.     {
  711.         int i;
  712.         /* Find a new pcr stream (Prefer Video Stream) */
  713.         p_sys->i_pcr_pid = 0x1fff;
  714.         p_sys->p_pcr_input = NULL;
  715.         for( i = 0; i < p_mux->i_nb_inputs; i++ )
  716.         {
  717.             if( p_mux->pp_inputs[i] == p_input )
  718.             {
  719.                 continue;
  720.             }
  721.             if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
  722.             {
  723.                 p_sys->i_pcr_pid  =
  724.                     ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
  725.                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
  726.                 break;
  727.             }
  728.             else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
  729.                      p_sys->i_pcr_pid == 0x1fff )
  730.             {
  731.                 p_sys->i_pcr_pid  =
  732.                     ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
  733.                 p_sys->p_pcr_input= p_mux->pp_inputs[i];
  734.             }
  735.         }
  736.         if( p_sys->p_pcr_input )
  737.         {
  738.             /* Empty TS buffer */
  739.             /* FIXME */
  740.         }
  741.         msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
  742.     }
  743.     /* Empty all data in chain_pes */
  744.     BufferChainClean( p_mux->p_sout, &p_stream->chain_pes );
  745.     if( p_stream->p_decoder_specific_info )
  746.     {
  747.         free( p_stream->p_decoder_specific_info );
  748.     }
  749.     if( p_stream->i_stream_id == 0xfa ||
  750.         p_stream->i_stream_id == 0xfb ||
  751.         p_stream->i_stream_id == 0xfe )
  752.     {
  753.         p_sys->i_mpeg4_streams--;
  754.     }
  755.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
  756.     if( val.i_int > 0 )
  757.     {
  758.         int i_pid_video = val.i_int;
  759.         if ( i_pid_video == p_stream->i_pid )
  760.         {
  761.             p_sys->i_pid_video = i_pid_video;
  762.             msg_Dbg( p_mux, "freeing video PID %d", i_pid_video );
  763.         }
  764.     }
  765.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
  766.     if( val.i_int > 0 )
  767.     {
  768.         int i_pid_audio = val.i_int;
  769.         if ( i_pid_audio == p_stream->i_pid )
  770.         {
  771.             p_sys->i_pid_audio = i_pid_audio;
  772.             msg_Dbg( p_mux, "freeing audio PID %d", i_pid_audio );
  773.         }
  774.     }
  775.     var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
  776.     if( val.i_int > 0 )
  777.     {
  778.         int i_pid_spu = val.i_int;
  779.         if ( i_pid_spu == p_stream->i_pid )
  780.         {
  781.             p_sys->i_pid_spu = i_pid_spu;
  782.             msg_Dbg( p_mux, "freeing spu PID %d", i_pid_spu );
  783.         }
  784.     }
  785.     free( p_stream );
  786.     /* We only change PMT version (PAT isn't changed) */
  787.     p_sys->i_pmt_version_number++; p_sys->i_pmt_version_number %= 32;
  788.     return VLC_SUCCESS;
  789. }
  790. /*****************************************************************************
  791.  * Mux: Call each time there is new data for at least one stream
  792.  *****************************************************************************
  793.  *
  794.  *****************************************************************************/
  795. static int Mux( sout_mux_t *p_mux )
  796. {
  797.     sout_mux_sys_t  *p_sys = p_mux->p_sys;
  798.     ts_stream_t     *p_pcr_stream;
  799.     if( p_sys->i_pcr_pid == 0x1fff )
  800.     {
  801.         msg_Dbg( p_mux, "waiting for PCR streams" );
  802.         msleep( 1000 );
  803.         return VLC_SUCCESS;
  804.     }
  805.     p_pcr_stream = (ts_stream_t*)p_sys->p_pcr_input->p_sys;
  806.     for( ;; )
  807.     {
  808.         sout_buffer_chain_t chain_ts;
  809.         int                 i_packet_count;
  810.         int                 i_packet_pos;
  811.         mtime_t             i_pcr_dts;
  812.         mtime_t             i_pcr_length;
  813.         mtime_t             i_shaping_delay;
  814.         int i;
  815.         if( p_pcr_stream->b_key_frame )
  816.         {
  817.             i_shaping_delay = p_pcr_stream->i_pes_length;
  818.         }
  819.         else
  820.         {
  821.             i_shaping_delay = p_sys->i_shaping_delay;
  822.         }
  823.         /* 1: get enough PES packet for all input */
  824.         for( ;; )
  825.         {
  826.             vlc_bool_t b_ok = VLC_TRUE;
  827.             block_t *p_data;
  828.             /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
  829.             /* Accumulate enough data in all other stream ( >= length of pcr)*/
  830.             for( i = 0; i < p_mux->i_nb_inputs; i++ )
  831.             {
  832.                 sout_input_t *p_input = p_mux->pp_inputs[i];
  833.                 ts_stream_t *p_stream = (ts_stream_t*)p_input->p_sys;
  834.                 int64_t i_spu_delay = 0;
  835.                 if( ( p_stream == p_pcr_stream &&
  836.                       p_stream->i_pes_length < i_shaping_delay ) ||
  837.                     p_stream->i_pes_dts + p_stream->i_pes_length <
  838.                     p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
  839.                 {
  840.                     /* Need more data */
  841.                     if( p_input->p_fifo->i_depth <= 1 )
  842.                     {
  843.                         if( p_input->p_fmt->i_cat == AUDIO_ES ||
  844.                             p_input->p_fmt->i_cat == VIDEO_ES )
  845.                         {
  846.                             /* We need more data */
  847.                             return VLC_SUCCESS;
  848.                         }
  849.                         else if( p_input->p_fifo->i_depth <= 0 )
  850.                         {
  851.                             /* spu, only one packet is needed */
  852.                             continue;
  853.                         }
  854.                         else
  855.                         {
  856.                             /* Don't mux the SPU yet if it is too early */
  857.                             block_t *p_spu = block_FifoShow( p_input->p_fifo );
  858.                             i_spu_delay =
  859.                                 p_spu->i_dts - p_pcr_stream->i_pes_dts;
  860.                             if( i_spu_delay > i_shaping_delay &&
  861.                                 i_spu_delay < I64C(100000000) )
  862.                                 continue;
  863.                             if ( i_spu_delay >= I64C(100000000)
  864.                                   || i_spu_delay < 10000 )
  865.                             {
  866.                                 BufferChainClean( p_mux->p_sout,
  867.                                                   &p_stream->chain_pes );
  868.                                 p_stream->i_pes_dts = 0;
  869.                                 p_stream->i_pes_used = 0;
  870.                                 p_stream->i_pes_length = 0;
  871.                                 continue;
  872.                             }
  873.                         }
  874.                     }
  875.                     b_ok = VLC_FALSE;
  876.                     p_data = block_FifoGet( p_input->p_fifo );
  877.                     if( p_input->p_fifo->i_depth > 0 &&
  878.                         p_input->p_fmt->i_cat != SPU_ES )
  879.                     {
  880.                         block_t *p_next = block_FifoShow( p_input->p_fifo );
  881.                         p_data->i_length = p_next->i_dts - p_data->i_dts;
  882.                     }
  883.                     else
  884.                         p_data->i_length = 1000;
  885.                     if( ( p_pcr_stream->i_pes_dts > 0 &&
  886.                           p_data->i_dts - 10000000 > p_pcr_stream->i_pes_dts +
  887.                           p_pcr_stream->i_pes_length ) ||
  888.                         p_data->i_dts < p_stream->i_pes_dts ||
  889.                         ( p_stream->i_pes_dts > 0 &&
  890.                           p_input->p_fmt->i_cat != SPU_ES &&
  891.                           p_data->i_dts - 10000000 > p_stream->i_pes_dts +
  892.                           p_stream->i_pes_length ) )
  893.                     {
  894.                         msg_Warn( p_mux, "packet with too strange dts "
  895.                                   "(dts="I64Fd",old="I64Fd",pcr="I64Fd")",
  896.                                   p_data->i_dts, p_stream->i_pes_dts,
  897.                                   p_pcr_stream->i_pes_dts );
  898.                         block_Release( p_data );
  899.                         BufferChainClean( p_mux->p_sout,
  900.                                           &p_stream->chain_pes );
  901.                         p_stream->i_pes_dts = 0;
  902.                         p_stream->i_pes_used = 0;
  903.                         p_stream->i_pes_length = 0;
  904.                         if( p_input->p_fmt->i_cat != SPU_ES )
  905.                         {
  906.                             BufferChainClean( p_mux->p_sout,
  907.                                               &p_pcr_stream->chain_pes );
  908.                             p_pcr_stream->i_pes_dts = 0;
  909.                             p_pcr_stream->i_pes_used = 0;
  910.                             p_pcr_stream->i_pes_length = 0;
  911.                         }
  912.                     }
  913.                     else
  914.                     {
  915.                         int i_header_size = 0;
  916.                         int b_data_alignment = 0;
  917.                         if( p_input->p_fmt->i_cat == SPU_ES )
  918.                         {
  919.                             if( p_input->p_fmt->i_codec ==
  920.                                 VLC_FOURCC('s','u','b','t') )
  921.                             {
  922.                                 /* Prepend header */
  923.                                 p_data = block_Realloc( p_data, 2,
  924.                                                         p_data->i_buffer );
  925.                                 p_data->p_buffer[0] =
  926.                                     ( (p_data->i_buffer - 2) >> 8) & 0xff;
  927.                                 p_data->p_buffer[1] =
  928.                                     ( (p_data->i_buffer - 2)     ) & 0xff;
  929.                                 /* remove trailling  if any */
  930.                                 if( p_data->i_buffer > 2 &&
  931.                                     p_data->p_buffer[p_data->i_buffer -1] ==
  932.                                     '' )
  933.                                     p_data->i_buffer--;
  934.                                 /* Append a empty sub (sub text only) */
  935.                                 if( p_data->i_length > 0 &&
  936.                                     !( p_data->i_buffer == 1 &&
  937.                                        *p_data->p_buffer == ' ' ) )
  938.                                 {
  939.                                     block_t *p_spu = block_New( p_mux, 3 );
  940.                                     p_spu->i_dts = p_spu->i_pts =
  941.                                         p_data->i_dts + p_data->i_length;
  942.                                     p_spu->i_length = 1000;
  943.                                     p_spu->p_buffer[0] = 0;
  944.                                     p_spu->p_buffer[1] = 1;
  945.                                     p_spu->p_buffer[2] = ' ';
  946.                                     E_(EStoPES)( p_mux->p_sout, &p_spu, p_spu,
  947.                                                  p_input->p_fmt,
  948.                                                  p_stream->i_stream_id, 1,
  949.                                                  0, 0 );
  950.                                     p_data->p_next = p_spu;
  951.                                 }
  952.                             }
  953.                             else if( p_input->p_fmt->i_codec ==
  954.                                        VLC_FOURCC('t','e','l','x') )
  955.                             {
  956.                                 /* EN 300 472 */
  957.                                 i_header_size = 0x24;
  958.                                 b_data_alignment = 1;
  959.                             }
  960.                         }
  961.                         else if( p_data->i_length < 0 ||
  962.                                  p_data->i_length > 2000000 )
  963.                         {
  964.                             /* FIXME choose a better value, but anyway we
  965.                              * should never have to do that */
  966.                             p_data->i_length = 1000;
  967.                         }
  968.                         p_stream->i_pes_length += p_data->i_length;
  969.                         if( p_stream->i_pes_dts == 0 )
  970.                         {
  971.                             p_stream->i_pes_dts = p_data->i_dts;
  972.                         }
  973.                         /* Convert to pes */
  974.                         if( p_stream->i_stream_id == 0xa0 &&
  975.                             p_data->i_pts <= 0 )
  976.                         {
  977.                             /* XXX yes I know, it's awfull, but it's needed,
  978.                              * so don't remove it ... */
  979.                             p_data->i_pts = p_data->i_dts;
  980.                         }
  981.                         E_( EStoPES )( p_mux->p_sout, &p_data, p_data,
  982.                                        p_input->p_fmt, p_stream->i_stream_id,
  983.                                        1, b_data_alignment, i_header_size );
  984.                         BufferChainAppend( &p_stream->chain_pes, p_data );
  985.                         if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
  986.                             && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
  987.                             && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
  988.                             && (p_stream->i_pes_length > 400000) )
  989.                         {
  990.                             i_shaping_delay = p_stream->i_pes_length;
  991.                             p_stream->b_key_frame = 1;
  992.                         }
  993.                     }
  994.                 }
  995.             }
  996.             if( b_ok )
  997.             {
  998.                 break;
  999.             }
  1000.         }
  1001.         /* save */
  1002.         i_pcr_dts      = p_pcr_stream->i_pes_dts;
  1003.         i_pcr_length   = p_pcr_stream->i_pes_length;
  1004.         p_pcr_stream->b_key_frame = 0;
  1005.         /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
  1006.         /* 2: calculate non accurate total size of muxed ts */
  1007.         i_packet_count = 0;
  1008.         for( i = 0; i < p_mux->i_nb_inputs; i++ )
  1009.         {
  1010.             ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
  1011.             block_t *p_pes;
  1012.             /* False for pcr stream but it will be enough to do PCR algo */
  1013.             for( p_pes = p_stream->chain_pes.p_first; p_pes != NULL;
  1014.                  p_pes = p_pes->p_next )
  1015.             {
  1016.                 int i_size = p_pes->i_buffer;
  1017.                 if( p_pes->i_dts + p_pes->i_length >
  1018.                     p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
  1019.                 {
  1020.                     mtime_t i_frag = p_pcr_stream->i_pes_dts +
  1021.                         p_pcr_stream->i_pes_length - p_pes->i_dts;
  1022.                     if( i_frag < 0 )
  1023.                     {
  1024.                         /* Next stream */
  1025.                         break;
  1026.                     }
  1027.                     i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
  1028.                 }
  1029.                 i_packet_count += ( i_size + 183 ) / 184;
  1030.             }
  1031.         }
  1032.         /* add overhead for PCR (not really exact) */
  1033.         i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
  1034.         /* 3: mux PES into TS */
  1035.         BufferChainInit( &chain_ts );
  1036.         /* append PAT/PMT  -> FIXME with big pcr delay it won't have enough pat/pmt */
  1037.         GetPAT( p_mux, &chain_ts);
  1038.         GetPMT( p_mux, &chain_ts );
  1039.         i_packet_pos = 0;
  1040.         i_packet_count += chain_ts.i_depth;
  1041.         /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
  1042.         for( ;; )
  1043.         {
  1044.             int         i_stream;
  1045.             mtime_t     i_dts;
  1046.             ts_stream_t *p_stream;
  1047.             sout_input_t *p_input;
  1048.             block_t *p_ts;
  1049.             vlc_bool_t   b_pcr;
  1050.             /* Select stream (lowest dts) */
  1051.             for( i = 0, i_stream = -1, i_dts = 0; i < p_mux->i_nb_inputs; i++ )
  1052.             {
  1053.                 p_input = p_mux->pp_inputs[i];
  1054.                 p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
  1055.                 if( p_stream->i_pes_dts == 0 )
  1056.                 {
  1057.                     continue;
  1058.                 }
  1059.                 if( i_stream == -1 ||
  1060.                     p_stream->i_pes_dts < i_dts )
  1061.                 {
  1062.                     i_stream = i;
  1063.                     i_dts = p_stream->i_pes_dts;
  1064.                 }
  1065.             }
  1066.             if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
  1067.             {
  1068.                 break;
  1069.             }
  1070.             p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
  1071.             /* do we need to issue pcr */
  1072.             b_pcr = VLC_FALSE;
  1073.             if( p_stream == p_pcr_stream &&
  1074.                 i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
  1075.                 p_sys->i_pcr + p_sys->i_pcr_delay )
  1076.             {
  1077.                 b_pcr = VLC_TRUE;
  1078.                 p_sys->i_pcr = i_pcr_dts + i_packet_pos *
  1079.                     i_pcr_length / i_packet_count;
  1080.             }
  1081.             /* Build the TS packet */
  1082.             p_ts = TSNew( p_mux, p_stream, b_pcr );
  1083.             if( p_sys->csa != NULL &&
  1084.                  (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) )
  1085.             {
  1086.                 p_ts->i_flags |= SOUT_BUFFER_FLAGS_PRIVATE_CSA;
  1087.             }
  1088.             i_packet_pos++;
  1089.             /* */
  1090.             BufferChainAppend( &chain_ts, p_ts );
  1091.         }
  1092.         /* 4: date and send */
  1093.         TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
  1094.     }
  1095. }
  1096. static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
  1097.                         mtime_t i_pcr_length, mtime_t i_pcr_dts )
  1098. {
  1099.     sout_mux_sys_t  *p_sys = p_mux->p_sys;
  1100.     sout_buffer_chain_t new_chain;
  1101.     int i_packet_count = p_chain_ts->i_depth;
  1102.     int i;
  1103.     BufferChainInit( &new_chain );
  1104.     if ( i_pcr_length <= 0 )
  1105.     {
  1106.         i_pcr_length = i_packet_count;
  1107.     }
  1108.     for( i = 0; i < i_packet_count; i++ )
  1109.     {
  1110.         block_t *p_ts = BufferChainGet( p_chain_ts );
  1111.         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
  1112.         BufferChainAppend( &new_chain, p_ts );
  1113.         if( p_ts->i_dts &&
  1114.             p_ts->i_dts + p_sys->i_dts_delay * 2/3 < i_new_dts )
  1115.         {
  1116.             mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
  1117.             mtime_t i_cut_dts = p_ts->i_dts;
  1118.             p_ts = BufferChainPeek( p_chain_ts );
  1119.             i++;
  1120.             i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
  1121.             while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
  1122.             {
  1123.                 p_ts = BufferChainGet( p_chain_ts );
  1124.                 i_max_diff = i_new_dts - p_ts->i_dts;
  1125.                 i_cut_dts = p_ts->i_dts;
  1126.                 BufferChainAppend( &new_chain, p_ts );
  1127.                 p_ts = BufferChainPeek( p_chain_ts );
  1128.                 i++;
  1129.                 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
  1130.             }
  1131.             msg_Dbg( p_mux, "adjusting rate at "I64Fd"/"I64Fd" (%d/%d)",
  1132.                      i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
  1133.                      p_chain_ts->i_depth );
  1134.             if ( new_chain.i_depth )
  1135.                 TSDate( p_mux, &new_chain,
  1136.                         i_cut_dts - i_pcr_dts,
  1137.                         i_pcr_dts );
  1138.             if ( p_chain_ts->i_depth )
  1139.                 TSSchedule( p_mux,
  1140.                             p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
  1141.                             i_cut_dts );
  1142.             return;
  1143.         }
  1144.     }
  1145.     if ( new_chain.i_depth )
  1146.         TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
  1147. }
  1148. static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
  1149.                     mtime_t i_pcr_length, mtime_t i_pcr_dts )
  1150. {
  1151.     sout_mux_sys_t  *p_sys = p_mux->p_sys;
  1152.     int i_packet_count = p_chain_ts->i_depth;
  1153.     int i;
  1154.     if ( i_pcr_length / 1000 > 0 )
  1155.     {
  1156.         int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
  1157.                           / (uint64_t)(i_pcr_length / 1000);
  1158.         if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
  1159.         {
  1160.             msg_Warn( p_mux, "max bitrate exceeded at "I64Fd
  1161.                       " (%d bi/s for %d pkt in "I64Fd" us)",
  1162.                       i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
  1163.                       i_bitrate, i_packet_count, i_pcr_length);
  1164.         }
  1165. #if 0
  1166.         else
  1167.         {
  1168.             msg_Dbg( p_mux, "starting at "I64Fd
  1169.                      " (%d bi/s for %d packets in "I64Fd" us)",
  1170.                      i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
  1171.                      i_bitrate, i_packet_count, i_pcr_length);
  1172.         }
  1173. #endif
  1174.     }
  1175.     else
  1176.     {
  1177.         /* This shouldn't happen, but happens in some rare heavy load
  1178.          * and packet losses conditions. */
  1179.         i_pcr_length = i_packet_count;
  1180.     }
  1181.     /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
  1182.     for( i = 0; i < i_packet_count; i++ )
  1183.     {
  1184.         block_t *p_ts = BufferChainGet( p_chain_ts );
  1185.         mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
  1186.         p_ts->i_dts    = i_new_dts;
  1187.         p_ts->i_length = i_pcr_length / i_packet_count;
  1188.         if( p_ts->i_flags & SOUT_BUFFER_FLAGS_PRIVATE_PCR )
  1189.         {
  1190.             /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
  1191.             TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay );
  1192.         }
  1193.         if( p_ts->i_flags & SOUT_BUFFER_FLAGS_PRIVATE_CSA )
  1194.         {
  1195.             csa_Encrypt( p_sys->csa, p_ts->p_buffer, 0 );
  1196.         }
  1197.         /* latency */
  1198.         p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
  1199.         sout_AccessOutWrite( p_mux->p_access, p_ts );
  1200.     }
  1201. }
  1202. static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream,
  1203.                        vlc_bool_t b_pcr )
  1204. {
  1205.     block_t *p_pes = p_stream->chain_pes.p_first;
  1206.     block_t *p_ts;
  1207.     vlc_bool_t b_new_pes = VLC_FALSE;
  1208.     vlc_bool_t b_adaptation_field = VLC_FALSE;
  1209.     int        i_payload_max = 184 - ( b_pcr ? 8 : 0 );
  1210.     int        i_payload;
  1211.     if( p_stream->i_pes_used <= 0 )
  1212.     {
  1213.         b_new_pes = VLC_TRUE;
  1214.     }
  1215.     i_payload = __MIN( (int)p_pes->i_buffer - p_stream->i_pes_used,
  1216.                        i_payload_max );
  1217.     if( b_pcr || i_payload < i_payload_max )
  1218.     {
  1219.         b_adaptation_field = VLC_TRUE;
  1220.     }
  1221.     p_ts = block_New( p_mux, 188 );
  1222.     p_ts->i_dts = p_pes->i_dts;
  1223.     p_ts->p_buffer[0] = 0x47;
  1224.     p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
  1225.         ( ( p_stream->i_pid >> 8 )&0x1f );
  1226.     p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
  1227.     p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
  1228.         p_stream->i_continuity_counter;
  1229.     p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
  1230.     if( b_adaptation_field )
  1231.     {
  1232.         int i;
  1233.         if( b_pcr )
  1234.         {
  1235.             int     i_stuffing = i_payload_max - i_payload;
  1236.             p_ts->i_flags |= SOUT_BUFFER_FLAGS_PRIVATE_PCR;
  1237.             p_ts->p_buffer[4] = 7 + i_stuffing;
  1238.             p_ts->p_buffer[5] = 0x10;   /* flags */
  1239.             p_ts->p_buffer[6] = ( 0 )&0xff;
  1240.             p_ts->p_buffer[7] = ( 0 )&0xff;
  1241.             p_ts->p_buffer[8] = ( 0 )&0xff;
  1242.             p_ts->p_buffer[9] = ( 0 )&0xff;
  1243.             p_ts->p_buffer[10]= ( 0 )&0x80;
  1244.             p_ts->p_buffer[11]= 0;
  1245.             for( i = 12; i < 12 + i_stuffing; i++ )
  1246.             {
  1247.                 p_ts->p_buffer[i] = 0xff;
  1248.             }
  1249.         }
  1250.         else
  1251.         {
  1252.             int i_stuffing = i_payload_max - i_payload;
  1253.             p_ts->p_buffer[4] = i_stuffing - 1;
  1254.             if( i_stuffing > 1 )
  1255.             {
  1256.                 p_ts->p_buffer[5] = 0x00;
  1257.                 for( i = 6; i < 6 + i_stuffing - 2; i++ )
  1258.                 {
  1259.                     p_ts->p_buffer[i] = 0xff;
  1260.                 }
  1261.             }
  1262.         }
  1263.     }
  1264.     /* copy payload */
  1265.     memcpy( &p_ts->p_buffer[188 - i_payload],
  1266.             &p_pes->p_buffer[p_stream->i_pes_used], i_payload );
  1267.     p_stream->i_pes_used += i_payload;
  1268.     p_stream->i_pes_dts = p_pes->i_dts + p_pes->i_length *
  1269.         p_stream->i_pes_used / p_pes->i_buffer;
  1270.     p_stream->i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
  1271.     if( p_stream->i_pes_used >= (int)p_pes->i_buffer )
  1272.     {
  1273.         p_pes = BufferChainGet( &p_stream->chain_pes );
  1274.         block_Release( p_pes );
  1275.         p_pes = p_stream->chain_pes.p_first;
  1276.         if( p_pes )
  1277.         {
  1278.             p_stream->i_pes_dts    = p_pes->i_dts;
  1279.             p_stream->i_pes_length = 0;
  1280.             while( p_pes )
  1281.             {
  1282.                 p_stream->i_pes_length += p_pes->i_length;
  1283.                 p_pes = p_pes->p_next;
  1284.             }
  1285.         }
  1286.         else
  1287.         {
  1288.             p_stream->i_pes_dts = 0;
  1289.             p_stream->i_pes_length = 0;
  1290.         }
  1291.         p_stream->i_pes_used = 0;
  1292.     }
  1293.     return p_ts;
  1294. }
  1295. static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
  1296. {
  1297.     mtime_t i_pcr = 9 * i_dts / 100;
  1298.     p_ts->p_buffer[6]  = ( i_pcr >> 25 )&0xff;
  1299.     p_ts->p_buffer[7]  = ( i_pcr >> 17 )&0xff;
  1300.     p_ts->p_buffer[8]  = ( i_pcr >> 9  )&0xff;
  1301.     p_ts->p_buffer[9]  = ( i_pcr >> 1  )&0xff;
  1302.     p_ts->p_buffer[10]|= ( i_pcr << 7  )&0x80;
  1303. }
  1304. #if 0
  1305. static void TSSetConstraints( sout_mux_t *p_mux, sout_buffer_chain_t *c,
  1306.                               mtime_t i_length, int i_bitrate_min,
  1307.                               int i_bitrate_max )
  1308. {
  1309.     sout_mux_sys_t  *p_sys = p_mux->p_sys;
  1310.     sout_buffer_chain_t s = *c;
  1311.     int i_packets = 0;
  1312.     int i_packets_min = 0;
  1313.     int i_packets_max = 0;
  1314.     if( i_length <= 0 )
  1315.     {
  1316.         return;
  1317.     }
  1318.     i_packets     = c->i_depth;
  1319.     i_packets_min = ( (int64_t)i_bitrate_min * i_length / 8 / 1000000  + 187 ) / 188;
  1320.     i_packets_max = ( (int64_t)i_bitrate_max * i_length / 8 / 1000000  + 187 ) / 188;
  1321.     if( i_packets < i_packets_min && i_packets_min > 0 )
  1322.     {
  1323.         block_t *p_pk;
  1324.         int i_div = ( i_packets_min - i_packets ) / i_packets;
  1325.         int i_mod = ( i_packets_min - i_packets ) % i_packets;
  1326.         int i_rest = 0;
  1327.         /* We need to pad with null packets (pid=0x1fff)
  1328.          * We try to melt null packets with true packets */
  1329.         msg_Dbg( p_mux,
  1330.                  "packets=%d but min=%d -> adding %d packets of padding",
  1331.                  i_packets, i_packets_min, i_packets_min - i_packets );
  1332.         BufferChainInit( c );
  1333.         while( ( p_pk = BufferChainGet( &s ) ) )
  1334.         {
  1335.             int i, i_null;
  1336.             BufferChainAppend( c, p_pk );
  1337.             i_null = i_div + ( i_rest + i_mod ) / i_packets;
  1338.             for( i = 0; i < i_null; i++ )
  1339.             {
  1340.                 block_t *p_null;
  1341.                 p_null = sout_BufferNew( p_mux->p_sout, 188 );
  1342.                 p_null->p_buffer[0] = 0x47;
  1343.                 p_null->p_buffer[1] = 0x1f;
  1344.                 p_null->p_buffer[2] = 0xff;
  1345.                 p_null->p_buffer[3] = 0x10 | p_sys->i_null_continuity_counter;
  1346.                 memset( &p_null->p_buffer[4], 0, 184 );
  1347.                 p_sys->i_null_continuity_counter =
  1348.                     ( p_sys->i_null_continuity_counter + 1 ) % 16;
  1349.                 BufferChainAppend( c, p_null );
  1350.             }
  1351.             i_rest = ( i_rest + i_mod ) % i_packets;
  1352.         }
  1353.     }
  1354.     else if( i_packets > i_packets_max && i_packets_max > 0 )
  1355.     {
  1356.         block_t *p_pk;
  1357.         int           i;
  1358.         /* Arg, we need to drop packets, I don't do something clever (like
  1359.          * dropping complete pid, b frames, ... ), I just get the right amount
  1360.          * of packets and discard the others */
  1361.         msg_Warn( p_mux,
  1362.                   "packets=%d but max=%d -> removing %d packets -> stream broken",
  1363.                   i_packets, i_packets_max, i_packets - i_packets_max );
  1364.         BufferChainInit( c );
  1365.         for( i = 0; i < i_packets_max; i++ )
  1366.         {
  1367.             BufferChainAppend( c, BufferChainGet( &s ) );
  1368.         }
  1369.         while( ( p_pk = BufferChainGet( &s ) ) )
  1370.         {
  1371.             sout_BufferDelete( p_mux->p_sout, p_pk );
  1372.         }
  1373.     }
  1374. }
  1375. #endif
  1376. static void PEStoTS( sout_instance_t *p_sout,
  1377.                      sout_buffer_chain_t *c, block_t *p_pes,
  1378.                      ts_stream_t *p_stream )
  1379. {
  1380.     uint8_t *p_data;
  1381.     int     i_size;
  1382.     int     b_new_pes;
  1383.     /* get PES total size */
  1384.     i_size = p_pes->i_buffer;
  1385.     p_data = p_pes->p_buffer;
  1386.     b_new_pes = VLC_TRUE;
  1387.     for( ;; )
  1388.     {
  1389.         int           b_adaptation_field;
  1390.         int           i_copy;
  1391.         block_t *p_ts;
  1392.         p_ts = block_New( p_sout, 188 );
  1393.         /* write header
  1394.          * 8b   0x47    sync byte
  1395.          * 1b           transport_error_indicator
  1396.          * 1b           payload_unit_start
  1397.          * 1b           transport_priority
  1398.          * 13b          pid
  1399.          * 2b           transport_scrambling_control
  1400.          * 2b           if adaptation_field 0x03 else 0x01
  1401.          * 4b           continuity_counter
  1402.          */
  1403.         i_copy    = __MIN( i_size, 184 );
  1404.         b_adaptation_field = i_size < 184 ? VLC_TRUE : VLC_FALSE;
  1405.         p_ts->p_buffer[0] = 0x47;
  1406.         p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 )|
  1407.                             ( ( p_stream->i_pid >> 8 )&0x1f );
  1408.         p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
  1409.         p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 )|
  1410.                             p_stream->i_continuity_counter;
  1411.         b_new_pes = VLC_FALSE;
  1412.         p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
  1413.         if( b_adaptation_field )
  1414.         {
  1415.             int i_stuffing = 184 - i_copy;
  1416.             int i;
  1417.             p_ts->p_buffer[4] = i_stuffing - 1;
  1418.             if( i_stuffing > 1 )
  1419.             {
  1420.                 p_ts->p_buffer[5] = 0x00;
  1421.                 for( i = 6; i < 6 + i_stuffing - 2; i++ )
  1422.                 {
  1423.                     p_ts->p_buffer[i] = 0xff;
  1424.                 }
  1425.             }
  1426.         }
  1427.         /* copy payload */
  1428.         memcpy( &p_ts->p_buffer[188 - i_copy], p_data, i_copy );
  1429.         p_data += i_copy;
  1430.         i_size -= i_copy;
  1431.         BufferChainAppend( c, p_ts );
  1432.         if( i_size <= 0 )
  1433.         {
  1434.             block_t *p_next = p_pes->p_next;
  1435.             p_pes->p_next = NULL;
  1436.             block_Release( p_pes );
  1437.             if( p_next == NULL )
  1438.             {
  1439.                 break;
  1440.             }
  1441.             b_new_pes = VLC_TRUE;
  1442.             p_pes = p_next;
  1443.             i_size = p_pes->i_buffer;
  1444.             p_data = p_pes->p_buffer;
  1445.         }
  1446.     }
  1447.     return;
  1448. }
  1449. static block_t *WritePSISection( sout_instance_t *p_sout,
  1450.                                        dvbpsi_psi_section_t* p_section )
  1451. {
  1452.     block_t   *p_psi, *p_first = NULL;
  1453.     while( p_section )
  1454.     {
  1455.         int             i_size;
  1456.         i_size =  (uint32_t)( p_section->p_payload_end - p_section->p_data )+
  1457.                   ( p_section->b_syntax_indicator ? 4 : 0 );
  1458.         p_psi = block_New( p_sout, i_size + 1 );
  1459.         p_psi->i_pts = 0;
  1460.         p_psi->i_dts = 0;
  1461.         p_psi->i_length = 0;
  1462.         p_psi->i_buffer = i_size + 1;
  1463.         p_psi->p_buffer[0] = 0; // pointer
  1464.         memcpy( p_psi->p_buffer + 1,
  1465.                 p_section->p_data,
  1466.                 i_size );
  1467.         block_ChainAppend( &p_first, p_psi );
  1468.         p_section = p_section->p_next;
  1469.     }
  1470.     return( p_first );
  1471. }
  1472. static void GetPAT( sout_mux_t *p_mux,
  1473.                     sout_buffer_chain_t *c )
  1474. {
  1475.     sout_mux_sys_t       *p_sys = p_mux->p_sys;
  1476.     block_t        *p_pat;
  1477.     dvbpsi_pat_t         pat;
  1478.     dvbpsi_psi_section_t *p_section;
  1479.     dvbpsi_InitPAT( &pat, p_sys->i_tsid, p_sys->i_pat_version_number,
  1480.                     1 );      // b_current_next
  1481.     /* add all program (only one) */
  1482.     dvbpsi_PATAddProgram( &pat,
  1483.                           1,                    // i_number
  1484.                           p_sys->pmt.i_pid );   // i_pid
  1485.     p_section = dvbpsi_GenPATSections( &pat,
  1486.                                        0 );     // max program per section
  1487.     p_pat = WritePSISection( p_mux->p_sout, p_section );
  1488.     PEStoTS( p_mux->p_sout, c, p_pat, &p_sys->pat );
  1489.     dvbpsi_DeletePSISections( p_section );
  1490.     dvbpsi_EmptyPAT( &pat );
  1491. }
  1492. static uint32_t GetDescriptorLength24b( int i_length )
  1493. {
  1494.     uint32_t i_l1, i_l2, i_l3;
  1495.     i_l1 = i_length&0x7f;
  1496.     i_l2 = ( i_length >> 7 )&0x7f;
  1497.     i_l3 = ( i_length >> 14 )&0x7f;
  1498.     return( 0x808000 | ( i_l3 << 16 ) | ( i_l2 << 8 ) | i_l1 );
  1499. }
  1500. static void GetPMT( sout_mux_t *p_mux,
  1501.                     sout_buffer_chain_t *c )
  1502. {
  1503.     sout_mux_sys_t  *p_sys = p_mux->p_sys;
  1504.     block_t   *p_pmt;
  1505.     dvbpsi_pmt_t        pmt;
  1506.     dvbpsi_pmt_es_t     *p_es;
  1507.     dvbpsi_psi_section_t *p_section;
  1508.     int                 i_stream;
  1509.     dvbpsi_InitPMT( &pmt,
  1510.                     0x01,   // program number
  1511.                     p_sys->i_pmt_version_number,
  1512.                     1,      // b_current_next
  1513.                     p_sys->i_pcr_pid );
  1514.     if( p_sys->i_mpeg4_streams > 0 )
  1515.     {
  1516.         uint8_t iod[4096];
  1517.         bits_buffer_t bits;
  1518.         bits_buffer_t bits_fix_IOD;
  1519.         /* Make valgrind happy : it works at byte level not bit one so
  1520.          * bit_write confuse it (but DON'T CHANGE the way that bit_write is
  1521.          * working (needed when fixing some bits) */
  1522.         memset( iod, 0, 4096 );
  1523.         bits_initwrite( &bits, 4096, iod );
  1524.         // IOD_label
  1525.         bits_write( &bits, 8,   0x01 );
  1526.         // InitialObjectDescriptor
  1527.         bits_align( &bits );
  1528.         bits_write( &bits, 8,   0x02 );     // tag
  1529.         bits_fix_IOD = bits;    // save states to fix length later
  1530.         bits_write( &bits, 24,
  1531.             GetDescriptorLength24b( 0 ) ); // variable length (fixed later)
  1532.         bits_write( &bits, 10,  0x01 );     // ObjectDescriptorID
  1533.         bits_write( &bits, 1,   0x00 );     // URL Flag
  1534.         bits_write( &bits, 1,   0x00 );     // includeInlineProfileLevelFlag
  1535.         bits_write( &bits, 4,   0x0f );     // reserved
  1536.         bits_write( &bits, 8,   0xff );     // ODProfile (no ODcapability )
  1537.         bits_write( &bits, 8,   0xff );     // sceneProfile
  1538.         bits_write( &bits, 8,   0xfe );     // audioProfile (unspecified)
  1539.         bits_write( &bits, 8,   0xfe );     // visualProfile( // )
  1540.         bits_write( &bits, 8,   0xff );     // graphicProfile (no )
  1541.         for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
  1542.         {
  1543.             ts_stream_t *p_stream;
  1544.             p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
  1545.             if( p_stream->i_stream_id == 0xfa ||
  1546.                 p_stream->i_stream_id == 0xfb ||
  1547.                 p_stream->i_stream_id == 0xfe )
  1548.             {
  1549.                 bits_buffer_t bits_fix_ESDescr, bits_fix_Decoder;
  1550.                 /* ES descriptor */
  1551.                 bits_align( &bits );
  1552.                 bits_write( &bits, 8,   0x03 );     // ES_DescrTag
  1553.                 bits_fix_ESDescr = bits;
  1554.                 bits_write( &bits, 24,
  1555.                             GetDescriptorLength24b( 0 ) ); // variable size
  1556.                 bits_write( &bits, 16,  p_stream->i_es_id );
  1557.                 bits_write( &bits, 1,   0x00 );     // streamDependency
  1558.                 bits_write( &bits, 1,   0x00 );     // URL Flag
  1559.                 bits_write( &bits, 1,   0x00 );     // OCRStreamFlag
  1560.                 bits_write( &bits, 5,   0x1f );     // streamPriority
  1561.                 // DecoderConfigDesciptor
  1562.                 bits_align( &bits );
  1563.                 bits_write( &bits, 8,   0x04 ); // DecoderConfigDescrTag
  1564.                 bits_fix_Decoder = bits;
  1565.                 bits_write( &bits, 24,  GetDescriptorLength24b( 0 ) );
  1566.                 if( p_stream->i_stream_type == 0x10 )
  1567.                 {
  1568.                     bits_write( &bits, 8, 0x20 );   // Visual 14496-2
  1569.                     bits_write( &bits, 6, 0x04 );   // VisualStream
  1570.                 }
  1571.                 else if( p_stream->i_stream_type == 0x11 )
  1572.                 {
  1573.                     bits_write( &bits, 8, 0x40 );   // Audio 14496-3
  1574.                     bits_write( &bits, 6, 0x05 );   // AudioStream
  1575.                 }
  1576.                 else if( p_stream->i_stream_type == 0x12 &&
  1577.                          p_stream->i_codec == VLC_FOURCC('s','u','b','t') )
  1578.                 {
  1579.                     bits_write( &bits, 8, 0x0B );   // Text Stream
  1580.                     bits_write( &bits, 6, 0x04 );   // VisualStream
  1581.                 }
  1582.                 else
  1583.                 {
  1584.                     bits_write( &bits, 8, 0x00 );
  1585.                     bits_write( &bits, 6, 0x00 );
  1586.                     msg_Err( p_mux->p_sout,"Unsupported stream_type => "
  1587.                              "broken IOD" );
  1588.                 }
  1589.                 bits_write( &bits, 1,   0x00 );     // UpStream
  1590.                 bits_write( &bits, 1,   0x01 );     // reserved
  1591.                 bits_write( &bits, 24,  1024 * 1024 );  // bufferSizeDB
  1592.                 bits_write( &bits, 32,  0x7fffffff );   // maxBitrate
  1593.                 bits_write( &bits, 32,  0 );            // avgBitrate
  1594.                 if( p_stream->i_decoder_specific_info > 0 )
  1595.                 {
  1596.                     int i;
  1597.                     // DecoderSpecificInfo
  1598.                     bits_align( &bits );
  1599.                     bits_write( &bits, 8,   0x05 ); // tag
  1600.                     bits_write( &bits, 24, GetDescriptorLength24b(
  1601.                                 p_stream->i_decoder_specific_info ) );
  1602.                     for( i = 0; i < p_stream->i_decoder_specific_info; i++ )
  1603.                     {
  1604.                         bits_write( &bits, 8,
  1605.                             ((uint8_t*)p_stream->p_decoder_specific_info)[i] );
  1606.                     }
  1607.                 }
  1608.                 /* fix Decoder length */
  1609.                 bits_write( &bits_fix_Decoder, 24,
  1610.                             GetDescriptorLength24b( bits.i_data -
  1611.                             bits_fix_Decoder.i_data - 3 ) );
  1612.                 /* SLConfigDescriptor : predifined (0x01) */
  1613.                 bits_align( &bits );
  1614.                 bits_write( &bits, 8,   0x06 ); // tag
  1615.                 bits_write( &bits, 24,  GetDescriptorLength24b( 8 ) );
  1616.                 bits_write( &bits, 8,   0x01 ); // predefined
  1617.                 bits_write( &bits, 1,   0 );   // durationFlag
  1618.                 bits_write( &bits, 32,  0 );   // OCRResolution
  1619.                 bits_write( &bits, 8,   0 );   // OCRLength
  1620.                 bits_write( &bits, 8,   0 );   // InstantBitrateLength
  1621.                 bits_align( &bits );
  1622.                 /* fix ESDescr length */
  1623.                 bits_write( &bits_fix_ESDescr, 24,
  1624.                             GetDescriptorLength24b( bits.i_data -
  1625.                             bits_fix_ESDescr.i_data - 3 ) );
  1626.             }
  1627.         }
  1628.         bits_align( &bits );
  1629.         /* fix IOD length */
  1630.         bits_write( &bits_fix_IOD, 24,
  1631.                     GetDescriptorLength24b( bits.i_data -
  1632.                                             bits_fix_IOD.i_data - 3 ) );
  1633.         dvbpsi_PMTAddDescriptor( &pmt, 0x1d, bits.i_data, bits.p_data );
  1634.     }
  1635.     for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
  1636.     {
  1637.         ts_stream_t *p_stream;
  1638.         p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
  1639.         p_es = dvbpsi_PMTAddES( &pmt, p_stream->i_stream_type,
  1640.                                 p_stream->i_pid );
  1641.         if( p_stream->i_stream_id == 0xfa || p_stream->i_stream_id == 0xfb )
  1642.         {
  1643.             uint8_t     es_id[2];
  1644.             /* SL descriptor */
  1645.             es_id[0] = (p_stream->i_es_id >> 8)&0xff;
  1646.             es_id[1] = (p_stream->i_es_id)&0xff;
  1647.             dvbpsi_PMTESAddDescriptor( p_es, 0x1f, 2, es_id );
  1648.         }
  1649.         else if( p_stream->i_stream_type == 0xa0 )
  1650.         {
  1651.             uint8_t data[512];
  1652.             int i_extra = __MIN( p_stream->i_decoder_specific_info, 502 );
  1653.             /* private DIV3 descripor */
  1654.             memcpy( &data[0], &p_stream->i_bih_codec, 4 );
  1655.             data[4] = ( p_stream->i_bih_width >> 8 )&0xff;
  1656.             data[5] = ( p_stream->i_bih_width      )&0xff;
  1657.             data[6] = ( p_stream->i_bih_height>> 8 )&0xff;
  1658.             data[7] = ( p_stream->i_bih_height     )&0xff;
  1659.             data[8] = ( i_extra >> 8 )&0xff;
  1660.             data[9] = ( i_extra      )&0xff;
  1661.             if( i_extra > 0 )
  1662.             {
  1663.                 memcpy( &data[10], p_stream->p_decoder_specific_info, i_extra );
  1664.             }
  1665.             /* 0xa0 is private */
  1666.             dvbpsi_PMTESAddDescriptor( p_es, 0xa0, i_extra + 10, data );
  1667.         }
  1668.         else if( p_stream->i_stream_type == 0x81 )
  1669.         {
  1670.             uint8_t format[4] = { 0x41, 0x43, 0x2d, 0x33 };
  1671.             /* "registration" descriptor : "AC-3" */
  1672.             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, format );
  1673.         }
  1674.         else if( p_stream->i_codec == VLC_FOURCC('d','t','s',' ') )
  1675.         {
  1676.             /* DTS registration descriptor (ETSI TS 101 154 Annex F) */
  1677.             /* DTS format identifier, frame size 1024 - FIXME */
  1678.             uint8_t data[4] = { 0x44, 0x54, 0x53, 0x32 };
  1679.             dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, data );
  1680.         }
  1681.         else if( p_stream->i_codec == VLC_FOURCC('t','e','l','x') )
  1682.         {
  1683.             dvbpsi_PMTESAddDescriptor( p_es, 0x56,
  1684.                                        p_stream->i_decoder_specific_info,
  1685.                                        p_stream->p_decoder_specific_info );
  1686.         }
  1687. #ifdef _DVBPSI_DR_59_H_
  1688.         else if( p_stream->i_codec == VLC_FOURCC('d','v','b','s') )
  1689.         {
  1690.             /* DVB subtitles */
  1691.             dvbpsi_subtitling_dr_t descr;
  1692.             dvbpsi_subtitle_t sub;
  1693.             dvbpsi_descriptor_t *p_descr;
  1694.             memcpy( sub.i_iso6392_language_code, p_stream->lang, 3 );
  1695.             sub.i_subtitling_type = 0x10; /* no aspect-ratio criticality */
  1696.             sub.i_composition_page_id = p_stream->i_es_id & 0xFF;
  1697.             sub.i_ancillary_page_id = p_stream->i_es_id >> 16;
  1698.             descr.i_subtitles_number = 1;
  1699.             descr.p_subtitle[0] = sub;
  1700.             p_descr = dvbpsi_GenSubtitlingDr( &descr, 0 );
  1701.             /* Work around bug in old libdvbpsi */ p_descr->i_length = 8;
  1702.             dvbpsi_PMTESAddDescriptor( p_es, p_descr->i_tag,
  1703.                                        p_descr->i_length, p_descr->p_data );
  1704.             continue;
  1705.         }
  1706. #endif /* _DVBPSI_DR_59_H_ */
  1707.         if( p_stream->lang[0] != 0 )
  1708.         {
  1709.             uint8_t data[4];
  1710.             /* I construct the content myself, way faster than looking at
  1711.              * over complicated/mind broken libdvbpsi way */
  1712.             data[0] = p_stream->lang[0];
  1713.             data[1] = p_stream->lang[1];
  1714.             data[2] = p_stream->lang[2];
  1715.             data[3] = 0x00; /* audio type: 0x00 undefined */
  1716.             dvbpsi_PMTESAddDescriptor( p_es, 0x0a, 4, data );
  1717.         }
  1718.     }
  1719.     p_section = dvbpsi_GenPMTSections( &pmt );
  1720.     p_pmt = WritePSISection( p_mux->p_sout, p_section );
  1721.     PEStoTS( p_mux->p_sout, c, p_pmt, &p_sys->pmt );
  1722.     dvbpsi_DeletePSISections( p_section );
  1723.     dvbpsi_EmptyPMT( &pmt );
  1724. }