mux:ts: fix variables that are mtime_t
[vlc.git] / modules / mux / mpeg / ts.c
blob65f28bedc380ae410107fd13825596a21b4880fa
1 /*****************************************************************************
2 * ts.c: MPEG-II TS Muxer
3 *****************************************************************************
4 * Copyright (C) 2001-2005 VLC authors and VideoLAN
5 * $Id$
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 /*****************************************************************************
28 * Preamble
29 *****************************************************************************/
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
35 #include <limits.h>
37 #include <vlc_common.h>
38 #include <vlc_plugin.h>
39 #include <vlc_sout.h>
40 #include <vlc_block.h>
41 #include <vlc_rand.h>
42 #include <vlc_charset.h>
44 #include <vlc_iso_lang.h>
46 #include "bits.h"
47 #include "pes.h"
48 #include "csa.h"
49 #include "tsutil.h"
50 #include "streams.h"
52 # include <dvbpsi/dvbpsi.h>
53 # include <dvbpsi/demux.h>
54 # include <dvbpsi/descriptor.h>
55 # include <dvbpsi/pat.h>
56 # include <dvbpsi/pmt.h>
57 # include <dvbpsi/sdt.h>
58 # include <dvbpsi/dr.h>
59 # include <dvbpsi/psi.h>
61 #include "dvbpsi_compat.h"
63 #include "tables.h"
65 #include "../../codec/jpeg2000.h"
68 * TODO:
69 * - check PCR frequency requirement
70 * - check PAT/PMT " "
71 * - check PCR/PCR "soft"
72 * - check if "registration" descriptor : "AC-3" should be a program
73 * descriptor or an es one. (xine want an es one)
75 * - remove creation of PAT/PMT without dvbpsi
76 * - ?
77 * FIXME:
78 * - subtitle support is far from perfect. I expect some subtitles drop
79 * if they arrive a bit late
80 * (We cannot rely on the fact that the fifo should be full)
83 /*****************************************************************************
84 * Callback prototypes
85 *****************************************************************************/
86 static int ChangeKeyCallback ( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
87 static int ActiveKeyCallback ( vlc_object_t *, char const *, vlc_value_t, vlc_value_t, void * );
89 /*****************************************************************************
90 * Module descriptor
91 *****************************************************************************/
92 static int Open ( vlc_object_t * );
93 static void Close ( vlc_object_t * );
95 static const char *const ts_standards_list[] =
96 { "dvb", "atsc", };
97 static const char *const ts_standards_list_text[] =
98 { "DVB", "ATSC", };
100 #define STANDARD_TEXT N_("Digital TV Standard")
102 #define VPID_TEXT N_("Video PID")
103 #define VPID_LONGTEXT N_("Assign a fixed PID to the video stream. The PCR " \
104 "PID will automatically be the video.")
105 #define APID_TEXT N_("Audio PID")
106 #define APID_LONGTEXT N_("Assign a fixed PID to the audio stream.")
107 #define SPUPID_TEXT N_("SPU PID")
108 #define SPUPID_LONGTEXT N_("Assign a fixed PID to the SPU.")
109 #define PMTPID_TEXT N_("PMT PID")
110 #define PMTPID_LONGTEXT N_("Assign a fixed PID to the PMT")
111 #define TSID_TEXT N_("TS ID")
112 #define TSID_LONGTEXT N_("Assign a fixed Transport Stream ID.")
113 #define NETID_TEXT N_("NET ID")
114 #define NETID_LONGTEXT N_("Assign a fixed Network ID (for SDT table)")
116 #define PMTPROG_TEXT N_("PMT Program numbers")
117 #define PMTPROG_LONGTEXT N_("Assign a program number to each PMT. This " \
118 "requires \"Set PID to ID of ES\" to be enabled." )
120 #define MUXPMT_TEXT N_("Mux PMT (requires --sout-ts-es-id-pid)")
121 #define MUXPMT_LONGTEXT N_("Define the pids to add to each pmt. This " \
122 "requires \"Set PID to ID of ES\" to be enabled." )
124 #define SDTDESC_TEXT N_("SDT Descriptors (requires --sout-ts-es-id-pid)")
125 #define SDTDESC_LONGTEXT N_("Defines the descriptors of each SDT. This " \
126 "requires \"Set PID to ID of ES\" to be enabled." )
128 #define PID_TEXT N_("Set PID to ID of ES")
129 #define PID_LONGTEXT N_("Sets PID to the ID if the incoming ES. This is for " \
130 "use with --ts-es-id-pid, and allows having the same PIDs in the input " \
131 "and output streams.")
133 #define ALIGNMENT_TEXT N_("Data alignment")
134 #define ALIGNMENT_LONGTEXT N_("Enforces alignment of all access units on " \
135 "PES boundaries. Disabling this might save some bandwidth but introduce incompatibilities.")
137 #define SHAPING_TEXT N_("Shaping delay (ms)")
138 #define SHAPING_LONGTEXT N_("Cut the " \
139 "stream in slices of the given duration, and ensure a constant bitrate " \
140 "between the two boundaries. This avoids having huge bitrate peaks, " \
141 "especially for reference frames." )
143 #define KEYF_TEXT N_("Use keyframes")
144 #define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " \
145 "the TS muxer will place the boundaries at the end of I pictures. In " \
146 "that case, the shaping duration given by the user is a worse case " \
147 "used when no reference frame is available. This enhances the efficiency " \
148 "of the shaping algorithm, since I frames are usually the biggest " \
149 "frames in the stream.")
151 #define PCR_TEXT N_("PCR interval (ms)")
152 #define PCR_LONGTEXT N_("Set at which interval " \
153 "PCRs (Program Clock Reference) will be sent (in milliseconds). " \
154 "This value should be below 100ms. (default is 70ms).")
156 #define BMIN_TEXT N_( "Minimum B (deprecated)")
157 #define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )
159 #define BMAX_TEXT N_( "Maximum B (deprecated)")
160 #define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")
162 #define DTS_TEXT N_("DTS delay (ms)")
163 #define DTS_LONGTEXT N_("Delay the DTS (decoding time " \
164 "stamps) and PTS (presentation timestamps) of the data in the " \
165 "stream, compared to the PCRs. This allows for some buffering inside " \
166 "the client decoder.")
168 #define ACRYPT_TEXT N_("Crypt audio")
169 #define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
170 #define VCRYPT_TEXT N_("Crypt video")
171 #define VCRYPT_LONGTEXT N_("Crypt video using CSA")
173 #define CK_TEXT N_("CSA Key")
174 #define CK_LONGTEXT N_("CSA encryption key. This must be a " \
175 "16 char string (8 hexadecimal bytes).")
177 #define CK2_TEXT N_("Second CSA Key")
178 #define CK2_LONGTEXT N_("The even CSA encryption key. This must be a " \
179 "16 char string (8 hexadecimal bytes).")
181 #define CU_TEXT N_("CSA Key in use")
182 #define CU_LONGTEXT N_("CSA encryption key used. It can be the odd/first/1 " \
183 "(default) or the even/second/2 one.")
185 #define CPKT_TEXT N_("Packet size in bytes to encrypt")
186 #define CPKT_LONGTEXT N_("Size of the TS packet to encrypt. " \
187 "The encryption routines subtract the TS-header from the value before " \
188 "encrypting." )
190 #define SOUT_CFG_PREFIX "sout-ts-"
191 #define MAX_PMT 64 /* Maximum number of programs. FIXME: I just chose an arbitrary number. Where is the maximum in the spec? */
192 #define MAX_PMT_PID 64 /* Maximum pids in each pmt. FIXME: I just chose an arbitrary number. Where is the maximum in the spec? */
193 #if MAX_SDT_DESC < MAX_PMT
194 #error "MAX_SDT_DESC < MAX_PMT"
195 #endif
197 #define BLOCK_FLAG_NO_KEYFRAME (1 << BLOCK_FLAG_PRIVATE_SHIFT) /* This is not a key frame for bitrate shaping */
199 vlc_module_begin ()
200 set_description( N_("TS muxer (libdvbpsi)") )
201 set_shortname( "MPEG-TS")
202 set_category( CAT_SOUT )
203 set_subcategory( SUBCAT_SOUT_MUX )
204 set_capability( "sout mux", 120 )
205 add_shortcut( "ts" )
207 add_string( SOUT_CFG_PREFIX "standard", "dvb", STANDARD_TEXT, NULL, true )
208 change_string_list( ts_standards_list, ts_standards_list_text )
209 add_integer(SOUT_CFG_PREFIX "pid-video", 100, VPID_TEXT, VPID_LONGTEXT, true)
210 change_integer_range( 32, 8190 )
211 add_integer(SOUT_CFG_PREFIX "pid-audio", 200, APID_TEXT, APID_LONGTEXT, true)
212 change_integer_range( 32, 8190 )
213 add_integer(SOUT_CFG_PREFIX "pid-spu", 300, SPUPID_TEXT, SPUPID_LONGTEXT, true)
214 change_integer_range( 32, 8190 )
215 add_integer(SOUT_CFG_PREFIX "pid-pmt", 32, PMTPID_TEXT, PMTPID_LONGTEXT, true)
216 change_integer_range( 32, 8190 )
217 add_integer(SOUT_CFG_PREFIX "tsid", 0, TSID_TEXT, TSID_LONGTEXT, true)
218 add_integer(SOUT_CFG_PREFIX "netid", 0, NETID_TEXT, NETID_LONGTEXT, true)
219 add_string(SOUT_CFG_PREFIX "program-pmt", NULL, PMTPROG_TEXT, PMTPROG_LONGTEXT, true)
220 add_bool(SOUT_CFG_PREFIX "es-id-pid", false, PID_TEXT, PID_LONGTEXT, true)
221 add_string(SOUT_CFG_PREFIX "muxpmt", NULL, MUXPMT_TEXT, MUXPMT_LONGTEXT, true)
222 add_string(SOUT_CFG_PREFIX "sdtdesc", NULL, SDTDESC_TEXT, SDTDESC_LONGTEXT, true)
223 add_bool(SOUT_CFG_PREFIX "alignment", true, ALIGNMENT_TEXT, ALIGNMENT_LONGTEXT, true)
225 add_integer(SOUT_CFG_PREFIX "shaping", 200, SHAPING_TEXT, SHAPING_LONGTEXT, true)
226 add_bool(SOUT_CFG_PREFIX "use-key-frames", false, KEYF_TEXT, KEYF_LONGTEXT, true)
228 add_integer( SOUT_CFG_PREFIX "pcr", 70, PCR_TEXT, PCR_LONGTEXT, true)
229 add_integer( SOUT_CFG_PREFIX "bmin", 0, BMIN_TEXT, BMIN_LONGTEXT, true)
230 add_integer( SOUT_CFG_PREFIX "bmax", 0, BMAX_TEXT, BMAX_LONGTEXT, true)
231 add_integer( SOUT_CFG_PREFIX "dts-delay", 400, DTS_TEXT, DTS_LONGTEXT, true)
233 add_bool( SOUT_CFG_PREFIX "crypt-audio", true, ACRYPT_TEXT, ACRYPT_LONGTEXT, true)
234 add_bool( SOUT_CFG_PREFIX "crypt-video", true, VCRYPT_TEXT, VCRYPT_LONGTEXT, true)
235 add_string( SOUT_CFG_PREFIX "csa-ck", NULL, CK_TEXT, CK_LONGTEXT, true)
236 add_string( SOUT_CFG_PREFIX "csa2-ck", NULL, CK2_TEXT, CK2_LONGTEXT, true)
237 add_string( SOUT_CFG_PREFIX "csa-use", "1", CU_TEXT, CU_LONGTEXT, true)
238 add_integer(SOUT_CFG_PREFIX "csa-pkt", 188, CPKT_TEXT, CPKT_LONGTEXT, true)
240 set_callbacks( Open, Close )
241 vlc_module_end ()
243 /*****************************************************************************
244 * Local data structures
245 *****************************************************************************/
246 static const char *const ppsz_sout_options[] = {
247 "standard",
248 "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid",
249 "netid", "sdtdesc",
250 "es-id-pid", "shaping", "pcr", "bmin", "bmax", "use-key-frames",
251 "dts-delay", "csa-ck", "csa2-ck", "csa-use", "csa-pkt", "crypt-audio", "crypt-video",
252 "muxpmt", "program-pmt", "alignment",
253 NULL
256 typedef struct pmt_map_t /* Holds the mapping between the pmt-pid/pmt table */
258 int i_pid;
259 unsigned i_prog;
260 } pmt_map_t;
262 typedef struct
264 int i_depth;
265 block_t *p_first;
266 block_t **pp_last;
267 } sout_buffer_chain_t;
269 static inline void BufferChainInit ( sout_buffer_chain_t *c )
271 c->i_depth = 0;
272 c->p_first = NULL;
273 c->pp_last = &c->p_first;
276 static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
278 *c->pp_last = b;
279 c->i_depth++;
281 while( b->p_next )
283 b = b->p_next;
284 c->i_depth++;
286 c->pp_last = &b->p_next;
289 static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
291 block_t *b = c->p_first;
293 if( b )
295 c->i_depth--;
296 c->p_first = b->p_next;
298 if( c->p_first == NULL )
300 c->pp_last = &c->p_first;
303 b->p_next = NULL;
305 return b;
308 static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
310 block_t *b = c->p_first;
312 return b;
315 static inline void BufferChainClean( sout_buffer_chain_t *c )
317 block_t *b;
319 while( ( b = BufferChainGet( c ) ) )
321 block_Release( b );
323 BufferChainInit( c );
326 typedef struct
328 sout_buffer_chain_t chain_pes;
329 mtime_t i_pes_dts;
330 mtime_t i_pes_length;
331 int i_pes_used;
332 bool b_key_frame;
334 } pes_state_t;
336 typedef struct
338 tsmux_stream_t ts;
339 pesmux_stream_t pes;
340 pes_state_t state;
341 } sout_input_sys_t;
343 typedef struct
345 sout_input_t *p_pcr_input;
347 vlc_mutex_t csa_lock;
349 dvbpsi_t *p_dvbpsi;
350 bool b_es_id_pid;
351 int i_pid_video;
352 int i_pid_audio;
353 int i_pid_spu;
355 int i_tsid;
356 unsigned i_num_pmt;
357 int i_pmtslots;
358 int i_pat_version_number;
359 tsmux_stream_t pat;
361 int i_pmt_version_number;
362 tsmux_stream_t pmt[MAX_PMT];
363 pmt_map_t pmtmap[MAX_PMT_PID];
364 int i_pmt_program_number[MAX_PMT];
365 bool b_data_alignment;
367 sdt_psi_t sdt;
368 ts_mux_standard standard;
370 /* for TS building */
371 int64_t i_bitrate_min;
372 int64_t i_bitrate_max;
374 int64_t i_shaping_delay;
375 int64_t i_pcr_delay;
377 mtime_t i_dts_delay;
378 mtime_t first_dts;
380 bool b_use_key_frames;
382 mtime_t i_pcr; /* last PCR emited */
384 csa_t *csa;
385 int i_csa_pkt_size;
386 bool b_crypt_audio;
387 bool b_crypt_video;
388 } sout_mux_sys_t;
391 static int GetNextFreePID( sout_mux_t *p_mux, int i_pid_start )
393 sout_mux_sys_t *p_sys = p_mux->p_sys;
395 restart:
396 for(unsigned i=i_pid_start; i<p_sys->i_num_pmt; i++)
398 if(p_sys->pmt[i].i_pid == i_pid_start)
400 i_pid_start++;
401 goto restart;
405 for(int i=0; i<p_mux->i_nb_inputs; i++)
407 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
408 if(p_stream->ts.i_pid == i_pid_start)
410 i_pid_start++;
411 goto restart;
415 if( i_pid_start > 8190 )
417 i_pid_start = 32;
418 goto restart;
421 return i_pid_start;
424 /* Reserve a pid and return it */
425 static int AllocatePID( sout_mux_t *p_mux, int i_cat )
427 sout_mux_sys_t *p_sys = p_mux->p_sys;
428 int i_pid;
429 int *pi_candidate_pid = NULL;
431 switch( i_cat )
433 case VIDEO_ES:
434 pi_candidate_pid = &p_sys->i_pid_video;
435 break;
437 case AUDIO_ES:
438 pi_candidate_pid = &p_sys->i_pid_audio;
439 break;
441 case SPU_ES:
442 default:
443 pi_candidate_pid = &p_sys->i_pid_spu;
444 break;
447 *pi_candidate_pid = GetNextFreePID( p_mux, *pi_candidate_pid );
448 i_pid = (*pi_candidate_pid)++;
450 return i_pid;
453 static int pmtcompare( const void *pa, const void *pb )
455 int id1 = ((pmt_map_t *)pa)->i_pid;
456 int id2 = ((pmt_map_t *)pb)->i_pid;
458 return id1 - id2;
461 static int intcompare( const void *pa, const void *pb )
463 return *(int*)pa - *(int*)pb;
466 /*****************************************************************************
467 * Local prototypes
468 *****************************************************************************/
469 static int Control ( sout_mux_t *, int, va_list );
470 static int AddStream( sout_mux_t *, sout_input_t * );
471 static void DelStream( sout_mux_t *, sout_input_t * );
472 static int Mux ( sout_mux_t * );
474 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo );
475 static block_t *Add_ADTS( block_t *, const es_format_t * );
476 static void TSSchedule ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
477 mtime_t i_pcr_length, mtime_t i_pcr_dts );
478 static void TSDate ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
479 mtime_t i_pcr_length, mtime_t i_pcr_dts );
480 static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
481 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
483 static block_t *TSNew( sout_mux_t *p_mux, sout_input_sys_t *p_stream, bool b_pcr );
484 static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
486 static csa_t *csaSetup( vlc_object_t *p_this )
488 sout_mux_t *p_mux = (sout_mux_t*)p_this;
489 sout_mux_sys_t *p_sys = p_mux->p_sys;
490 char *csack = var_CreateGetNonEmptyStringCommand( p_mux, SOUT_CFG_PREFIX "csa-ck" );
491 if( !csack )
492 return NULL;
494 csa_t *csa = csa_New();
496 if( csa_SetCW( p_this, csa, csack, true ) )
498 free(csack);
499 csa_Delete( csa );
500 return NULL;
503 vlc_mutex_init( &p_sys->csa_lock );
504 p_sys->b_crypt_audio = var_GetBool( p_mux, SOUT_CFG_PREFIX "crypt-audio" );
505 p_sys->b_crypt_video = var_GetBool( p_mux, SOUT_CFG_PREFIX "crypt-video" );
507 char *csa2ck = var_CreateGetNonEmptyStringCommand( p_mux, SOUT_CFG_PREFIX "csa2-ck");
508 if (!csa2ck || csa_SetCW( p_this, csa, csa2ck, false ) )
509 csa_SetCW( p_this, csa, csack, false );
510 free(csa2ck);
512 var_Create( p_mux, SOUT_CFG_PREFIX "csa-use", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );
513 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
514 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, (void *)1 );
515 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
517 vlc_value_t use_val;
518 var_Get( p_mux, SOUT_CFG_PREFIX "csa-use", &use_val );
519 if ( var_Set( p_mux, SOUT_CFG_PREFIX "csa-use", use_val ) )
520 var_SetString( p_mux, SOUT_CFG_PREFIX "csa-use", "odd" );
521 free( use_val.psz_string );
523 p_sys->i_csa_pkt_size = var_GetInteger( p_mux, SOUT_CFG_PREFIX "csa-pkt" );
524 if( p_sys->i_csa_pkt_size < 12 || p_sys->i_csa_pkt_size > 188 )
526 msg_Err( p_mux, "wrong packet size %d specified",
527 p_sys->i_csa_pkt_size );
528 p_sys->i_csa_pkt_size = 188;
531 msg_Dbg( p_mux, "encrypting %d bytes of packet", p_sys->i_csa_pkt_size );
533 free(csack);
535 return csa;
538 /*****************************************************************************
539 * Open:
540 *****************************************************************************/
541 static int Open( vlc_object_t *p_this )
543 sout_mux_t *p_mux =(sout_mux_t*)p_this;
544 sout_mux_sys_t *p_sys = NULL;
546 config_ChainParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
548 p_sys = calloc( 1, sizeof( sout_mux_sys_t ) );
549 if( !p_sys )
550 return VLC_ENOMEM;
551 p_sys->i_num_pmt = 1;
553 p_sys->p_dvbpsi = dvbpsi_new( &dvbpsi_messages, DVBPSI_MSG_DEBUG );
554 if( !p_sys->p_dvbpsi )
556 free( p_sys );
557 return VLC_ENOMEM;
559 p_sys->p_dvbpsi->p_sys = (void *) p_mux;
561 char *psz_standard = var_GetString( p_mux, SOUT_CFG_PREFIX "standard" );
562 if( psz_standard && !strcmp("atsc", psz_standard) )
563 p_sys->standard = TS_MUX_STANDARD_ATSC;
564 free( psz_standard );
566 p_sys->b_es_id_pid = var_GetBool( p_mux, SOUT_CFG_PREFIX "es-id-pid" );
569 fetch string of pmts. Here's a sample: --sout-ts-muxpmt="0x451,0x200,0x28a,0x240,,0x450,0x201,0x28b,0x241,,0x452,0x202,0x28c,0x242"
570 This would mean 0x451, 0x200, 0x28a, 0x240 would fall under one pmt (program), 0x450,0x201,0x28b,0x241 would fall under another
572 char *muxpmt = var_GetNonEmptyString(p_mux, SOUT_CFG_PREFIX "muxpmt");
573 for (char *psz = muxpmt; psz; )
575 char *psz_next;
576 uint16_t i_pid = strtoul( psz, &psz_next, 0 );
577 psz = *psz_next ? &psz_next[1] : NULL;
579 if ( i_pid == 0 )
581 if ( ++p_sys->i_num_pmt > MAX_PMT )
583 msg_Err( p_mux, "Number of PMTs > %d)", MAX_PMT );
584 p_sys->i_num_pmt = MAX_PMT;
587 else
589 p_sys->pmtmap[p_sys->i_pmtslots].i_pid = i_pid;
590 p_sys->pmtmap[p_sys->i_pmtslots].i_prog = p_sys->i_num_pmt - 1;
591 if ( ++p_sys->i_pmtslots >= MAX_PMT_PID )
593 msg_Err( p_mux, "Number of pids in PMT > %d", MAX_PMT_PID );
594 p_sys->i_pmtslots = MAX_PMT_PID - 1;
598 /* Now sort according to pids for fast search later on */
599 qsort( (void *)p_sys->pmtmap, p_sys->i_pmtslots,
600 sizeof(pmt_map_t), pmtcompare );
601 free(muxpmt);
603 unsigned short subi[3];
604 vlc_rand_bytes(subi, sizeof(subi));
605 p_sys->i_pat_version_number = nrand48(subi) & 0x1f;
607 vlc_value_t val;
608 var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
609 if ( val.i_int )
610 p_sys->i_tsid = val.i_int;
611 else
612 p_sys->i_tsid = nrand48(subi) & 0xffff;
614 var_Get( p_mux, SOUT_CFG_PREFIX "netid", &val );
615 if ( val.i_int )
616 p_sys->sdt.i_netid = val.i_int;
617 else
618 p_sys->sdt.i_netid = 0xff00 | ( nrand48(subi) & 0xfa );
620 p_sys->i_pmt_version_number = nrand48(subi) & 0x1f;
621 p_sys->sdt.ts.i_pid = 0x11;
623 char *sdtdesc = var_GetNonEmptyString( p_mux, SOUT_CFG_PREFIX "sdtdesc" );
625 /* Syntax is provider_sdt1,service_name_sdt1,provider_sdt2,service_name_sdt2... */
626 if( sdtdesc )
628 char *psz_sdttoken = sdtdesc;
630 for (int i = 0; i < MAX_SDT_DESC * 2 && psz_sdttoken; i++)
632 char *psz_end = strchr( psz_sdttoken, ',' );
633 if ( psz_end )
634 *psz_end++ = '\0';
636 if (i % 2)
637 p_sys->sdt.desc[i/2].psz_service_name = FromLocaleDup( psz_sdttoken );
638 else
639 p_sys->sdt.desc[i/2].psz_provider = FromLocaleDup( psz_sdttoken );
641 psz_sdttoken = psz_end;
643 free(sdtdesc);
646 p_sys->b_data_alignment = var_GetBool( p_mux, SOUT_CFG_PREFIX "alignment" );
648 char *pgrpmt = var_GetNonEmptyString(p_mux, SOUT_CFG_PREFIX "program-pmt");
649 if( pgrpmt )
651 char *psz = pgrpmt;
652 char *psz_next = psz;
654 for (int i = 0; psz; )
656 uint16_t i_pid = strtoul( psz, &psz_next, 0 );
657 if( psz_next[0] != '\0' )
658 psz = &psz_next[1];
659 else
660 psz = NULL;
662 if( i_pid == 0 )
664 if( i >= MAX_PMT )
665 msg_Err( p_mux, "Number of PMTs > maximum (%d)", MAX_PMT );
667 else
669 p_sys->i_pmt_program_number[i] = i_pid;
670 i++;
673 free(pgrpmt);
675 else
677 /* Option not specified, use 1, 2, 3... */
678 for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
679 p_sys->i_pmt_program_number[i] = i + 1;
682 var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
683 for (unsigned i = 0; i < p_sys->i_num_pmt; i++ )
684 p_sys->pmt[i].i_pid = val.i_int + i;
686 p_sys->i_pid_video = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
687 p_sys->i_pid_audio = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
688 p_sys->i_pid_spu = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
690 /* Allow to create constrained stream */
691 p_sys->i_bitrate_min = var_GetInteger( p_mux, SOUT_CFG_PREFIX "bmin" );
693 p_sys->i_bitrate_max = var_GetInteger( p_mux, SOUT_CFG_PREFIX "bmax" );
695 if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
696 p_sys->i_bitrate_min > p_sys->i_bitrate_max )
698 msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
699 "disabling bitrate control" );
700 p_sys->i_bitrate_min = 0;
701 p_sys->i_bitrate_max = 0;
703 if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
705 msg_Err( p_mux, "bmin and bmax no more supported "
706 "(if you need them report it)" );
709 var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
710 p_sys->i_shaping_delay = val.i_int * 1000;
711 if( p_sys->i_shaping_delay <= 0 )
713 msg_Err( p_mux,
714 "invalid shaping (%"PRId64"ms) resetting to 200ms",
715 p_sys->i_shaping_delay / 1000 );
716 p_sys->i_shaping_delay = 200000;
719 var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
720 p_sys->i_pcr_delay = val.i_int * 1000;
721 if( p_sys->i_pcr_delay <= 0 ||
722 p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
724 msg_Err( p_mux,
725 "invalid pcr delay (%"PRId64"ms) resetting to 70ms",
726 p_sys->i_pcr_delay / 1000 );
727 p_sys->i_pcr_delay = 70000;
730 var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
731 p_sys->i_dts_delay = val.i_int * 1000;
733 msg_Dbg( p_mux, "shaping=%"PRId64" pcr=%"PRId64" dts_delay=%"PRId64,
734 p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );
736 p_sys->b_use_key_frames = var_GetBool( p_mux, SOUT_CFG_PREFIX "use-key-frames" );
738 p_mux->p_sys = p_sys;
740 p_sys->csa = csaSetup(p_this);
742 p_mux->pf_control = Control;
743 p_mux->pf_addstream = AddStream;
744 p_mux->pf_delstream = DelStream;
745 p_mux->pf_mux = Mux;
747 return VLC_SUCCESS;
750 /*****************************************************************************
751 * Close:
752 *****************************************************************************/
753 static void Close( vlc_object_t * p_this )
755 sout_mux_t *p_mux = (sout_mux_t*)p_this;
756 sout_mux_sys_t *p_sys = p_mux->p_sys;
758 if( p_sys->p_dvbpsi )
759 dvbpsi_delete( p_sys->p_dvbpsi );
761 if( p_sys->csa )
763 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, NULL );
764 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
765 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
766 csa_Delete( p_sys->csa );
767 vlc_mutex_destroy( &p_sys->csa_lock );
770 for (int i = 0; i < MAX_SDT_DESC; i++ )
772 free( p_sys->sdt.desc[i].psz_service_name );
773 free( p_sys->sdt.desc[i].psz_provider );
776 free( p_sys );
779 /*****************************************************************************
780 * ChangeKeyCallback: called when changing the odd encryption key on the fly.
781 *****************************************************************************/
782 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
783 vlc_value_t oldval, vlc_value_t newval,
784 void *p_data )
786 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
787 sout_mux_t *p_mux = (sout_mux_t*)p_this;
788 sout_mux_sys_t *p_sys = p_mux->p_sys;
789 int ret;
791 vlc_mutex_lock(&p_sys->csa_lock);
792 ret = csa_SetCW(p_this, p_sys->csa, newval.psz_string, !!(intptr_t)p_data);
793 vlc_mutex_unlock(&p_sys->csa_lock);
795 return ret;
798 /*****************************************************************************
799 * ActiveKeyCallback: called when changing the active (in use) encryption key on the fly.
800 *****************************************************************************/
801 static int ActiveKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
802 vlc_value_t oldval, vlc_value_t newval,
803 void *p_data )
805 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(p_data);
806 sout_mux_t *p_mux = (sout_mux_t*)p_this;
807 sout_mux_sys_t *p_sys = p_mux->p_sys;
808 int i_res, use_odd = -1;
810 if( !strcmp(newval.psz_string, "odd" ) ||
811 !strcmp(newval.psz_string, "first" ) ||
812 !strcmp(newval.psz_string, "1" ) )
814 use_odd = 1;
816 else if( !strcmp(newval.psz_string, "even" ) ||
817 !strcmp(newval.psz_string, "second" ) ||
818 !strcmp(newval.psz_string, "2" ) )
820 use_odd = 0;
823 if (use_odd < 0)
824 return VLC_EBADVAR;
826 vlc_mutex_lock( &p_sys->csa_lock );
827 i_res = csa_UseKey( p_this, p_sys->csa, use_odd );
828 vlc_mutex_unlock( &p_sys->csa_lock );
830 return i_res;
833 /*****************************************************************************
834 * Control:
835 *****************************************************************************/
836 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
838 VLC_UNUSED(p_mux);
839 bool *pb_bool;
840 char **ppsz;
842 switch( i_query )
844 case MUX_CAN_ADD_STREAM_WHILE_MUXING:
845 pb_bool = va_arg( args, bool * );
846 *pb_bool = true;
847 return VLC_SUCCESS;
849 case MUX_GET_ADD_STREAM_WAIT:
850 pb_bool = va_arg( args, bool * );
851 *pb_bool = false;
852 return VLC_SUCCESS;
854 case MUX_GET_MIME:
855 ppsz = va_arg( args, char ** );
856 *ppsz = strdup( "video/mp2t" );
857 return VLC_SUCCESS;
859 default:
860 return VLC_EGENERIC;
864 /* returns a pointer to a valid string, with length 0 or 3 */
865 static const char *GetIso639_2LangCode(const char *lang)
867 const iso639_lang_t *pl;
869 if (strlen(lang) == 2)
871 pl = GetLang_1(lang);
873 else
875 pl = GetLang_2B(lang); /* try native code first */
876 if (!*pl->psz_iso639_2T)
877 pl = GetLang_2T(lang); /* else fallback to english code */
881 return pl->psz_iso639_2T; /* returns the english code */
884 static void SelectPCRStream( sout_mux_t *p_mux, sout_input_t *p_removed_pcr_input )
886 sout_mux_sys_t *p_sys = p_mux->p_sys;
888 /* Find a new pcr stream (Prefer Video Stream) */
889 if( p_removed_pcr_input != NULL )
890 p_sys->p_pcr_input = NULL;
892 for ( int i = 0; i < p_mux->i_nb_inputs; i++ )
894 sout_input_t *p_input = p_mux->pp_inputs[i];
895 if( p_input == p_removed_pcr_input )
896 continue;
898 if( p_input->p_fmt->i_cat == VIDEO_ES &&
899 (p_sys->p_pcr_input == NULL ||
900 p_sys->p_pcr_input->p_fmt->i_cat != VIDEO_ES) )
902 p_sys->p_pcr_input = p_input;
903 break;
905 else if( p_input->p_fmt->i_cat != SPU_ES &&
906 p_sys->p_pcr_input == NULL )
908 p_sys->p_pcr_input = p_input;
912 if( p_sys->p_pcr_input )
914 /* Empty TS buffer */
915 /* FIXME */
916 msg_Dbg( p_mux, "new PCR PID is %d",
917 ((sout_input_sys_t *)p_sys->p_pcr_input->p_sys)->ts.i_pid );
922 /*****************************************************************************
923 * AddStream: called for each stream addition
924 *****************************************************************************/
925 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
927 sout_mux_sys_t *p_sys = p_mux->p_sys;
928 sout_input_sys_t *p_stream;
930 p_input->p_sys = p_stream = calloc( 1, sizeof( sout_input_sys_t ) );
931 if( !p_stream )
932 goto oom;
934 if ( p_sys->b_es_id_pid )
935 p_stream->ts.i_pid = p_input->fmt.i_id & 0x1fff;
936 else
937 p_stream->ts.i_pid = AllocatePID( p_mux, p_input->p_fmt->i_cat );
939 if( FillPMTESParams( p_sys->standard, p_input->p_fmt,
940 &p_stream->ts, &p_stream->pes ) != VLC_SUCCESS )
942 msg_Warn( p_mux, "rejecting stream with unsupported codec %4.4s",
943 (char*)&p_input->p_fmt->i_codec );
944 free( p_stream );
945 return VLC_EGENERIC;
948 p_stream->pes.i_langs = 1 + p_input->p_fmt->i_extra_languages;
949 p_stream->pes.lang = calloc(1, p_stream->pes.i_langs * 4);
950 if( !p_stream->pes.lang )
951 goto oom;
953 msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
954 (char*)&p_input->fmt.i_codec, p_stream->ts.i_pid );
956 for (size_t i = 0; i < p_stream->pes.i_langs; i++) {
957 char *lang = (i == 0)
958 ? p_input->p_fmt->psz_language
959 : p_input->p_fmt->p_extra_languages[i-1].psz_language;
961 if (!lang)
962 continue;
964 const char *code = GetIso639_2LangCode(lang);
965 if (*code)
967 memcpy(&p_stream->pes.lang[i*4], code, 3);
968 p_stream->pes.lang[i*4+3] = 0x00; /* audio type: 0x00 undefined */
969 msg_Dbg( p_mux, " - lang=%3.3s", &p_stream->pes.lang[i*4] );
973 /* Init pes chain */
974 BufferChainInit( &p_stream->state.chain_pes );
976 /* We only change PMT version (PAT isn't changed) */
977 p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;
979 /* Update pcr_pid */
980 SelectPCRStream( p_mux, NULL );
982 return VLC_SUCCESS;
984 oom:
985 if(p_stream)
987 free(p_stream->pes.lang);
988 free(p_stream);
990 return VLC_ENOMEM;
993 /*****************************************************************************
994 * DelStream: called before a stream deletion
995 *****************************************************************************/
996 static void DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
998 sout_mux_sys_t *p_sys = p_mux->p_sys;
999 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1000 int pid;
1002 msg_Dbg( p_mux, "removing input pid=%d", p_stream->ts.i_pid );
1004 if( p_sys->p_pcr_input == p_input )
1006 /* Repick new PCR */
1007 SelectPCRStream( p_mux, p_input );
1010 /* Empty all data in chain_pes */
1011 BufferChainClean( &p_stream->state.chain_pes );
1013 pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-video" );
1014 if ( pid > 0 && pid == p_stream->ts.i_pid )
1016 p_sys->i_pid_video = pid;
1017 msg_Dbg( p_mux, "freeing video PID %d", pid);
1019 pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-audio" );
1020 if ( pid > 0 && pid == p_stream->ts.i_pid )
1022 p_sys->i_pid_audio = pid;
1023 msg_Dbg( p_mux, "freeing audio PID %d", pid);
1025 pid = var_GetInteger( p_mux, SOUT_CFG_PREFIX "pid-spu" );
1026 if ( pid > 0 && pid == p_stream->ts.i_pid )
1028 p_sys->i_pid_spu = pid;
1029 msg_Dbg( p_mux, "freeing spu PID %d", pid);
1032 free(p_stream->pes.lang);
1033 free( p_stream );
1035 /* We only change PMT version (PAT isn't changed) */
1036 p_sys->i_pmt_version_number++;
1037 p_sys->i_pmt_version_number %= 32;
1040 static void SetHeader( sout_buffer_chain_t *c,
1041 int depth )
1043 block_t *p_ts = BufferChainPeek( c );
1044 while( depth > 0 )
1046 p_ts = p_ts->p_next;
1047 depth--;
1049 p_ts->i_flags |= BLOCK_FLAG_HEADER;
1052 static block_t *Pack_Opus(block_t *p_data)
1054 lldiv_t d = lldiv(p_data->i_buffer, 255);
1055 p_data = block_Realloc(p_data, 2 + d.quot + 1, p_data->i_buffer);
1056 if (p_data) { /* no flags */
1057 p_data->p_buffer[0] = 0x7f;
1058 p_data->p_buffer[1] = 0xe0;
1059 memset(&p_data->p_buffer[2], 0xff, d.quot);
1060 p_data->p_buffer[2+d.quot] = d.rem;
1063 return p_data;
1066 static void SetBlockDuration( sout_input_t *p_input, block_t *p_data )
1068 sout_input_sys_t *p_stream = (sout_input_sys_t*) p_input->p_sys;
1070 if( p_input->p_fmt->i_cat != SPU_ES &&
1071 block_FifoCount( p_input->p_fifo ) > 0 )
1073 block_t *p_next = block_FifoShow( p_input->p_fifo );
1074 mtime_t i_diff = p_next->i_dts - p_data->i_dts;
1075 if( i_diff > 0 &&
1076 (p_next->i_flags & BLOCK_FLAG_DISCONTINUITY) == 0 )
1078 p_data->i_length = i_diff;
1080 else if ( p_data->i_length == 0 )
1082 /* Try rates */
1083 if( p_input->p_fmt->i_cat == VIDEO_ES &&
1084 p_input->p_fmt->video.i_frame_rate &&
1085 p_input->p_fmt->video.i_frame_rate_base )
1087 p_data->i_length = CLOCK_FREQ *
1088 p_input->p_fmt->video.i_frame_rate /
1089 p_input->p_fmt->video.i_frame_rate_base;
1091 else if( p_input->p_fmt->i_cat == AUDIO_ES &&
1092 p_input->p_fmt->audio.i_bytes_per_frame &&
1093 p_input->p_fmt->audio.i_frame_length )
1095 p_data->i_length = p_data->i_buffer *
1096 p_input->p_fmt->audio.i_frame_length /
1097 p_input->p_fmt->audio.i_bytes_per_frame;
1099 /* Try a previous duration */
1100 else if( p_stream->state.chain_pes.p_first )
1101 p_data->i_length = p_stream->state.chain_pes.p_first->i_length;
1102 /* Or next */
1103 else if( p_next->i_length > 0 )
1104 p_data->i_length = p_next->i_length;
1105 /* or worse */
1106 else
1107 p_data->i_length = 1000;
1110 else if( p_input->p_fmt->i_codec != VLC_CODEC_SUBT )
1112 p_data->i_length = 1000;
1116 static block_t *Encap_J2K( block_t *p_data, const es_format_t *p_fmt )
1118 size_t i_offset = 0;
1119 uint32_t i_box = 0;
1120 while( p_data->i_buffer > 8 && p_data->i_buffer - i_offset > 8 )
1122 const uint32_t i_size = GetDWBE( &p_data->p_buffer[i_offset] );
1123 i_box = VLC_FOURCC( p_data->p_buffer[i_offset + 4],
1124 p_data->p_buffer[i_offset + 5],
1125 p_data->p_buffer[i_offset + 6],
1126 p_data->p_buffer[i_offset + 7] );
1127 if( p_data->i_buffer - i_offset < i_size || i_size < 8 )
1129 i_box = 0;
1130 break;
1132 else if( i_box == J2K_BOX_JP2C )
1134 break;
1137 i_offset += i_size;
1140 if( i_box != J2K_BOX_JP2C )
1142 block_Release( p_data );
1143 return NULL;
1146 if( i_offset < 38 )
1148 block_t *p_realloc = block_Realloc( p_data, 38 - i_offset, p_data->i_buffer );
1149 if( unlikely(!p_realloc) )
1151 block_Release( p_data );
1152 return NULL;
1154 p_data = p_realloc;
1156 else
1158 p_data->p_buffer += (i_offset - 38);
1159 p_data->i_buffer -= (i_offset - 38);
1162 const int profile = j2k_get_profile( p_fmt->video.i_visible_width,
1163 p_fmt->video.i_visible_height,
1164 p_fmt->video.i_frame_rate,
1165 p_fmt->video.i_frame_rate_base, true );
1166 memcpy( p_data->p_buffer, "elsmfrat", 8 );
1167 SetWBE( &p_data->p_buffer[8], p_fmt->video.i_frame_rate_base );
1168 SetWBE( &p_data->p_buffer[10], p_fmt->video.i_frame_rate );
1169 memcpy( &p_data->p_buffer[12], "brat", 4 );
1170 unsigned min = j2k_profiles_rates[profile].min * 1000000;
1171 unsigned max = j2k_profiles_rates[profile].max * 1000000;
1172 SetDWBE(&p_data->p_buffer[16], max );
1173 SetDWBE(&p_data->p_buffer[20], min );
1174 memcpy( &p_data->p_buffer[24], "tcod", 4 );
1175 const unsigned s = p_data->i_pts / CLOCK_FREQ;
1176 const unsigned m = s / 60;
1177 const unsigned h = m / 60;
1178 const uint64_t l = p_fmt->video.i_frame_rate_base * CLOCK_FREQ /
1179 p_fmt->video.i_frame_rate;
1180 const unsigned f = (p_data->i_pts % CLOCK_FREQ) / l;
1181 p_data->p_buffer[28] = h;
1182 p_data->p_buffer[29] = m % 60;
1183 p_data->p_buffer[30] = s % 60;
1184 p_data->p_buffer[31] = f;
1185 memcpy( &p_data->p_buffer[32], "bcol", 4 );
1186 p_data->p_buffer[36] = j2k_get_color_spec( p_fmt->video.primaries,
1187 p_fmt->video.transfer,
1188 p_fmt->video.space );
1189 p_data->p_buffer[37] = 0;
1191 return p_data;
1194 /* returns true if needs more data */
1195 static bool MuxStreams(sout_mux_t *p_mux )
1197 sout_mux_sys_t *p_sys = p_mux->p_sys;
1198 sout_input_sys_t *p_pcr_stream = (sout_input_sys_t*)p_sys->p_pcr_input->p_sys;
1200 sout_buffer_chain_t chain_ts;
1201 mtime_t i_shaping_delay = p_pcr_stream->state.b_key_frame
1202 ? p_pcr_stream->state.i_pes_length
1203 : p_sys->i_shaping_delay;
1205 bool b_ok = true;
1207 /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
1208 /* Accumulate enough data in all other stream ( >= length of pcr)*/
1209 for (int i = -1; !b_ok || i < p_mux->i_nb_inputs; i++ )
1211 if (i == p_mux->i_nb_inputs)
1213 /* get enough PES packet for all input */
1214 b_ok = true;
1215 i = -1;
1217 sout_input_t *p_input;
1219 if( i == -1 )
1220 p_input = p_sys->p_pcr_input;
1221 else if( p_mux->pp_inputs[i] != p_sys->p_pcr_input )
1222 p_input = p_mux->pp_inputs[i];
1223 else
1224 continue;
1226 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1228 if( ( p_stream != p_pcr_stream ||
1229 p_stream->state.i_pes_length >= i_shaping_delay ) &&
1230 p_stream->state.i_pes_dts + p_stream->state.i_pes_length >=
1231 p_pcr_stream->state.i_pes_dts + p_pcr_stream->state.i_pes_length )
1232 continue;
1234 /* Need more data */
1235 if( block_FifoCount( p_input->p_fifo ) <= 1 )
1237 if( ( p_input->p_fmt->i_cat == AUDIO_ES ) ||
1238 ( p_input->p_fmt->i_cat == VIDEO_ES ) )
1240 /* We need more data */
1241 return true;
1243 else if( block_FifoCount( p_input->p_fifo ) <= 0 )
1245 /* spu, only one packet is needed */
1246 continue;
1248 else if( p_input->p_fmt->i_cat == SPU_ES )
1250 /* Don't mux the SPU yet if it is too early */
1251 block_t *p_spu = block_FifoShow( p_input->p_fifo );
1253 int64_t i_spu_delay = p_spu->i_dts - p_pcr_stream->state.i_pes_dts;
1254 if( ( i_spu_delay > i_shaping_delay ) &&
1255 ( i_spu_delay < 100 * CLOCK_FREQ ) )
1256 continue;
1258 if ( ( i_spu_delay >= 100 * CLOCK_FREQ ) ||
1259 ( i_spu_delay < CLOCK_FREQ / 100 ) )
1261 BufferChainClean( &p_stream->state.chain_pes );
1262 p_stream->state.i_pes_dts = 0;
1263 p_stream->state.i_pes_used = 0;
1264 p_stream->state.i_pes_length = 0;
1265 continue;
1269 b_ok = false;
1271 block_t *p_data;
1272 if( p_stream == p_pcr_stream || p_sys->b_data_alignment
1273 || ((p_input->p_fmt->i_codec != VLC_CODEC_MPGA ) &&
1274 (p_input->p_fmt->i_codec != VLC_CODEC_MP3) ) )
1276 p_data = block_FifoGet( p_input->p_fifo );
1277 if( p_data->i_dts == VLC_TS_INVALID )
1278 p_data->i_dts = p_data->i_pts;
1279 else if ( p_data->i_pts == VLC_TS_INVALID )
1280 p_data->i_pts = p_data->i_dts;
1282 if( p_input->p_fmt->i_codec == VLC_CODEC_MP4A )
1283 p_data = Add_ADTS( p_data, p_input->p_fmt );
1284 else if( p_input->p_fmt->i_codec == VLC_CODEC_OPUS )
1285 p_data = Pack_Opus( p_data );
1287 else
1288 p_data = FixPES( p_mux, p_input->p_fifo );
1290 SetBlockDuration( p_input, p_data );
1292 if( p_data->i_dts == VLC_TS_INVALID )
1294 msg_Err( p_mux, "non dated packet dropped" );
1295 block_Release( p_data );
1296 continue;
1299 if ( p_sys->first_dts == 0 )
1301 /* Pick the really first DTS */
1302 p_sys->first_dts = p_data->i_dts;
1303 for (int j = 0; j < p_mux->i_nb_inputs; j++ )
1305 if( p_mux->pp_inputs[j] != p_input &&
1306 block_FifoCount( p_mux->pp_inputs[j]->p_fifo) > 0 )
1308 block_t *p_block = block_FifoShow( p_mux->pp_inputs[j]->p_fifo );
1309 if( p_block->i_dts != VLC_TS_INVALID &&
1310 p_block->i_dts < p_sys->first_dts )
1311 p_sys->first_dts = p_block->i_dts;
1316 if( ( p_pcr_stream->state.i_pes_dts > 0 &&
1317 p_data->i_dts - 10 * CLOCK_FREQ > p_pcr_stream->state.i_pes_dts +
1318 p_pcr_stream->state.i_pes_length ) ||
1319 p_data->i_dts + i_shaping_delay < p_stream->state.i_pes_dts ||
1320 ( p_stream->state.i_pes_dts > 0 &&
1321 p_input->p_fmt->i_cat != SPU_ES &&
1322 p_data->i_dts - 10 * CLOCK_FREQ > p_stream->state.i_pes_dts +
1323 p_stream->state.i_pes_length ) )
1325 msg_Warn( p_mux, "packet with too strange dts on pid %d (%4.4s)"
1326 "(dts=%"PRId64",old=%"PRId64",pcr=%"PRId64")",
1327 p_stream->ts.i_pid, (char *) &p_input->fmt.i_codec,
1328 p_data->i_dts, p_stream->state.i_pes_dts,
1329 p_pcr_stream->state.i_pes_dts );
1330 block_Release( p_data );
1332 BufferChainClean( &p_stream->state.chain_pes );
1333 p_stream->state.i_pes_dts = 0;
1334 p_stream->state.i_pes_used = 0;
1335 p_stream->state.i_pes_length = 0;
1337 if( p_input->p_fmt->i_cat != SPU_ES )
1339 BufferChainClean( &p_pcr_stream->state.chain_pes );
1340 p_pcr_stream->state.i_pes_dts = 0;
1341 p_pcr_stream->state.i_pes_used = 0;
1342 p_pcr_stream->state.i_pes_length = 0;
1345 continue;
1348 int i_header_size = 0;
1349 int i_max_pes_size = 0;
1350 int b_data_alignment = 0;
1351 if( p_input->p_fmt->i_cat == SPU_ES ) switch (p_input->p_fmt->i_codec)
1353 case VLC_CODEC_SUBT:
1354 /* Prepend header */
1355 p_data = block_Realloc( p_data, 2, p_data->i_buffer );
1356 p_data->p_buffer[0] = ( (p_data->i_buffer - 2) >> 8) & 0xff;
1357 p_data->p_buffer[1] = ( (p_data->i_buffer - 2) ) & 0xff;
1359 /* remove trailling \0 if any */
1360 if( p_data->i_buffer > 2 && !p_data->p_buffer[p_data->i_buffer-1] )
1361 p_data->i_buffer--;
1363 /* Append a empty sub (sub text only) */
1364 if( p_data->i_length > 0 &&
1365 ( p_data->i_buffer != 1 || *p_data->p_buffer != ' ' ) )
1367 block_t *p_spu = block_Alloc( 3 );
1369 p_spu->i_dts = p_data->i_dts + p_data->i_length;
1370 p_spu->i_pts = p_spu->i_dts;
1371 p_spu->i_length = 1000;
1373 p_spu->p_buffer[0] = 0;
1374 p_spu->p_buffer[1] = 1;
1375 p_spu->p_buffer[2] = ' ';
1377 EStoPES( &p_spu, p_input->p_fmt,
1378 p_stream->pes.i_stream_id, 1, 0, 0, 0,
1379 p_sys->first_dts - p_sys->i_dts_delay );
1380 p_data->p_next = p_spu;
1382 break;
1384 case VLC_CODEC_TELETEXT:
1385 /* EN 300 472 */
1386 i_header_size = 0x24;
1387 b_data_alignment = 1;
1388 break;
1390 case VLC_CODEC_DVBS:
1391 /* EN 300 743 */
1392 b_data_alignment = 1;
1393 break;
1395 else if( p_input->fmt.i_cat == VIDEO_ES )
1397 if( p_input->fmt.i_codec == VLC_CODEC_JPEG2000 )
1399 if( p_data->i_flags & BLOCK_FLAG_INTERLACED_MASK )
1400 msg_Warn( p_mux, "Unsupported interlaced J2K content. Expect broken result");
1401 p_data = Encap_J2K( p_data, &p_input->fmt );
1402 if( !p_data )
1403 return false;
1406 else if( p_data->i_length < 0 || p_data->i_length > 2000000 )
1408 /* FIXME choose a better value, but anyway we
1409 * should never have to do that */
1410 p_data->i_length = 1000;
1413 p_stream->state.i_pes_length += p_data->i_length;
1414 if( p_stream->state.i_pes_dts == 0 )
1416 p_stream->state.i_pes_dts = p_data->i_dts;
1419 /* Convert to pes */
1420 if( p_stream->pes.i_stream_id == 0xa0 && p_data->i_pts <= 0 )
1422 /* XXX yes I know, it's awful, but it's needed,
1423 * so don't remove it ... */
1424 p_data->i_pts = p_data->i_dts;
1427 if( (p_input->p_fmt->i_codec == VLC_CODEC_DIRAC) ||
1428 (p_input->p_fmt->i_codec == VLC_CODEC_H264) ||
1429 (p_input->p_fmt->i_codec == VLC_CODEC_HEVC) ||
1430 (p_input->p_fmt->i_codec == VLC_CODEC_MP2V)
1433 b_data_alignment = 1;
1434 /* dirac and mpeg video pes packets should be unbounded in
1435 * length, specify a suitibly large max size */
1436 i_max_pes_size = INT_MAX;
1439 EStoPES ( &p_data, p_input->p_fmt, p_stream->pes.i_stream_id,
1440 1, b_data_alignment, i_header_size,
1441 i_max_pes_size, p_sys->first_dts - p_sys->i_dts_delay );
1443 BufferChainAppend( &p_stream->state.chain_pes, p_data );
1445 if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1446 && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
1447 && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
1448 && (p_stream->state.i_pes_length > 400000) )
1450 i_shaping_delay = p_stream->state.i_pes_length;
1451 p_stream->state.b_key_frame = 1;
1455 /* save */
1456 const mtime_t i_pcr_length = p_pcr_stream->state.i_pes_length;
1457 p_pcr_stream->state.b_key_frame = 0;
1459 /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
1460 /* 2: calculate non accurate total size of muxed ts */
1461 int i_packet_count = 0;
1462 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1464 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
1466 /* False for pcr stream but it will be enough to do PCR algo */
1467 for (block_t *p_pes = p_stream->state.chain_pes.p_first; p_pes != NULL;
1468 p_pes = p_pes->p_next )
1470 int i_size = p_pes->i_buffer;
1471 if( p_pes->i_dts + p_pes->i_length >
1472 p_pcr_stream->state.i_pes_dts + p_pcr_stream->state.i_pes_length )
1474 mtime_t i_frag = p_pcr_stream->state.i_pes_dts +
1475 p_pcr_stream->state.i_pes_length - p_pes->i_dts;
1476 if( i_frag < 0 )
1478 /* Next stream */
1479 break;
1481 i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1483 i_packet_count += ( i_size + 183 ) / 184;
1486 /* add overhead for PCR (not really exact) */
1487 i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1489 /* 3: mux PES into TS */
1490 BufferChainInit( &chain_ts );
1491 /* append PAT/PMT -> FIXME with big pcr delay it won't have enough pat/pmt */
1492 bool pat_was_previous = true; //This is to prevent unnecessary double PAT/PMT insertions
1493 GetPAT( p_mux, &chain_ts );
1494 GetPMT( p_mux, &chain_ts );
1495 int i_packet_pos = 0;
1496 i_packet_count += chain_ts.i_depth;
1497 /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1499 const mtime_t i_pcr_dts = p_pcr_stream->state.i_pes_dts;
1500 for (;;)
1502 int i_stream = -1;
1503 mtime_t i_dts = 0;
1504 sout_input_sys_t *p_stream;
1506 /* Select stream (lowest dts) */
1507 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1509 p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i]->p_sys;
1511 if( p_stream->state.i_pes_dts == 0 )
1513 continue;
1516 if( i_stream == -1 || p_stream->state.i_pes_dts < i_dts )
1518 i_stream = i;
1519 i_dts = p_stream->state.i_pes_dts;
1522 if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1524 break;
1526 p_stream = (sout_input_sys_t*)p_mux->pp_inputs[i_stream]->p_sys;
1527 sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1529 /* do we need to issue pcr */
1530 bool b_pcr = false;
1531 if( p_stream == p_pcr_stream &&
1532 i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
1533 p_sys->i_pcr + p_sys->i_pcr_delay )
1535 b_pcr = true;
1536 p_sys->i_pcr = i_pcr_dts + i_packet_pos *
1537 i_pcr_length / i_packet_count;
1540 /* Build the TS packet */
1541 block_t *p_ts = TSNew( p_mux, p_stream, b_pcr );
1542 if( p_sys->csa != NULL &&
1543 (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) &&
1544 (p_input->p_fmt->i_cat != VIDEO_ES || p_sys->b_crypt_video) )
1546 p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1548 i_packet_pos++;
1550 /* Write PAT/PMT before every keyframe if use-key-frames is enabled,
1551 * this helps to do segmenting with livehttp-output so it can cut segment
1552 * and start new one with pat,pmt,keyframe*/
1553 if( ( p_sys->b_use_key_frames ) &&
1554 ( p_input->p_fmt->i_cat == VIDEO_ES ) &&
1555 ( p_ts->i_flags & BLOCK_FLAG_TYPE_I ) )
1557 if( likely( !pat_was_previous ) )
1559 int startcount = chain_ts.i_depth;
1560 GetPAT( p_mux, &chain_ts );
1561 GetPMT( p_mux, &chain_ts );
1562 SetHeader( &chain_ts, startcount );
1563 i_packet_count += (chain_ts.i_depth - startcount );
1564 } else {
1565 SetHeader( &chain_ts, 0); //We just inserted pat/pmt,so just flag it instead of adding new one
1568 pat_was_previous = false;
1570 /* */
1571 BufferChainAppend( &chain_ts, p_ts );
1574 /* 4: date and send */
1575 TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
1576 return false;
1579 /*****************************************************************************
1580 * Mux: Call each time there is new data for at least one stream
1581 *****************************************************************************
1583 *****************************************************************************/
1584 static int Mux( sout_mux_t *p_mux )
1586 sout_mux_sys_t *p_sys = p_mux->p_sys;
1588 if( p_sys->p_pcr_input == NULL )
1590 for (int i = 0; i < p_mux->i_nb_inputs; i++ )
1592 block_FifoEmpty( p_mux->pp_inputs[i]->p_fifo );
1594 msg_Dbg( p_mux, "waiting for PCR streams" );
1595 return VLC_SUCCESS;
1598 while (!MuxStreams(p_mux))
1600 return VLC_SUCCESS;
1603 #define STD_PES_PAYLOAD 170
1604 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo )
1606 VLC_UNUSED(p_mux);
1607 block_t *p_data;
1608 size_t i_size;
1610 p_data = block_FifoShow( p_fifo );
1611 i_size = p_data->i_buffer;
1613 if( i_size == STD_PES_PAYLOAD )
1615 return block_FifoGet( p_fifo );
1617 else if( i_size > STD_PES_PAYLOAD )
1619 block_t *p_new = block_Alloc( STD_PES_PAYLOAD );
1620 memcpy( p_new->p_buffer, p_data->p_buffer, STD_PES_PAYLOAD );
1621 p_new->i_pts = p_data->i_pts;
1622 p_new->i_dts = p_data->i_dts;
1623 p_new->i_length = p_data->i_length * STD_PES_PAYLOAD
1624 / p_data->i_buffer;
1625 p_data->i_buffer -= STD_PES_PAYLOAD;
1626 p_data->p_buffer += STD_PES_PAYLOAD;
1627 p_data->i_pts += p_new->i_length;
1628 p_data->i_dts += p_new->i_length;
1629 p_data->i_length -= p_new->i_length;
1630 p_data->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1631 return p_new;
1633 else
1635 block_t *p_next;
1636 int i_copy;
1638 p_data = block_FifoGet( p_fifo );
1639 p_data = block_Realloc( p_data, 0, STD_PES_PAYLOAD );
1640 p_next = block_FifoShow( p_fifo );
1641 if ( p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME )
1643 p_data->i_flags &= ~BLOCK_FLAG_NO_KEYFRAME;
1644 p_data->i_pts = p_next->i_pts;
1645 p_data->i_dts = p_next->i_dts;
1647 i_copy = __MIN( STD_PES_PAYLOAD - i_size, p_next->i_buffer );
1649 memcpy( &p_data->p_buffer[i_size], p_next->p_buffer, i_copy );
1650 if( p_next->i_pts )
1651 p_next->i_pts += p_next->i_length * i_copy / p_next->i_buffer;
1652 if( p_next->i_dts )
1653 p_next->i_dts += p_next->i_length * i_copy / p_next->i_buffer;
1654 p_next->i_length -= p_next->i_length * i_copy / p_next->i_buffer;
1655 p_next->i_buffer -= i_copy;
1656 p_next->p_buffer += i_copy;
1657 p_next->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1659 if( !p_next->i_buffer )
1661 p_next = block_FifoGet( p_fifo );
1662 block_Release( p_next );
1664 return p_data;
1668 static block_t *Add_ADTS( block_t *p_data, const es_format_t *p_fmt )
1670 #define ADTS_HEADER_SIZE 7 /* CRC needs 2 more bytes */
1672 const uint8_t *p_extra = p_fmt->p_extra;
1674 if( !p_data || p_fmt->i_extra < 2 || !p_extra )
1675 return p_data; /* no data to construct the headers */
1677 size_t frame_length = p_data->i_buffer + ADTS_HEADER_SIZE;
1678 int i_index = ( (p_extra[0] << 1) | (p_extra[1] >> 7) ) & 0x0f;
1679 int i_profile = (p_extra[0] >> 3) - 1; /* i_profile < 4 */
1681 if( i_index == 0x0f && p_fmt->i_extra < 5 )
1682 return p_data; /* not enough data */
1684 int i_channels = (p_extra[i_index == 0x0f ? 4 : 1] >> 3) & 0x0f;
1686 block_t *p_new_block = block_Realloc( p_data, ADTS_HEADER_SIZE,
1687 p_data->i_buffer );
1688 uint8_t *p_buffer = p_new_block->p_buffer;
1690 /* fixed header */
1691 p_buffer[0] = 0xff;
1692 p_buffer[1] = 0xf1; /* 0xf0 | 0x00 | 0x00 | 0x01 */
1693 p_buffer[2] = (i_profile << 6) | ((i_index & 0x0f) << 2) | ((i_channels >> 2) & 0x01) ;
1694 p_buffer[3] = (i_channels << 6) | ((frame_length >> 11) & 0x03);
1696 /* variable header (starts at last 2 bits of 4th byte) */
1698 int i_fullness = 0x7ff; /* 0x7ff means VBR */
1699 /* XXX: We should check if it's CBR or VBR, but no known implementation
1700 * do that, and it's a pain to calculate this field */
1702 p_buffer[4] = frame_length >> 3;
1703 p_buffer[5] = ((frame_length & 0x07) << 5) | ((i_fullness >> 6) & 0x1f);
1704 p_buffer[6] = ((i_fullness & 0x3f) << 2) /* | 0xfc */;
1706 return p_new_block;
1709 static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1710 mtime_t i_pcr_length, mtime_t i_pcr_dts )
1712 sout_mux_sys_t *p_sys = p_mux->p_sys;
1713 sout_buffer_chain_t new_chain;
1714 int i_packet_count = p_chain_ts->i_depth;
1716 BufferChainInit( &new_chain );
1718 if ( i_pcr_length <= 0 )
1720 i_pcr_length = i_packet_count;
1723 for (int i = 0; i < i_packet_count; i++ )
1725 block_t *p_ts = BufferChainGet( p_chain_ts );
1726 mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1728 BufferChainAppend( &new_chain, p_ts );
1730 if (!p_ts->i_dts || p_ts->i_dts + p_sys->i_dts_delay * 2/3 >= i_new_dts)
1731 continue;
1733 mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
1734 mtime_t i_cut_dts = p_ts->i_dts;
1736 p_ts = BufferChainPeek( p_chain_ts );
1737 i++;
1738 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1739 while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1741 p_ts = BufferChainGet( p_chain_ts );
1742 i_max_diff = i_new_dts - p_ts->i_dts;
1743 i_cut_dts = p_ts->i_dts;
1744 BufferChainAppend( &new_chain, p_ts );
1746 p_ts = BufferChainPeek( p_chain_ts );
1747 i++;
1748 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1750 msg_Dbg( p_mux, "adjusting rate at %"PRId64"/%"PRId64" (%d/%d)",
1751 i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
1752 p_chain_ts->i_depth );
1753 if ( new_chain.i_depth )
1754 TSDate( p_mux, &new_chain, i_cut_dts - i_pcr_dts, i_pcr_dts );
1755 if ( p_chain_ts->i_depth )
1756 TSSchedule( p_mux, p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
1757 i_cut_dts );
1758 return;
1761 if ( new_chain.i_depth )
1762 TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
1765 static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1766 mtime_t i_pcr_length, mtime_t i_pcr_dts )
1768 sout_mux_sys_t *p_sys = p_mux->p_sys;
1769 int i_packet_count = p_chain_ts->i_depth;
1771 if ( i_pcr_length / 1000 > 0 )
1773 int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
1774 / (uint64_t)(i_pcr_length / 1000);
1775 if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
1777 msg_Warn( p_mux, "max bitrate exceeded at %"PRId64
1778 " (%d bi/s for %d pkt in %"PRId64" us)",
1779 i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1780 i_bitrate, i_packet_count, i_pcr_length);
1783 else
1785 /* This shouldn't happen, but happens in some rare heavy load
1786 * and packet losses conditions. */
1787 i_pcr_length = i_packet_count;
1790 /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
1791 for (int i = 0; i < i_packet_count; i++ )
1793 block_t *p_ts = BufferChainGet( p_chain_ts );
1794 mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1796 p_ts->i_dts = i_new_dts;
1797 p_ts->i_length = i_pcr_length / i_packet_count;
1799 if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1801 /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
1802 TSSetPCR( p_ts, p_ts->i_dts - p_sys->first_dts );
1804 if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1806 vlc_mutex_lock( &p_sys->csa_lock );
1807 csa_Encrypt( p_sys->csa, p_ts->p_buffer, p_sys->i_csa_pkt_size );
1808 vlc_mutex_unlock( &p_sys->csa_lock );
1811 /* latency */
1812 p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
1814 sout_AccessOutWrite( p_mux->p_access, p_ts );
1818 static block_t *TSNew( sout_mux_t *p_mux, sout_input_sys_t *p_stream,
1819 bool b_pcr )
1821 VLC_UNUSED(p_mux);
1822 block_t *p_pes = p_stream->state.chain_pes.p_first;
1824 bool b_new_pes = false;
1825 bool b_adaptation_field = false;
1827 int i_payload_max = 184 - ( b_pcr ? 8 : 0 );
1829 if( p_stream->state.i_pes_used <= 0 )
1831 b_new_pes = true;
1833 int i_payload = __MIN( (int)p_pes->i_buffer - p_stream->state.i_pes_used,
1834 i_payload_max );
1836 if( b_pcr || i_payload < i_payload_max )
1838 b_adaptation_field = true;
1841 block_t *p_ts = block_Alloc( 188 );
1843 if (b_new_pes && !(p_pes->i_flags & BLOCK_FLAG_NO_KEYFRAME) && p_pes->i_flags & BLOCK_FLAG_TYPE_I)
1845 p_ts->i_flags |= BLOCK_FLAG_TYPE_I;
1848 p_ts->i_dts = p_pes->i_dts;
1850 p_ts->p_buffer[0] = 0x47;
1851 p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
1852 ( ( p_stream->ts.i_pid >> 8 )&0x1f );
1853 p_ts->p_buffer[2] = p_stream->ts.i_pid & 0xff;
1854 p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
1855 p_stream->ts.i_continuity_counter;
1857 p_stream->ts.i_continuity_counter = (p_stream->ts.i_continuity_counter+1)%16;
1858 p_stream->ts.b_discontinuity = p_pes->i_flags & BLOCK_FLAG_DISCONTINUITY;
1860 if( b_adaptation_field )
1862 int i_stuffing = i_payload_max - i_payload;
1863 if( b_pcr )
1865 p_ts->i_flags |= BLOCK_FLAG_CLOCK;
1867 p_ts->p_buffer[4] = 7 + i_stuffing;
1868 p_ts->p_buffer[5] = 1 << 4; /* PCR_flag */
1869 if( p_stream->ts.b_discontinuity )
1871 p_ts->p_buffer[5] |= 0x80; /* flag TS dicontinuity */
1872 p_stream->ts.b_discontinuity = false;
1874 memset(&p_ts->p_buffer[12], 0xff, i_stuffing);
1876 else
1878 p_ts->p_buffer[4] = --i_stuffing;
1879 if( i_stuffing-- )
1881 p_ts->p_buffer[5] = 0;
1882 memset(&p_ts->p_buffer[6], 0xff, i_stuffing);
1887 /* copy payload */
1888 memcpy( &p_ts->p_buffer[188 - i_payload],
1889 &p_pes->p_buffer[p_stream->state.i_pes_used], i_payload );
1891 p_stream->state.i_pes_used += i_payload;
1892 p_stream->state.i_pes_dts = p_pes->i_dts + p_pes->i_length *
1893 p_stream->state.i_pes_used / p_pes->i_buffer;
1894 p_stream->state.i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
1896 if( p_stream->state.i_pes_used >= (int)p_pes->i_buffer )
1898 block_Release(BufferChainGet( &p_stream->state.chain_pes ));
1900 p_pes = p_stream->state.chain_pes.p_first;
1901 p_stream->state.i_pes_length = 0;
1902 if( p_pes )
1904 p_stream->state.i_pes_dts = p_pes->i_dts;
1905 while( p_pes )
1907 p_stream->state.i_pes_length += p_pes->i_length;
1908 p_pes = p_pes->p_next;
1911 else
1913 p_stream->state.i_pes_dts = 0;
1915 p_stream->state.i_pes_used = 0;
1918 return p_ts;
1921 static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
1923 mtime_t i_pcr = 9 * i_dts / 100;
1925 p_ts->p_buffer[6] = ( i_pcr >> 25 )&0xff;
1926 p_ts->p_buffer[7] = ( i_pcr >> 17 )&0xff;
1927 p_ts->p_buffer[8] = ( i_pcr >> 9 )&0xff;
1928 p_ts->p_buffer[9] = ( i_pcr >> 1 )&0xff;
1929 p_ts->p_buffer[10] = ( i_pcr << 7 )&0x80;
1930 p_ts->p_buffer[10] |= 0x7e;
1931 p_ts->p_buffer[11] = 0; /* we don't set PCR extension */
1934 void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
1936 sout_mux_sys_t *p_sys = p_mux->p_sys;
1938 BuildPAT( p_sys->p_dvbpsi,
1939 c, (PEStoTSCallback)BufferChainAppend,
1940 p_sys->i_tsid, p_sys->i_pat_version_number,
1941 &p_sys->pat,
1942 p_sys->i_num_pmt, p_sys->pmt, p_sys->i_pmt_program_number );
1945 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
1947 sout_mux_sys_t *p_sys = p_mux->p_sys;
1948 pes_mapped_stream_t mappeds[p_mux->i_nb_inputs];
1950 for (int i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
1952 sout_input_t *p_input = p_mux->pp_inputs[i_stream];
1953 sout_input_sys_t *p_stream = (sout_input_sys_t*)p_input->p_sys;
1955 int i_pidinput = p_input->p_fmt->i_id;
1956 pmt_map_t *p_usepid = bsearch( &i_pidinput, p_sys->pmtmap,
1957 p_sys->i_pmtslots, sizeof(pmt_map_t), intcompare );
1959 /* If there's an error somewhere, dump it to the first pmt */
1960 mappeds[i_stream].i_mapped_prog = p_usepid ? p_usepid->i_prog : 0;
1961 mappeds[i_stream].fmt = p_input->p_fmt;
1962 mappeds[i_stream].pes = &p_stream->pes;
1963 mappeds[i_stream].ts = &p_stream->ts;
1966 BuildPMT( p_sys->p_dvbpsi, VLC_OBJECT(p_mux), p_sys->standard,
1967 c, (PEStoTSCallback)BufferChainAppend,
1968 p_sys->i_tsid, p_sys->i_pmt_version_number,
1969 ((sout_input_sys_t *)p_sys->p_pcr_input->p_sys)->ts.i_pid,
1970 &p_sys->sdt,
1971 p_sys->i_num_pmt, p_sys->pmt, p_sys->i_pmt_program_number,
1972 p_mux->i_nb_inputs, mappeds );