1 /*****************************************************************************
2 * ts.c: MPEG-II TS Muxer
3 *****************************************************************************
4 * Copyright (C) 2001-2005 VLC authors and VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Eric Petit <titer@videolan.org>
9 * Jean-Paul Saman <jpsaman #_at_# m2x.nl>
10 * Wallace Wadge <wwadge #_at_# gmail.com>
12 * This program is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU Lesser General Public License as published by
14 * the Free Software Foundation; either version 2.1 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public License
23 * along with this program; if not, write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
37 #include <vlc_common.h>
38 #include <vlc_plugin.h>
40 #include <vlc_block.h>
43 #include <vlc_iso_lang.h>
51 # include <dvbpsi/dvbpsi.h>
52 # include <dvbpsi/demux.h>
53 # include <dvbpsi/descriptor.h>
54 # include <dvbpsi/pat.h>
55 # include <dvbpsi/pmt.h>
56 # include <dvbpsi/sdt.h>
57 # include <dvbpsi/dr.h>
58 # include <dvbpsi/psi.h>
60 #include "dvbpsi_compat.h"
66 * - check PCR frequency requirement
68 * - check PCR/PCR "soft"
69 * - check if "registration" descriptor : "AC-3" should be a program
70 * descriptor or an es one. (xine want an es one)
72 * - remove creation of PAT/PMT without dvbpsi
75 * - subtitle support is far from perfect. I expect some subtitles drop
76 * if they arrive a bit late
77 * (We cannot rely on the fact that the fifo should be full)
80 /*****************************************************************************
82 *****************************************************************************/
83 static int ChangeKeyCallback ( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
84 static int ActiveKeyCallback ( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
86 /*****************************************************************************
88 *****************************************************************************/
89 static int Open ( vlc_object_t * );
90 static void Close ( vlc_object_t * );
92 #define VPID_TEXT N_("Video PID")
93 #define VPID_LONGTEXT N_("Assign a fixed PID to the video stream. The PCR " \
94 "PID will automatically be the video.")
95 #define APID_TEXT N_("Audio PID")
96 #define APID_LONGTEXT N_("Assign a fixed PID to the audio stream.")
97 #define SPUPID_TEXT N_("SPU PID")
98 #define SPUPID_LONGTEXT N_("Assign a fixed PID to the SPU.")
99 #define PMTPID_TEXT N_("PMT PID")
100 #define PMTPID_LONGTEXT N_("Assign a fixed PID to the PMT")
101 #define TSID_TEXT N_("TS ID")
102 #define TSID_LONGTEXT N_("Assign a fixed Transport Stream ID.")
103 #define NETID_TEXT N_("NET ID")
104 #define NETID_LONGTEXT N_("Assign a fixed Network ID (for SDT table)")
106 #define PMTPROG_TEXT N_("PMT Program numbers")
107 #define PMTPROG_LONGTEXT N_("Assign a program number to each PMT. This " \
108 "requires \"Set PID to ID of ES\" to be enabled." )
110 #define MUXPMT_TEXT N_("Mux PMT (requires --sout-ts-es-id-pid)")
111 #define MUXPMT_LONGTEXT N_("Define the pids to add to each pmt. This " \
112 "requires \"Set PID to ID of ES\" to be enabled." )
114 #define SDTDESC_TEXT N_("SDT Descriptors (requires --sout-ts-es-id-pid)")
115 #define SDTDESC_LONGTEXT N_("Defines the descriptors of each SDT. This" \
116 "requires \"Set PID to ID of ES\" to be enabled." )
118 #define PID_TEXT N_("Set PID to ID of ES")
119 #define PID_LONGTEXT N_("Sets PID to the ID if the incoming ES. This is for " \
120 "use with --ts-es-id-pid, and allows having the same PIDs in the input " \
121 "and output streams.")
123 #define ALIGNMENT_TEXT N_("Data alignment")
124 #define ALIGNMENT_LONGTEXT N_("Enforces alignment of all access units on " \
125 "PES boundaries. Disabling this might save some bandwidth but introduce incompatibilities.")
127 #define SHAPING_TEXT N_("Shaping delay (ms)")
128 #define SHAPING_LONGTEXT N_("Cut the " \
129 "stream in slices of the given duration, and ensure a constant bitrate " \
130 "between the two boundaries. This avoids having huge bitrate peaks, " \
131 "especially for reference frames." )
133 #define KEYF_TEXT N_("Use keyframes")
134 #define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " \
135 "the TS muxer will place the boundaries at the end of I pictures. In " \
136 "that case, the shaping duration given by the user is a worse case " \
137 "used when no reference frame is available. This enhances the efficiency " \
138 "of the shaping algorithm, since I frames are usually the biggest " \
139 "frames in the stream.")
141 #define PCR_TEXT N_("PCR interval (ms)")
142 #define PCR_LONGTEXT N_("Set at which interval " \
143 "PCRs (Program Clock Reference) will be sent (in milliseconds). " \
144 "This value should be below 100ms. (default is 70ms).")
146 #define BMIN_TEXT N_( "Minimum B (deprecated)")
147 #define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )
149 #define BMAX_TEXT N_( "Maximum B (deprecated)")
150 #define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")
152 #define DTS_TEXT N_("DTS delay (ms)")
153 #define DTS_LONGTEXT N_("Delay the DTS (decoding time " \
154 "stamps) and PTS (presentation timestamps) of the data in the " \
155 "stream, compared to the PCRs. This allows for some buffering inside " \
156 "the client decoder.")
158 #define ACRYPT_TEXT N_("Crypt audio")
159 #define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
160 #define VCRYPT_TEXT N_("Crypt video")
161 #define VCRYPT_LONGTEXT N_("Crypt video using CSA")
163 #define CK_TEXT N_("CSA Key")
164 #define CK_LONGTEXT N_("CSA encryption key. This must be a " \
165 "16 char string (8 hexadecimal bytes).")
167 #define CK2_TEXT N_("Second CSA Key")
168 #define CK2_LONGTEXT N_("The even CSA encryption key. This must be a " \
169 "16 char string (8 hexadecimal bytes).")
171 #define CU_TEXT N_("CSA Key in use")
172 #define CU_LONGTEXT N_("CSA encryption key used. It can be the odd/first/1 " \
173 "(default) or the even/second/2 one.")
175 #define CPKT_TEXT N_("Packet size in bytes to encrypt")
176 #define CPKT_LONGTEXT N_("Size of the TS packet to encrypt. " \
177 "The encryption routines subtract the TS-header from the value before " \
180 #define SOUT_CFG_PREFIX "sout-ts-"
181 #define MAX_PMT 64 /* Maximum number of programs. FIXME: I just chose an arbitrary number. Where is the maximum in the spec? */
182 #define MAX_PMT_PID 64 /* Maximum pids in each pmt. FIXME: I just chose an arbitrary number. Where is the maximum in the spec? */
183 #if MAX_SDT_DESC < MAX_PMT
184 #error "MAX_SDT_DESC < MAX_PMT"
188 set_description( N_("TS muxer (libdvbpsi)") )
189 set_shortname( "MPEG-TS")
190 set_category( CAT_SOUT )
191 set_subcategory( SUBCAT_SOUT_MUX )
192 set_capability( "sout mux", 120 )
195 add_integer(SOUT_CFG_PREFIX "pid-video", 100, VPID_TEXT, VPID_LONGTEXT, true)
196 change_integer_range( 32, 8190 )
197 add_integer(SOUT_CFG_PREFIX "pid-audio", 200, APID_TEXT, APID_LONGTEXT, true)
198 change_integer_range( 32, 8190 )
199 add_integer(SOUT_CFG_PREFIX "pid-spu", 300, SPUPID_TEXT, SPUPID_LONGTEXT, true)
200 change_integer_range( 32, 8190 )
201 add_integer(SOUT_CFG_PREFIX "pid-pmt", 32, PMTPID_TEXT, PMTPID_LONGTEXT, true)
202 change_integer_range( 32, 8190 )
203 add_integer(SOUT_CFG_PREFIX "tsid", 0, TSID_TEXT, TSID_LONGTEXT, true)
204 add_integer(SOUT_CFG_PREFIX "netid", 0, NETID_TEXT, NETID_LONGTEXT, true)
205 add_string(SOUT_CFG_PREFIX "program-pmt", NULL, PMTPROG_TEXT, PMTPROG_LONGTEXT, true)
206 add_bool(SOUT_CFG_PREFIX "es-id-pid", false, PID_TEXT, PID_LONGTEXT, true)
207 add_string(SOUT_CFG_PREFIX "muxpmt", NULL, MUXPMT_TEXT, MUXPMT_LONGTEXT, true)
208 add_string(SOUT_CFG_PREFIX "sdtdesc", NULL, SDTDESC_TEXT, SDTDESC_LONGTEXT, true)
209 add_bool(SOUT_CFG_PREFIX "alignment", true, ALIGNMENT_TEXT, ALIGNMENT_LONGTEXT, true)
211 add_integer(SOUT_CFG_PREFIX "shaping", 200, SHAPING_TEXT, SHAPING_LONGTEXT, true)
212 add_bool(SOUT_CFG_PREFIX "use-key-frames", false, KEYF_TEXT, KEYF_LONGTEXT, true)
214 add_integer( SOUT_CFG_PREFIX "pcr", 70, PCR_TEXT, PCR_LONGTEXT, true)
215 add_integer( SOUT_CFG_PREFIX "bmin", 0, BMIN_TEXT, BMIN_LONGTEXT, true)
216 add_integer( SOUT_CFG_PREFIX "bmax", 0, BMAX_TEXT, BMAX_LONGTEXT, true)
217 add_integer( SOUT_CFG_PREFIX "dts-delay", 400, DTS_TEXT, DTS_LONGTEXT, true)
219 add_bool( SOUT_CFG_PREFIX "crypt-audio", true, ACRYPT_TEXT, ACRYPT_LONGTEXT, true)
220 add_bool( SOUT_CFG_PREFIX "crypt-video", true, VCRYPT_TEXT, VCRYPT_LONGTEXT, true)
221 add_string( SOUT_CFG_PREFIX "csa-ck", NULL, CK_TEXT, CK_LONGTEXT, true)
222 add_string( SOUT_CFG_PREFIX "csa2-ck", NULL, CK2_TEXT, CK2_LONGTEXT, true)
223 add_string( SOUT_CFG_PREFIX "csa-use", "1", CU_TEXT, CU_LONGTEXT, true)
224 add_integer(SOUT_CFG_PREFIX "csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true)
226 set_callbacks( Open, Close )
229 /*****************************************************************************
230 * Local data structures
231 *****************************************************************************/
232 static const char *const ppsz_sout_options[] = {
233 "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid",
235 "es-id-pid", "shaping", "pcr", "bmin", "bmax", "use-key-frames",
236 "dts-delay", "csa-ck", "csa2-ck", "csa-use", "csa-pkt", "crypt-audio", "crypt-video",
237 "muxpmt", "program-pmt", "alignment",
241 typedef struct pmt_map_t /* Holds the mapping between the pmt-pid/pmt table */
252 } sout_buffer_chain_t;
254 static inline void BufferChainInit ( sout_buffer_chain_t *c )
258 c->pp_last = &c->p_first;
261 static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
271 c->pp_last = &b->p_next;
274 static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
276 block_t *b = c->p_first;
281 c->p_first = b->p_next;
283 if( c->p_first == NULL )
285 c->pp_last = &c->p_first;
293 static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
295 block_t *b = c->p_first;
300 static inline void BufferChainClean( sout_buffer_chain_t *c )
304 while( ( b = BufferChainGet( c ) ) )
308 BufferChainInit( c );
313 sout_buffer_chain_t chain_pes;
315 mtime_t i_pes_length;
328 struct sout_mux_sys_t
331 sout_input_t *p_pcr_input;
333 vlc_mutex_t csa_lock;
335 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
347 int i_pat_version_number;
350 int i_pmt_version_number;
351 ts_stream_t pmt[MAX_PMT];
352 pmt_map_t pmtmap[MAX_PMT_PID];
353 int i_pmt_program_number[MAX_PMT];
354 bool b_data_alignment;
358 /* for TS building */
359 int64_t i_bitrate_min;
360 int64_t i_bitrate_max;
362 int64_t i_shaping_delay;
368 bool b_use_key_frames;
370 mtime_t i_pcr; /* last PCR emited */
379 static int GetNextFreePID( sout_mux_t *p_mux, int i_pid_start )
381 sout_mux_sys_t *p_sys = p_mux->p_sys;
384 for(unsigned i=i_pid_start; i<p_sys->i_num_pmt; i++)
386 if(p_sys->pmt[i].i_pid == i_pid_start)
393 for(int i=0; i<p_mux->i_nb_inputs; i++)
395 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
396 if(p_stream->ts.i_pid == i_pid_start)
403 if( i_pid_start > 8190 )
412 /* Reserve a pid and return it */
413 static int AllocatePID( sout_mux_t *p_mux, int i_cat )
415 sout_mux_sys_t *p_sys = p_mux->p_sys;
417 int *pi_candidate_pid = NULL;
422 pi_candidate_pid = &p_sys->i_pid_video;
426 pi_candidate_pid = &p_sys->i_pid_audio;
431 pi_candidate_pid = &p_sys->i_pid_spu;
435 *pi_candidate_pid = GetNextFreePID( p_mux, *pi_candidate_pid );
436 i_pid = (*pi_candidate_pid)++;
441 static int pmtcompare( const void *pa, const void *pb )
443 int id1 = ((pmt_map_t *)pa)->i_pid;
444 int id2 = ((pmt_map_t *)pb)->i_pid;
449 static int intcompare( const void *pa, const void *pb )
451 return *(int*)pa - *(int*)pb;
454 /*****************************************************************************
456 *****************************************************************************/
457 static int Control ( sout_mux_t *, int, va_list );
458 static int AddStream( sout_mux_t *, sout_input_t * );
459 static int DelStream( sout_mux_t *, sout_input_t * );
460 static int Mux ( sout_mux_t * );
462 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo );
463 static block_t *Add_ADTS( block_t *, es_format_t * );
464 static void TSSchedule ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
465 mtime_t i_pcr_length, mtime_t i_pcr_dts );
466 static void TSDate ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
467 mtime_t i_pcr_length, mtime_t i_pcr_dts );
468 static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
469 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
471 static block_t *TSNew( sout_mux_t *p_mux, sout_input_sys_t *p_stream, bool b_pcr );
472 static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
474 static csa_t *csaSetup( vlc_object_t *p_this )
476 sout_mux_t *p_mux = (sout_mux_t*)p_this;
477 sout_mux_sys_t *p_sys = p_mux->p_sys;
478 char *csack = var_CreateGetNonEmptyStringCommand( p_mux, SOUT_CFG_PREFIX "csa-ck" );
482 csa_t *csa = csa_New();
484 if( csa_SetCW( p_this, csa, csack, true ) )
491 vlc_mutex_init( &p_sys->csa_lock );
492 p_sys->b_crypt_audio = var_GetBool( p_mux, SOUT_CFG_PREFIX "crypt-audio" );
493 p_sys->b_crypt_video = var_GetBool( p_mux, SOUT_CFG_PREFIX "crypt-video" );
495 char *csa2ck = var_CreateGetNonEmptyStringCommand( p_mux, SOUT_CFG_PREFIX "csa2-ck");
496 if (!csa2ck || csa_SetCW( p_this, csa, csa2ck, false ) )
497 csa_SetCW( p_this, csa, csack, false );
500 var_Create( p_mux, SOUT_CFG_PREFIX "csa-use", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );
501 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
502 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, (void *)1 );
503 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
506 var_Get( p_mux, SOUT_CFG_PREFIX "csa-use", &use_val );
507 if ( var_Set( p_mux, SOUT_CFG_PREFIX "csa-use", use_val ) )
508 var_SetString( p_mux, SOUT_CFG_PREFIX "csa-use", "odd" );
509 free( use_val.psz_string );
511 p_sys->i_csa_pkt_size = var_GetInteger( p_mux, SOUT_CFG_PREFIX "csa-pkt" );
512 if( p_sys->i_csa_pkt_size < 12 || p_sys->i_csa_pkt_size > 188 )
514 msg_Err( p_mux, "wrong packet size %d specified",
515 p_sys->i_csa_pkt_size );
516 p_sys->i_csa_pkt_size = 188;
519 msg_Dbg( p_mux, "encrypting %d bytes of packet", p_sys->i_csa_pkt_size );
526 /*****************************************************************************
528 *****************************************************************************/
529 static int Open( vlc_object_t *p_this )
531 sout_mux_t *p_mux =(sout_mux_t*)p_this;
532 sout_mux_sys_t *p_sys = NULL;
534 config_ChainParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
536 p_sys = calloc( 1, sizeof( sout_mux_sys_t ) );
539 p_sys->i_num_pmt = 1;
542 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
543 p_sys->p_dvbpsi = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
544 if( !p_sys->p_dvbpsi )
549 p_sys->p_dvbpsi->p_sys = (void *) p_mux;
552 p_sys->b_es_id_pid = var_GetBool( p_mux, SOUT_CFG_PREFIX "es-id-pid" );
555 fetch string of pmts. Here's a sample: --sout-ts-muxpmt="0x451,0x200,0x28a,0x240,,0x450,0x201,0x28b,0x241,,0x452,0x202,0x28c,0x242"
556 This would mean 0x451, 0x200, 0x28a, 0x240 would fall under one pmt (program), 0x450,0x201,0x28b,0x241 would fall under another
558 char *muxpmt = var_GetNonEmptyString(p_mux, SOUT_CFG_PREFIX "muxpmt");
559 for (char *psz = muxpmt; psz; )
562 uint16_t i_pid = strtoul( psz, &psz_next, 0 );
563 psz = *psz_next ? &psz_next[1] : NULL;
567 if ( ++p_sys->i_num_pmt > MAX_PMT )
569 msg_Err( p_mux, "Number of PMTs > %d)", MAX_PMT );
570 p_sys->i_num_pmt = MAX_PMT;
575 p_sys->pmtmap[p_sys->i_pmtslots].i_pid = i_pid;
576 p_sys->pmtmap[p_sys->i_pmtslots].i_prog = p_sys->i_num_pmt - 1;
577 if ( ++p_sys->i_pmtslots >= MAX_PMT_PID )
579 msg_Err( p_mux, "Number of pids in PMT > %d", MAX_PMT_PID );
580 p_sys->i_pmtslots = MAX_PMT_PID - 1;
584 /* Now sort according to pids for fast search later on */
585 qsort( (void *)p_sys->pmtmap, p_sys->i_pmtslots,
586 sizeof(pmt_map_t), pmtcompare );
589 unsigned short subi[3];
590 vlc_rand_bytes(subi, sizeof(subi));
591 p_sys->i_pat_version_number = nrand48(subi) & 0x1f;
594 var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
596 p_sys->i_tsid = val.i_int;
598 p_sys->i_tsid = nrand48(subi) & 0xffff;
600 p_sys->sdt.i_netid = nrand48(subi) & 0xffff;
602 var_Get( p_mux, SOUT_CFG_PREFIX "netid", &val );
604 p_sys->sdt.i_netid = val.i_int;
606 p_sys->i_pmt_version_number = nrand48(subi) & 0x1f;
607 p_sys->sdt.ts.i_pid = 0x11;
609 char *sdtdesc = var_GetNonEmptyString( p_mux, SOUT_CFG_PREFIX "sdtdesc" );
611 /* Syntax is provider_sdt1,service_name_sdt1,provider_sdt2,service_name_sdt2... */
616 char *psz_sdttoken = sdtdesc;
618 for (int i = 0; i < MAX_SDT_DESC * 2 && psz_sdttoken; i++)
620 char *psz_end = strchr( psz_sdttoken, ',' );
625 p_sys->sdt.desc[i/2].psz_service_name = strdup(psz_sdttoken);
627 p_sys->sdt.desc[i/2].psz_provider = strdup(psz_sdttoken);
629 psz_sdttoken = psz_end;
634 p_sys->b_data_alignment = var_GetBool( p_mux, SOUT_CFG_PREFIX "alignment" );
636 char *pgrpmt = var_GetNonEmptyString(p_mux, SOUT_CFG_PREFIX "program-pmt");
640 char *psz_next = psz;
642 for (int i = 0; psz; )
644 uint16_t i_pid = strtoul( psz, &psz_next, 0 );
645 if( psz_next[0] != '\0' )
653 msg_Err( p_mux, "Number of PMTs > maximum (%d)", MAX_PMT );
657 p_sys->i_pmt_program_number[i] = i_pid;
665 /* Option not specified, use 1, 2, 3... */
666 for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
667 p_sys->i_pmt_program_number[i] = i + 1;
670 var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
671 for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
672 p_sys->pmt[i].i_pid = val.i_int + i;
674 p_sys->i_pid_video = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
675 p_sys->i_pid_audio = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
676 p_sys->i_pid_spu = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
678 p_sys->i_pcr_pid = 0x1fff;
680 /* Allow to create constrained stream */
681 p_sys->i_bitrate_min = var_GetInteger( p_mux, SOUT_CFG_PREFIX "bmin" );
683 p_sys->i_bitrate_max = var_GetInteger( p_mux, SOUT_CFG_PREFIX "bmax" );
685 if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
686 p_sys->i_bitrate_min > p_sys->i_bitrate_max )
688 msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
689 "disabling bitrate control" );
690 p_sys->i_bitrate_min = 0;
691 p_sys->i_bitrate_max = 0;
693 if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
695 msg_Err( p_mux, "bmin and bmax no more supported "
696 "(if you need them report it)" );
699 var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
700 p_sys->i_shaping_delay = val.i_int * 1000;
701 if( p_sys->i_shaping_delay <= 0 )
704 "invalid shaping (%"PRId64"ms) resetting to 200ms",
705 p_sys->i_shaping_delay / 1000 );
706 p_sys->i_shaping_delay = 200000;
709 var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
710 p_sys->i_pcr_delay = val.i_int * 1000;
711 if( p_sys->i_pcr_delay <= 0 ||
712 p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
715 "invalid pcr delay (%"PRId64"ms) resetting to 70ms",
716 p_sys->i_pcr_delay / 1000 );
717 p_sys->i_pcr_delay = 70000;
720 var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
721 p_sys->i_dts_delay = val.i_int * 1000;
723 msg_Dbg( p_mux, "shaping=%"PRId64" pcr=%"PRId64" dts_delay=%"PRId64,
724 p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );
726 p_sys->b_use_key_frames = var_GetBool( p_mux, SOUT_CFG_PREFIX "use-key-frames" );
728 p_mux->p_sys = p_sys;
730 p_sys->csa = csaSetup(p_this);
732 p_mux->pf_control = Control;
733 p_mux->pf_addstream = AddStream;
734 p_mux->pf_delstream = DelStream;
740 /*****************************************************************************
742 *****************************************************************************/
743 static void Close( vlc_object_t * p_this )
745 sout_mux_t *p_mux = (sout_mux_t*)p_this;
746 sout_mux_sys_t *p_sys = p_mux->p_sys;
748 #if (DVBPSI_VERSION_INT >= DVBPSI_VERSION_WANTED(1,0,0))
749 if( p_sys->p_dvbpsi )
750 dvbpsi_delete( p_sys->p_dvbpsi );
755 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, NULL );
756 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
757 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
758 csa_Delete( p_sys->csa );
759 vlc_mutex_destroy( &p_sys->csa_lock );
762 for (int i = 0; i < MAX_SDT_DESC; i++ )
764 free( p_sys->sdt.desc[i].psz_service_name );
765 free( p_sys->sdt.desc[i].psz_provider );
771 /*****************************************************************************
772 * ChangeKeyCallback: called when changing the odd encryption key on the fly.
773 *****************************************************************************/
774 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
775 vlc_value_t oldval, vlc_value_t newval,
778 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
779 sout_mux_t *p_mux = (sout_mux_t*)p_this;
780 sout_mux_sys_t *p_sys = p_mux->p_sys;
783 vlc_mutex_lock(&p_sys->csa_lock);
784 ret = csa_SetCW(p_this, p_sys->csa, newval.psz_string, !!(intptr_t)p_data);
785 vlc_mutex_unlock(&p_sys->csa_lock);
790 /*****************************************************************************
791 * ActiveKeyCallback: called when changing the active (in use) encryption key on the fly.
792 *****************************************************************************/
793 static int ActiveKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
794 vlc_value_t oldval, vlc_value_t newval,
797 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(p_data);
798 sout_mux_t *p_mux = (sout_mux_t*)p_this;
799 sout_mux_sys_t *p_sys = p_mux->p_sys;
800 int i_res, use_odd = -1;
802 if( !strcmp(newval.psz_string, "odd" ) ||
803 !strcmp(newval.psz_string, "first" ) ||
804 !strcmp(newval.psz_string, "1" ) )
808 else if( !strcmp(newval.psz_string, "even" ) ||
809 !strcmp(newval.psz_string, "second" ) ||
810 !strcmp(newval.psz_string, "2" ) )
818 vlc_mutex_lock( &p_sys->csa_lock );
819 i_res = csa_UseKey( p_this, p_sys->csa, use_odd );
820 vlc_mutex_unlock( &p_sys->csa_lock );
825 /*****************************************************************************
827 *****************************************************************************/
828 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
836 case MUX_CAN_ADD_STREAM_WHILE_MUXING:
837 pb_bool = (bool*)va_arg( args, bool * );
841 case MUX_GET_ADD_STREAM_WAIT:
842 pb_bool = (bool*)va_arg( args, bool * );
847 ppsz = (char**)va_arg( args, char ** );
848 *ppsz = strdup( "video/mp2t" );
856 /* returns a pointer to a valid string, with length 0 or 3 */
857 static const char *GetIso639_2LangCode(const char *lang)
859 const iso639_lang_t *pl;
861 if (strlen(lang) == 2)
863 pl = GetLang_1(lang);
867 pl = GetLang_2B(lang); /* try native code first */
868 if (!*pl->psz_iso639_2T)
869 pl = GetLang_2T(lang); /* else fallback to english code */
873 return pl->psz_iso639_2T; /* returns the english code */
876 /*****************************************************************************
877 * AddStream: called for each stream addition
878 *****************************************************************************/
879 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
881 sout_mux_sys_t *p_sys = p_mux->p_sys;
882 sout_input_sys_t *p_stream;
884 p_input->p_sys = p_stream = calloc( 1, sizeof( sout_input_sys_t ) );
888 if ( p_sys->b_es_id_pid )
889 p_stream->ts.i_pid = p_input->p_fmt->i_id & 0x1fff;
891 p_stream->ts.i_pid = AllocatePID( p_mux, p_input->p_fmt->i_cat );
893 p_stream->pes.i_codec = p_input->p_fmt->i_codec;
895 p_stream->pes.i_stream_type = -1;
896 switch( p_input->p_fmt->i_codec )
903 /* TODO: do we need to check MPEG-I/II ? */
904 p_stream->pes.i_stream_type = 0x02;
905 p_stream->pes.i_stream_id = 0xe0;
908 p_stream->pes.i_stream_type = 0x10;
909 p_stream->pes.i_stream_id = 0xe0;
910 p_stream->pes.i_es_id = p_stream->ts.i_pid;
913 p_stream->pes.i_stream_type = 0x24;
914 p_stream->pes.i_stream_id = 0xe0;
917 p_stream->pes.i_stream_type = 0x1b;
918 p_stream->pes.i_stream_id = 0xe0;
920 /* XXX dirty dirty but somebody want crapy MS-codec XXX */
921 case VLC_CODEC_H263I:
930 p_stream->pes.i_stream_type = 0xa0; /* private */
931 p_stream->pes.i_stream_id = 0xa0; /* beurk */
932 p_stream->pes.i_bih_codec = p_input->p_fmt->i_codec;
933 p_stream->pes.i_bih_width = p_input->p_fmt->video.i_width;
934 p_stream->pes.i_bih_height = p_input->p_fmt->video.i_height;
936 case VLC_CODEC_DIRAC:
937 /* stream_id makes use of stream_id_extension */
938 p_stream->pes.i_stream_id = (PES_EXTENDED_STREAM_ID << 8) | 0x60;
939 p_stream->pes.i_stream_type = 0xd1;
946 p_stream->pes.i_stream_type =
947 p_input->p_fmt->audio.i_rate >= 32000 ? 0x03 : 0x04;
948 p_stream->pes.i_stream_id = 0xc0;
951 p_stream->pes.i_stream_type = 0x81;
952 p_stream->pes.i_stream_id = 0xbd;
954 case VLC_CODEC_DVD_LPCM:
955 p_stream->pes.i_stream_type = 0x83;
956 p_stream->pes.i_stream_id = 0xbd;
959 if (p_input->p_fmt->audio.i_channels > 8) {
960 msg_Err(p_mux, "Too many opus channels (%d > 8)",
961 p_input->p_fmt->audio.i_channels);
966 p_stream->pes.i_stream_type = 0x06;
967 p_stream->pes.i_stream_id = 0xbd;
970 /* XXX: make that configurable in some way when LOAS
971 * is implemented for AAC in TS */
972 //p_stream->pes.i_stream_type = 0x11; /* LOAS/LATM */
973 p_stream->pes.i_stream_type = 0x0f; /* ADTS */
974 p_stream->pes.i_stream_id = 0xc0;
975 p_stream->pes.i_es_id = p_stream->ts.i_pid;
981 p_stream->pes.i_stream_type = 0x82;
982 p_stream->pes.i_stream_id = 0xbd;
985 p_stream->pes.i_stream_type = 0x12;
986 p_stream->pes.i_stream_id = 0xfa;
987 p_stream->pes.i_es_id = p_stream->ts.i_pid;
990 p_stream->pes.i_stream_type = 0x06;
991 p_stream->pes.i_es_id = p_input->p_fmt->subs.dvb.i_id;
992 p_stream->pes.i_stream_id = 0xbd;
994 case VLC_CODEC_TELETEXT:
995 p_stream->pes.i_stream_type = 0x06;
996 p_stream->pes.i_stream_id = 0xbd; /* FIXME */
1000 if (p_stream->pes.i_stream_type == -1)
1002 msg_Warn( p_mux, "rejecting stream with unsupported codec %4.4s",
1003 (char*)&p_stream->pes.i_codec );
1005 return VLC_EGENERIC;
1008 p_stream->pes.i_langs = 1 + p_input->p_fmt->i_extra_languages;
1009 p_stream->pes.lang = calloc(1, p_stream->pes.i_langs * 4);
1010 if( !p_stream->pes.lang )
1013 msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
1014 (char*)&p_stream->pes.i_codec, p_stream->ts.i_pid );
1016 for (int i = 0; i < p_stream->pes.i_langs; i++) {
1017 char *lang = (i == 0)
1018 ? p_input->p_fmt->psz_language
1019 : p_input->p_fmt->p_extra_languages[i-1].psz_language;
1024 const char *code = GetIso639_2LangCode(lang);
1027 memcpy(&p_stream->pes.lang[i*4], code, 3);
1028 p_stream->pes.lang[i*4+3] = 0x00; /* audio type: 0x00 undefined */
1029 msg_Dbg( p_mux, " - lang=%3.3s", &p_stream->pes.lang[i*4] );
1033 /* Create decoder specific info for subt */
1034 if( p_stream->pes.i_codec == VLC_CODEC_SUBT )
1036 p_stream->pes.i_extra = 55;
1037 p_stream->pes.p_extra = malloc( p_stream->pes.i_extra );
1038 if (!p_stream->pes.p_extra)
1041 uint8_t *p = p_stream->pes.p_extra;
1042 p[0] = 0x10; /* textFormat, 0x10 for 3GPP TS 26.245 */
1043 p[1] = 0x00; /* flags: 1b: associated video info flag
1047 p[2] = 52; /* remaining size */
1051 p[0] = p[1] = p[2] = p[3] = 0; p+=4; /* display flags */
1052 *p++ = 0; /* horizontal justification (-1: left, 0 center, 1 right) */
1053 *p++ = 1; /* vertical justification (-1: top, 0 center, 1 bottom) */
1055 p[0] = p[1] = p[2] = 0x00; p+=3;/* background rgb */
1056 *p++ = 0xff; /* background a */
1058 p[0] = p[1] = 0; p += 2; /* text box top */
1059 p[0] = p[1] = 0; p += 2; /* text box left */
1060 p[0] = p[1] = 0; p += 2; /* text box bottom */
1061 p[0] = p[1] = 0; p += 2; /* text box right */
1063 p[0] = p[1] = 0; p += 2; /* start char */
1064 p[0] = p[1] = 0; p += 2; /* end char */
1065 p[0] = p[1] = 0; p += 2; /* default font id */
1067 *p++ = 0; /* font style flags */
1068 *p++ = 12; /* font size */
1070 p[0] = p[1] = p[2] = 0x00; p+=3;/* foreground rgb */
1071 *p++ = 0x00; /* foreground a */
1073 p[0] = p[1] = p[2] = 0; p[3] = 22; p += 4;
1074 memcpy( p, "ftab", 4 ); p += 4;
1075 *p++ = 0; *p++ = 1; /* entry count */
1076 p[0] = p[1] = 0; p += 2; /* font id */
1077 *p++ = 9; /* font name length */
1078 memcpy( p, "Helvetica", 9 ); /* font name */
1082 /* Copy extra data (VOL for MPEG-4 and extra BitMapInfoHeader for VFW */
1083 es_format_t *fmt = p_input->p_fmt;
1084 if( fmt->i_extra > 0 )
1086 p_stream->pes.i_extra = fmt->i_extra;
1087 p_stream->pes.p_extra = malloc( fmt->i_extra );
1088 if( !p_stream->pes.p_extra )
1091 memcpy( p_stream->pes.p_extra, fmt->p_extra, fmt->i_extra );
1095 /* Init pes chain */
1096 BufferChainInit( &p_stream->state.chain_pes );
1098 /* We only change PMT version (PAT isn't changed) */
1099 p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;
1101 /* Update pcr_pid */
1102 if( p_input->p_fmt->i_cat != SPU_ES &&
1103 ( p_sys->i_pcr_pid == 0x1fff || p_input->p_fmt->i_cat == VIDEO_ES ) )
1105 if( p_sys->p_pcr_input )
1107 /* There was already a PCR stream, so clean context */
1110 p_sys->i_pcr_pid = p_stream->ts.i_pid;
1111 p_sys->p_pcr_input = p_input;
1113 msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1121 free(p_stream->pes.lang);
1127 /*****************************************************************************
1128 * DelStream: called before a stream deletion
1129 *****************************************************************************/
1130 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
1132 sout_mux_sys_t *p_sys = p_mux->p_sys;
1133 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1136 msg_Dbg( p_mux, "removing input pid=%d", p_stream->ts.i_pid );
1138 if( p_sys->i_pcr_pid == p_stream->ts.i_pid )
1140 /* Find a new pcr stream (Prefer Video Stream) */
1141 p_sys->i_pcr_pid = 0x1fff;
1142 p_sys->p_pcr_input = NULL;
1143 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1145 if( p_mux->pp_inputs[i] == p_input )
1150 if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
1153 ((sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys)->ts.i_pid;
1154 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1157 else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
1158 p_sys->i_pcr_pid == 0x1fff )
1161 ((sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys)->ts.i_pid;
1162 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1165 if( p_sys->p_pcr_input )
1167 /* Empty TS buffer */
1170 msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1173 /* Empty all data in chain_pes */
1174 BufferChainClean( &p_stream->state.chain_pes );
1176 free(p_stream->pes.lang);
1177 free( p_stream->pes.p_extra );
1179 pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
1180 if ( pid > 0 && pid == p_stream->ts.i_pid )
1182 p_sys->i_pid_video = pid;
1183 msg_Dbg( p_mux, "freeing video PID %d", pid);
1185 pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
1186 if ( pid > 0 && pid == p_stream->ts.i_pid )
1188 p_sys->i_pid_audio = pid;
1189 msg_Dbg( p_mux, "freeing audio PID %d", pid);
1191 pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
1192 if ( pid > 0 && pid == p_stream->ts.i_pid )
1194 p_sys->i_pid_spu = pid;
1195 msg_Dbg( p_mux, "freeing spu PID %d", pid);
1200 /* We only change PMT version (PAT isn't changed) */
1201 p_sys->i_pmt_version_number++;
1202 p_sys->i_pmt_version_number %= 32;
1207 static void SetHeader( sout_buffer_chain_t *c,
1210 block_t *p_ts = BufferChainPeek( c );
1213 p_ts = p_ts->p_next;
1216 p_ts->i_flags |= BLOCK_FLAG_HEADER;
1219 static block_t *Pack_Opus(block_t *p_data)
1221 lldiv_t d = lldiv(p_data->i_buffer, 255);
1222 p_data = block_Realloc(p_data, 2 + d.quot + 1, p_data->i_buffer);
1223 if (p_data) { /* no flags */
1224 p_data->p_buffer[0] = 0x7f;
1225 p_data->p_buffer[1] = 0xe0;
1226 memset(&p_data->p_buffer[2], 0xff, d.quot);
1227 p_data->p_buffer[2+d.quot] = d.rem;
1233 /* returns true if needs more data */
1234 static bool MuxStreams(sout_mux_t *p_mux )
1236 sout_mux_sys_t *p_sys = p_mux->p_sys;
1237 sout_input_sys_t *p_pcr_stream = (sout_input_sys_t*)p_sys->p_pcr_input->p_sys;
1239 sout_buffer_chain_t chain_ts;
1240 mtime_t i_shaping_delay = p_pcr_stream->state.b_key_frame
1241 ? p_pcr_stream->state.i_pes_length
1242 : p_sys->i_shaping_delay;
1246 /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
1247 /* Accumulate enough data in all other stream ( >= length of pcr)*/
1248 for (int i = -1; !b_ok || i < p_mux->i_nb_inputs; i++ )
1250 if (i == p_mux->i_nb_inputs)
1252 /* get enough PES packet for all input */
1256 sout_input_t *p_input;
1259 p_input = p_sys->p_pcr_input;
1260 else if( p_mux->pp_inputs[i]->p_sys == p_pcr_stream )
1263 p_input = p_mux->pp_inputs[i];
1264 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1266 if( ( p_stream != p_pcr_stream ||
1267 p_stream->state.i_pes_length >= i_shaping_delay ) &&
1268 p_stream->state.i_pes_dts + p_stream->state.i_pes_length >=
1269 p_pcr_stream->state.i_pes_dts + p_pcr_stream->state.i_pes_length )
1272 /* Need more data */
1273 if( block_FifoCount( p_input->p_fifo ) <= 1 )
1275 if( ( p_input->p_fmt->i_cat == AUDIO_ES ) ||
1276 ( p_input->p_fmt->i_cat == VIDEO_ES ) )
1278 /* We need more data */
1281 else if( block_FifoCount( p_input->p_fifo ) <= 0 )
1283 /* spu, only one packet is needed */
1286 else if( p_input->p_fmt->i_cat == SPU_ES )
1288 /* Don't mux the SPU yet if it is too early */
1289 block_t *p_spu = block_FifoShow( p_input->p_fifo );
1291 int64_t i_spu_delay = p_spu->i_dts - p_pcr_stream->state.i_pes_dts;
1292 if( ( i_spu_delay > i_shaping_delay ) &&
1293 ( i_spu_delay < 100 * CLOCK_FREQ ) )
1296 if ( ( i_spu_delay >= 100 * CLOCK_FREQ ) ||
1297 ( i_spu_delay < CLOCK_FREQ / 100 ) )
1299 BufferChainClean( &p_stream->state.chain_pes );
1300 p_stream->state.i_pes_dts = 0;
1301 p_stream->state.i_pes_used = 0;
1302 p_stream->state.i_pes_length = 0;
1310 if( p_stream == p_pcr_stream || p_sys->b_data_alignment
1311 || ((p_input->p_fmt->i_codec != VLC_CODEC_MPGA ) &&
1312 (p_input->p_fmt->i_codec != VLC_CODEC_MP3) ) )
1314 p_data = block_FifoGet( p_input->p_fifo );
1315 if (p_data->i_pts <= VLC_TS_INVALID)
1316 p_data->i_pts = p_data->i_dts;
1318 if( p_input->p_fmt->i_codec == VLC_CODEC_MP4A )
1319 p_data = Add_ADTS( p_data, p_input->p_fmt );
1320 else if( p_input->p_fmt->i_codec == VLC_CODEC_OPUS )
1321 p_data = Pack_Opus( p_data );
1324 p_data = FixPES( p_mux, p_input->p_fifo );
1326 if( block_FifoCount( p_input->p_fifo ) > 0 &&
1327 p_input->p_fmt->i_cat != SPU_ES )
1329 block_t *p_next = block_FifoShow( p_input->p_fifo );
1330 p_data->i_length = p_next->i_dts - p_data->i_dts;
1332 else if( p_input->p_fmt->i_codec !=
1334 p_data->i_length = 1000;
1336 if (p_sys->first_dts == 0)
1337 p_sys->first_dts = p_data->i_dts;
1339 if( ( p_pcr_stream->state.i_pes_dts > 0 &&
1340 p_data->i_dts - 10 * CLOCK_FREQ > p_pcr_stream->state.i_pes_dts +
1341 p_pcr_stream->state.i_pes_length ) ||
1342 p_data->i_dts < p_stream->state.i_pes_dts ||
1343 ( p_stream->state.i_pes_dts > 0 &&
1344 p_input->p_fmt->i_cat != SPU_ES &&
1345 p_data->i_dts - 10 * CLOCK_FREQ > p_stream->state.i_pes_dts +
1346 p_stream->state.i_pes_length ) )
1348 msg_Warn( p_mux, "packet with too strange dts "
1349 "(dts=%"PRId64",old=%"PRId64",pcr=%"PRId64")",
1350 p_data->i_dts, p_stream->state.i_pes_dts,
1351 p_pcr_stream->state.i_pes_dts );
1352 block_Release( p_data );
1354 BufferChainClean( &p_stream->state.chain_pes );
1355 p_stream->state.i_pes_dts = 0;
1356 p_stream->state.i_pes_used = 0;
1357 p_stream->state.i_pes_length = 0;
1359 if( p_input->p_fmt->i_cat != SPU_ES )
1361 BufferChainClean( &p_pcr_stream->state.chain_pes );
1362 p_pcr_stream->state.i_pes_dts = 0;
1363 p_pcr_stream->state.i_pes_used = 0;
1364 p_pcr_stream->state.i_pes_length = 0;
1370 int i_header_size = 0;
1371 int i_max_pes_size = 0;
1372 int b_data_alignment = 0;
1373 if( p_input->p_fmt->i_cat == SPU_ES ) switch (p_input->p_fmt->i_codec)
1375 case VLC_CODEC_SUBT:
1376 /* Prepend header */
1377 p_data = block_Realloc( p_data, 2, p_data->i_buffer );
1378 p_data->p_buffer[0] = ( (p_data->i_buffer - 2) >> 8) & 0xff;
1379 p_data->p_buffer[1] = ( (p_data->i_buffer - 2) ) & 0xff;
1381 /* remove trailling \0 if any */
1382 if( p_data->i_buffer > 2 && !p_data->p_buffer[p_data->i_buffer-1] )
1385 /* Append a empty sub (sub text only) */
1386 if( p_data->i_length > 0 &&
1387 ( p_data->i_buffer != 1 || *p_data->p_buffer != ' ' ) )
1389 block_t *p_spu = block_Alloc( 3 );
1391 p_spu->i_dts = p_data->i_dts + p_data->i_length;
1392 p_spu->i_pts = p_spu->i_dts;
1393 p_spu->i_length = 1000;
1395 p_spu->p_buffer[0] = 0;
1396 p_spu->p_buffer[1] = 1;
1397 p_spu->p_buffer[2] = ' ';
1399 EStoPES( &p_spu, p_input->p_fmt,
1400 p_stream->pes.i_stream_id, 1, 0, 0, 0, p_sys->first_dts );
1401 p_data->p_next = p_spu;
1405 case VLC_CODEC_TELETEXT:
1407 i_header_size = 0x24;
1408 b_data_alignment = 1;
1411 case VLC_CODEC_DVBS:
1413 b_data_alignment = 1;
1416 else if( p_data->i_length < 0 || p_data->i_length > 2000000 )
1418 /* FIXME choose a better value, but anyway we
1419 * should never have to do that */
1420 p_data->i_length = 1000;
1423 p_stream->state.i_pes_length += p_data->i_length;
1424 if( p_stream->state.i_pes_dts == 0 )
1426 p_stream->state.i_pes_dts = p_data->i_dts;
1429 /* Convert to pes */
1430 if( p_stream->pes.i_stream_id == 0xa0 && p_data->i_pts <= 0 )
1432 /* XXX yes I know, it's awful, but it's needed,
1433 * so don't remove it ... */
1434 p_data->i_pts = p_data->i_dts;
1437 if( p_input->p_fmt->i_codec == VLC_CODEC_DIRAC )
1439 b_data_alignment = 1;
1440 /* dirac pes packets should be unbounded in
1441 * length, specify a suitibly large max size */
1442 i_max_pes_size = INT_MAX;
1445 EStoPES ( &p_data, p_input->p_fmt, p_stream->pes.i_stream_id,
1446 1, b_data_alignment, i_header_size,
1447 i_max_pes_size, p_sys->first_dts );
1449 BufferChainAppend( &p_stream->state.chain_pes, p_data );
1451 if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1452 && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
1453 && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
1454 && (p_stream->state.i_pes_length > 400000) )
1456 i_shaping_delay = p_stream->state.i_pes_length;
1457 p_stream->state.b_key_frame = 1;
1462 const mtime_t i_pcr_length = p_pcr_stream->state.i_pes_length;
1463 p_pcr_stream->state.b_key_frame = 0;
1465 /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
1466 /* 2: calculate non accurate total size of muxed ts */
1467 int i_packet_count = 0;
1468 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1470 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
1472 /* False for pcr stream but it will be enough to do PCR algo */
1473 for (block_t *p_pes = p_stream->state.chain_pes.p_first; p_pes != NULL;
1474 p_pes = p_pes->p_next )
1476 int i_size = p_pes->i_buffer;
1477 if( p_pes->i_dts + p_pes->i_length >
1478 p_pcr_stream->state.i_pes_dts + p_pcr_stream->state.i_pes_length )
1480 mtime_t i_frag = p_pcr_stream->state.i_pes_dts +
1481 p_pcr_stream->state.i_pes_length - p_pes->i_dts;
1487 i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1489 i_packet_count += ( i_size + 183 ) / 184;
1492 /* add overhead for PCR (not really exact) */
1493 i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1495 /* 3: mux PES into TS */
1496 BufferChainInit( &chain_ts );
1497 /* append PAT/PMT -> FIXME with big pcr delay it won't have enough pat/pmt */
1498 bool pat_was_previous = true; //This is to prevent unnecessary double PAT/PMT insertions
1499 GetPAT( p_mux, &chain_ts );
1500 GetPMT( p_mux, &chain_ts );
1501 int i_packet_pos = 0;
1502 i_packet_count += chain_ts.i_depth;
1503 /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1505 const mtime_t i_pcr_dts = p_pcr_stream->state.i_pes_dts;
1510 sout_input_sys_t *p_stream;
1512 /* Select stream (lowest dts) */
1513 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1515 p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
1517 if( p_stream->state.i_pes_dts == 0 )
1522 if( i_stream == -1 || p_stream->state.i_pes_dts < i_dts )
1525 i_dts = p_stream->state.i_pes_dts;
1528 if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1532 p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i_stream]->p_sys;
1533 sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1535 /* do we need to issue pcr */
1537 if( p_stream == p_pcr_stream &&
1538 i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
1539 p_sys->i_pcr + p_sys->i_pcr_delay )
1542 p_sys->i_pcr = i_pcr_dts + i_packet_pos *
1543 i_pcr_length / i_packet_count;
1546 /* Build the TS packet */
1547 block_t *p_ts = TSNew( p_mux, p_stream, b_pcr );
1548 if( p_sys->csa != NULL &&
1549 (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) &&
1550 (p_input->p_fmt->i_cat != VIDEO_ES || p_sys->b_crypt_video) )
1552 p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1556 /* Write PAT/PMT before every keyframe if use-key-frames is enabled,
1557 * this helps to do segmenting with livehttp-output so it can cut segment
1558 * and start new one with pat,pmt,keyframe*/
1559 if( ( p_sys->b_use_key_frames ) && ( p_ts->i_flags & BLOCK_FLAG_TYPE_I ) )
1561 if( likely( !pat_was_previous ) )
1563 int startcount = chain_ts.i_depth;
1564 GetPAT( p_mux, &chain_ts );
1565 GetPMT( p_mux, &chain_ts );
1566 SetHeader( &chain_ts, startcount );
1567 i_packet_count += (chain_ts.i_depth - startcount );
1569 SetHeader( &chain_ts, 0); //We just inserted pat/pmt,so just flag it instead of adding new one
1572 pat_was_previous = false;
1575 BufferChainAppend( &chain_ts, p_ts );
1578 /* 4: date and send */
1579 TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
1583 /*****************************************************************************
1584 * Mux: Call each time there is new data for at least one stream
1585 *****************************************************************************
1587 *****************************************************************************/
1588 static int Mux( sout_mux_t *p_mux )
1590 sout_mux_sys_t *p_sys = p_mux->p_sys;
1592 if( p_sys->i_pcr_pid == 0x1fff )
1594 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1596 block_FifoEmpty( p_mux->pp_inputs[i]->p_fifo );
1598 msg_Dbg( p_mux, "waiting for PCR streams" );
1602 while (!MuxStreams(p_mux))
1607 #define STD_PES_PAYLOAD 170
1608 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo )
1614 p_data = block_FifoShow( p_fifo );
1615 i_size = p_data->i_buffer;
1617 if( i_size == STD_PES_PAYLOAD )
1619 return block_FifoGet( p_fifo );
1621 else if( i_size > STD_PES_PAYLOAD )
1623 block_t *p_new = block_Alloc( STD_PES_PAYLOAD );
1624 memcpy( p_new->p_buffer, p_data->p_buffer, STD_PES_PAYLOAD );
1625 p_new->i_pts = p_data->i_pts;
1626 p_new->i_dts = p_data->i_dts;
1627 p_new->i_length = p_data->i_length * STD_PES_PAYLOAD
1629 p_data->i_buffer -= STD_PES_PAYLOAD;
1630 p_data->p_buffer += STD_PES_PAYLOAD;
1631 p_data->i_pts += p_new->i_length;
1632 p_data->i_dts += p_new->i_length;
1633 p_data->i_length -= p_new->i_length;
1634 p_data->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1642 p_data = block_FifoGet( p_fifo );
1643 p_data = block_Realloc( p_data, 0, STD_PES_PAYLOAD );
1644 p_next = block_FifoShow( p_fifo );
1645 if ( p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME )
1647 p_data->i_flags &= ~BLOCK_FLAG_NO_KEYFRAME;
1648 p_data->i_pts = p_next->i_pts;
1649 p_data->i_dts = p_next->i_dts;
1651 i_copy = __MIN( STD_PES_PAYLOAD - i_size, p_next->i_buffer );
1653 memcpy( &p_data->p_buffer[i_size], p_next->p_buffer, i_copy );
1654 p_next->i_pts += p_next->i_length * i_copy / p_next->i_buffer;
1655 p_next->i_dts += p_next->i_length * i_copy / p_next->i_buffer;
1656 p_next->i_length -= p_next->i_length * i_copy / p_next->i_buffer;
1657 p_next->i_buffer -= i_copy;
1658 p_next->p_buffer += i_copy;
1659 p_next->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1661 if( !p_next->i_buffer )
1663 p_next = block_FifoGet( p_fifo );
1664 block_Release( p_next );
1670 static block_t *Add_ADTS( block_t *p_data, es_format_t *p_fmt )
1672 #define ADTS_HEADER_SIZE 7 /* CRC needs 2 more bytes */
1674 uint8_t *p_extra = p_fmt->p_extra;
1676 if( !p_data || p_fmt->i_extra < 2 || !p_extra )
1677 return p_data; /* no data to construct the headers */
1679 size_t frame_length = p_data->i_buffer + ADTS_HEADER_SIZE;
1680 int i_index = ( (p_extra[0] << 1) | (p_extra[1] >> 7) ) & 0x0f;
1681 int i_profile = (p_extra[0] >> 3) - 1; /* i_profile < 4 */
1683 if( i_index == 0x0f && p_fmt->i_extra < 5 )
1684 return p_data; /* not enough data */
1686 int i_channels = (p_extra[i_index == 0x0f ? 4 : 1] >> 3) & 0x0f;
1688 block_t *p_new_block = block_Realloc( p_data, ADTS_HEADER_SIZE,
1690 uint8_t *p_buffer = p_new_block->p_buffer;
1694 p_buffer[1] = 0xf1; /* 0xf0 | 0x00 | 0x00 | 0x01 */
1695 p_buffer[2] = (i_profile << 6) | ((i_index & 0x0f) << 2) | ((i_channels >> 2) & 0x01) ;
1696 p_buffer[3] = (i_channels << 6) | ((frame_length >> 11) & 0x03);
1698 /* variable header (starts at last 2 bits of 4th byte) */
1700 int i_fullness = 0x7ff; /* 0x7ff means VBR */
1701 /* XXX: We should check if it's CBR or VBR, but no known implementation
1702 * do that, and it's a pain to calculate this field */
1704 p_buffer[4] = frame_length >> 3;
1705 p_buffer[5] = ((frame_length & 0x07) << 5) | ((i_fullness >> 6) & 0x1f);
1706 p_buffer[6] = ((i_fullness & 0x3f) << 2) /* | 0xfc */;
1711 static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1712 mtime_t i_pcr_length, mtime_t i_pcr_dts )
1714 sout_mux_sys_t *p_sys = p_mux->p_sys;
1715 sout_buffer_chain_t new_chain;
1716 int i_packet_count = p_chain_ts->i_depth;
1718 BufferChainInit( &new_chain );
1720 if ( i_pcr_length <= 0 )
1722 i_pcr_length = i_packet_count;
1725 for (int i = 0; i < i_packet_count; i++ )
1727 block_t *p_ts = BufferChainGet( p_chain_ts );
1728 mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1730 BufferChainAppend( &new_chain, p_ts );
1732 if (!p_ts->i_dts || p_ts->i_dts + p_sys->i_dts_delay * 2/3 >= i_new_dts)
1735 mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
1736 mtime_t i_cut_dts = p_ts->i_dts;
1738 p_ts = BufferChainPeek( p_chain_ts );
1740 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1741 while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1743 p_ts = BufferChainGet( p_chain_ts );
1744 i_max_diff = i_new_dts - p_ts->i_dts;
1745 i_cut_dts = p_ts->i_dts;
1746 BufferChainAppend( &new_chain, p_ts );
1748 p_ts = BufferChainPeek( p_chain_ts );
1750 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1752 msg_Dbg( p_mux, "adjusting rate at %"PRId64"/%"PRId64" (%d/%d)",
1753 i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
1754 p_chain_ts->i_depth );
1755 if ( new_chain.i_depth )
1756 TSDate( p_mux, &new_chain, i_cut_dts - i_pcr_dts, i_pcr_dts );
1757 if ( p_chain_ts->i_depth )
1758 TSSchedule( p_mux, p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
1763 if ( new_chain.i_depth )
1764 TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
1767 static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1768 mtime_t i_pcr_length, mtime_t i_pcr_dts )
1770 sout_mux_sys_t *p_sys = p_mux->p_sys;
1771 int i_packet_count = p_chain_ts->i_depth;
1773 if ( i_pcr_length / 1000 > 0 )
1775 int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
1776 / (uint64_t)(i_pcr_length / 1000);
1777 if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
1779 msg_Warn( p_mux, "max bitrate exceeded at %"PRId64
1780 " (%d bi/s for %d pkt in %"PRId64" us)",
1781 i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1782 i_bitrate, i_packet_count, i_pcr_length);
1787 /* This shouldn't happen, but happens in some rare heavy load
1788 * and packet losses conditions. */
1789 i_pcr_length = i_packet_count;
1792 /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
1793 for (int i = 0; i < i_packet_count; i++ )
1795 block_t *p_ts = BufferChainGet( p_chain_ts );
1796 mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1798 p_ts->i_dts = i_new_dts;
1799 p_ts->i_length = i_pcr_length / i_packet_count;
1801 if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1803 /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
1804 TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay - p_sys->first_dts );
1806 if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1808 vlc_mutex_lock( &p_sys->csa_lock );
1809 csa_Encrypt( p_sys->csa, p_ts->p_buffer, p_sys->i_csa_pkt_size );
1810 vlc_mutex_unlock( &p_sys->csa_lock );
1814 p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
1816 sout_AccessOutWrite( p_mux->p_access, p_ts );
1820 static block_t *TSNew( sout_mux_t *p_mux, sout_input_sys_t *p_stream,
1824 block_t *p_pes = p_stream->state.chain_pes.p_first;
1826 bool b_new_pes = false;
1827 bool b_adaptation_field = false;
1829 int i_payload_max = 184 - ( b_pcr ? 8 : 0 );
1831 if( p_stream->state.i_pes_used <= 0 )
1835 int i_payload = __MIN( (int)p_pes->i_buffer - p_stream->state.i_pes_used,
1838 if( b_pcr || i_payload < i_payload_max )
1840 b_adaptation_field = true;
1843 block_t *p_ts = block_Alloc( 188 );
1845 if (b_new_pes && !(p_pes->i_flags & BLOCK_FLAG_NO_KEYFRAME) && p_pes->i_flags & BLOCK_FLAG_TYPE_I)
1847 p_ts->i_flags |= BLOCK_FLAG_TYPE_I;
1850 p_ts->i_dts = p_pes->i_dts;
1852 p_ts->p_buffer[0] = 0x47;
1853 p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
1854 ( ( p_stream->ts.i_pid >> 8 )&0x1f );
1855 p_ts->p_buffer[2] = p_stream->ts.i_pid & 0xff;
1856 p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
1857 p_stream->ts.i_continuity_counter;
1859 p_stream->ts.i_continuity_counter = (p_stream->ts.i_continuity_counter+1)%16;
1860 p_stream->ts.b_discontinuity = p_pes->i_flags & BLOCK_FLAG_DISCONTINUITY;
1862 if( b_adaptation_field )
1864 int i_stuffing = i_payload_max - i_payload;
1867 p_ts->i_flags |= BLOCK_FLAG_CLOCK;
1869 p_ts->p_buffer[4] = 7 + i_stuffing;
1870 p_ts->p_buffer[5] = 1 << 4; /* PCR_flag */
1871 if( p_stream->ts.b_discontinuity )
1873 p_ts->p_buffer[5] |= 0x80; /* flag TS dicontinuity */
1874 p_stream->ts.b_discontinuity = false;
1876 memset(&p_ts->p_buffer[12], 0xff, i_stuffing);
1880 p_ts->p_buffer[4] = --i_stuffing;
1883 p_ts->p_buffer[5] = 0;
1884 memset(&p_ts->p_buffer[6], 0xff, i_stuffing);
1890 memcpy( &p_ts->p_buffer[188 - i_payload],
1891 &p_pes->p_buffer[p_stream->state.i_pes_used], i_payload );
1893 p_stream->state.i_pes_used += i_payload;
1894 p_stream->state.i_pes_dts = p_pes->i_dts + p_pes->i_length *
1895 p_stream->state.i_pes_used / p_pes->i_buffer;
1896 p_stream->state.i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
1898 if( p_stream->state.i_pes_used >= (int)p_pes->i_buffer )
1900 block_Release(BufferChainGet( &p_stream->state.chain_pes ));
1902 p_pes = p_stream->state.chain_pes.p_first;
1903 p_stream->state.i_pes_length = 0;
1906 p_stream->state.i_pes_dts = p_pes->i_dts;
1909 p_stream->state.i_pes_length += p_pes->i_length;
1910 p_pes = p_pes->p_next;
1915 p_stream->state.i_pes_dts = 0;
1917 p_stream->state.i_pes_used = 0;
1923 static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
1925 mtime_t i_pcr = 9 * i_dts / 100;
1927 p_ts->p_buffer[6] = ( i_pcr >> 25 )&0xff;
1928 p_ts->p_buffer[7] = ( i_pcr >> 17 )&0xff;
1929 p_ts->p_buffer[8] = ( i_pcr >> 9 )&0xff;
1930 p_ts->p_buffer[9] = ( i_pcr >> 1 )&0xff;
1931 p_ts->p_buffer[10] = ( i_pcr << 7 )&0x80;
1932 p_ts->p_buffer[10] |= 0x7e;
1933 p_ts->p_buffer[11] = 0; /* we don't set PCR extension */
1936 void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
1938 sout_mux_sys_t *p_sys = p_mux->p_sys;
1940 BuildPAT( DVBPSI_HANDLE_PARAM(p_sys->p_dvbpsi)
1941 c, (PEStoTSCallback)BufferChainAppend,
1942 p_sys->i_tsid, p_sys->i_pat_version_number,
1944 p_sys->i_num_pmt, p_sys->pmt, p_sys->i_pmt_program_number );
1947 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
1949 sout_mux_sys_t *p_sys = p_mux->p_sys;
1950 pes_mapped_stream_t mappeds[p_mux->i_nb_inputs];
1952 for (int i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
1954 sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1955 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1957 int i_pidinput = p_input->p_fmt->i_id;
1958 pmt_map_t *p_usepid = bsearch( &i_pidinput, p_sys->pmtmap,
1959 p_sys->i_pmtslots, sizeof(pmt_map_t), intcompare );
1961 /* If there's an error somewhere, dump it to the first pmt */
1962 mappeds[i_stream].i_mapped_prog = p_usepid ? p_usepid->i_prog : 0;
1963 mappeds[i_stream].fmt = p_input->p_fmt;
1964 mappeds[i_stream].pes = &p_stream->pes;
1965 mappeds[i_stream].ts = &p_stream->ts;
1968 BuildPMT( DVBPSI_HANDLE_PARAM(p_sys->p_dvbpsi) VLC_OBJECT(p_mux),
1969 c, (PEStoTSCallback)BufferChainAppend,
1970 p_sys->i_tsid, p_sys->i_pmt_version_number,
1973 p_sys->i_num_pmt, p_sys->pmt, p_sys->i_pmt_program_number,
1974 p_mux->i_nb_inputs, mappeds );