packetizer: hxxx: fix DirectTV extraction
[vlc.git] / modules / access_output / livehttp.c
blob235b26b819a7d8f0746260a2a88ab739237ca88f
1 /*****************************************************************************
2 * livehttp.c: Live HTTP Streaming
3 *****************************************************************************
4 * Copyright © 2001, 2002, 2013 VLC authors and VideoLAN
5 * Copyright © 2009-2010 by Keary Griffin
7 * Authors: Keary Griffin <kearygriffin at gmail.com>
8 * Ilkka Ollakka <ileoo at videolan dot org>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
33 #include <sys/types.h>
34 #include <time.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #include <unistd.h>
39 #include <vlc_common.h>
40 #include <vlc_plugin.h>
41 #include <vlc_sout.h>
42 #include <vlc_block.h>
43 #include <vlc_fs.h>
44 #include <vlc_strings.h>
45 #include <vlc_charset.h>
47 #include <gcrypt.h>
48 #include <vlc_gcrypt.h>
50 #include <vlc_rand.h>
52 #ifndef O_LARGEFILE
53 # define O_LARGEFILE 0
54 #endif
56 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
58 #define MAX_RENAME_RETRIES 10
60 /*****************************************************************************
61 * Module descriptor
62 *****************************************************************************/
63 static int Open ( vlc_object_t * );
64 static void Close( vlc_object_t * );
66 #define SOUT_CFG_PREFIX "sout-livehttp-"
67 #define SEGLEN_TEXT N_("Segment length")
68 #define SEGLEN_LONGTEXT N_("Length of TS stream segments")
70 #define SPLITANYWHERE_TEXT N_("Split segments anywhere")
71 #define SPLITANYWHERE_LONGTEXT N_("Don't require a keyframe before splitting "\
72 "a segment. Needed for audio only.")
74 #define NUMSEGS_TEXT N_("Number of segments")
75 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
77 #define NOCACHE_TEXT N_("Allow cache")
78 #define NOCACHE_LONGTEXT N_("Add EXT-X-ALLOW-CACHE:NO directive in playlist-file if this is disabled")
80 #define INDEX_TEXT N_("Index file")
81 #define INDEX_LONGTEXT N_("Path to the index file to create")
83 #define INDEXURL_TEXT N_("Full URL to put in index file")
84 #define INDEXURL_LONGTEXT N_("Full URL to put in index file. "\
85 "Use #'s to represent segment number")
87 #define DELSEGS_TEXT N_("Delete segments")
88 #define DELSEGS_LONGTEXT N_("Delete segments when they are no longer needed")
90 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
92 #define KEYURI_TEXT N_("AES key URI to place in playlist")
94 #define KEYFILE_TEXT N_("AES key file")
95 #define KEYFILE_LONGTEXT N_("File containing the 16 bytes encryption key")
97 #define KEYLOADFILE_TEXT N_("File where vlc reads key-uri and keyfile-location")
98 #define KEYLOADFILE_LONGTEXT N_("File is read when segment starts and is assumed to be in format: "\
99 "key-uri\\nkey-file. File is read on the segment opening and "\
100 "values are used on that segment.")
102 #define RANDOMIV_TEXT N_("Use randomized IV for encryption")
103 #define RANDOMIV_LONGTEXT N_("Generate IV instead using segment-number as IV")
105 #define INTITIAL_SEG_TEXT N_("Number of first segment")
106 #define INITIAL_SEG_LONGTEXT N_("The number of the first segment generated")
108 vlc_module_begin ()
109 set_description( N_("HTTP Live streaming output") )
110 set_shortname( N_("LiveHTTP" ))
111 add_shortcut( "livehttp" )
112 set_capability( "sout access", 0 )
113 set_category( CAT_SOUT )
114 set_subcategory( SUBCAT_SOUT_ACO )
115 add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, false )
116 add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, false )
117 add_integer( SOUT_CFG_PREFIX "initial-segment-number", 1, INTITIAL_SEG_TEXT, INITIAL_SEG_LONGTEXT, false )
118 add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
119 SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
120 add_bool( SOUT_CFG_PREFIX "delsegs", true,
121 DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
122 add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
123 RATECONTROL_TEXT, RATECONTROL_TEXT, true )
124 add_bool( SOUT_CFG_PREFIX "caching", false,
125 NOCACHE_TEXT, NOCACHE_LONGTEXT, true )
126 add_bool( SOUT_CFG_PREFIX "generate-iv", false,
127 RANDOMIV_TEXT, RANDOMIV_LONGTEXT, true )
128 add_string( SOUT_CFG_PREFIX "index", NULL,
129 INDEX_TEXT, INDEX_LONGTEXT, false )
130 add_string( SOUT_CFG_PREFIX "index-url", NULL,
131 INDEXURL_TEXT, INDEXURL_LONGTEXT, false )
132 add_string( SOUT_CFG_PREFIX "key-uri", NULL,
133 KEYURI_TEXT, KEYURI_TEXT, true )
134 add_loadfile( SOUT_CFG_PREFIX "key-file", NULL,
135 KEYFILE_TEXT, KEYFILE_LONGTEXT, true )
136 add_loadfile( SOUT_CFG_PREFIX "key-loadfile", NULL,
137 KEYLOADFILE_TEXT, KEYLOADFILE_LONGTEXT, true )
138 set_callbacks( Open, Close )
139 vlc_module_end ()
142 /*****************************************************************************
143 * Exported prototypes
144 *****************************************************************************/
145 static const char *const ppsz_sout_options[] = {
146 "seglen",
147 "splitanywhere",
148 "numsegs",
149 "delsegs",
150 "index",
151 "index-url",
152 "ratecontrol",
153 "caching",
154 "key-uri",
155 "key-file",
156 "key-loadfile",
157 "generate-iv",
158 "initial-segment-number",
159 NULL
162 static ssize_t Write( sout_access_out_t *, block_t * );
163 static int Control( sout_access_out_t *, int, va_list );
165 typedef struct output_segment
167 char *psz_filename;
168 char *psz_uri;
169 char *psz_key_uri;
170 char *psz_duration;
171 float f_seglength;
172 uint32_t i_segment_number;
173 uint8_t aes_ivs[16];
174 } output_segment_t;
176 struct sout_access_out_sys_t
178 char *psz_cursegPath;
179 char *psz_indexPath;
180 char *psz_indexUrl;
181 char *psz_keyfile;
182 mtime_t i_keyfile_modification;
183 mtime_t i_opendts;
184 mtime_t i_dts_offset;
185 mtime_t i_seglenm;
186 uint32_t i_segment;
187 size_t i_seglen;
188 float f_seglen;
189 block_t *full_segments;
190 block_t **full_segments_end;
191 block_t *ongoing_segment;
192 block_t **ongoing_segment_end;
193 int i_handle;
194 unsigned i_numsegs;
195 unsigned i_initial_segment;
196 bool b_delsegs;
197 bool b_ratecontrol;
198 bool b_splitanywhere;
199 bool b_caching;
200 bool b_generate_iv;
201 bool b_segment_has_data;
202 uint8_t aes_ivs[16];
203 gcry_cipher_hd_t aes_ctx;
204 char *key_uri;
205 uint8_t stuffing_bytes[16];
206 ssize_t stuffing_size;
207 vlc_array_t segments_t;
210 static int LoadCryptFile( sout_access_out_t *p_access);
211 static int CryptSetup( sout_access_out_t *p_access, char *keyfile );
212 static int CheckSegmentChange( sout_access_out_t *p_access, block_t *p_buffer );
213 static ssize_t writeSegment( sout_access_out_t *p_access );
214 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys );
215 /*****************************************************************************
216 * Open: open the file
217 *****************************************************************************/
218 static int Open( vlc_object_t *p_this )
220 sout_access_out_t *p_access = (sout_access_out_t*)p_this;
221 sout_access_out_sys_t *p_sys;
222 char *psz_idx;
224 config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
226 if( !p_access->psz_path )
228 msg_Err( p_access, "no file name specified" );
229 return VLC_EGENERIC;
232 if( unlikely( !( p_sys = calloc ( 1, sizeof( *p_sys ) ) ) ) )
233 return VLC_ENOMEM;
235 /* Try to get within asked segment length */
236 p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
238 p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen;
239 p_sys->full_segments = NULL;
240 p_sys->full_segments_end = &p_sys->full_segments;
242 p_sys->ongoing_segment = NULL;
243 p_sys->ongoing_segment_end = &p_sys->ongoing_segment;
245 p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
246 p_sys->i_initial_segment = var_GetInteger( p_access, SOUT_CFG_PREFIX "initial-segment-number" );
247 p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
248 p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
249 p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
250 p_sys->b_caching = var_GetBool( p_access, SOUT_CFG_PREFIX "caching") ;
251 p_sys->b_generate_iv = var_GetBool( p_access, SOUT_CFG_PREFIX "generate-iv") ;
252 p_sys->b_segment_has_data = false;
254 vlc_array_init( &p_sys->segments_t );
256 p_sys->stuffing_size = 0;
257 p_sys->i_opendts = VLC_TS_INVALID;
258 p_sys->i_dts_offset = 0;
260 p_sys->psz_indexPath = NULL;
261 psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
262 if ( psz_idx )
264 char *psz_tmp;
265 psz_tmp = vlc_strftime( psz_idx );
266 free( psz_idx );
267 if ( !psz_tmp )
269 free( p_sys );
270 return VLC_ENOMEM;
272 p_sys->psz_indexPath = psz_tmp;
273 if( p_sys->i_initial_segment != 1 )
274 vlc_unlink( p_sys->psz_indexPath );
277 p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
278 p_sys->psz_keyfile = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-loadfile" );
279 p_sys->key_uri = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-uri" );
281 p_access->p_sys = p_sys;
283 if( p_sys->psz_keyfile && ( LoadCryptFile( p_access ) < 0 ) )
285 free( p_sys->psz_indexUrl );
286 free( p_sys->psz_indexPath );
287 free( p_sys );
288 msg_Err( p_access, "Encryption init failed" );
289 return VLC_EGENERIC;
291 else if( !p_sys->psz_keyfile && ( CryptSetup( p_access, NULL ) < 0 ) )
293 free( p_sys->psz_indexUrl );
294 free( p_sys->psz_indexPath );
295 free( p_sys );
296 msg_Err( p_access, "Encryption init failed" );
297 return VLC_EGENERIC;
300 p_sys->i_handle = -1;
301 p_sys->i_segment = p_sys->i_initial_segment-1;
302 p_sys->psz_cursegPath = NULL;
304 p_access->pf_write = Write;
305 p_access->pf_control = Control;
307 return VLC_SUCCESS;
310 /************************************************************************
311 * CryptSetup: Initialize encryption
312 ************************************************************************/
313 static int CryptSetup( sout_access_out_t *p_access, char *key_file )
315 sout_access_out_sys_t *p_sys = p_access->p_sys;
316 uint8_t key[16];
317 char *keyfile = NULL;
319 if( !p_sys->key_uri ) /*No key uri, assume no encryption wanted*/
321 msg_Dbg( p_access, "No key uri, no encryption");
322 return VLC_SUCCESS;
325 if( key_file )
326 keyfile = strdup( key_file );
327 else
328 keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
330 if( unlikely(keyfile == NULL) )
332 msg_Err( p_access, "No key-file, no encryption" );
333 return VLC_EGENERIC;
336 vlc_gcrypt_init();
338 /*Setup encryption cipher*/
339 gcry_error_t err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
340 GCRY_CIPHER_MODE_CBC, 0 );
341 if( err )
343 msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
344 free( keyfile );
345 return VLC_EGENERIC;
348 int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
349 if( unlikely( keyfd == -1 ) )
351 msg_Err( p_access, "Unable to open keyfile %s: %s", keyfile,
352 vlc_strerror_c(errno) );
353 free( keyfile );
354 gcry_cipher_close( p_sys->aes_ctx );
355 return VLC_EGENERIC;
357 free( keyfile );
359 ssize_t keylen = read( keyfd, key, 16 );
361 vlc_close( keyfd );
362 if( keylen < 16 )
364 msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
365 gcry_cipher_close( p_sys->aes_ctx );
366 return VLC_EGENERIC;
369 err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
370 if(err)
372 msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
373 gcry_cipher_close( p_sys->aes_ctx );
374 return VLC_EGENERIC;
377 if( p_sys->b_generate_iv )
378 vlc_rand_bytes( p_sys->aes_ivs, sizeof(uint8_t)*16);
380 return VLC_SUCCESS;
384 /************************************************************************
385 * LoadCryptFile: Try to parse key_uri and keyfile-location from file
386 ************************************************************************/
387 static int LoadCryptFile( sout_access_out_t *p_access )
389 sout_access_out_sys_t *p_sys = p_access->p_sys;
391 FILE *stream = vlc_fopen( p_sys->psz_keyfile, "rt" );
392 char *key_file=NULL,*key_uri=NULL;
394 if( unlikely( stream == NULL ) )
396 msg_Err( p_access, "Unable to open keyloadfile %s: %s",
397 p_sys->psz_keyfile, vlc_strerror_c(errno) );
398 return VLC_EGENERIC;
402 //First read key_uri
403 ssize_t len = getline( &key_uri, &(size_t){0}, stream );
404 if( unlikely( len == -1 ) )
406 msg_Err( p_access, "Cannot read %s: %s", p_sys->psz_keyfile,
407 vlc_strerror_c(errno) );
408 clearerr( stream );
409 fclose( stream );
410 free( key_uri );
411 return VLC_EGENERIC;
413 //Strip the newline from uri, maybe scanf would be better?
414 key_uri[len-1]='\0';
416 len = getline( &key_file, &(size_t){0}, stream );
417 if( unlikely( len == -1 ) )
419 msg_Err( p_access, "Cannot read %s: %s", p_sys->psz_keyfile,
420 vlc_strerror_c(errno) );
421 clearerr( stream );
422 fclose( stream );
424 free( key_uri );
425 free( key_file );
426 return VLC_EGENERIC;
428 // Strip the last newline from filename
429 key_file[len-1]='\0';
430 fclose( stream );
432 int returncode = VLC_SUCCESS;
433 if( !p_sys->key_uri || strcmp( p_sys->key_uri, key_uri ) )
435 if( p_sys->key_uri )
437 free( p_sys->key_uri );
438 p_sys->key_uri = NULL;
440 p_sys->key_uri = strdup( key_uri );
441 returncode = CryptSetup( p_access, key_file );
443 free( key_file );
444 free( key_uri );
445 return returncode;
448 /************************************************************************
449 * CryptKey: Set encryption IV to current segment number
450 ************************************************************************/
451 static int CryptKey( sout_access_out_t *p_access, uint32_t i_segment )
453 sout_access_out_sys_t *p_sys = p_access->p_sys;
455 if( !p_sys->b_generate_iv )
457 /* Use segment number as IV if randomIV isn't selected*/
458 memset( p_sys->aes_ivs, 0, 16 * sizeof(uint8_t));
459 p_sys->aes_ivs[15] = i_segment & 0xff;
460 p_sys->aes_ivs[14] = (i_segment >> 8 ) & 0xff;
461 p_sys->aes_ivs[13] = (i_segment >> 16 ) & 0xff;
462 p_sys->aes_ivs[12] = (i_segment >> 24 ) & 0xff;
465 gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
466 p_sys->aes_ivs, 16);
467 if( err )
469 msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
470 gcry_cipher_close( p_sys->aes_ctx);
471 return VLC_EGENERIC;
473 return VLC_SUCCESS;
477 #define SEG_NUMBER_PLACEHOLDER "#"
478 /*****************************************************************************
479 * formatSegmentPath: create segment path name based on seg #
480 *****************************************************************************/
481 static char *formatSegmentPath( char *psz_path, uint32_t i_seg )
483 char *psz_result;
484 char *psz_firstNumSign;
486 if ( ! ( psz_result = vlc_strftime( psz_path ) ) )
487 return NULL;
489 psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
490 if ( *psz_firstNumSign )
492 char *psz_newResult;
493 int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
494 int ret;
496 *psz_firstNumSign = '\0';
497 ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
498 free ( psz_result );
499 if ( ret < 0 )
500 return NULL;
501 psz_result = psz_newResult;
504 return psz_result;
507 static void destroySegment( output_segment_t *segment )
509 free( segment->psz_filename );
510 free( segment->psz_duration );
511 free( segment->psz_uri );
512 free( segment->psz_key_uri );
513 free( segment );
516 /************************************************************************
517 * segmentAmountNeeded: check that playlist has atleast 3*p_sys->i_seglength of segments
518 * return how many segments are needed for that (max of p_sys->i_segment )
519 ************************************************************************/
520 static uint32_t segmentAmountNeeded( sout_access_out_sys_t *p_sys )
522 float duration = .0f;
523 for( size_t index = 1; index <= vlc_array_count( &p_sys->segments_t ); index++ )
525 output_segment_t* segment = vlc_array_item_at_index( &p_sys->segments_t, vlc_array_count( &p_sys->segments_t ) - index );
526 duration += segment->f_seglength;
528 if( duration >= (float)( 3 * p_sys->i_seglen ) )
529 return __MAX(index, p_sys->i_numsegs);
531 return vlc_array_count( &p_sys->segments_t ) - 1;
536 /************************************************************************
537 * isFirstItemRemovable: Check for draft 11 section 6.2.2
538 * check that the first item has been around outside playlist
539 * segment->f_seglength + (p_sys->i_numsegs * p_sys->i_seglen) before it is removed.
540 ************************************************************************/
541 static bool isFirstItemRemovable( sout_access_out_sys_t *p_sys, uint32_t i_firstseg, uint32_t i_index_offset )
543 float duration = .0f;
545 /* Check that segment has been out of playlist for seglength + (p_sys->i_numsegs * p_sys->i_seglen) amount
546 * We check this by calculating duration of the items that replaced first item in playlist
548 for( unsigned int index = 0; index < i_index_offset; index++ )
550 output_segment_t *segment = vlc_array_item_at_index( &p_sys->segments_t, p_sys->i_segment - i_firstseg + index );
551 duration += segment->f_seglength;
553 output_segment_t *first = vlc_array_item_at_index( &p_sys->segments_t, 0 );
555 return duration >= (first->f_seglength + (float)(p_sys->i_numsegs * p_sys->i_seglen));
558 /************************************************************************
559 * updateIndexAndDel: If necessary, update index file & delete old segments
560 ************************************************************************/
561 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
564 uint32_t i_firstseg;
565 unsigned i_index_offset = 0;
567 if ( p_sys->i_numsegs == 0 ||
568 p_sys->i_segment < ( p_sys->i_numsegs + p_sys->i_initial_segment ) )
570 i_firstseg = p_sys->i_initial_segment;
572 else
574 unsigned numsegs = segmentAmountNeeded( p_sys );
575 i_firstseg = ( p_sys->i_segment - numsegs ) + 1;
576 i_index_offset = vlc_array_count( &p_sys->segments_t ) - numsegs;
579 // First update index
580 if ( p_sys->psz_indexPath )
582 int val;
583 FILE *fp;
584 char *psz_idxTmp;
585 if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
586 return -1;
588 fp = vlc_fopen( psz_idxTmp, "wt");
589 if ( !fp )
591 msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
592 free( psz_idxTmp );
593 return -1;
596 if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-VERSION:3\n#EXT-X-ALLOW-CACHE:%s"
597 "%s\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n%s", p_sys->i_seglen,
598 p_sys->b_caching ? "YES" : "NO",
599 p_sys->i_numsegs > 0 ? "" : b_isend ? "\n#EXT-X-PLAYLIST-TYPE:VOD" : "\n#EXT-X-PLAYLIST-TYPE:EVENT",
600 i_firstseg, ((p_sys->i_initial_segment > 1) && (p_sys->i_initial_segment == i_firstseg)) ? "#EXT-X-DISCONTINUITY\n" : ""
601 ) < 0 )
603 free( psz_idxTmp );
604 fclose( fp );
605 return -1;
607 char *psz_current_uri=NULL;
610 for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
612 //scale to i_index_offset..numsegs + i_index_offset
613 uint32_t index = i - i_firstseg + i_index_offset;
615 output_segment_t *segment = vlc_array_item_at_index( &p_sys->segments_t, index );
616 if( p_sys->key_uri &&
617 ( !psz_current_uri || strcmp( psz_current_uri, segment->psz_key_uri ) )
620 int ret = 0;
621 free( psz_current_uri );
622 psz_current_uri = strdup( segment->psz_key_uri );
623 if( p_sys->b_generate_iv )
625 unsigned long long iv_hi = segment->aes_ivs[0];
626 unsigned long long iv_lo = segment->aes_ivs[8];
627 for( unsigned short j = 1; j < 8; j++ )
629 iv_hi <<= 8;
630 iv_hi |= segment->aes_ivs[j] & 0xff;
631 iv_lo <<= 8;
632 iv_lo |= segment->aes_ivs[8+j] & 0xff;
634 ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\",IV=0X%16.16llx%16.16llx\n",
635 segment->psz_key_uri, iv_hi, iv_lo );
637 } else {
638 ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", segment->psz_key_uri );
640 if( ret < 0 )
642 free( psz_current_uri );
643 free( psz_idxTmp );
644 fclose( fp );
645 return -1;
649 val = fprintf( fp, "#EXTINF:%s,\n%s\n", segment->psz_duration, segment->psz_uri);
650 if ( val < 0 )
652 free( psz_current_uri );
653 free( psz_idxTmp );
654 fclose( fp );
655 return -1;
658 free( psz_current_uri );
660 if ( b_isend )
662 if ( fputs ( STR_ENDLIST, fp ) < 0)
664 free( psz_idxTmp );
665 fclose( fp ) ;
666 return -1;
670 fclose( fp );
672 val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
674 if ( val < 0 )
676 vlc_unlink( psz_idxTmp );
677 msg_Err( p_access, "Error moving LiveHttp index file" );
679 else
680 msg_Dbg( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
682 free( psz_idxTmp );
685 // Then take care of deletion
686 // Try to follow pantos draft 11 section 6.2.2
687 while( p_sys->b_delsegs && p_sys->i_numsegs &&
688 isFirstItemRemovable( p_sys, i_firstseg, i_index_offset )
691 output_segment_t *segment = vlc_array_item_at_index( &p_sys->segments_t, 0 );
692 msg_Dbg( p_access, "Removing segment number %d", segment->i_segment_number );
693 vlc_array_remove( &p_sys->segments_t, 0 );
695 if ( segment->psz_filename )
697 vlc_unlink( segment->psz_filename );
700 destroySegment( segment );
701 i_index_offset -=1;
705 return 0;
708 /*****************************************************************************
709 * closeCurrentSegment: Close the segment file
710 *****************************************************************************/
711 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
713 if ( p_sys->i_handle >= 0 )
715 output_segment_t *segment = vlc_array_item_at_index( &p_sys->segments_t, vlc_array_count( &p_sys->segments_t ) - 1 );
717 if( p_sys->key_uri )
719 size_t pad = 16 - p_sys->stuffing_size;
720 memset(&p_sys->stuffing_bytes[p_sys->stuffing_size], pad, pad);
721 gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx, p_sys->stuffing_bytes, 16, NULL, 0 );
723 if( err ) {
724 msg_Err( p_access, "Couldn't encrypt 16 bytes: %s", gpg_strerror(err) );
725 } else {
727 int ret = vlc_write( p_sys->i_handle, p_sys->stuffing_bytes, 16 );
728 if( ret != 16 )
729 msg_Err( p_access, "Couldn't write 16 bytes" );
731 p_sys->stuffing_size = 0;
735 vlc_close( p_sys->i_handle );
736 p_sys->i_handle = -1;
738 if( ! ( us_asprintf( &segment->psz_duration, "%.2f", p_sys->f_seglen ) ) )
740 msg_Err( p_access, "Couldn't set duration on closed segment");
741 return;
743 segment->f_seglength = p_sys->f_seglen;
745 segment->i_segment_number = p_sys->i_segment;
747 if ( p_sys->psz_cursegPath )
749 msg_Dbg( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
750 free( p_sys->psz_cursegPath );
751 p_sys->psz_cursegPath = 0;
752 updateIndexAndDel( p_access, p_sys, b_isend );
757 /*****************************************************************************
758 * Close: close the target
759 *****************************************************************************/
760 static void Close( vlc_object_t * p_this )
762 sout_access_out_t *p_access = (sout_access_out_t*)p_this;
763 sout_access_out_sys_t *p_sys = p_access->p_sys;
765 if( p_sys->ongoing_segment )
766 block_ChainLastAppend( &p_sys->full_segments_end, p_sys->ongoing_segment );
767 p_sys->ongoing_segment = NULL;
768 p_sys->ongoing_segment_end = &p_sys->ongoing_segment;
770 block_t *output_block = p_sys->full_segments;
771 p_sys->full_segments = NULL;
772 p_sys->full_segments_end = &p_sys->full_segments;
774 while( output_block )
776 block_t *p_next = output_block->p_next;
777 output_block->p_next = NULL;
779 Write( p_access, output_block );
780 output_block = p_next;
782 if( p_sys->ongoing_segment )
784 block_ChainLastAppend( &p_sys->full_segments_end, p_sys->ongoing_segment );
785 p_sys->ongoing_segment = NULL;
786 p_sys->ongoing_segment_end = &p_sys->ongoing_segment;
789 ssize_t writevalue = writeSegment( p_access );
790 msg_Dbg( p_access, "Writing.. %zd", writevalue );
791 if( unlikely( writevalue < 0 ) )
793 if( p_sys->full_segments )
794 block_ChainRelease( p_sys->full_segments );
795 if( p_sys->ongoing_segment )
796 block_ChainRelease( p_sys->ongoing_segment );
799 closeCurrentSegment( p_access, p_sys, true );
801 if( p_sys->key_uri )
803 gcry_cipher_close( p_sys->aes_ctx );
804 free( p_sys->key_uri );
807 while( vlc_array_count( &p_sys->segments_t ) > 0 )
809 output_segment_t *segment = vlc_array_item_at_index( &p_sys->segments_t, 0 );
810 vlc_array_remove( &p_sys->segments_t, 0 );
811 if( p_sys->b_delsegs && p_sys->i_numsegs && segment->psz_filename )
813 msg_Dbg( p_access, "Removing segment number %d name %s", segment->i_segment_number, segment->psz_filename );
814 vlc_unlink( segment->psz_filename );
817 destroySegment( segment );
820 free( p_sys->psz_indexUrl );
821 free( p_sys->psz_indexPath );
822 free( p_sys );
824 msg_Dbg( p_access, "livehttp access output closed" );
827 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
829 sout_access_out_sys_t *p_sys = p_access->p_sys;
831 switch( i_query )
833 case ACCESS_OUT_CONTROLS_PACE:
835 bool *pb = va_arg( args, bool * );
836 *pb = !p_sys->b_ratecontrol;
837 //*pb = true;
838 break;
841 default:
842 return VLC_EGENERIC;
844 return VLC_SUCCESS;
847 /*****************************************************************************
848 * openNextFile: Open the segment file
849 *****************************************************************************/
850 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
852 int fd;
854 uint32_t i_newseg = p_sys->i_segment + 1;
856 /* Create segment and fill it info that we can (everything excluding duration */
857 output_segment_t *segment = (output_segment_t*)calloc(1, sizeof(output_segment_t));
858 if( unlikely( !segment ) )
859 return -1;
861 segment->i_segment_number = i_newseg;
862 segment->psz_filename = formatSegmentPath( p_access->psz_path, i_newseg );
863 char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
864 segment->psz_uri = formatSegmentPath( psz_idxFormat , i_newseg );
866 if ( unlikely( !segment->psz_filename ) )
868 msg_Err( p_access, "Format segmentpath failed");
869 destroySegment( segment );
870 return -1;
873 fd = vlc_open( segment->psz_filename, O_WRONLY | O_CREAT | O_LARGEFILE |
874 O_TRUNC, 0666 );
875 if ( fd == -1 )
877 msg_Err( p_access, "cannot open `%s' (%s)", segment->psz_filename,
878 vlc_strerror_c(errno) );
879 destroySegment( segment );
880 return -1;
883 vlc_array_append( &p_sys->segments_t, segment );
885 if( p_sys->psz_keyfile )
887 LoadCryptFile( p_access );
890 if( p_sys->key_uri )
892 segment->psz_key_uri = strdup( p_sys->key_uri );
893 CryptKey( p_access, i_newseg );
894 if( p_sys->b_generate_iv )
895 memcpy( segment->aes_ivs, p_sys->aes_ivs, sizeof(uint8_t)*16 );
897 msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , segment->psz_filename, i_newseg );
899 p_sys->psz_cursegPath = strdup(segment->psz_filename);
900 p_sys->i_handle = fd;
901 p_sys->i_segment = i_newseg;
902 p_sys->b_segment_has_data = false;
903 return fd;
905 /*****************************************************************************
906 * CheckSegmentChange: Check if segment needs to be closed and new opened
907 *****************************************************************************/
908 static int CheckSegmentChange( sout_access_out_t *p_access, block_t *p_buffer )
910 sout_access_out_sys_t *p_sys = p_access->p_sys;
911 ssize_t writevalue = 0;
913 if( p_sys->i_handle > 0 && p_sys->b_segment_has_data &&
914 (( p_buffer->i_length + p_buffer->i_dts - p_sys->i_opendts ) >= p_sys->i_seglenm ) )
916 writevalue = writeSegment( p_access );
917 if( unlikely( writevalue < 0 ) )
919 block_ChainRelease ( p_buffer );
920 return -1;
922 closeCurrentSegment( p_access, p_sys, false );
923 return writevalue;
926 if ( unlikely( p_sys->i_handle < 0 ) )
928 p_sys->i_opendts = p_buffer->i_dts;
930 if( p_sys->ongoing_segment && ( p_sys->ongoing_segment->i_dts < p_sys->i_opendts) )
931 p_sys->i_opendts = p_sys->ongoing_segment->i_dts;
933 if( p_sys->full_segments && ( p_sys->full_segments->i_dts < p_sys->i_opendts) )
934 p_sys->i_opendts = p_sys->full_segments->i_dts;
936 msg_Dbg( p_access, "Setting new opendts %"PRId64, p_sys->i_opendts );
938 if ( openNextFile( p_access, p_sys ) < 0 )
939 return -1;
941 return writevalue;
944 static ssize_t writeSegment( sout_access_out_t *p_access )
946 sout_access_out_sys_t *p_sys = p_access->p_sys;
947 msg_Dbg( p_access, "Writing all full segments" );
949 block_t *output = p_sys->full_segments;
950 mtime_t output_last_length = 0;
951 if( output )
952 output_last_length = output->i_length;
953 if( *p_sys->full_segments_end )
954 output_last_length = (*p_sys->full_segments_end)->i_length;
955 p_sys->full_segments = NULL;
956 p_sys->full_segments_end = &p_sys->full_segments;
958 ssize_t i_write=0;
959 bool crypted = false;
960 while( output )
962 if( p_sys->key_uri && !crypted )
964 if( p_sys->stuffing_size )
966 output = block_Realloc( output, p_sys->stuffing_size, output->i_buffer );
967 if( unlikely(!output ) )
968 return VLC_ENOMEM;
969 memcpy( output->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
970 p_sys->stuffing_size = 0;
972 size_t original = output->i_buffer;
973 size_t padded = (output->i_buffer + 15 ) & ~15;
974 size_t pad = padded - original;
975 if( pad )
977 p_sys->stuffing_size = 16-pad;
978 output->i_buffer -= p_sys->stuffing_size;
979 memcpy(p_sys->stuffing_bytes, &output->p_buffer[output->i_buffer], p_sys->stuffing_size);
982 gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
983 output->p_buffer, output->i_buffer, NULL, 0 );
984 if( err )
986 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
987 return -1;
989 crypted=true;
993 ssize_t val = vlc_write( p_sys->i_handle, output->p_buffer, output->i_buffer );
994 if ( val == -1 )
996 if ( errno == EINTR )
997 continue;
998 return -1;
1001 p_sys->f_seglen =
1002 (float)(output_last_length +
1003 output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
1005 if ( (size_t)val >= output->i_buffer )
1007 block_t *p_next = output->p_next;
1008 block_Release (output);
1009 output = p_next;
1010 crypted=false;
1012 else
1014 output->p_buffer += val;
1015 output->i_buffer -= val;
1017 i_write += val;
1019 return i_write;
1022 /*****************************************************************************
1023 * Write: standard write on a file descriptor.
1024 *****************************************************************************/
1025 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
1027 size_t i_write = 0;
1028 sout_access_out_sys_t *p_sys = p_access->p_sys;
1029 while( p_buffer )
1031 /* Check if current block is already past segment-length
1032 and we want to write gathered blocks into segment
1033 and update playlist */
1034 if( p_sys->ongoing_segment && ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
1036 msg_Dbg( p_access, "Moving ongoing segment to full segments-queue" );
1037 block_ChainLastAppend( &p_sys->full_segments_end, p_sys->ongoing_segment );
1038 p_sys->ongoing_segment = NULL;
1039 p_sys->ongoing_segment_end = &p_sys->ongoing_segment;
1040 p_sys->b_segment_has_data = true;
1043 ssize_t ret = CheckSegmentChange( p_access, p_buffer );
1044 if( ret < 0 )
1046 msg_Err( p_access, "Error in write loop");
1047 return ret;
1049 i_write += ret;
1051 block_t *p_temp = p_buffer->p_next;
1052 p_buffer->p_next = NULL;
1053 block_ChainLastAppend( &p_sys->ongoing_segment_end, p_buffer );
1054 p_buffer = p_temp;
1057 return i_write;