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 /*****************************************************************************
27 *****************************************************************************/
33 #include <sys/types.h>
39 #include <vlc_common.h>
40 #include <vlc_plugin.h>
42 #include <vlc_block.h>
44 #include <vlc_strings.h>
45 #include <vlc_charset.h>
48 #include <vlc_gcrypt.h>
53 # define O_LARGEFILE 0
56 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
58 #define MAX_RENAME_RETRIES 10
60 /*****************************************************************************
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 assumet 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")
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 )
142 /*****************************************************************************
143 * Exported prototypes
144 *****************************************************************************/
145 static const char *const ppsz_sout_options[] = {
158 "initial-segment-number",
162 static ssize_t Write( sout_access_out_t *, block_t * );
163 static int Seek ( sout_access_out_t *, off_t );
164 static int Control( sout_access_out_t *, int, va_list );
166 typedef struct output_segment
173 uint32_t i_segment_number;
177 struct sout_access_out_sys_t
179 char *psz_cursegPath;
183 mtime_t i_keyfile_modification;
185 mtime_t i_dts_offset;
190 block_t *block_buffer;
193 unsigned i_initial_segment;
196 bool b_splitanywhere;
199 bool b_segment_has_data;
201 gcry_cipher_hd_t aes_ctx;
203 uint8_t stuffing_bytes[16];
204 ssize_t stuffing_size;
205 vlc_array_t *segments_t;
208 static int LoadCryptFile( sout_access_out_t *p_access);
209 static int CryptSetup( sout_access_out_t *p_access, char *keyfile );
210 static int CheckSegmentChange( sout_access_out_t *p_access, block_t *p_buffer );
211 static ssize_t writeSegment( sout_access_out_t *p_access );
212 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys );
213 /*****************************************************************************
214 * Open: open the file
215 *****************************************************************************/
216 static int Open( vlc_object_t *p_this )
218 sout_access_out_t *p_access = (sout_access_out_t*)p_this;
219 sout_access_out_sys_t *p_sys;
222 config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
224 if( !p_access->psz_path )
226 msg_Err( p_access, "no file name specified" );
230 if( unlikely( !( p_sys = calloc ( 1, sizeof( *p_sys ) ) ) ) )
233 p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
234 /* Try to get within asked segment length */
235 p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen;
236 p_sys->block_buffer = NULL;
238 p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
239 p_sys->i_initial_segment = var_GetInteger( p_access, SOUT_CFG_PREFIX "initial-segment-number" );
240 p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
241 p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
242 p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
243 p_sys->b_caching = var_GetBool( p_access, SOUT_CFG_PREFIX "caching") ;
244 p_sys->b_generate_iv = var_GetBool( p_access, SOUT_CFG_PREFIX "generate-iv") ;
245 p_sys->b_segment_has_data = false;
247 p_sys->segments_t = vlc_array_new();
249 p_sys->stuffing_size = 0;
250 p_sys->i_opendts = VLC_TS_INVALID;
251 p_sys->i_dts_offset = 0;
253 p_sys->psz_indexPath = NULL;
254 psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
258 psz_tmp = str_format_time( psz_idx );
265 path_sanitize( psz_tmp );
266 p_sys->psz_indexPath = psz_tmp;
267 if( p_sys->i_initial_segment != 1 )
268 vlc_unlink( p_sys->psz_indexPath );
271 p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
272 p_sys->psz_keyfile = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-loadfile" );
273 p_sys->key_uri = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-uri" );
275 p_access->p_sys = p_sys;
277 if( p_sys->psz_keyfile && ( LoadCryptFile( p_access ) < 0 ) )
279 free( p_sys->psz_indexUrl );
280 free( p_sys->psz_indexPath );
282 msg_Err( p_access, "Encryption init failed" );
285 else if( !p_sys->psz_keyfile && ( CryptSetup( p_access, NULL ) < 0 ) )
287 free( p_sys->psz_indexUrl );
288 free( p_sys->psz_indexPath );
290 msg_Err( p_access, "Encryption init failed" );
294 p_sys->i_handle = -1;
295 p_sys->i_segment = p_sys->i_initial_segment-1;
296 p_sys->psz_cursegPath = NULL;
298 p_access->pf_write = Write;
299 p_access->pf_seek = Seek;
300 p_access->pf_control = Control;
305 /************************************************************************
306 * CryptSetup: Initialize encryption
307 ************************************************************************/
308 static int CryptSetup( sout_access_out_t *p_access, char *key_file )
310 sout_access_out_sys_t *p_sys = p_access->p_sys;
312 char *keyfile = NULL;
314 if( !p_sys->key_uri ) /*No key uri, assume no encryption wanted*/
316 msg_Dbg( p_access, "No key uri, no encryption");
321 keyfile = strdup( key_file );
323 keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
325 if( unlikely(keyfile == NULL) )
327 msg_Err( p_access, "No key-file, no encryption" );
333 /*Setup encryption cipher*/
334 gcry_error_t err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
335 GCRY_CIPHER_MODE_CBC, 0 );
338 msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
343 int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
344 if( unlikely( keyfd == -1 ) )
346 msg_Err( p_access, "Unable to open keyfile %s: %s", keyfile,
347 vlc_strerror_c(errno) );
349 gcry_cipher_close( p_sys->aes_ctx );
354 ssize_t keylen = read( keyfd, key, 16 );
359 msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
360 gcry_cipher_close( p_sys->aes_ctx );
364 err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
367 msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
368 gcry_cipher_close( p_sys->aes_ctx );
372 if( p_sys->b_generate_iv )
373 vlc_rand_bytes( p_sys->aes_ivs, sizeof(uint8_t)*16);
379 /************************************************************************
380 * LoadCryptFile: Try to parse key_uri and keyfile-location from file
381 ************************************************************************/
382 static int LoadCryptFile( sout_access_out_t *p_access )
384 sout_access_out_sys_t *p_sys = p_access->p_sys;
386 FILE *stream = vlc_fopen( p_sys->psz_keyfile, "rt" );
387 char *key_file=NULL,*key_uri=NULL;
389 if( unlikely( stream == NULL ) )
391 msg_Err( p_access, "Unable to open keyloadfile %s: %s",
392 p_sys->psz_keyfile, vlc_strerror_c(errno) );
398 ssize_t len = getline( &key_uri, &(size_t){0}, stream );
399 if( unlikely( len == -1 ) )
401 msg_Err( p_access, "Cannot read %s: %s", p_sys->psz_keyfile,
402 vlc_strerror_c(errno) );
408 //Strip the newline from uri, maybe scanf would be better?
411 len = getline( &key_file, &(size_t){0}, stream );
412 if( unlikely( len == -1 ) )
414 msg_Err( p_access, "Cannot read %s: %s", p_sys->psz_keyfile,
415 vlc_strerror_c(errno) );
423 // Strip the last newline from filename
424 key_file[len-1]='\0';
427 int returncode = VLC_SUCCESS;
428 if( !p_sys->key_uri || strcmp( p_sys->key_uri, key_uri ) )
432 free( p_sys->key_uri );
433 p_sys->key_uri = NULL;
435 p_sys->key_uri = strdup( key_uri );
436 returncode = CryptSetup( p_access, key_file );
443 /************************************************************************
444 * CryptKey: Set encryption IV to current segment number
445 ************************************************************************/
446 static int CryptKey( sout_access_out_t *p_access, uint32_t i_segment )
448 sout_access_out_sys_t *p_sys = p_access->p_sys;
450 if( !p_sys->b_generate_iv )
452 /* Use segment number as IV if randomIV isn't selected*/
453 memset( p_sys->aes_ivs, 0, 16 * sizeof(uint8_t));
454 p_sys->aes_ivs[15] = i_segment & 0xff;
455 p_sys->aes_ivs[14] = (i_segment >> 8 ) & 0xff;
456 p_sys->aes_ivs[13] = (i_segment >> 16 ) & 0xff;
457 p_sys->aes_ivs[12] = (i_segment >> 24 ) & 0xff;
460 gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
464 msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
465 gcry_cipher_close( p_sys->aes_ctx);
472 #define SEG_NUMBER_PLACEHOLDER "#"
473 /*****************************************************************************
474 * formatSegmentPath: create segment path name based on seg #
475 *****************************************************************************/
476 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
479 char *psz_firstNumSign;
481 if ( ! ( psz_result = str_format_time( psz_path ) ) )
484 psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
485 if ( *psz_firstNumSign )
488 int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
491 *psz_firstNumSign = '\0';
492 ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
496 psz_result = psz_newResult;
500 path_sanitize( psz_result );
505 static void destroySegment( output_segment_t *segment )
507 free( segment->psz_filename );
508 free( segment->psz_duration );
509 free( segment->psz_uri );
510 free( segment->psz_key_uri );
514 /************************************************************************
515 * segmentAmountNeeded: check that playlist has atleast 3*p_sys->i_seglength of segments
516 * return how many segments are needed for that (max of p_sys->i_segment )
517 ************************************************************************/
518 static uint32_t segmentAmountNeeded( sout_access_out_sys_t *p_sys )
520 float duration = .0f;
521 for( unsigned index = 1; (int)index <= vlc_array_count( p_sys->segments_t ); index++ )
523 output_segment_t* segment = vlc_array_item_at_index( p_sys->segments_t, vlc_array_count( p_sys->segments_t ) - index );
524 duration += segment->f_seglength;
526 if( duration >= (float)( 3 * p_sys->i_seglen ) )
527 return __MAX(index, p_sys->i_numsegs);
529 return vlc_array_count( p_sys->segments_t )-1;
534 /************************************************************************
535 * isFirstItemRemovable: Check for draft 11 section 6.2.2
536 * check that the first item has been around outside playlist
537 * segment->f_seglength + (p_sys->i_numsegs * p_sys->i_seglen) before it is removed.
538 ************************************************************************/
539 static bool isFirstItemRemovable( sout_access_out_sys_t *p_sys, uint32_t i_firstseg, uint32_t i_index_offset )
541 float duration = .0f;
543 /* Check that segment has been out of playlist for seglenght + (p_sys->i_numsegs * p_sys->i_seglen) amount
544 * We check this by calculating duration of the items that replaced first item in playlist
546 for( unsigned int index = 0; index < i_index_offset; index++ )
548 output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, p_sys->i_segment - i_firstseg + index );
549 duration += segment->f_seglength;
551 output_segment_t *first = vlc_array_item_at_index( p_sys->segments_t, 0 );
553 return duration >= (first->f_seglength + (float)(p_sys->i_numsegs * p_sys->i_seglen));
556 /************************************************************************
557 * updateIndexAndDel: If necessary, update index file & delete old segments
558 ************************************************************************/
559 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
563 unsigned i_index_offset = 0;
565 if ( p_sys->i_numsegs == 0 ||
566 p_sys->i_segment < ( p_sys->i_numsegs + p_sys->i_initial_segment ) )
568 i_firstseg = p_sys->i_initial_segment;
572 unsigned numsegs = segmentAmountNeeded( p_sys );
573 i_firstseg = ( p_sys->i_segment - numsegs ) + 1;
574 i_index_offset = vlc_array_count( p_sys->segments_t ) - numsegs;
577 // First update index
578 if ( p_sys->psz_indexPath )
583 if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
586 fp = vlc_fopen( psz_idxTmp, "wt");
589 msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
594 if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-VERSION:3\n#EXT-X-ALLOW-CACHE:%s"
595 "%s\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n%s", p_sys->i_seglen,
596 p_sys->b_caching ? "YES" : "NO",
597 p_sys->i_numsegs > 0 ? "" : b_isend ? "\n#EXT-X-PLAYLIST-TYPE:VOD" : "\n#EXT-X-PLAYLIST-TYPE:EVENT",
598 i_firstseg, ((p_sys->i_initial_segment > 1) && (p_sys->i_initial_segment == i_firstseg)) ? "#EXT-X-DISCONTINUITY\n" : ""
605 char *psz_current_uri=NULL;
608 for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
610 //scale to i_index_offset..numsegs + i_index_offset
611 uint32_t index = i - i_firstseg + i_index_offset;
613 output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, index );
614 if( p_sys->key_uri &&
615 ( !psz_current_uri || strcmp( psz_current_uri, segment->psz_key_uri ) )
619 free( psz_current_uri );
620 psz_current_uri = strdup( segment->psz_key_uri );
621 if( p_sys->b_generate_iv )
623 unsigned long long iv_hi = segment->aes_ivs[0];
624 unsigned long long iv_lo = segment->aes_ivs[8];
625 for( unsigned short i = 1; i < 8; i++ )
628 iv_hi |= segment->aes_ivs[i] & 0xff;
630 iv_lo |= segment->aes_ivs[8+i] & 0xff;
632 ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\",IV=0X%16.16llx%16.16llx\n",
633 segment->psz_key_uri, iv_hi, iv_lo );
636 ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", segment->psz_key_uri );
640 free( psz_current_uri );
647 val = fprintf( fp, "#EXTINF:%s,\n%s\n", segment->psz_duration, segment->psz_uri);
650 free( psz_current_uri );
656 free( psz_current_uri );
660 if ( fputs ( STR_ENDLIST, fp ) < 0)
670 val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
674 vlc_unlink( psz_idxTmp );
675 msg_Err( p_access, "Error moving LiveHttp index file" );
678 msg_Dbg( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
683 // Then take care of deletion
684 // Try to follow pantos draft 11 section 6.2.2
685 while( p_sys->b_delsegs && p_sys->i_numsegs &&
686 isFirstItemRemovable( p_sys, i_firstseg, i_index_offset )
689 output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
690 msg_Dbg( p_access, "Removing segment number %d", segment->i_segment_number );
691 vlc_array_remove( p_sys->segments_t, 0 );
693 if ( segment->psz_filename )
695 vlc_unlink( segment->psz_filename );
698 destroySegment( segment );
706 /*****************************************************************************
707 * closeCurrentSegment: Close the segment file
708 *****************************************************************************/
709 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
711 if ( p_sys->i_handle >= 0 )
713 output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, vlc_array_count( p_sys->segments_t ) - 1 );
717 size_t pad = 16 - p_sys->stuffing_size;
718 memset(&p_sys->stuffing_bytes[p_sys->stuffing_size], pad, pad);
719 gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx, p_sys->stuffing_bytes, 16, NULL, 0 );
722 msg_Err( p_access, "Couldn't encrypt 16 bytes: %s", gpg_strerror(err) );
724 int ret = write( p_sys->i_handle, p_sys->stuffing_bytes, 16 );
726 msg_Err( p_access, "Couldn't write 16 bytes" );
728 p_sys->stuffing_size = 0;
732 close( p_sys->i_handle );
733 p_sys->i_handle = -1;
735 if( ! ( us_asprintf( &segment->psz_duration, "%.2f", p_sys->f_seglen ) ) )
737 msg_Err( p_access, "Couldn't set duration on closed segment");
740 segment->f_seglength = p_sys->f_seglen;
742 segment->i_segment_number = p_sys->i_segment;
744 if ( p_sys->psz_cursegPath )
746 msg_Dbg( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
747 free( p_sys->psz_cursegPath );
748 p_sys->psz_cursegPath = 0;
749 updateIndexAndDel( p_access, p_sys, b_isend );
754 /*****************************************************************************
755 * Close: close the target
756 *****************************************************************************/
757 static void Close( vlc_object_t * p_this )
759 sout_access_out_t *p_access = (sout_access_out_t*)p_this;
760 sout_access_out_sys_t *p_sys = p_access->p_sys;
761 block_t *output_block = p_sys->block_buffer;
762 p_sys->block_buffer = NULL;
764 while( output_block )
766 block_t *p_next = output_block->p_next;
767 output_block->p_next = NULL;
769 /* Since we are flushing, check the segment change by hand and don't wait
770 * possible keyframe*/
771 if( p_sys->b_segment_has_data && (float)(output_block->i_length + p_sys->i_dts_offset +
772 output_block->i_dts - p_sys->i_opendts) >= p_sys->i_seglenm )
774 closeCurrentSegment( p_access, p_sys, false );
775 p_sys->i_dts_offset = 0;
776 if( unlikely(openNextFile( p_access, p_sys ) < 0 ) )
778 block_ChainRelease( output_block );
780 block_ChainRelease( p_next );
782 /* Jump out of the loop so we can close rest of the stuff*/
785 p_sys->i_opendts = p_sys->block_buffer ? p_sys->block_buffer->i_dts : output_block->i_dts;
787 Write( p_access, output_block );
788 output_block = p_next;
791 ssize_t writevalue = writeSegment( p_access );
792 msg_Dbg( p_access, "Writing.. %zd", writevalue );
793 if( unlikely( writevalue < 0 ) )
795 block_ChainRelease( p_sys->block_buffer );
796 p_sys->block_buffer = NULL;
799 closeCurrentSegment( p_access, p_sys, true );
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 );
819 vlc_array_destroy( p_sys->segments_t );
821 free( p_sys->psz_indexUrl );
822 free( p_sys->psz_indexPath );
825 msg_Dbg( p_access, "livehttp access output closed" );
828 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
830 sout_access_out_sys_t *p_sys = p_access->p_sys;
834 case ACCESS_OUT_CONTROLS_PACE:
836 bool *pb = va_arg( args, bool * );
837 *pb = !p_sys->b_ratecontrol;
848 /*****************************************************************************
849 * openNextFile: Open the segment file
850 *****************************************************************************/
851 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
855 uint32_t i_newseg = p_sys->i_segment + 1;
857 /* Create segment and fill it info that we can (everything excluding duration */
858 output_segment_t *segment = (output_segment_t*)calloc(1, sizeof(output_segment_t));
859 if( unlikely( !segment ) )
862 segment->i_segment_number = i_newseg;
863 segment->psz_filename = formatSegmentPath( p_access->psz_path, i_newseg, true );
864 char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
865 segment->psz_uri = formatSegmentPath( psz_idxFormat , i_newseg, false );
867 if ( unlikely( !segment->psz_filename ) )
869 msg_Err( p_access, "Format segmentpath failed");
870 destroySegment( segment );
874 fd = vlc_open( segment->psz_filename, O_WRONLY | O_CREAT | O_LARGEFILE |
878 msg_Err( p_access, "cannot open `%s' (%s)", segment->psz_filename,
879 vlc_strerror_c(errno) );
880 destroySegment( segment );
884 vlc_array_append( p_sys->segments_t, segment);
886 if( p_sys->psz_keyfile )
888 LoadCryptFile( p_access );
893 segment->psz_key_uri = strdup( p_sys->key_uri );
894 CryptKey( p_access, i_newseg );
895 if( p_sys->b_generate_iv )
896 memcpy( segment->aes_ivs, p_sys->aes_ivs, sizeof(uint8_t)*16 );
898 msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , segment->psz_filename, i_newseg );
900 p_sys->psz_cursegPath = strdup(segment->psz_filename);
901 p_sys->i_handle = fd;
902 p_sys->i_segment = i_newseg;
903 p_sys->b_segment_has_data = false;
906 /*****************************************************************************
907 * CheckSegmentChange: Check if segment needs to be closed and new opened
908 *****************************************************************************/
909 static int CheckSegmentChange( sout_access_out_t *p_access, block_t *p_buffer )
911 sout_access_out_sys_t *p_sys = p_access->p_sys;
912 block_t *output = p_sys->block_buffer;
914 /* let's check if we need to store offset to keep
915 * better count of actual duration */
916 if( unlikely( p_buffer->i_dts < p_sys->i_opendts ) )
918 block_t *last_buffer = p_sys->block_buffer;
919 while( last_buffer->p_next )
920 last_buffer = last_buffer->p_next;
921 p_sys->i_dts_offset += last_buffer->i_dts - p_sys->i_opendts;
922 p_sys->i_opendts = p_buffer->i_dts;
923 msg_Dbg( p_access, "dts offset %"PRId64, p_sys->i_dts_offset );
926 if( p_sys->i_handle > 0 && p_sys->b_segment_has_data &&
927 (( p_buffer->i_length + p_buffer->i_dts - p_sys->i_opendts +
928 p_sys->i_dts_offset ) >= p_sys->i_seglenm ) )
930 closeCurrentSegment( p_access, p_sys, false );
933 if ( unlikely( p_sys->i_handle < 0 ) )
935 p_sys->i_dts_offset = 0;
936 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
937 //For first segment we can get negative duration otherwise...?
938 if( ( p_sys->i_opendts != VLC_TS_INVALID ) &&
939 ( p_buffer->i_dts < p_sys->i_opendts ) )
940 p_sys->i_opendts = p_buffer->i_dts;
942 if ( openNextFile( p_access, p_sys ) < 0 )
948 static ssize_t writeSegment( sout_access_out_t *p_access )
950 sout_access_out_sys_t *p_sys = p_access->p_sys;
951 block_t *output = p_sys->block_buffer ? block_ChainGather( p_sys->block_buffer ) : NULL;
952 p_sys->block_buffer = NULL;
954 bool crypted = false;
957 if( p_sys->key_uri && !crypted )
959 if( p_sys->stuffing_size )
961 output = block_Realloc( output, p_sys->stuffing_size, output->i_buffer );
962 if( unlikely(!output ) )
964 memcpy( output->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
965 p_sys->stuffing_size = 0;
967 size_t original = output->i_buffer;
968 size_t padded = (output->i_buffer + 15 ) & ~15;
969 size_t pad = padded - original;
972 p_sys->stuffing_size = 16-pad;
973 output->i_buffer -= p_sys->stuffing_size;
974 memcpy(p_sys->stuffing_bytes, &output->p_buffer[output->i_buffer], p_sys->stuffing_size);
977 gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
978 output->p_buffer, output->i_buffer, NULL, 0 );
981 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
987 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
990 if ( errno == EINTR )
996 (float)(output->i_length +
997 output->i_dts - p_sys->i_opendts + p_sys->i_dts_offset) / CLOCK_FREQ;
999 if ( (size_t)val >= output->i_buffer )
1001 block_t *p_next = output->p_next;
1002 block_Release (output);
1008 output->p_buffer += val;
1009 output->i_buffer -= val;
1016 /*****************************************************************************
1017 * Write: standard write on a file descriptor.
1018 *****************************************************************************/
1019 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
1022 sout_access_out_sys_t *p_sys = p_access->p_sys;
1026 if( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
1028 if( unlikely( CheckSegmentChange( p_access, p_buffer ) != VLC_SUCCESS ) )
1030 block_ChainRelease ( p_buffer );
1034 ssize_t writevalue = writeSegment( p_access );
1035 if( unlikely( writevalue < 0 ) )
1037 block_ChainRelease ( p_buffer );
1040 p_sys->b_segment_has_data = true;
1041 i_write += writevalue;
1044 p_temp = p_buffer->p_next;
1045 p_buffer->p_next = NULL;
1046 block_ChainAppend( &p_sys->block_buffer, p_buffer );
1053 /*****************************************************************************
1054 * Seek: seek to a specific location in a file
1055 *****************************************************************************/
1056 static int Seek( sout_access_out_t *p_access, off_t i_pos )
1059 msg_Err( p_access, "livehttp sout access cannot seek" );