1 /*****************************************************************************
2 * ts.c: MPEG-II TS Muxer
3 *****************************************************************************
4 * Copyright (C) 2001-2005 the VideoLAN team
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
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 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 General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
38 #include <vlc_codecs.h>
39 #include <vlc_block.h>
41 #include <vlc_iso_lang.h>
47 #ifdef HAVE_DVBPSI_DR_H
48 # include <dvbpsi/dvbpsi.h>
49 # include <dvbpsi/demux.h>
50 # include <dvbpsi/descriptor.h>
51 # include <dvbpsi/pat.h>
52 # include <dvbpsi/pmt.h>
53 # include <dvbpsi/sdt.h>
54 # include <dvbpsi/dr.h>
55 # include <dvbpsi/psi.h>
59 # include "descriptor.h"
60 # include "tables/pat.h"
61 # include "tables/pmt.h"
62 # include "tables/sdt.h"
63 # include "descriptors/dr.h"
69 * - check PCR frequency requirement
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
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 /*****************************************************************************
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 /*****************************************************************************
91 *****************************************************************************/
92 static int Open ( vlc_object_t * );
93 static void Close ( vlc_object_t * );
95 #define VPID_TEXT N_("Video PID")
96 #define VPID_LONGTEXT N_("Assign a fixed PID to the video stream. The PCR " \
97 "PID will automatically be the video.")
98 #define APID_TEXT N_("Audio PID")
99 #define APID_LONGTEXT N_("Assign a fixed PID to the audio stream.")
100 #define SPUPID_TEXT N_("SPU PID")
101 #define SPUPID_LONGTEXT N_("Assign a fixed PID to the SPU.")
102 #define PMTPID_TEXT N_("PMT PID")
103 #define PMTPID_LONGTEXT N_("Assign a fixed PID to the PMT")
104 #define TSID_TEXT N_("TS ID")
105 #define TSID_LONGTEXT N_("Assign a fixed Transport Stream ID.")
106 #define NETID_TEXT N_("NET ID")
107 #define NETID_LONGTEXT N_("Assign a fixed Network ID (for SDT table)")
109 #define PMTPROG_TEXT N_("PMT Program numbers")
110 #define PMTPROG_LONGTEXT N_("Assign a program number to each PMT. This " \
111 "requires \"Set PID to ID of ES\" to be enabled." )
113 #define MUXPMT_TEXT N_("Mux PMT (requires --sout-ts-es-id-pid)")
114 #define MUXPMT_LONGTEXT N_("Define the pids to add to each pmt. This " \
115 "requires \"Set PID to ID of ES\" to be enabled." )
117 #define SDTDESC_TEXT N_("SDT Descriptors (requires --sout-ts-es-id-pid)")
118 #define SDTDESC_LONGTEXT N_("Defines the descriptors of each SDT. This" \
119 "requires \"Set PID to ID of ES\" to be enabled." )
121 #define PID_TEXT N_("Set PID to ID of ES")
122 #define PID_LONGTEXT N_("Sets PID to the ID if the incoming ES. This is for " \
123 "use with --ts-es-id-pid, and allows to have the same PIDs in the input " \
124 "and output streams.")
126 #define ALIGNMENT_TEXT N_("Data alignment")
127 #define ALIGNMENT_LONGTEXT N_("Enforces alignment of all access units on " \
128 "PES boundaries. Disabling this might save some bandwidth but introduce incompatibilities.")
130 #define SHAPING_TEXT N_("Shaping delay (ms)")
131 #define SHAPING_LONGTEXT N_("Cut the " \
132 "stream in slices of the given duration, and ensure a constant bitrate " \
133 "between the two boundaries. This avoids having huge bitrate peaks, " \
134 "especially for reference frames." )
136 #define KEYF_TEXT N_("Use keyframes")
137 #define KEYF_LONGTEXT N_("If enabled, and shaping is specified, " \
138 "the TS muxer will place the boundaries at the end of I pictures. In " \
139 "that case, the shaping duration given by the user is a worse case " \
140 "used when no reference frame is available. This enhances the efficiency " \
141 "of the shaping algorithm, since I frames are usually the biggest " \
142 "frames in the stream.")
144 #define PCR_TEXT N_("PCR delay (ms)")
145 #define PCR_LONGTEXT N_("Set at which interval " \
146 "PCRs (Program Clock Reference) will be sent (in milliseconds). " \
147 "This value should be below 100ms. (default is 70ms).")
149 #define BMIN_TEXT N_( "Minimum B (deprecated)")
150 #define BMIN_LONGTEXT N_( "This setting is deprecated and not used anymore" )
152 #define BMAX_TEXT N_( "Maximum B (deprecated)")
153 #define BMAX_LONGTEXT N_( "This setting is deprecated and not used anymore")
155 #define DTS_TEXT N_("DTS delay (ms)")
156 #define DTS_LONGTEXT N_("Delay the DTS (decoding time " \
157 "stamps) and PTS (presentation timestamps) of the data in the " \
158 "stream, compared to the PCRs. This allows for some buffering inside " \
159 "the client decoder.")
161 #define ACRYPT_TEXT N_("Crypt audio")
162 #define ACRYPT_LONGTEXT N_("Crypt audio using CSA")
163 #define VCRYPT_TEXT N_("Crypt video")
164 #define VCRYPT_LONGTEXT N_("Crypt video using CSA")
166 #define CK_TEXT N_("CSA Key")
167 #define CK_LONGTEXT N_("CSA encryption key. This must be a " \
168 "16 char string (8 hexadecimal bytes).")
170 #define CK2_TEXT N_("Second CSA Key")
171 #define CK2_LONGTEXT N_("The even CSA encryption key. This must be a " \
172 "16 char string (8 hexadecimal bytes).")
174 #define CU_TEXT N_("CSA Key in use")
175 #define CU_LONGTEXT N_("CSA encryption key used. It can be the odd/first/1 " \
176 "(default) or the even/second/2 one.")
178 #define CPKT_TEXT N_("Packet size in bytes to encrypt")
179 #define CPKT_LONGTEXT N_("Size of the TS packet to encrypt. " \
180 "The encryption routines subtract the TS-header from the value before " \
183 #define SOUT_CFG_PREFIX "sout-ts-"
185 # define MAX_PMT 64 /* Maximum number of programs. FIXME: I just chose an arbitary number. Where is the maximum in the spec? */
189 #define MAX_PMT_PID 64 /* Maximum pids in each pmt. FIXME: I just chose an arbitary number. Where is the maximum in the spec? */
192 set_description( N_("TS muxer (libdvbpsi)") );
193 set_shortname( "MPEG-TS");
194 set_category( CAT_SOUT );
195 set_subcategory( SUBCAT_SOUT_MUX );
196 set_capability( "sout mux", 120 );
197 add_shortcut( "ts" );
199 add_integer( SOUT_CFG_PREFIX "pid-video", 0, NULL,VPID_TEXT, VPID_LONGTEXT,
201 add_integer( SOUT_CFG_PREFIX "pid-audio", 0, NULL, APID_TEXT,
202 APID_LONGTEXT, true );
203 add_integer( SOUT_CFG_PREFIX "pid-spu", 0, NULL, SPUPID_TEXT,
204 SPUPID_LONGTEXT, true );
205 add_integer( SOUT_CFG_PREFIX "pid-pmt", 0, NULL, PMTPID_TEXT,
206 PMTPID_LONGTEXT, true );
207 add_integer( SOUT_CFG_PREFIX "tsid", 0, NULL, TSID_TEXT,
208 TSID_LONGTEXT, true );
209 #ifdef HAVE_DVBPSI_SDT
210 add_integer( SOUT_CFG_PREFIX "netid", 0, NULL, NETID_TEXT,
211 NETID_LONGTEXT, true );
213 add_string( SOUT_CFG_PREFIX "program-pmt", NULL, NULL, PMTPROG_TEXT,
214 PMTPROG_LONGTEXT, true );
215 add_bool( SOUT_CFG_PREFIX "es-id-pid", 0, NULL, PID_TEXT, PID_LONGTEXT,
217 add_string( SOUT_CFG_PREFIX "muxpmt", NULL, NULL, MUXPMT_TEXT, MUXPMT_LONGTEXT, true );
218 #ifdef HAVE_DVBPSI_SDT
219 add_string( SOUT_CFG_PREFIX "sdtdesc", NULL, NULL, SDTDESC_TEXT, SDTDESC_LONGTEXT, true );
221 add_bool( SOUT_CFG_PREFIX "alignment", true, NULL, ALIGNMENT_TEXT,
222 ALIGNMENT_LONGTEXT, true );
224 add_integer( SOUT_CFG_PREFIX "shaping", 200, NULL, SHAPING_TEXT,
225 SHAPING_LONGTEXT, true );
226 add_bool( SOUT_CFG_PREFIX "use-key-frames", false, NULL, KEYF_TEXT,
227 KEYF_LONGTEXT, true );
229 add_integer( SOUT_CFG_PREFIX "pcr", 70, NULL, PCR_TEXT, PCR_LONGTEXT,
231 add_integer( SOUT_CFG_PREFIX "bmin", 0, NULL, BMIN_TEXT, BMIN_LONGTEXT,
233 add_integer( SOUT_CFG_PREFIX "bmax", 0, NULL, BMAX_TEXT, BMAX_LONGTEXT,
235 add_integer( SOUT_CFG_PREFIX "dts-delay", 400, NULL, DTS_TEXT,
236 DTS_LONGTEXT, true );
238 add_bool( SOUT_CFG_PREFIX "crypt-audio", true, NULL, ACRYPT_TEXT,
239 ACRYPT_LONGTEXT, true );
240 add_bool( SOUT_CFG_PREFIX "crypt-video", true, NULL, VCRYPT_TEXT,
241 VCRYPT_LONGTEXT, true );
243 add_string( SOUT_CFG_PREFIX "csa-ck", NULL, NULL, CK_TEXT, CK_LONGTEXT,
245 add_string( SOUT_CFG_PREFIX "csa2-ck", NULL, NULL, CK2_TEXT, CK2_LONGTEXT,
247 add_string( SOUT_CFG_PREFIX "csa-use", "1", NULL, CU_TEXT, CU_LONGTEXT,
249 add_integer( SOUT_CFG_PREFIX "csa-pkt", 188, NULL, CPKT_TEXT, CPKT_LONGTEXT, true );
251 set_callbacks( Open, Close );
254 /*****************************************************************************
255 * Local data structures
256 *****************************************************************************/
257 static const char *const ppsz_sout_options[] = {
258 "pid-video", "pid-audio", "pid-spu", "pid-pmt", "tsid", "netid",
259 "es-id-pid", "shaping", "pcr", "bmin", "bmax", "use-key-frames",
260 "dts-delay", "csa-ck", "csa2-ck", "csa-use", "csa-pkt", "crypt-audio", "crypt-video",
261 "muxpmt", "sdtdesc", "program-pmt", "alignment",
265 typedef struct pmt_map_t /* Holds the mapping between the pmt-pid/pmt table */
268 unsigned long i_prog;
271 typedef struct sdt_desc_t
274 char *psz_service_name; /* name of program */
282 } sout_buffer_chain_t;
284 static inline void BufferChainInit ( sout_buffer_chain_t *c )
288 c->pp_last = &c->p_first;
291 static inline void BufferChainAppend( sout_buffer_chain_t *c, block_t *b )
301 c->pp_last = &b->p_next;
304 static inline block_t *BufferChainGet( sout_buffer_chain_t *c )
306 block_t *b = c->p_first;
311 c->p_first = b->p_next;
313 if( c->p_first == NULL )
315 c->pp_last = &c->p_first;
323 static inline block_t *BufferChainPeek( sout_buffer_chain_t *c )
325 block_t *b = c->p_first;
330 static inline void BufferChainClean( sout_buffer_chain_t *c )
334 while( ( b = BufferChainGet( c ) ) )
338 BufferChainInit( c );
341 typedef struct ts_stream_t
344 vlc_fourcc_t i_codec;
348 int i_continuity_counter;
349 bool b_discontinuity;
351 /* to be used for carriege of DIV3 */
352 vlc_fourcc_t i_bih_codec;
353 int i_bih_width, i_bih_height;
355 /* Specific to mpeg4 in mpeg2ts */
358 int i_decoder_specific_info;
359 uint8_t *p_decoder_specific_info;
361 /* language is iso639-2T */
365 sout_buffer_chain_t chain_pes;
367 mtime_t i_pes_length;
373 struct sout_mux_sys_t
376 sout_input_t *p_pcr_input;
378 vlc_mutex_t csa_lock;
388 int i_pid_free; /* first usable pid */
394 int i_pat_version_number;
397 int i_pmt_version_number;
398 ts_stream_t pmt[MAX_PMT];
399 pmt_map_t pmtmap[MAX_PMT_PID];
400 int i_pmt_program_number[MAX_PMT];
401 sdt_desc_t sdt_descriptors[MAX_PMT];
402 bool b_data_alignment;
406 int i_null_continuity_counter; /* Needed ? */
408 dvbpsi_pmt_t *dvbpmt;
410 /* for TS building */
411 int64_t i_bitrate_min;
412 int64_t i_bitrate_max;
414 int64_t i_shaping_delay;
419 bool b_use_key_frames;
421 mtime_t i_pcr; /* last PCR emited */
429 /* Reserve a pid and return it */
430 static int AllocatePID( sout_mux_sys_t *p_sys, int i_cat )
433 if ( i_cat == VIDEO_ES && p_sys->i_pid_video )
435 i_pid = p_sys->i_pid_video;
436 p_sys->i_pid_video = 0;
438 else if ( i_cat == AUDIO_ES && p_sys->i_pid_audio )
440 i_pid = p_sys->i_pid_audio;
441 p_sys->i_pid_audio = 0;
443 else if ( i_cat == SPU_ES && p_sys->i_pid_spu )
445 i_pid = p_sys->i_pid_spu;
446 p_sys->i_pid_spu = 0;
450 i_pid = ++p_sys->i_pid_free;
455 static int pmtcompare( const void *pa, const void *pb )
457 if ( ((pmt_map_t *)pa)->i_pid < ((pmt_map_t *)pb)->i_pid )
459 else if ( ((pmt_map_t *)pa)->i_pid > ((pmt_map_t *)pb)->i_pid )
465 static int intcompare( const void *pa, const void *pb )
467 if ( *(int *)pa < *(int *)pb )
469 else if ( *(int *)pa > *(int *)pb )
475 /*****************************************************************************
477 *****************************************************************************/
478 static int Control ( sout_mux_t *, int, va_list );
479 static int AddStream( sout_mux_t *, sout_input_t * );
480 static int DelStream( sout_mux_t *, sout_input_t * );
481 static int Mux ( sout_mux_t * );
483 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo );
484 static block_t *Add_ADTS( block_t *, es_format_t * );
485 static void TSSchedule ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
486 mtime_t i_pcr_length, mtime_t i_pcr_dts );
487 static void TSDate ( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
488 mtime_t i_pcr_length, mtime_t i_pcr_dts );
489 static void GetPAT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
490 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c );
492 static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream, bool b_pcr );
493 static void TSSetPCR( block_t *p_ts, mtime_t i_dts );
495 static void PEStoTS ( sout_instance_t *, sout_buffer_chain_t *, block_t *, ts_stream_t * );
497 /*****************************************************************************
499 *****************************************************************************/
500 static int Open( vlc_object_t *p_this )
502 sout_mux_t *p_mux =(sout_mux_t*)p_this;
503 sout_mux_sys_t *p_sys = NULL;
507 config_ChainParse( p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg );
509 p_sys = malloc( sizeof( sout_mux_sys_t ) );
512 p_sys->i_pmtslots = p_sys->b_sdt = 0;
513 p_sys->i_num_pmt = 1;
514 p_sys->dvbpmt = NULL;
515 memset( &p_sys->pmtmap, 0, sizeof(p_sys->pmtmap) );
517 vlc_mutex_init( &p_sys->csa_lock );
519 p_mux->pf_control = Control;
520 p_mux->pf_addstream = AddStream;
521 p_mux->pf_delstream = DelStream;
523 p_mux->p_sys = p_sys;
525 srand( (uint32_t)mdate() );
526 for ( i = 0; i < MAX_PMT; i++ )
527 p_sys->sdt_descriptors[i].psz_service_name
528 = p_sys->sdt_descriptors[i].psz_provider = NULL;
529 memset( p_sys->sdt_descriptors, 0, sizeof(sdt_desc_t) );
531 p_sys->i_audio_bound = 0;
532 p_sys->i_video_bound = 0;
534 var_Get( p_mux, SOUT_CFG_PREFIX "es-id-pid", &val );
535 p_sys->b_es_id_pid = val.b_bool;
537 var_Get( p_mux, SOUT_CFG_PREFIX "muxpmt", &val );
539 fetch string of pmts. Here's a sample: --sout-ts-muxpmt="0x451,0x200,0x28a,0x240,,0x450,0x201,0x28b,0x241,,0x452,0x202,0x28c,0x242"
540 This would mean 0x451, 0x200, 0x28a, 0x240 would fall under one pmt (program), 0x450,0x201,0x28b,0x241 would fall under another
542 if( val.psz_string != NULL && *val.psz_string )
545 char *psz = val.psz_string;
551 i_pid = strtoul( psz, &psz_next, 0 );
553 if ( strlen(psz_next) > 0 )
558 if ( p_sys->i_num_pmt > MAX_PMT )
561 "Number of PMTs greater than compiled maximum (%d)", MAX_PMT );
562 p_sys->i_num_pmt = MAX_PMT;
567 p_sys->pmtmap[p_sys->i_pmtslots].i_pid = i_pid;
568 p_sys->pmtmap[p_sys->i_pmtslots].i_prog = p_sys->i_num_pmt - 1;
570 if ( p_sys->i_pmtslots > MAX_PMT_PID )
573 "Number of pids in PMT greater than compiled maximum (%d)",
575 p_sys->i_pmtslots = MAX_PMT_PID;
579 /* Now sort according to pids for fast search later on */
580 qsort( (void *)p_sys->pmtmap, p_sys->i_pmtslots,
581 sizeof(pmt_map_t), &pmtcompare );
586 free( val.psz_string );
588 p_sys->i_pat_version_number = rand() % 32;
589 p_sys->pat.i_pid = 0;
590 p_sys->pat.i_continuity_counter = 0;
591 p_sys->pat.b_discontinuity = false;
593 var_Get( p_mux, SOUT_CFG_PREFIX "tsid", &val );
595 p_sys->i_tsid = val.i_int;
597 p_sys->i_tsid = rand() % 65536;
599 p_sys->i_netid = rand() % 65536;
600 #ifdef HAVE_DVBPSI_SDT
601 var_Get( p_mux, SOUT_CFG_PREFIX "netid", &val );
603 p_sys->i_netid = val.i_int;
606 p_sys->i_pmt_version_number = rand() % 32;
607 for( i = 0; i < p_sys->i_num_pmt; i++ )
609 p_sys->pmt[i].i_continuity_counter = 0;
610 p_sys->pmt[i].b_discontinuity = false;
613 p_sys->sdt.i_pid = 0x11;
614 p_sys->sdt.i_continuity_counter = 0;
615 p_sys->sdt.b_discontinuity = false;
617 #ifdef HAVE_DVBPSI_SDT
618 var_Get( p_mux, SOUT_CFG_PREFIX "sdtdesc", &val );
619 p_sys->b_sdt = val.psz_string && *val.psz_string ? true : false;
621 /* Syntax is provider_sdt1,service_name_sdt1,provider_sdt2,service_name_sdt2... */
625 char *psz = val.psz_string;
626 char *psz_sdttoken = psz;
629 while ( psz_sdttoken != NULL )
631 char *psz_end = strchr( psz_sdttoken, ',' );
632 if( psz_end != NULL )
638 p_sys->sdt_descriptors[i/2].psz_provider
639 = strdup(psz_sdttoken);
643 p_sys->sdt_descriptors[i/2].psz_service_name
644 = strdup(psz_sdttoken);
648 psz_sdttoken = psz_end;
651 free( val.psz_string );
653 p_sys->b_sdt = false;
656 var_Get( p_mux, SOUT_CFG_PREFIX "alignment", &val );
657 p_sys->b_data_alignment = val.b_bool;
659 var_Get( p_mux, SOUT_CFG_PREFIX "program-pmt", &val );
660 if( val.psz_string && *val.psz_string )
663 char *psz = val.psz_string;
668 while ( psz != NULL )
670 i_pid = strtoul( psz, &psz_next, 0 );
671 if( strlen(psz_next) > 0 )
679 msg_Err( p_mux, "Number of PMTs > maximum (%d)",
684 p_sys->i_pmt_program_number[i] = i_pid;
691 /* Option not specified, use 1, 2, 3... */
692 for( i = 0; i < p_sys->i_num_pmt; i++ )
693 p_sys->i_pmt_program_number[i] = i + 1;
695 free( val.psz_string );
697 var_Get( p_mux, SOUT_CFG_PREFIX "pid-pmt", &val );
700 for( i = 0; i < p_sys->i_num_pmt; i++ )
701 p_sys->pmt[i].i_pid = val.i_int + i; /* Does this make any sense? */
705 for( i = 0; i < p_sys->i_num_pmt; i++ )
706 p_sys->pmt[i].i_pid = 0x42 + i;
709 p_sys->i_pid_free = p_sys->pmt[p_sys->i_num_pmt - 1].i_pid + 1;
711 var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
712 p_sys->i_pid_video = val.i_int;
713 if ( p_sys->i_pid_video > p_sys->i_pid_free )
715 p_sys->i_pid_free = p_sys->i_pid_video + 1;
718 var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
719 p_sys->i_pid_audio = val.i_int;
720 if ( p_sys->i_pid_audio > p_sys->i_pid_free )
722 p_sys->i_pid_free = p_sys->i_pid_audio + 1;
725 var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
726 p_sys->i_pid_spu = val.i_int;
727 if ( p_sys->i_pid_spu > p_sys->i_pid_free )
729 p_sys->i_pid_free = p_sys->i_pid_spu + 1;
732 p_sys->i_pcr_pid = 0x1fff;
733 p_sys->p_pcr_input = NULL;
735 p_sys->i_mpeg4_streams = 0;
737 p_sys->i_null_continuity_counter = 0;
739 /* Allow to create constrained stream */
740 var_Get( p_mux, SOUT_CFG_PREFIX "bmin", &val );
741 p_sys->i_bitrate_min = val.i_int;
743 var_Get( p_mux, SOUT_CFG_PREFIX "bmax", &val );
744 p_sys->i_bitrate_max = val.i_int;
746 if( p_sys->i_bitrate_min > 0 && p_sys->i_bitrate_max > 0 &&
747 p_sys->i_bitrate_min > p_sys->i_bitrate_max )
749 msg_Err( p_mux, "incompatible minimum and maximum bitrate, "
750 "disabling bitrate control" );
751 p_sys->i_bitrate_min = 0;
752 p_sys->i_bitrate_max = 0;
754 if( p_sys->i_bitrate_min > 0 || p_sys->i_bitrate_max > 0 )
756 msg_Err( p_mux, "bmin and bmax no more supported "
757 "(if you need them report it)" );
760 var_Get( p_mux, SOUT_CFG_PREFIX "shaping", &val );
761 p_sys->i_shaping_delay = (int64_t)val.i_int * 1000;
762 if( p_sys->i_shaping_delay <= 0 )
765 "invalid shaping (%"PRId64"ms) resetting to 200ms",
766 p_sys->i_shaping_delay / 1000 );
767 p_sys->i_shaping_delay = 200000;
770 var_Get( p_mux, SOUT_CFG_PREFIX "pcr", &val );
771 p_sys->i_pcr_delay = (int64_t)val.i_int * 1000;
772 if( p_sys->i_pcr_delay <= 0 ||
773 p_sys->i_pcr_delay >= p_sys->i_shaping_delay )
776 "invalid pcr delay (%"PRId64"ms) resetting to 70ms",
777 p_sys->i_pcr_delay / 1000 );
778 p_sys->i_pcr_delay = 70000;
781 var_Get( p_mux, SOUT_CFG_PREFIX "dts-delay", &val );
782 p_sys->i_dts_delay = (int64_t)val.i_int * 1000;
784 msg_Dbg( p_mux, "shaping=%"PRId64" pcr=%"PRId64" dts_delay=%"PRId64,
785 p_sys->i_shaping_delay, p_sys->i_pcr_delay, p_sys->i_dts_delay );
787 var_Get( p_mux, SOUT_CFG_PREFIX "use-key-frames", &val );
788 p_sys->b_use_key_frames = val.b_bool;
790 /* for TS generation */
794 var_Create( p_mux, SOUT_CFG_PREFIX "csa-ck", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );
795 var_Get( p_mux, SOUT_CFG_PREFIX "csa-ck", &val );
796 if( val.psz_string && *val.psz_string )
801 p_sys->csa = csa_New();
803 var_Create( p_mux, SOUT_CFG_PREFIX "csa2-ck", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );
804 var_Get( p_mux, SOUT_CFG_PREFIX "csa2-ck", &csa2 );
805 i_res = csa_SetCW( (vlc_object_t*)p_mux, p_sys->csa, val.psz_string, true );
806 if( i_res == VLC_SUCCESS && csa2.psz_string && *csa2.psz_string )
808 if( csa_SetCW( (vlc_object_t*)p_mux, p_sys->csa, csa2.psz_string, false ) != VLC_SUCCESS )
810 csa_SetCW( (vlc_object_t*)p_mux, p_sys->csa, val.psz_string, false );
813 else if( i_res == VLC_SUCCESS )
815 csa_SetCW( (vlc_object_t*)p_mux, p_sys->csa, val.psz_string, false );
819 csa_Delete( p_sys->csa );
825 vlc_value_t use_val, pkt_val;
827 var_Create( p_mux, SOUT_CFG_PREFIX "csa-use", VLC_VAR_STRING | VLC_VAR_DOINHERIT | VLC_VAR_ISCOMMAND );
828 var_Get( p_mux, SOUT_CFG_PREFIX "csa-use", &use_val );
829 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
830 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, (void *)1 );
831 var_AddCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
833 if ( var_Set( p_mux, SOUT_CFG_PREFIX "csa-use", use_val ) != VLC_SUCCESS )
835 var_SetString( p_mux, SOUT_CFG_PREFIX "csa-use", "odd" );
837 free( use_val.psz_string );
839 var_Get( p_mux, SOUT_CFG_PREFIX "csa-pkt", &pkt_val );
840 if( pkt_val.i_int < 12 || pkt_val.i_int > 188 )
842 msg_Err( p_mux, "wrong packet size %d specified.", pkt_val.i_int );
843 msg_Warn( p_mux, "using default packet size of 188 bytes" );
844 p_sys->i_csa_pkt_size = 188;
846 else p_sys->i_csa_pkt_size = pkt_val.i_int;
847 msg_Dbg( p_mux, "encrypting %d bytes of packet", p_sys->i_csa_pkt_size );
849 free( csa2.psz_string );
851 free( val.psz_string );
853 var_Get( p_mux, SOUT_CFG_PREFIX "crypt-audio", &val );
854 p_sys->b_crypt_audio = val.b_bool;
856 var_Get( p_mux, SOUT_CFG_PREFIX "crypt-video", &val );
857 p_sys->b_crypt_video = val.b_bool;
862 /*****************************************************************************
864 *****************************************************************************/
865 static void Close( vlc_object_t * p_this )
867 sout_mux_t *p_mux = (sout_mux_t*)p_this;
868 sout_mux_sys_t *p_sys = p_mux->p_sys;
871 vlc_mutex_lock( &p_sys->csa_lock );
874 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-ck", ChangeKeyCallback, NULL );
875 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa2-ck", ChangeKeyCallback, NULL );
876 var_DelCallback( p_mux, SOUT_CFG_PREFIX "csa-use", ActiveKeyCallback, NULL );
877 csa_Delete( p_sys->csa );
880 vlc_mutex_unlock( &p_sys->csa_lock );
882 for( i = 0; i < MAX_PMT; i++ )
884 free( p_sys->sdt_descriptors[i].psz_service_name );
885 free( p_sys->sdt_descriptors[i].psz_provider );
888 vlc_mutex_destroy( &p_sys->csa_lock );
889 free( p_sys->dvbpmt );
893 /*****************************************************************************
894 * ChangeKeyCallback: called when changing the odd encryption key on the fly.
895 *****************************************************************************/
896 static int ChangeKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
897 vlc_value_t oldval, vlc_value_t newval,
900 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
901 sout_mux_t *p_mux = (sout_mux_t*)p_this;
902 sout_mux_sys_t *p_sys = p_mux->p_sys;
903 int i_tmp = (int)p_data;
905 vlc_mutex_lock( &p_sys->csa_lock );
908 i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, true );
912 i_tmp = csa_SetCW( p_this, p_sys->csa, newval.psz_string, false );
914 vlc_mutex_unlock( &p_sys->csa_lock );
919 /*****************************************************************************
920 * ActiveKeyCallback: called when changing the active (in use) encryption key on the fly.
921 *****************************************************************************/
922 static int ActiveKeyCallback( vlc_object_t *p_this, char const *psz_cmd,
923 vlc_value_t oldval, vlc_value_t newval,
926 VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval); VLC_UNUSED(p_data);
927 sout_mux_t *p_mux = (sout_mux_t*)p_this;
928 sout_mux_sys_t *p_sys = p_mux->p_sys;
929 int i_res = VLC_EBADVAR;
931 vlc_mutex_lock( &p_sys->csa_lock );
932 if( !strcmp(newval.psz_string, "odd" ) || !strcmp(newval.psz_string, "first" ) || !strcmp(newval.psz_string, "1" ) )
934 i_res = csa_UseKey( (vlc_object_t*)p_mux, p_sys->csa, 1 );
936 else if( !strcmp(newval.psz_string, "even" ) || !strcmp(newval.psz_string, "second" ) || !strcmp(newval.psz_string, "2" ) )
938 i_res = csa_UseKey( (vlc_object_t*)p_mux, p_sys->csa, 0 );
940 vlc_mutex_unlock( &p_sys->csa_lock );
945 /*****************************************************************************
947 *****************************************************************************/
948 static int Control( sout_mux_t *p_mux, int i_query, va_list args )
956 case MUX_CAN_ADD_STREAM_WHILE_MUXING:
957 pb_bool = (bool*)va_arg( args, bool * );
961 case MUX_GET_ADD_STREAM_WAIT:
962 pb_bool = (bool*)va_arg( args, bool * );
967 ppsz = (char**)va_arg( args, char ** );
968 *ppsz = strdup( "video/mpeg" ); /* FIXME not sure */
976 /*****************************************************************************
977 * AddStream: called for each stream addition
978 *****************************************************************************/
979 static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
981 sout_mux_sys_t *p_sys = p_mux->p_sys;
982 ts_stream_t *p_stream;
985 p_input->p_sys = p_stream = malloc( sizeof( ts_stream_t ) );
986 if( !p_input->p_sys )
989 /* Init this new stream */
990 if ( p_sys->b_es_id_pid )
991 p_stream->i_pid = p_input->p_fmt->i_id & 0x1fff;
993 p_stream->i_pid = AllocatePID( p_sys, p_input->p_fmt->i_cat );
994 p_stream->i_codec = p_input->p_fmt->i_codec;
995 p_stream->i_continuity_counter = 0;
996 p_stream->b_discontinuity = false;
997 p_stream->i_decoder_specific_info = 0;
998 p_stream->p_decoder_specific_info = NULL;
1000 msg_Dbg( p_mux, "adding input codec=%4.4s pid=%d",
1001 (char*)&p_input->p_fmt->i_codec, p_stream->i_pid );
1003 /* All others fields depand on codec */
1004 switch( p_input->p_fmt->i_cat )
1007 switch( p_input->p_fmt->i_codec )
1009 case VLC_FOURCC( 'm', 'p','g', 'v' ):
1010 /* TODO: do we need to check MPEG-I/II ? */
1011 p_stream->i_stream_type = 0x02;
1012 p_stream->i_stream_id = 0xe0;
1014 case VLC_FOURCC( 'm', 'p','4', 'v' ):
1015 p_stream->i_stream_type = 0x10;
1016 p_stream->i_stream_id = 0xe0;
1017 p_stream->i_es_id = p_stream->i_pid;
1019 case VLC_FOURCC( 'h', '2','6', '4' ):
1020 p_stream->i_stream_type = 0x1b;
1021 p_stream->i_stream_id = 0xe0;
1023 /* XXX dirty dirty but somebody want that:
1024 * using crapy MS-codec XXX */
1025 /* I didn't want to do that :P */
1026 case VLC_FOURCC( 'H', '2', '6', '3' ):
1027 case VLC_FOURCC( 'I', '2', '6', '3' ):
1028 case VLC_FOURCC( 'W', 'M', 'V', '3' ):
1029 case VLC_FOURCC( 'W', 'M', 'V', '2' ):
1030 case VLC_FOURCC( 'W', 'M', 'V', '1' ):
1031 case VLC_FOURCC( 'D', 'I', 'V', '3' ):
1032 case VLC_FOURCC( 'D', 'I', 'V', '2' ):
1033 case VLC_FOURCC( 'D', 'I', 'V', '1' ):
1034 case VLC_FOURCC( 'M', 'J', 'P', 'G' ):
1035 p_stream->i_stream_type = 0xa0; /* private */
1036 p_stream->i_stream_id = 0xa0; /* beurk */
1037 p_stream->i_bih_codec = p_input->p_fmt->i_codec;
1038 p_stream->i_bih_width = p_input->p_fmt->video.i_width;
1039 p_stream->i_bih_height = p_input->p_fmt->video.i_height;
1043 return VLC_EGENERIC;
1045 p_sys->i_video_bound++;
1049 switch( p_input->p_fmt->i_codec )
1051 case VLC_FOURCC( 'm', 'p','g', 'a' ):
1052 case VLC_FOURCC( 'm', 'p', '3', ' ' ):
1053 p_stream->i_stream_type =
1054 p_input->p_fmt->audio.i_rate >= 32000 ? 0x03 : 0x04;
1055 p_stream->i_stream_id = 0xc0;
1057 case VLC_FOURCC( 'a', '5','2', ' ' ):
1058 p_stream->i_stream_type = 0x81;
1059 p_stream->i_stream_id = 0xbd;
1061 case VLC_FOURCC( 'l', 'p','c', 'm' ):
1062 p_stream->i_stream_type = 0x83;
1063 p_stream->i_stream_id = 0xbd;
1065 case VLC_FOURCC( 'd', 't','s', ' ' ):
1066 p_stream->i_stream_type = 0x06;
1067 p_stream->i_stream_id = 0xbd;
1069 case VLC_FOURCC( 'm', 'p','4', 'a' ):
1070 /* XXX: make that configurable in some way when LOAS
1071 * is implemented for AAC in TS */
1072 //p_stream->i_stream_type = 0x11; /* LOAS/LATM */
1073 p_stream->i_stream_type = 0x0f; /* ADTS */
1074 p_stream->i_stream_id = 0xfa;
1075 p_sys->i_mpeg4_streams++;
1076 p_stream->i_es_id = p_stream->i_pid;
1080 return VLC_EGENERIC;
1082 p_sys->i_audio_bound++;
1086 switch( p_input->p_fmt->i_codec )
1088 case VLC_FOURCC( 's', 'p','u', ' ' ):
1089 p_stream->i_stream_type = 0x82;
1090 p_stream->i_stream_id = 0xbd;
1092 case VLC_FOURCC( 's', 'u','b', 't' ):
1093 p_stream->i_stream_type = 0x12;
1094 p_stream->i_stream_id = 0xfa;
1095 p_sys->i_mpeg4_streams++;
1096 p_stream->i_es_id = p_stream->i_pid;
1098 case VLC_FOURCC('d','v','b','s'):
1099 p_stream->i_stream_type = 0x06;
1100 p_stream->i_es_id = p_input->p_fmt->subs.dvb.i_id;
1101 p_stream->i_stream_id = 0xbd;
1103 case VLC_FOURCC('t','e','l','x'):
1104 p_stream->i_stream_type = 0x06;
1105 p_stream->i_stream_id = 0xbd; /* FIXME */
1109 return VLC_EGENERIC;
1115 return VLC_EGENERIC;
1118 p_stream->i_langs = 1+p_input->p_fmt->i_extra_languages;
1119 p_stream->lang = malloc(p_stream->i_langs*3);
1120 if( !p_stream->lang )
1122 p_stream->i_langs = 0;
1129 p_stream->lang[2] = '\0';
1130 if( p_input->p_fmt->psz_language )
1132 char *psz = p_input->p_fmt->psz_language;
1133 const iso639_lang_t *pl = NULL;
1135 if( strlen( psz ) == 2 )
1137 pl = GetLang_1( psz );
1139 else if( strlen( psz ) == 3 )
1141 pl = GetLang_2B( psz );
1142 if( !strcmp( pl->psz_iso639_1, "??" ) )
1144 pl = GetLang_2T( psz );
1147 if( pl && strcmp( pl->psz_iso639_1, "??" ) )
1149 p_stream->lang[0] = pl->psz_iso639_2T[0];
1150 p_stream->lang[1] = pl->psz_iso639_2T[1];
1151 p_stream->lang[2] = pl->psz_iso639_2T[2];
1153 msg_Dbg( p_mux, " - lang=%c%c%c",
1154 p_stream->lang[0], p_stream->lang[1],
1155 p_stream->lang[2] );
1158 while( i < p_stream->i_langs ) {
1159 if( p_input->p_fmt->p_extra_languages[i-1].psz_language )
1161 char *psz = p_input->p_fmt->p_extra_languages[i-1].psz_language;
1162 const iso639_lang_t *pl = NULL;
1164 if( strlen( psz ) == 2 )
1166 pl = GetLang_1( psz );
1168 else if( strlen( psz ) == 3 )
1170 pl = GetLang_2B( psz );
1171 if( !strcmp( pl->psz_iso639_1, "??" ) )
1173 pl = GetLang_2T( psz );
1176 if( pl && strcmp( pl->psz_iso639_1, "??" ) )
1178 p_stream->lang[i*3+0] = pl->psz_iso639_2T[0];
1179 p_stream->lang[i*3+1] = pl->psz_iso639_2T[1];
1180 p_stream->lang[i*3+2] = pl->psz_iso639_2T[2];
1182 msg_Dbg( p_mux, " - lang=%c%c%c",
1183 p_stream->lang[i*3+0], p_stream->lang[i*3+1],
1184 p_stream->lang[i*3+2] );
1190 /* Create decoder specific info for subt */
1191 if( p_stream->i_codec == VLC_FOURCC( 's', 'u','b', 't' ) )
1195 p_stream->i_decoder_specific_info = 55;
1196 p_stream->p_decoder_specific_info = p =
1197 malloc( p_stream->i_decoder_specific_info );
1200 p[0] = 0x10; /* textFormat, 0x10 for 3GPP TS 26.245 */
1201 p[1] = 0x00; /* flags: 1b: associated video info flag
1205 p[2] = 52; /* remaining size */
1209 p[0] = p[1] = p[2] = p[3] = 0; p+=4; /* display flags */
1210 *p++ = 0; /* horizontal justification (-1: left, 0 center, 1 right) */
1211 *p++ = 1; /* vertical justification (-1: top, 0 center, 1 bottom) */
1213 p[0] = p[1] = p[2] = 0x00; p+=3;/* background rgb */
1214 *p++ = 0xff; /* background a */
1216 p[0] = p[1] = 0; p += 2; /* text box top */
1217 p[0] = p[1] = 0; p += 2; /* text box left */
1218 p[0] = p[1] = 0; p += 2; /* text box bottom */
1219 p[0] = p[1] = 0; p += 2; /* text box right */
1221 p[0] = p[1] = 0; p += 2; /* start char */
1222 p[0] = p[1] = 0; p += 2; /* end char */
1223 p[0] = p[1] = 0; p += 2; /* default font id */
1225 *p++ = 0; /* font style flags */
1226 *p++ = 12; /* font size */
1228 p[0] = p[1] = p[2] = 0x00; p+=3;/* foreground rgb */
1229 *p++ = 0x00; /* foreground a */
1231 p[0] = p[1] = p[2] = 0; p[3] = 22; p += 4;
1232 memcpy( p, "ftab", 4 ); p += 4;
1233 *p++ = 0; *p++ = 1; /* entry count */
1234 p[0] = p[1] = 0; p += 2; /* font id */
1235 *p++ = 9; /* font name length */
1236 memcpy( p, "Helvetica", 9 ); /* font name */
1238 else p_stream->i_decoder_specific_info = 0;
1242 /* Copy extra data (VOL for MPEG-4 and extra BitMapInfoHeader for VFW */
1243 p_stream->i_decoder_specific_info = p_input->p_fmt->i_extra;
1244 if( p_stream->i_decoder_specific_info > 0 )
1246 p_stream->p_decoder_specific_info =
1247 malloc( p_stream->i_decoder_specific_info );
1248 if( p_stream->p_decoder_specific_info )
1250 memcpy( p_stream->p_decoder_specific_info,
1251 p_input->p_fmt->p_extra,
1252 p_input->p_fmt->i_extra );
1254 else p_stream->i_decoder_specific_info = 0;
1258 /* Init pes chain */
1259 BufferChainInit( &p_stream->chain_pes );
1260 p_stream->i_pes_dts = 0;
1261 p_stream->i_pes_length = 0;
1262 p_stream->i_pes_used = 0;
1263 p_stream->b_key_frame = 0;
1265 /* We only change PMT version (PAT isn't changed) */
1266 p_sys->i_pmt_version_number = ( p_sys->i_pmt_version_number + 1 )%32;
1268 /* Update pcr_pid */
1269 if( p_input->p_fmt->i_cat != SPU_ES &&
1270 ( p_sys->i_pcr_pid == 0x1fff || p_input->p_fmt->i_cat == VIDEO_ES ) )
1272 if( p_sys->p_pcr_input )
1274 /* There was already a PCR stream, so clean context */
1277 p_sys->i_pcr_pid = p_stream->i_pid;
1278 p_sys->p_pcr_input = p_input;
1280 msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1286 /*****************************************************************************
1287 * DelStream: called before a stream deletion
1288 *****************************************************************************/
1289 static int DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
1291 sout_mux_sys_t *p_sys = p_mux->p_sys;
1292 ts_stream_t *p_stream;
1295 p_stream = (ts_stream_t*)p_input->p_sys;
1296 msg_Dbg( p_mux, "removing input pid=%d", p_stream->i_pid );
1298 if( p_sys->i_pcr_pid == p_stream->i_pid )
1302 /* Find a new pcr stream (Prefer Video Stream) */
1303 p_sys->i_pcr_pid = 0x1fff;
1304 p_sys->p_pcr_input = NULL;
1305 for( i = 0; i < p_mux->i_nb_inputs; i++ )
1307 if( p_mux->pp_inputs[i] == p_input )
1312 if( p_mux->pp_inputs[i]->p_fmt->i_cat == VIDEO_ES )
1315 ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
1316 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1319 else if( p_mux->pp_inputs[i]->p_fmt->i_cat != SPU_ES &&
1320 p_sys->i_pcr_pid == 0x1fff )
1323 ((ts_stream_t*)p_mux->pp_inputs[i]->p_sys)->i_pid;
1324 p_sys->p_pcr_input= p_mux->pp_inputs[i];
1327 if( p_sys->p_pcr_input )
1329 /* Empty TS buffer */
1332 msg_Dbg( p_mux, "new PCR PID is %d", p_sys->i_pcr_pid );
1335 /* Empty all data in chain_pes */
1336 BufferChainClean( &p_stream->chain_pes );
1338 free(p_stream->lang);
1339 free( p_stream->p_decoder_specific_info );
1340 if( p_stream->i_stream_id == 0xfa ||
1341 p_stream->i_stream_id == 0xfb ||
1342 p_stream->i_stream_id == 0xfe )
1344 p_sys->i_mpeg4_streams--;
1347 var_Get( p_mux, SOUT_CFG_PREFIX "pid-video", &val );
1350 int i_pid_video = val.i_int;
1351 if ( i_pid_video == p_stream->i_pid )
1353 p_sys->i_pid_video = i_pid_video;
1354 msg_Dbg( p_mux, "freeing video PID %d", i_pid_video );
1357 var_Get( p_mux, SOUT_CFG_PREFIX "pid-audio", &val );
1360 int i_pid_audio = val.i_int;
1361 if ( i_pid_audio == p_stream->i_pid )
1363 p_sys->i_pid_audio = i_pid_audio;
1364 msg_Dbg( p_mux, "freeing audio PID %d", i_pid_audio );
1367 var_Get( p_mux, SOUT_CFG_PREFIX "pid-spu", &val );
1370 int i_pid_spu = val.i_int;
1371 if ( i_pid_spu == p_stream->i_pid )
1373 p_sys->i_pid_spu = i_pid_spu;
1374 msg_Dbg( p_mux, "freeing spu PID %d", i_pid_spu );
1379 /* We only change PMT version (PAT isn't changed) */
1380 p_sys->i_pmt_version_number++; p_sys->i_pmt_version_number %= 32;
1385 /*****************************************************************************
1386 * Mux: Call each time there is new data for at least one stream
1387 *****************************************************************************
1389 *****************************************************************************/
1390 static int Mux( sout_mux_t *p_mux )
1392 sout_mux_sys_t *p_sys = p_mux->p_sys;
1393 ts_stream_t *p_pcr_stream;
1395 if( p_sys->i_pcr_pid == 0x1fff )
1398 for( i = 0; i < p_mux->i_nb_inputs; i++ )
1400 block_FifoEmpty( p_mux->pp_inputs[i]->p_fifo );
1402 msg_Dbg( p_mux, "waiting for PCR streams" );
1406 p_pcr_stream = (ts_stream_t*)p_sys->p_pcr_input->p_sys;
1410 sout_buffer_chain_t chain_ts;
1414 mtime_t i_pcr_length;
1415 mtime_t i_shaping_delay;
1418 if( p_pcr_stream->b_key_frame )
1420 i_shaping_delay = p_pcr_stream->i_pes_length;
1424 i_shaping_delay = p_sys->i_shaping_delay;
1427 /* 1: get enough PES packet for all input */
1433 /* Accumulate enough data in the pcr stream (>i_shaping_delay) */
1434 /* Accumulate enough data in all other stream ( >= length of pcr)*/
1435 for( i = -1; i < p_mux->i_nb_inputs; i++ )
1437 sout_input_t *p_input;
1438 ts_stream_t *p_stream;
1439 int64_t i_spu_delay = 0;
1442 p_input = p_sys->p_pcr_input;
1443 else if( p_mux->pp_inputs[i]->p_sys == p_pcr_stream )
1446 p_input = p_mux->pp_inputs[i];
1447 p_stream = (ts_stream_t*)p_input->p_sys;
1449 if( ( ( p_stream == p_pcr_stream ) &&
1450 ( p_stream->i_pes_length < i_shaping_delay ) ) ||
1451 ( p_stream->i_pes_dts + p_stream->i_pes_length <
1452 p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length ) )
1454 /* Need more data */
1455 if( block_FifoCount( p_input->p_fifo ) <= 1 )
1457 if( ( p_input->p_fmt->i_cat == AUDIO_ES ) ||
1458 ( p_input->p_fmt->i_cat == VIDEO_ES ) )
1460 /* We need more data */
1463 else if( block_FifoCount( p_input->p_fifo ) <= 0 )
1465 /* spu, only one packet is needed */
1468 else if( p_input->p_fmt->i_cat == SPU_ES )
1470 /* Don't mux the SPU yet if it is too early */
1471 block_t *p_spu = block_FifoShow( p_input->p_fifo );
1474 p_spu->i_dts - p_pcr_stream->i_pes_dts;
1476 if( ( i_spu_delay > i_shaping_delay ) &&
1477 ( i_spu_delay < INT64_C(100000000) ) )
1480 if ( ( i_spu_delay >= INT64_C(100000000) ) ||
1481 ( i_spu_delay < INT64_C(10000) ) )
1483 BufferChainClean( &p_stream->chain_pes );
1484 p_stream->i_pes_dts = 0;
1485 p_stream->i_pes_used = 0;
1486 p_stream->i_pes_length = 0;
1493 if( p_stream == p_pcr_stream || p_sys->b_data_alignment
1494 || p_input->p_fmt->i_codec !=
1495 VLC_FOURCC('m', 'p', 'g', 'a') )
1497 p_data = block_FifoGet( p_input->p_fifo );
1499 if( p_input->p_fmt->i_codec ==
1500 VLC_FOURCC('m', 'p', '4', 'a' ) )
1501 p_data = Add_ADTS( p_data, p_input->p_fmt );
1504 p_data = FixPES( p_mux, p_input->p_fifo );
1506 if( block_FifoCount( p_input->p_fifo ) > 0 &&
1507 p_input->p_fmt->i_cat != SPU_ES )
1509 block_t *p_next = block_FifoShow( p_input->p_fifo );
1510 p_data->i_length = p_next->i_dts - p_data->i_dts;
1512 else if( p_input->p_fmt->i_codec !=
1513 VLC_FOURCC('s', 'u', 'b', 't' ) )
1514 p_data->i_length = 1000;
1516 if( ( p_pcr_stream->i_pes_dts > 0 &&
1517 p_data->i_dts - 10000000 > p_pcr_stream->i_pes_dts +
1518 p_pcr_stream->i_pes_length ) ||
1519 p_data->i_dts < p_stream->i_pes_dts ||
1520 ( p_stream->i_pes_dts > 0 &&
1521 p_input->p_fmt->i_cat != SPU_ES &&
1522 p_data->i_dts - 10000000 > p_stream->i_pes_dts +
1523 p_stream->i_pes_length ) )
1525 msg_Warn( p_mux, "packet with too strange dts "
1526 "(dts=%"PRId64",old=%"PRId64",pcr=%"PRId64")",
1527 p_data->i_dts, p_stream->i_pes_dts,
1528 p_pcr_stream->i_pes_dts );
1529 block_Release( p_data );
1531 BufferChainClean( &p_stream->chain_pes );
1532 p_stream->i_pes_dts = 0;
1533 p_stream->i_pes_used = 0;
1534 p_stream->i_pes_length = 0;
1536 if( p_input->p_fmt->i_cat != SPU_ES )
1538 BufferChainClean( &p_pcr_stream->chain_pes );
1539 p_pcr_stream->i_pes_dts = 0;
1540 p_pcr_stream->i_pes_used = 0;
1541 p_pcr_stream->i_pes_length = 0;
1546 int i_header_size = 0;
1547 int b_data_alignment = 0;
1548 if( p_input->p_fmt->i_cat == SPU_ES )
1550 if( p_input->p_fmt->i_codec ==
1551 VLC_FOURCC('s','u','b','t') )
1553 /* Prepend header */
1554 p_data = block_Realloc( p_data, 2,
1556 p_data->p_buffer[0] =
1557 ( (p_data->i_buffer - 2) >> 8) & 0xff;
1558 p_data->p_buffer[1] =
1559 ( (p_data->i_buffer - 2) ) & 0xff;
1561 /* remove trailling \0 if any */
1562 if( p_data->i_buffer > 2 &&
1563 p_data->p_buffer[p_data->i_buffer -1] ==
1567 /* Append a empty sub (sub text only) */
1568 if( p_data->i_length > 0 &&
1569 !( p_data->i_buffer == 1 &&
1570 *p_data->p_buffer == ' ' ) )
1572 block_t *p_spu = block_New( p_mux, 3 );
1574 p_spu->i_dts = p_spu->i_pts =
1575 p_data->i_dts + p_data->i_length;
1576 p_spu->i_length = 1000;
1578 p_spu->p_buffer[0] = 0;
1579 p_spu->p_buffer[1] = 1;
1580 p_spu->p_buffer[2] = ' ';
1582 EStoPES( p_mux->p_sout, &p_spu, p_spu,
1584 p_stream->i_stream_id, 1,
1586 p_data->p_next = p_spu;
1589 else if( p_input->p_fmt->i_codec ==
1590 VLC_FOURCC('t','e','l','x') )
1593 i_header_size = 0x24;
1594 b_data_alignment = 1;
1596 else if( p_input->p_fmt->i_codec ==
1597 VLC_FOURCC('d','v','b','s') )
1600 b_data_alignment = 1;
1603 else if( p_data->i_length < 0 ||
1604 p_data->i_length > 2000000 )
1606 /* FIXME choose a better value, but anyway we
1607 * should never have to do that */
1608 p_data->i_length = 1000;
1611 p_stream->i_pes_length += p_data->i_length;
1612 if( p_stream->i_pes_dts == 0 )
1614 p_stream->i_pes_dts = p_data->i_dts;
1617 /* Convert to pes */
1618 if( p_stream->i_stream_id == 0xa0 &&
1619 p_data->i_pts <= 0 )
1621 /* XXX yes I know, it's awful, but it's needed,
1622 * so don't remove it ... */
1623 p_data->i_pts = p_data->i_dts;
1626 EStoPES ( p_mux->p_sout, &p_data, p_data,
1627 p_input->p_fmt, p_stream->i_stream_id,
1628 1, b_data_alignment, i_header_size, 0 );
1630 BufferChainAppend( &p_stream->chain_pes, p_data );
1632 if( p_sys->b_use_key_frames && p_stream == p_pcr_stream
1633 && (p_data->i_flags & BLOCK_FLAG_TYPE_I)
1634 && !(p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME)
1635 && (p_stream->i_pes_length > 400000) )
1637 i_shaping_delay = p_stream->i_pes_length;
1638 p_stream->b_key_frame = 1;
1651 i_pcr_dts = p_pcr_stream->i_pes_dts;
1652 i_pcr_length = p_pcr_stream->i_pes_length;
1653 p_pcr_stream->b_key_frame = 0;
1655 /* msg_Dbg( p_mux, "starting muxing %lldms", i_pcr_length / 1000 ); */
1656 /* 2: calculate non accurate total size of muxed ts */
1658 for( i = 0; i < p_mux->i_nb_inputs; i++ )
1660 ts_stream_t *p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1663 /* False for pcr stream but it will be enough to do PCR algo */
1664 for( p_pes = p_stream->chain_pes.p_first; p_pes != NULL;
1665 p_pes = p_pes->p_next )
1667 int i_size = p_pes->i_buffer;
1668 if( p_pes->i_dts + p_pes->i_length >
1669 p_pcr_stream->i_pes_dts + p_pcr_stream->i_pes_length )
1671 mtime_t i_frag = p_pcr_stream->i_pes_dts +
1672 p_pcr_stream->i_pes_length - p_pes->i_dts;
1678 i_size = p_pes->i_buffer * i_frag / p_pes->i_length;
1680 i_packet_count += ( i_size + 183 ) / 184;
1683 /* add overhead for PCR (not really exact) */
1684 i_packet_count += (8 * i_pcr_length / p_sys->i_pcr_delay + 175) / 176;
1686 /* 3: mux PES into TS */
1687 BufferChainInit( &chain_ts );
1688 /* append PAT/PMT -> FIXME with big pcr delay it won't have enough pat/pmt */
1689 GetPAT( p_mux, &chain_ts );
1690 GetPMT( p_mux, &chain_ts );
1692 i_packet_count += chain_ts.i_depth;
1693 /* msg_Dbg( p_mux, "estimated pck=%d", i_packet_count ); */
1699 ts_stream_t *p_stream;
1700 sout_input_t *p_input;
1704 /* Select stream (lowest dts) */
1705 for( i = 0, i_stream = -1, i_dts = 0; i < p_mux->i_nb_inputs; i++ )
1707 p_stream = (ts_stream_t*)p_mux->pp_inputs[i]->p_sys;
1709 if( p_stream->i_pes_dts == 0 )
1714 if( i_stream == -1 ||
1715 p_stream->i_pes_dts < i_dts )
1718 i_dts = p_stream->i_pes_dts;
1721 if( i_stream == -1 || i_dts > i_pcr_dts + i_pcr_length )
1725 p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
1726 p_input = p_mux->pp_inputs[i_stream];
1728 /* do we need to issue pcr */
1730 if( p_stream == p_pcr_stream &&
1731 i_pcr_dts + i_packet_pos * i_pcr_length / i_packet_count >=
1732 p_sys->i_pcr + p_sys->i_pcr_delay )
1735 p_sys->i_pcr = i_pcr_dts + i_packet_pos *
1736 i_pcr_length / i_packet_count;
1739 /* Build the TS packet */
1740 p_ts = TSNew( p_mux, p_stream, b_pcr );
1741 if( p_sys->csa != NULL &&
1742 (p_input->p_fmt->i_cat != AUDIO_ES || p_sys->b_crypt_audio) &&
1743 (p_input->p_fmt->i_cat != VIDEO_ES || p_sys->b_crypt_video) )
1745 p_ts->i_flags |= BLOCK_FLAG_SCRAMBLED;
1750 BufferChainAppend( &chain_ts, p_ts );
1753 /* 4: date and send */
1754 TSSchedule( p_mux, &chain_ts, i_pcr_length, i_pcr_dts );
1758 #define STD_PES_PAYLOAD 170
1759 static block_t *FixPES( sout_mux_t *p_mux, block_fifo_t *p_fifo )
1764 p_data = block_FifoShow( p_fifo );
1765 i_size = p_data->i_buffer;
1767 if( i_size == STD_PES_PAYLOAD )
1769 return block_FifoGet( p_fifo );
1771 else if( i_size > STD_PES_PAYLOAD )
1773 block_t *p_new = block_New( p_mux, STD_PES_PAYLOAD );
1774 vlc_memcpy( p_new->p_buffer, p_data->p_buffer, STD_PES_PAYLOAD );
1775 p_new->i_pts = p_data->i_pts;
1776 p_new->i_dts = p_data->i_dts;
1777 p_new->i_length = p_data->i_length * STD_PES_PAYLOAD
1779 p_data->i_buffer -= STD_PES_PAYLOAD;
1780 p_data->p_buffer += STD_PES_PAYLOAD;
1781 p_data->i_pts += p_new->i_length;
1782 p_data->i_dts += p_new->i_length;
1783 p_data->i_length -= p_new->i_length;
1784 p_data->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1792 p_data = block_FifoGet( p_fifo );
1793 p_data = block_Realloc( p_data, 0, STD_PES_PAYLOAD );
1794 p_next = block_FifoShow( p_fifo );
1795 if ( p_data->i_flags & BLOCK_FLAG_NO_KEYFRAME )
1797 p_data->i_flags &= ~BLOCK_FLAG_NO_KEYFRAME;
1798 p_data->i_pts = p_next->i_pts;
1799 p_data->i_dts = p_next->i_dts;
1801 i_copy = __MIN( STD_PES_PAYLOAD - i_size, p_next->i_buffer );
1803 vlc_memcpy( &p_data->p_buffer[i_size], p_next->p_buffer, i_copy );
1804 p_next->i_pts += p_next->i_length * i_copy / p_next->i_buffer;
1805 p_next->i_dts += p_next->i_length * i_copy / p_next->i_buffer;
1806 p_next->i_length -= p_next->i_length * i_copy / p_next->i_buffer;
1807 p_next->i_buffer -= i_copy;
1808 p_next->p_buffer += i_copy;
1809 p_next->i_flags |= BLOCK_FLAG_NO_KEYFRAME;
1811 if( !p_next->i_buffer )
1813 p_next = block_FifoGet( p_fifo );
1814 block_Release( p_next );
1820 static block_t *Add_ADTS( block_t *p_data, es_format_t *p_fmt )
1822 uint8_t *p_extra = p_fmt->p_extra;
1824 if( !p_data || p_fmt->i_extra < 2 || !p_extra )
1825 return p_data; /* no data to construct the headers */
1827 int i_index = ( (p_extra[0] << 1) | (p_extra[1] >> 7) ) & 0x0f;
1828 int i_profile = (p_extra[0] >> 3) - 1; /* i_profile < 4 */
1830 if( i_index == 0x0f && p_fmt->i_extra < 5 )
1831 return p_data; /* not enough data */
1833 int i_channels = (p_extra[i_index == 0x0f ? 4 : 1] >> 3) & 0x0f;
1835 #define ADTS_HEADER_SIZE 7 /* CRC needs 2 more bytes */
1838 /* keep a copy in case block_Realloc() fails */
1839 block_t *p_bak_block = block_Duplicate( p_data );
1840 if( !p_bak_block ) /* OOM, block_Realloc() is likely to lose our block */
1841 return p_data; /* the frame isn't correct but that's the best we have */
1843 block_t *p_new_block = block_Realloc( p_data, ADTS_HEADER_SIZE,
1846 return p_bak_block; /* OOM, send the (incorrect) original frame */
1848 block_Release( p_bak_block ); /* we don't need the copy anymore */
1851 uint8_t *p_buffer = p_new_block->p_buffer;
1855 p_buffer[1] = 0xf1; /* 0xf0 | 0x00 | 0x00 | 0x01 */
1856 p_buffer[2] = (i_profile << 6) | ((i_index & 0x0f) << 2) | ((i_channels >> 2) & 0x01) ;
1857 p_buffer[3] = (i_channels << 6) | ((p_data->i_buffer >> 11) & 0x03);
1859 /* variable header (starts at last 2 bits of 4th byte) */
1861 int i_fullness = 0x7ff; /* 0x7ff means VBR */
1862 /* XXX: We should check if it's CBR or VBR, but no known implementation
1863 * do that, and it's a pain to calculate this field */
1865 p_buffer[4] = p_data->i_buffer >> 3;
1866 p_buffer[5] = ((p_data->i_buffer & 0x07) << 5) | ((i_fullness >> 6) & 0x1f);
1867 p_buffer[6] = ((i_fullness & 0x3f) << 2) /* | 0xfc */;
1872 static void TSSchedule( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1873 mtime_t i_pcr_length, mtime_t i_pcr_dts )
1875 sout_mux_sys_t *p_sys = p_mux->p_sys;
1876 sout_buffer_chain_t new_chain;
1877 int i_packet_count = p_chain_ts->i_depth;
1880 BufferChainInit( &new_chain );
1882 if ( i_pcr_length <= 0 )
1884 i_pcr_length = i_packet_count;
1887 for( i = 0; i < i_packet_count; i++ )
1889 block_t *p_ts = BufferChainGet( p_chain_ts );
1890 mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1892 BufferChainAppend( &new_chain, p_ts );
1895 p_ts->i_dts + p_sys->i_dts_delay * 2/3 < i_new_dts )
1897 mtime_t i_max_diff = i_new_dts - p_ts->i_dts;
1898 mtime_t i_cut_dts = p_ts->i_dts;
1900 p_ts = BufferChainPeek( p_chain_ts );
1902 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1903 while ( p_ts != NULL && i_new_dts - p_ts->i_dts >= i_max_diff )
1905 p_ts = BufferChainGet( p_chain_ts );
1906 i_max_diff = i_new_dts - p_ts->i_dts;
1907 i_cut_dts = p_ts->i_dts;
1908 BufferChainAppend( &new_chain, p_ts );
1910 p_ts = BufferChainPeek( p_chain_ts );
1912 i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1914 msg_Dbg( p_mux, "adjusting rate at %"PRId64"/%"PRId64" (%d/%d)",
1915 i_cut_dts - i_pcr_dts, i_pcr_length, new_chain.i_depth,
1916 p_chain_ts->i_depth );
1917 if ( new_chain.i_depth )
1918 TSDate( p_mux, &new_chain,
1919 i_cut_dts - i_pcr_dts,
1921 if ( p_chain_ts->i_depth )
1923 p_chain_ts, i_pcr_dts + i_pcr_length - i_cut_dts,
1929 if ( new_chain.i_depth )
1930 TSDate( p_mux, &new_chain, i_pcr_length, i_pcr_dts );
1933 static void TSDate( sout_mux_t *p_mux, sout_buffer_chain_t *p_chain_ts,
1934 mtime_t i_pcr_length, mtime_t i_pcr_dts )
1936 sout_mux_sys_t *p_sys = p_mux->p_sys;
1937 int i_packet_count = p_chain_ts->i_depth;
1940 if ( i_pcr_length / 1000 > 0 )
1942 int i_bitrate = ((uint64_t)i_packet_count * 188 * 8000)
1943 / (uint64_t)(i_pcr_length / 1000);
1944 if ( p_sys->i_bitrate_max && p_sys->i_bitrate_max < i_bitrate )
1946 msg_Warn( p_mux, "max bitrate exceeded at %"PRId64
1947 " (%d bi/s for %d pkt in %"PRId64" us)",
1948 i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1949 i_bitrate, i_packet_count, i_pcr_length);
1954 msg_Dbg( p_mux, "starting at %"PRId64
1955 " (%d bi/s for %d packets in %"PRId64" us)",
1956 i_pcr_dts + p_sys->i_shaping_delay * 3 / 2 - mdate(),
1957 i_bitrate, i_packet_count, i_pcr_length);
1963 /* This shouldn't happen, but happens in some rare heavy load
1964 * and packet losses conditions. */
1965 i_pcr_length = i_packet_count;
1968 /* msg_Dbg( p_mux, "real pck=%d", i_packet_count ); */
1969 for( i = 0; i < i_packet_count; i++ )
1971 block_t *p_ts = BufferChainGet( p_chain_ts );
1972 mtime_t i_new_dts = i_pcr_dts + i_pcr_length * i / i_packet_count;
1974 p_ts->i_dts = i_new_dts;
1975 p_ts->i_length = i_pcr_length / i_packet_count;
1977 if( p_ts->i_flags & BLOCK_FLAG_CLOCK )
1979 /* msg_Dbg( p_mux, "pcr=%lld ms", p_ts->i_dts / 1000 ); */
1980 TSSetPCR( p_ts, p_ts->i_dts - p_sys->i_dts_delay );
1982 if( p_ts->i_flags & BLOCK_FLAG_SCRAMBLED )
1984 vlc_mutex_lock( &p_sys->csa_lock );
1985 csa_Encrypt( p_sys->csa, p_ts->p_buffer, p_sys->i_csa_pkt_size );
1986 vlc_mutex_unlock( &p_sys->csa_lock );
1990 p_ts->i_dts += p_sys->i_shaping_delay * 3 / 2;
1992 sout_AccessOutWrite( p_mux->p_access, p_ts );
1996 static block_t *TSNew( sout_mux_t *p_mux, ts_stream_t *p_stream,
1999 block_t *p_pes = p_stream->chain_pes.p_first;
2002 bool b_new_pes = false;
2003 bool b_adaptation_field = false;
2005 int i_payload_max = 184 - ( b_pcr ? 8 : 0 );
2008 if( p_stream->i_pes_used <= 0 )
2012 i_payload = __MIN( (int)p_pes->i_buffer - p_stream->i_pes_used,
2015 if( b_pcr || i_payload < i_payload_max )
2017 b_adaptation_field = true;
2020 p_ts = block_New( p_mux, 188 );
2021 p_ts->i_dts = p_pes->i_dts;
2023 p_ts->p_buffer[0] = 0x47;
2024 p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 ) |
2025 ( ( p_stream->i_pid >> 8 )&0x1f );
2026 p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
2027 p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 ) |
2028 p_stream->i_continuity_counter;
2030 p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
2031 p_stream->b_discontinuity = (p_pes->i_flags & BLOCK_FLAG_DISCONTINUITY);
2033 if( b_adaptation_field )
2039 int i_stuffing = i_payload_max - i_payload;
2041 p_ts->i_flags |= BLOCK_FLAG_CLOCK;
2043 p_ts->p_buffer[4] = 7 + i_stuffing;
2044 p_ts->p_buffer[5] = 0x10; /* flags */
2045 if( p_stream->b_discontinuity )
2047 p_ts->p_buffer[5] |= 0x80; /* flag TS dicontinuity */
2048 p_stream->b_discontinuity = false;
2050 p_ts->p_buffer[6] = ( 0 )&0xff;
2051 p_ts->p_buffer[7] = ( 0 )&0xff;
2052 p_ts->p_buffer[8] = ( 0 )&0xff;
2053 p_ts->p_buffer[9] = ( 0 )&0xff;
2054 p_ts->p_buffer[10]= ( ( 0 )&0x80 ) | 0x7e;
2055 p_ts->p_buffer[11]= 0;
2057 for( i = 12; i < 12 + i_stuffing; i++ )
2059 p_ts->p_buffer[i] = 0xff;
2064 int i_stuffing = i_payload_max - i_payload;
2066 p_ts->p_buffer[4] = i_stuffing - 1;
2067 if( i_stuffing > 1 )
2069 p_ts->p_buffer[5] = 0x00;
2070 for( i = 6; i < 6 + i_stuffing - 2; i++ )
2072 p_ts->p_buffer[i] = 0xff;
2079 memcpy( &p_ts->p_buffer[188 - i_payload],
2080 &p_pes->p_buffer[p_stream->i_pes_used], i_payload );
2082 p_stream->i_pes_used += i_payload;
2083 p_stream->i_pes_dts = p_pes->i_dts + p_pes->i_length *
2084 p_stream->i_pes_used / p_pes->i_buffer;
2085 p_stream->i_pes_length -= p_pes->i_length * i_payload / p_pes->i_buffer;
2087 if( p_stream->i_pes_used >= (int)p_pes->i_buffer )
2089 p_pes = BufferChainGet( &p_stream->chain_pes );
2090 block_Release( p_pes );
2092 p_pes = p_stream->chain_pes.p_first;
2095 p_stream->i_pes_dts = p_pes->i_dts;
2096 p_stream->i_pes_length = 0;
2099 p_stream->i_pes_length += p_pes->i_length;
2101 p_pes = p_pes->p_next;
2106 p_stream->i_pes_dts = 0;
2107 p_stream->i_pes_length = 0;
2109 p_stream->i_pes_used = 0;
2115 static void TSSetPCR( block_t *p_ts, mtime_t i_dts )
2117 mtime_t i_pcr = 9 * i_dts / 100;
2119 p_ts->p_buffer[6] = ( i_pcr >> 25 )&0xff;
2120 p_ts->p_buffer[7] = ( i_pcr >> 17 )&0xff;
2121 p_ts->p_buffer[8] = ( i_pcr >> 9 )&0xff;
2122 p_ts->p_buffer[9] = ( i_pcr >> 1 )&0xff;
2123 p_ts->p_buffer[10]|= ( i_pcr << 7 )&0x80;
2127 static void TSSetConstraints( sout_mux_t *p_mux, sout_buffer_chain_t *c,
2128 mtime_t i_length, int i_bitrate_min,
2131 sout_mux_sys_t *p_sys = p_mux->p_sys;
2132 sout_buffer_chain_t s = *c;
2135 int i_packets_min = 0;
2136 int i_packets_max = 0;
2143 i_packets = c->i_depth;
2144 i_packets_min = ( (int64_t)i_bitrate_min * i_length / 8 / 1000000 + 187 ) / 188;
2145 i_packets_max = ( (int64_t)i_bitrate_max * i_length / 8 / 1000000 + 187 ) / 188;
2147 if( i_packets < i_packets_min && i_packets_min > 0 )
2150 int i_div = ( i_packets_min - i_packets ) / i_packets;
2151 int i_mod = ( i_packets_min - i_packets ) % i_packets;
2154 /* We need to pad with null packets (pid=0x1fff)
2155 * We try to melt null packets with true packets */
2157 "packets=%d but min=%d -> adding %d packets of padding",
2158 i_packets, i_packets_min, i_packets_min - i_packets );
2160 BufferChainInit( c );
2161 while( ( p_pk = BufferChainGet( &s ) ) )
2165 BufferChainAppend( c, p_pk );
2167 i_null = i_div + ( i_rest + i_mod ) / i_packets;
2169 for( i = 0; i < i_null; i++ )
2173 p_null = sout_BufferNew( p_mux->p_sout, 188 );
2174 p_null->p_buffer[0] = 0x47;
2175 p_null->p_buffer[1] = 0x1f;
2176 p_null->p_buffer[2] = 0xff;
2177 p_null->p_buffer[3] = 0x10 | p_sys->i_null_continuity_counter;
2178 memset( &p_null->p_buffer[4], 0, 184 );
2179 p_sys->i_null_continuity_counter =
2180 ( p_sys->i_null_continuity_counter + 1 ) % 16;
2182 BufferChainAppend( c, p_null );
2185 i_rest = ( i_rest + i_mod ) % i_packets;
2188 else if( i_packets > i_packets_max && i_packets_max > 0 )
2193 /* Arg, we need to drop packets, I don't do something clever (like
2194 * dropping complete pid, b frames, ... ), I just get the right amount
2195 * of packets and discard the others */
2197 "packets=%d but max=%d -> removing %d packets -> stream broken",
2198 i_packets, i_packets_max, i_packets - i_packets_max );
2200 BufferChainInit( c );
2201 for( i = 0; i < i_packets_max; i++ )
2203 BufferChainAppend( c, BufferChainGet( &s ) );
2206 while( ( p_pk = BufferChainGet( &s ) ) )
2208 sout_BufferDelete( p_mux->p_sout, p_pk );
2214 static void PEStoTS( sout_instance_t *p_sout,
2215 sout_buffer_chain_t *c, block_t *p_pes,
2216 ts_stream_t *p_stream )
2222 /* get PES total size */
2223 i_size = p_pes->i_buffer;
2224 p_data = p_pes->p_buffer;
2230 int b_adaptation_field;
2234 p_ts = block_New( p_sout, 188 );
2237 * 1b transport_error_indicator
2238 * 1b payload_unit_start
2239 * 1b transport_priority
2241 * 2b transport_scrambling_control
2242 * 2b if adaptation_field 0x03 else 0x01
2243 * 4b continuity_counter
2246 i_copy = __MIN( i_size, 184 );
2247 b_adaptation_field = i_size < 184 ? true : false;
2249 p_ts->p_buffer[0] = 0x47;
2250 p_ts->p_buffer[1] = ( b_new_pes ? 0x40 : 0x00 )|
2251 ( ( p_stream->i_pid >> 8 )&0x1f );
2252 p_ts->p_buffer[2] = p_stream->i_pid & 0xff;
2253 p_ts->p_buffer[3] = ( b_adaptation_field ? 0x30 : 0x10 )|
2254 p_stream->i_continuity_counter;
2257 p_stream->i_continuity_counter = (p_stream->i_continuity_counter+1)%16;
2259 if( b_adaptation_field )
2261 int i_stuffing = 184 - i_copy;
2264 p_ts->p_buffer[4] = i_stuffing - 1;
2265 if( i_stuffing > 1 )
2267 p_ts->p_buffer[5] = 0x00;
2268 if( p_stream->b_discontinuity )
2270 p_ts->p_buffer[5] |= 0x80;
2271 p_stream->b_discontinuity = false;
2273 for( i = 6; i < 6 + i_stuffing - 2; i++ )
2275 p_ts->p_buffer[i] = 0xff;
2280 memcpy( &p_ts->p_buffer[188 - i_copy], p_data, i_copy );
2284 BufferChainAppend( c, p_ts );
2288 block_t *p_next = p_pes->p_next;
2290 p_pes->p_next = NULL;
2291 block_Release( p_pes );
2292 if( p_next == NULL )
2298 i_size = p_pes->i_buffer;
2299 p_data = p_pes->p_buffer;
2306 static block_t *WritePSISection( sout_instance_t *p_sout,
2307 dvbpsi_psi_section_t* p_section )
2309 block_t *p_psi, *p_first = NULL;
2315 i_size = (uint32_t)( p_section->p_payload_end - p_section->p_data )+
2316 ( p_section->b_syntax_indicator ? 4 : 0 );
2318 p_psi = block_New( p_sout, i_size + 1 );
2321 p_psi->i_length = 0;
2322 p_psi->i_buffer = i_size + 1;
2324 p_psi->p_buffer[0] = 0; /* pointer */
2325 memcpy( p_psi->p_buffer + 1,
2329 block_ChainAppend( &p_first, p_psi );
2331 p_section = p_section->p_next;
2337 static void GetPAT( sout_mux_t *p_mux,
2338 sout_buffer_chain_t *c )
2340 sout_mux_sys_t *p_sys = p_mux->p_sys;
2343 dvbpsi_psi_section_t *p_section;
2346 dvbpsi_InitPAT( &pat, p_sys->i_tsid, p_sys->i_pat_version_number,
2347 1 ); /* b_current_next */
2348 /* add all programs */
2349 for ( i = 0; i < p_sys->i_num_pmt; i++ )
2350 dvbpsi_PATAddProgram( &pat,
2351 p_sys->i_pmt_program_number[i],
2352 p_sys->pmt[i].i_pid );
2354 p_section = dvbpsi_GenPATSections( &pat,
2355 0 ); /* max program per section */
2357 p_pat = WritePSISection( p_mux->p_sout, p_section );
2359 PEStoTS( p_mux->p_sout, c, p_pat, &p_sys->pat );
2361 dvbpsi_DeletePSISections( p_section );
2362 dvbpsi_EmptyPAT( &pat );
2365 static uint32_t GetDescriptorLength24b( int i_length )
2367 uint32_t i_l1, i_l2, i_l3;
2369 i_l1 = i_length&0x7f;
2370 i_l2 = ( i_length >> 7 )&0x7f;
2371 i_l3 = ( i_length >> 14 )&0x7f;
2373 return( 0x808000 | ( i_l3 << 16 ) | ( i_l2 << 8 ) | i_l1 );
2376 static void GetPMT( sout_mux_t *p_mux, sout_buffer_chain_t *c )
2378 sout_mux_sys_t *p_sys = p_mux->p_sys;
2379 block_t *p_pmt[MAX_PMT];
2381 dvbpsi_pmt_es_t *p_es;
2382 dvbpsi_psi_section_t *p_section[MAX_PMT];
2387 int *p_usepid = NULL;
2389 #ifdef HAVE_DVBPSI_SDT
2393 dvbpsi_psi_section_t* p_section2;
2394 dvbpsi_sdt_service_t *p_service;
2396 uint8_t *psz_sdt_desc;
2399 if( p_sys->dvbpmt == NULL )
2401 p_sys->dvbpmt = malloc( p_sys->i_num_pmt * sizeof(dvbpsi_pmt_t) );
2402 if( !p_sys->dvbpmt )
2407 #ifdef HAVE_DVBPSI_SDT
2409 dvbpsi_InitSDT( &sdt, p_sys->i_tsid, 1, 1, p_sys->i_netid );
2412 for( i = 0; i < p_sys->i_num_pmt; i++ )
2414 dvbpsi_InitPMT( &p_sys->dvbpmt[i],
2415 p_sys->i_pmt_program_number[i], /* program number */
2416 p_sys->i_pmt_version_number,
2417 1, /* b_current_next */
2420 #ifdef HAVE_DVBPSI_SDT
2423 p_service = dvbpsi_SDTAddService( &sdt,
2424 p_sys->i_pmt_program_number[i], /* service id */
2425 0, /* eit schedule */
2426 0, /* eit present */
2427 4, /* running status ("4=RUNNING") */
2430 #define psz_sdtprov p_sys->sdt_descriptors[i].psz_provider
2431 #define psz_sdtserv p_sys->sdt_descriptors[i].psz_service_name
2433 /* FIXME: Ineffecient malloc's & ugly code...... */
2434 if( ( psz_sdtprov != NULL ) && ( psz_sdtserv != NULL ) )
2436 psz_sdt_desc = malloc( 3 + strlen(psz_sdtprov)
2437 + strlen(psz_sdtserv) );
2440 psz_sdt_desc[0] = 0x01; /* digital television service */
2442 /* service provider name length */
2443 psz_sdt_desc[1] = (char)strlen(psz_sdtprov);
2444 memcpy( &psz_sdt_desc[2], psz_sdtprov, strlen(psz_sdtprov) );
2446 /* service name length */
2447 psz_sdt_desc[ 2 + strlen(psz_sdtprov) ]
2448 = (char)strlen(psz_sdtserv);
2449 memcpy( &psz_sdt_desc[3+strlen(psz_sdtprov)], psz_sdtserv,
2450 strlen(psz_sdtserv) );
2452 dvbpsi_SDTServiceAddDescriptor( p_service, 0x48,
2453 3 + strlen(psz_sdtprov) + strlen(psz_sdtserv),
2454 (uint8_t *)psz_sdt_desc );
2455 free( psz_sdt_desc );
2456 psz_sdt_desc = NULL;
2465 if( p_sys->i_mpeg4_streams > 0 )
2469 bits_buffer_t bits_fix_IOD;
2471 /* Make valgrind happy : it works at byte level not bit one so
2472 * bit_write confuse it (but DON'T CHANGE the way that bit_write is
2473 * working (needed when fixing some bits) */
2474 memset( iod, 0, 4096 );
2476 bits_initwrite( &bits, 4096, iod );
2477 /* IOD_label_scope */
2478 bits_write( &bits, 8, 0x11 );
2480 bits_write( &bits, 8, 0x01 );
2481 /* InitialObjectDescriptor */
2482 bits_align( &bits );
2483 bits_write( &bits, 8, 0x02 ); /* tag */
2484 bits_fix_IOD = bits; /* save states to fix length later */
2485 bits_write( &bits, 24,
2486 GetDescriptorLength24b( 0 ) ); /* variable length (fixed later) */
2487 bits_write( &bits, 10, 0x01 ); /* ObjectDescriptorID */
2488 bits_write( &bits, 1, 0x00 ); /* URL Flag */
2489 bits_write( &bits, 1, 0x00 ); /* includeInlineProfileLevelFlag */
2490 bits_write( &bits, 4, 0x0f ); /* reserved */
2491 bits_write( &bits, 8, 0xff ); /* ODProfile (no ODcapability ) */
2492 bits_write( &bits, 8, 0xff ); /* sceneProfile */
2493 bits_write( &bits, 8, 0xfe ); /* audioProfile (unspecified) */
2494 bits_write( &bits, 8, 0xfe ); /* visualProfile( // ) */
2495 bits_write( &bits, 8, 0xff ); /* graphicProfile (no ) */
2496 for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
2498 ts_stream_t *p_stream;
2499 p_stream = (ts_stream_t*)p_mux->pp_inputs[i_stream]->p_sys;
2501 if( p_stream->i_stream_id == 0xfa ||
2502 p_stream->i_stream_id == 0xfb ||
2503 p_stream->i_stream_id == 0xfe )
2505 bits_buffer_t bits_fix_ESDescr, bits_fix_Decoder;
2507 bits_align( &bits );
2508 bits_write( &bits, 8, 0x03 ); /* ES_DescrTag */
2509 bits_fix_ESDescr = bits;
2510 bits_write( &bits, 24,
2511 GetDescriptorLength24b( 0 ) ); /* variable size */
2512 bits_write( &bits, 16, p_stream->i_es_id );
2513 bits_write( &bits, 1, 0x00 ); /* streamDependency */
2514 bits_write( &bits, 1, 0x00 ); /* URL Flag */
2515 bits_write( &bits, 1, 0x00 ); /* OCRStreamFlag */
2516 bits_write( &bits, 5, 0x1f ); /* streamPriority */
2518 /* DecoderConfigDesciptor */
2519 bits_align( &bits );
2520 bits_write( &bits, 8, 0x04 ); /* DecoderConfigDescrTag */
2521 bits_fix_Decoder = bits;
2522 bits_write( &bits, 24, GetDescriptorLength24b( 0 ) );
2523 if( p_stream->i_stream_type == 0x10 )
2525 bits_write( &bits, 8, 0x20 ); /* Visual 14496-2 */
2526 bits_write( &bits, 6, 0x04 ); /* VisualStream */
2528 else if( p_stream->i_stream_type == 0x1b )
2530 bits_write( &bits, 8, 0x21 ); /* Visual 14496-2 */
2531 bits_write( &bits, 6, 0x04 ); /* VisualStream */
2533 else if( p_stream->i_stream_type == 0x11 ||
2534 p_stream->i_stream_type == 0x0f )
2536 bits_write( &bits, 8, 0x40 ); /* Audio 14496-3 */
2537 bits_write( &bits, 6, 0x05 ); /* AudioStream */
2539 else if( p_stream->i_stream_type == 0x12 &&
2540 p_stream->i_codec == VLC_FOURCC('s','u','b','t') )
2542 bits_write( &bits, 8, 0x0B ); /* Text Stream */
2543 bits_write( &bits, 6, 0x04 ); /* VisualStream */
2547 bits_write( &bits, 8, 0x00 );
2548 bits_write( &bits, 6, 0x00 );
2550 msg_Err( p_mux->p_sout,"Unsupported stream_type => "
2553 bits_write( &bits, 1, 0x00 ); /* UpStream */
2554 bits_write( &bits, 1, 0x01 ); /* reserved */
2555 bits_write( &bits, 24, 1024 * 1024 ); /* bufferSizeDB */
2556 bits_write( &bits, 32, 0x7fffffff ); /* maxBitrate */
2557 bits_write( &bits, 32, 0 ); /* avgBitrate */
2559 if( p_stream->i_decoder_specific_info > 0 )
2562 /* DecoderSpecificInfo */
2563 bits_align( &bits );
2564 bits_write( &bits, 8, 0x05 ); /* tag */
2565 bits_write( &bits, 24, GetDescriptorLength24b(
2566 p_stream->i_decoder_specific_info ) );
2567 for( i = 0; i < p_stream->i_decoder_specific_info; i++ )
2569 bits_write( &bits, 8,
2570 ((uint8_t*)p_stream->p_decoder_specific_info)[i] );
2573 /* fix Decoder length */
2574 bits_write( &bits_fix_Decoder, 24,
2575 GetDescriptorLength24b( bits.i_data -
2576 bits_fix_Decoder.i_data - 3 ) );
2578 /* SLConfigDescriptor : predefined (0x01) */
2579 bits_align( &bits );
2580 bits_write( &bits, 8, 0x06 ); /* tag */
2581 bits_write( &bits, 24, GetDescriptorLength24b( 8 ) );
2582 bits_write( &bits, 8, 0x01 );/* predefined */
2583 bits_write( &bits, 1, 0 ); /* durationFlag */
2584 bits_write( &bits, 32, 0 ); /* OCRResolution */
2585 bits_write( &bits, 8, 0 ); /* OCRLength */
2586 bits_write( &bits, 8, 0 ); /* InstantBitrateLength */
2587 bits_align( &bits );
2589 /* fix ESDescr length */
2590 bits_write( &bits_fix_ESDescr, 24,
2591 GetDescriptorLength24b( bits.i_data -
2592 bits_fix_ESDescr.i_data - 3 ) );
2595 bits_align( &bits );
2596 /* fix IOD length */
2597 bits_write( &bits_fix_IOD, 24,
2598 GetDescriptorLength24b( bits.i_data -
2599 bits_fix_IOD.i_data - 3 ) );
2601 #if 0//def HAVE_BSEARCH /* FIXME!!! This can't possibly work */
2602 i_pidinput = p_mux->pp_inputs[i]->p_fmt->i_id;
2603 p_usepid = bsearch( &i_pidinput, p_sys->pmtmap, p_sys->i_pmtslots,
2604 sizeof(pmt_map_t), intcompare );
2605 p_usepid = bsearch( &p_usepid, p_sys->pmtmap, p_sys->i_num_pmt,
2606 sizeof(pmt_map_t), pmtcompare );
2607 if( p_usepid != NULL )
2608 dvbpsi_PMTAddDescriptor(
2609 &p_sys->dvbpmt[((pmt_map_t *)p_usepid)->i_prog], 0x1d,
2610 bits.i_data, bits.p_data );
2612 msg_Err( p_mux, "Received an unmapped PID" );
2614 dvbpsi_PMTAddDescriptor( &p_sys->dvbpmt[0], 0x1d, bits.i_data,
2619 for( i_stream = 0; i_stream < p_mux->i_nb_inputs; i_stream++ )
2621 ts_stream_t *p_stream;
2623 p_stream = (ts_stream_t *)p_mux->pp_inputs[i_stream]->p_sys;
2626 i_pidinput = p_mux->pp_inputs[i_stream]->p_fmt->i_id;
2627 p_usepid = bsearch( &i_pidinput, p_sys->pmtmap, p_sys->i_pmtslots,
2628 sizeof(pmt_map_t), intcompare );
2630 if( p_usepid != NULL )
2631 p_es = dvbpsi_PMTAddES(
2632 &p_sys->dvbpmt[((pmt_map_t *)p_usepid)->i_prog],
2633 p_stream->i_stream_type, p_stream->i_pid );
2635 /* If there's an error somewhere, dump it to the first pmt */
2637 p_es = dvbpsi_PMTAddES( &p_sys->dvbpmt[0], p_stream->i_stream_type,
2640 if( p_stream->i_stream_id == 0xfa || p_stream->i_stream_id == 0xfb )
2645 es_id[0] = (p_stream->i_es_id >> 8)&0xff;
2646 es_id[1] = (p_stream->i_es_id)&0xff;
2647 dvbpsi_PMTESAddDescriptor( p_es, 0x1f, 2, es_id );
2649 else if( p_stream->i_stream_type == 0xa0 )
2652 int i_extra = __MIN( p_stream->i_decoder_specific_info, 502 );
2654 /* private DIV3 descripor */
2655 memcpy( &data[0], &p_stream->i_bih_codec, 4 );
2656 data[4] = ( p_stream->i_bih_width >> 8 )&0xff;
2657 data[5] = ( p_stream->i_bih_width )&0xff;
2658 data[6] = ( p_stream->i_bih_height>> 8 )&0xff;
2659 data[7] = ( p_stream->i_bih_height )&0xff;
2660 data[8] = ( i_extra >> 8 )&0xff;
2661 data[9] = ( i_extra )&0xff;
2664 memcpy( &data[10], p_stream->p_decoder_specific_info, i_extra );
2667 /* 0xa0 is private */
2668 dvbpsi_PMTESAddDescriptor( p_es, 0xa0, i_extra + 10, data );
2670 else if( p_stream->i_stream_type == 0x81 )
2672 uint8_t format[4] = { 0x41, 0x43, 0x2d, 0x33 };
2674 /* "registration" descriptor : "AC-3" */
2675 dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, format );
2677 else if( p_stream->i_codec == VLC_FOURCC('d','t','s',' ') )
2679 /* DTS registration descriptor (ETSI TS 101 154 Annex F) */
2681 /* DTS format identifier, frame size 1024 - FIXME */
2682 uint8_t data[4] = { 0x44, 0x54, 0x53, 0x32 };
2683 dvbpsi_PMTESAddDescriptor( p_es, 0x05, 4, data );
2685 else if( p_stream->i_codec == VLC_FOURCC('t','e','l','x') )
2687 if( p_stream->i_decoder_specific_info )
2689 dvbpsi_PMTESAddDescriptor( p_es, 0x56,
2690 p_stream->i_decoder_specific_info,
2691 p_stream->p_decoder_specific_info );
2695 else if( p_stream->i_codec == VLC_FOURCC('d','v','b','s') )
2698 if( p_stream->i_decoder_specific_info )
2700 /* pass-through from the TS demux */
2701 dvbpsi_PMTESAddDescriptor( p_es, 0x59,
2702 p_stream->i_decoder_specific_info,
2703 p_stream->p_decoder_specific_info );
2705 #ifdef _DVBPSI_DR_59_H_
2708 /* from the dvbsub transcoder */
2709 dvbpsi_subtitling_dr_t descr;
2710 dvbpsi_subtitle_t sub;
2711 dvbpsi_descriptor_t *p_descr;
2713 memcpy( sub.i_iso6392_language_code, p_stream->lang, 3 );
2714 sub.i_subtitling_type = 0x10; /* no aspect-ratio criticality */
2715 sub.i_composition_page_id = p_stream->i_es_id & 0xFF;
2716 sub.i_ancillary_page_id = p_stream->i_es_id >> 16;
2718 descr.i_subtitles_number = 1;
2719 descr.p_subtitle[0] = sub;
2721 p_descr = dvbpsi_GenSubtitlingDr( &descr, 0 );
2722 /* Work around bug in old libdvbpsi */ p_descr->i_length = 8;
2723 dvbpsi_PMTESAddDescriptor( p_es, p_descr->i_tag,
2724 p_descr->i_length, p_descr->p_data );
2726 #endif /* _DVBPSI_DR_59_H_ */
2730 if( p_stream->lang[0] != 0 )
2732 uint8_t data[4*p_stream->i_langs];
2734 /* I construct the content myself, way faster than looking at
2735 * over complicated/mind broken libdvbpsi way */
2736 for(i = 0; i < p_stream->i_langs; i++ )
2738 data[i*4+0] = p_stream->lang[i*3+0];
2739 data[i*4+1] = p_stream->lang[i*3+1];
2740 data[i*4+2] = p_stream->lang[i*3+2];
2741 data[i*4+3] = 0x00; /* audio type: 0x00 undefined */
2743 dvbpsi_PMTESAddDescriptor( p_es, 0x0a, 4*p_stream->i_langs, data );
2747 for( i = 0; i < p_sys->i_num_pmt; i++ )
2749 p_section[i] = dvbpsi_GenPMTSections( &p_sys->dvbpmt[i] );
2750 p_pmt[i] = WritePSISection( p_mux->p_sout, p_section[i] );
2751 PEStoTS( p_mux->p_sout, c, p_pmt[i], &p_sys->pmt[i] );
2752 dvbpsi_DeletePSISections( p_section[i] );
2753 dvbpsi_EmptyPMT( &p_sys->dvbpmt[i] );
2756 #ifdef HAVE_DVBPSI_SDT
2759 p_section2 = dvbpsi_GenSDTSections( &sdt );
2760 p_sdt = WritePSISection( p_mux->p_sout, p_section2 );
2761 PEStoTS( p_mux->p_sout, c, p_sdt, &p_sys->sdt );
2762 dvbpsi_DeletePSISections( p_section2 );
2763 dvbpsi_EmptySDT( &sdt );