]> git.sesse.net Git - vlc/blob - modules/access_output/livehttp.c
321b4477203b6bd7a11c62092fba0b14621fdcf2
[vlc] / modules / access_output / livehttp.c
1 /*****************************************************************************
2  * livehttp.c: Live HTTP Streaming
3  *****************************************************************************
4  * Copyright © 2001, 2002, 2013 VLC authors and VideoLAN
5  * Copyright © 2009-2010 by Keary Griffin
6  *
7  * Authors: Keary Griffin <kearygriffin at gmail.com>
8  *          Ilkka Ollakka <ileoo at videolan dot org>
9  *
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.
14  *
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.
19  *
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  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <sys/types.h>
34 #include <time.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
40
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
43 #include <vlc_sout.h>
44 #include <vlc_block.h>
45 #include <vlc_fs.h>
46 #include <vlc_strings.h>
47 #include <vlc_charset.h>
48
49 #include <gcrypt.h>
50 #include <vlc_gcrypt.h>
51
52 #include <vlc_rand.h>
53
54 #ifndef O_LARGEFILE
55 #   define O_LARGEFILE 0
56 #endif
57
58 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
59
60 #define MAX_RENAME_RETRIES        10
61
62 /*****************************************************************************
63  * Module descriptor
64  *****************************************************************************/
65 static int  Open ( vlc_object_t * );
66 static void Close( vlc_object_t * );
67
68 #define SOUT_CFG_PREFIX "sout-livehttp-"
69 #define SEGLEN_TEXT N_("Segment length")
70 #define SEGLEN_LONGTEXT N_("Length of TS stream segments")
71
72 #define SPLITANYWHERE_TEXT N_("Split segments anywhere")
73 #define SPLITANYWHERE_LONGTEXT N_("Don't require a keyframe before splitting "\
74                                 "a segment. Needed for audio only.")
75
76 #define NUMSEGS_TEXT N_("Number of segments")
77 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
78
79 #define NOCACHE_TEXT N_("Allow cache")
80 #define NOCACHE_LONGTEXT N_("Add EXT-X-ALLOW-CACHE:NO directive in playlist-file if this is disabled")
81
82 #define INDEX_TEXT N_("Index file")
83 #define INDEX_LONGTEXT N_("Path to the index file to create")
84
85 #define INDEXURL_TEXT N_("Full URL to put in index file")
86 #define INDEXURL_LONGTEXT N_("Full URL to put in index file. "\
87                           "Use #'s to represent segment number")
88
89 #define DELSEGS_TEXT N_("Delete segments")
90 #define DELSEGS_LONGTEXT N_("Delete segments when they are no longer needed")
91
92 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
93
94 #define KEYURI_TEXT N_("AES key URI to place in playlist")
95
96 #define KEYFILE_TEXT N_("AES key file")
97 #define KEYFILE_LONGTEXT N_("File containing the 16 bytes encryption key")
98
99 #define KEYLOADFILE_TEXT N_("File where vlc reads key-uri and keyfile-location")
100 #define KEYLOADFILE_LONGTEXT N_("File is read when segment starts and is assumet to be in format: "\
101                                 "key-uri\\nkey-file. File is read on the segment opening and "\
102                                 "values are used on that segment.")
103
104 #define RANDOMIV_TEXT N_("Use randomized IV for encryption")
105 #define RANDOMIV_LONGTEXT N_("Generate IV instead using segment-number as IV")
106
107 #define INTITIAL_SEG_TEXT N_("Number of first segment")
108 #define INITIAL_SEG_LONGTEXT N_("The number of the segmented generated")
109
110 vlc_module_begin ()
111     set_description( N_("HTTP Live streaming output") )
112     set_shortname( N_("LiveHTTP" ))
113     add_shortcut( "livehttp" )
114     set_capability( "sout access", 0 )
115     set_category( CAT_SOUT )
116     set_subcategory( SUBCAT_SOUT_ACO )
117     add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, false )
118     add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, false )
119     add_integer( SOUT_CFG_PREFIX "initial-segment-number", 1, INTITIAL_SEG_TEXT, INITIAL_SEG_LONGTEXT, false )
120     add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
121               SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
122     add_bool( SOUT_CFG_PREFIX "delsegs", true,
123               DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
124     add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
125               RATECONTROL_TEXT, RATECONTROL_TEXT, true )
126     add_bool( SOUT_CFG_PREFIX "caching", false,
127               NOCACHE_TEXT, NOCACHE_LONGTEXT, true )
128     add_bool( SOUT_CFG_PREFIX "generate-iv", false,
129               RANDOMIV_TEXT, RANDOMIV_LONGTEXT, true )
130     add_string( SOUT_CFG_PREFIX "index", NULL,
131                 INDEX_TEXT, INDEX_LONGTEXT, false )
132     add_string( SOUT_CFG_PREFIX "index-url", NULL,
133                 INDEXURL_TEXT, INDEXURL_LONGTEXT, false )
134     add_string( SOUT_CFG_PREFIX "key-uri", NULL,
135                 KEYURI_TEXT, KEYURI_TEXT, true )
136     add_loadfile( SOUT_CFG_PREFIX "key-file", NULL,
137                 KEYFILE_TEXT, KEYFILE_LONGTEXT, true )
138     add_loadfile( SOUT_CFG_PREFIX "key-loadfile", NULL,
139                 KEYLOADFILE_TEXT, KEYLOADFILE_LONGTEXT, true )
140     set_callbacks( Open, Close )
141 vlc_module_end ()
142
143
144 /*****************************************************************************
145  * Exported prototypes
146  *****************************************************************************/
147 static const char *const ppsz_sout_options[] = {
148     "seglen",
149     "splitanywhere",
150     "numsegs",
151     "delsegs",
152     "index",
153     "index-url",
154     "ratecontrol",
155     "caching",
156     "key-uri",
157     "key-file",
158     "key-loadfile",
159     "generate-iv",
160     "initial-segment-number",
161     NULL
162 };
163
164 static ssize_t Write( sout_access_out_t *, block_t * );
165 static int Seek ( sout_access_out_t *, off_t  );
166 static int Control( sout_access_out_t *, int, va_list );
167
168 typedef struct output_segment
169 {
170     char *psz_filename;
171     char *psz_uri;
172     char *psz_key_uri;
173     char *psz_duration;
174     float f_seglength;
175     uint32_t i_segment_number;
176     uint8_t aes_ivs[16];
177 } output_segment_t;
178
179 struct sout_access_out_sys_t
180 {
181     char *psz_cursegPath;
182     char *psz_indexPath;
183     char *psz_indexUrl;
184     char *psz_keyfile;
185     mtime_t i_keyfile_modification;
186     mtime_t i_opendts;
187     mtime_t  i_seglenm;
188     uint32_t i_segment;
189     size_t  i_seglen;
190     float   f_seglen;
191     block_t *block_buffer;
192     int i_handle;
193     unsigned i_numsegs;
194     unsigned i_initial_segment;
195     bool b_delsegs;
196     bool b_ratecontrol;
197     bool b_splitanywhere;
198     bool b_caching;
199     bool b_generate_iv;
200     uint8_t aes_ivs[16];
201     gcry_cipher_hd_t aes_ctx;
202     char *key_uri;
203     uint8_t stuffing_bytes[16];
204     ssize_t stuffing_size;
205     vlc_array_t *segments_t;
206 };
207
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 )
217 {
218     sout_access_out_t   *p_access = (sout_access_out_t*)p_this;
219     sout_access_out_sys_t *p_sys;
220     char *psz_idx;
221
222     config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
223
224     if( !p_access->psz_path )
225     {
226         msg_Err( p_access, "no file name specified" );
227         return VLC_EGENERIC;
228     }
229
230     if( unlikely( !( p_sys = calloc ( 1, sizeof( *p_sys ) ) ) ) )
231         return VLC_ENOMEM;
232
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;
237
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
246     p_sys->segments_t = vlc_array_new();
247
248     p_sys->stuffing_size = 0;
249     p_sys->i_opendts = VLC_TS_INVALID;
250
251     p_sys->psz_indexPath = NULL;
252     psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
253     if ( psz_idx )
254     {
255         char *psz_tmp;
256         psz_tmp = str_format_time( psz_idx );
257         free( psz_idx );
258         if ( !psz_tmp )
259         {
260             free( p_sys );
261             return VLC_ENOMEM;
262         }
263         path_sanitize( psz_tmp );
264         p_sys->psz_indexPath = psz_tmp;
265         vlc_unlink( p_sys->psz_indexPath );
266     }
267
268     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
269     p_sys->psz_keyfile  = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-loadfile" );
270     p_sys->key_uri      = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-uri" );
271
272     p_access->p_sys = p_sys;
273
274     if( p_sys->psz_keyfile && ( LoadCryptFile( p_access ) < 0 ) )
275     {
276         free( p_sys->psz_indexUrl );
277         free( p_sys->psz_indexPath );
278         free( p_sys );
279         msg_Err( p_access, "Encryption init failed" );
280         return VLC_EGENERIC;
281     }
282     else if( !p_sys->psz_keyfile && ( CryptSetup( p_access, NULL ) < 0 ) )
283     {
284         free( p_sys->psz_indexUrl );
285         free( p_sys->psz_indexPath );
286         free( p_sys );
287         msg_Err( p_access, "Encryption init failed" );
288         return VLC_EGENERIC;
289     }
290
291     p_sys->i_handle = -1;
292     p_sys->i_segment = p_sys->i_initial_segment > 0 ? p_sys->i_initial_segment -1 : 0;
293     p_sys->psz_cursegPath = NULL;
294
295     p_access->pf_write = Write;
296     p_access->pf_seek  = Seek;
297     p_access->pf_control = Control;
298
299     return VLC_SUCCESS;
300 }
301
302 /************************************************************************
303  * CryptSetup: Initialize encryption
304  ************************************************************************/
305 static int CryptSetup( sout_access_out_t *p_access, char *key_file )
306 {
307     sout_access_out_sys_t *p_sys = p_access->p_sys;
308     uint8_t key[16];
309     char *keyfile = NULL;
310
311     if( !p_sys->key_uri ) /*No key uri, assume no encryption wanted*/
312     {
313         msg_Dbg( p_access, "No key uri, no encryption");
314         return VLC_SUCCESS;
315     }
316
317     if( key_file )
318         keyfile = strdup( key_file );
319     else
320         keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
321
322     if( unlikely(keyfile == NULL) )
323     {
324         msg_Err( p_access, "No key-file, no encryption" );
325         return VLC_EGENERIC;
326     }
327
328     vlc_gcrypt_init();
329
330     /*Setup encryption cipher*/
331     gcry_error_t err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
332                                          GCRY_CIPHER_MODE_CBC, 0 );
333     if( err )
334     {
335         msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
336         free( keyfile );
337         return VLC_EGENERIC;
338     }
339
340     int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
341     if( unlikely( keyfd == -1 ) )
342     {
343         msg_Err( p_access, "Unable to open keyfile %s: %m", keyfile );
344         free( keyfile );
345         gcry_cipher_close( p_sys->aes_ctx );
346         return VLC_EGENERIC;
347     }
348     free( keyfile );
349
350     ssize_t keylen = read( keyfd, key, 16 );
351
352     close( keyfd );
353     if( keylen < 16 )
354     {
355         msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
356         gcry_cipher_close( p_sys->aes_ctx );
357         return VLC_EGENERIC;
358     }
359
360     err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
361     if(err)
362     {
363         msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
364         gcry_cipher_close( p_sys->aes_ctx );
365         return VLC_EGENERIC;
366     }
367
368     if( p_sys->b_generate_iv )
369         vlc_rand_bytes( p_sys->aes_ivs, sizeof(uint8_t)*16);
370
371     return VLC_SUCCESS;
372 }
373
374
375 /************************************************************************
376  * LoadCryptFile: Try to parse key_uri and keyfile-location from file
377  ************************************************************************/
378 static int LoadCryptFile( sout_access_out_t *p_access )
379 {
380     sout_access_out_sys_t *p_sys = p_access->p_sys;
381
382     FILE *stream = vlc_fopen( p_sys->psz_keyfile, "rt" );
383     char *key_file=NULL,*key_uri=NULL;
384
385     if( unlikely( stream == NULL ) )
386     {
387         msg_Err( p_access, "Unable to open keyloadfile %s: %m", p_sys->psz_keyfile );
388         return VLC_EGENERIC;
389     }
390
391
392     //First read key_uri
393     ssize_t len = getline( &key_uri, &(size_t){0}, stream );
394     if( unlikely( len == -1 ) )
395     {
396         msg_Err( p_access, "Cannot read %s: %m", p_sys->psz_keyfile );
397         clearerr( stream );
398         fclose( stream );
399         free( key_uri );
400         return VLC_EGENERIC;
401     }
402     //Strip the newline from uri, maybe scanf would be better?
403     key_uri[len-1]='\0';
404
405     len = getline( &key_file, &(size_t){0}, stream );
406     if( unlikely( len == -1 ) )
407     {
408         msg_Err( p_access, "Cannot read %s: %m", p_sys->psz_keyfile );
409         clearerr( stream );
410         fclose( stream );
411
412         free( key_uri );
413         free( key_file );
414         return VLC_EGENERIC;
415     }
416     // Strip the last newline from filename
417     key_file[len-1]='\0';
418     fclose( stream );
419
420     int returncode = VLC_SUCCESS;
421     if( !p_sys->key_uri || strcmp( p_sys->key_uri, key_uri ) )
422     {
423         if( p_sys->key_uri )
424         {
425             free( p_sys->key_uri );
426             p_sys->key_uri = NULL;
427         }
428         p_sys->key_uri = strdup( key_uri );
429         returncode = CryptSetup( p_access, key_file );
430     }
431     free( key_file );
432     free( key_uri );
433     return returncode;
434 }
435
436 /************************************************************************
437  * CryptKey: Set encryption IV to current segment number
438  ************************************************************************/
439 static int CryptKey( sout_access_out_t *p_access, uint32_t i_segment )
440 {
441     sout_access_out_sys_t *p_sys = p_access->p_sys;
442
443     if( !p_sys->b_generate_iv )
444     {
445         /* Use segment number as IV if randomIV isn't selected*/
446         memset( p_sys->aes_ivs, 0, 16 * sizeof(uint8_t));
447         p_sys->aes_ivs[15] = i_segment & 0xff;
448         p_sys->aes_ivs[14] = (i_segment >> 8 ) & 0xff;
449         p_sys->aes_ivs[13] = (i_segment >> 16 ) & 0xff;
450         p_sys->aes_ivs[12] = (i_segment >> 24 ) & 0xff;
451     }
452
453     gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
454                                           p_sys->aes_ivs, 16);
455     if( err )
456     {
457         msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
458         gcry_cipher_close( p_sys->aes_ctx);
459         return VLC_EGENERIC;
460     }
461     return VLC_SUCCESS;
462 }
463
464
465 #define SEG_NUMBER_PLACEHOLDER "#"
466 /*****************************************************************************
467  * formatSegmentPath: create segment path name based on seg #
468  *****************************************************************************/
469 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
470 {
471     char *psz_result;
472     char *psz_firstNumSign;
473
474     if ( ! ( psz_result  = str_format_time( psz_path ) ) )
475         return NULL;
476
477     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
478     if ( *psz_firstNumSign )
479     {
480         char *psz_newResult;
481         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
482         int ret;
483
484         *psz_firstNumSign = '\0';
485         ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
486         free ( psz_result );
487         if ( ret < 0 )
488             return NULL;
489         psz_result = psz_newResult;
490     }
491
492     if ( b_sanitize )
493         path_sanitize( psz_result );
494
495     return psz_result;
496 }
497
498 static void destroySegment( output_segment_t *segment )
499 {
500     free( segment->psz_filename );
501     free( segment->psz_duration );
502     free( segment->psz_uri );
503     free( segment->psz_key_uri );
504     free( segment );
505 }
506
507 /************************************************************************
508  * segmentAmountNeeded: check that playlist has atleast 3*p_sys->i_seglength of segments
509  * return how many segments are needed for that (max of p_sys->i_segment )
510  ************************************************************************/
511 static uint32_t segmentAmountNeeded( sout_access_out_sys_t *p_sys )
512 {
513     float duration = .0f;
514     for( unsigned index = 1; (int)index <= vlc_array_count( p_sys->segments_t ); index++ )
515     {
516         output_segment_t* segment = vlc_array_item_at_index( p_sys->segments_t, vlc_array_count( p_sys->segments_t ) - index );
517         duration += segment->f_seglength;
518
519         if( duration >= (float)( 3 * p_sys->i_seglen ) )
520             return __MAX(index, p_sys->i_numsegs);
521     }
522     return vlc_array_count( p_sys->segments_t )-1;
523
524 }
525
526
527 /************************************************************************
528  * isFirstItemRemovable: Check for draft 11 section 6.2.2
529  * check that the first item has been around outside playlist
530  * segment->f_seglength + (p_sys->i_numsegs * p_sys->i_seglen) before it is removed.
531  ************************************************************************/
532 static bool isFirstItemRemovable( sout_access_out_sys_t *p_sys, uint32_t i_firstseg, uint32_t i_index_offset )
533 {
534     float duration = .0f;
535
536     /* Check that segment has been out of playlist for seglenght + (p_sys->i_numsegs * p_sys->i_seglen) amount
537      * We check this by calculating duration of the items that replaced first item in playlist
538      */
539     for( unsigned int index = 0; index < i_index_offset; index++ )
540     {
541         output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, p_sys->i_segment - i_firstseg + index );
542         duration += segment->f_seglength;
543     }
544     output_segment_t *first = vlc_array_item_at_index( p_sys->segments_t, 0 );
545
546     return duration >= (first->f_seglength + (float)(p_sys->i_numsegs * p_sys->i_seglen));
547 }
548
549 /************************************************************************
550  * updateIndexAndDel: If necessary, update index file & delete old segments
551  ************************************************************************/
552 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
553 {
554
555     uint32_t i_firstseg;
556     unsigned i_index_offset = 0;
557
558     if ( p_sys->i_numsegs == 0 ||
559          p_sys->i_segment < ( p_sys->i_numsegs + p_sys->i_initial_segment ) )
560     {
561         i_firstseg = p_sys->i_initial_segment == 0 ? 1 : p_sys->i_initial_segment;
562     }
563     else
564     {
565         unsigned numsegs = segmentAmountNeeded( p_sys );
566         i_firstseg = ( p_sys->i_segment - numsegs ) + 1;
567         i_index_offset = vlc_array_count( p_sys->segments_t ) - numsegs;
568     }
569
570     // First update index
571     if ( p_sys->psz_indexPath )
572     {
573         int val;
574         FILE *fp;
575         char *psz_idxTmp;
576         if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
577             return -1;
578
579         fp = vlc_fopen( psz_idxTmp, "wt");
580         if ( !fp )
581         {
582             msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
583             free( psz_idxTmp );
584             return -1;
585         }
586
587         if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-VERSION:3\n#EXT-X-ALLOW-CACHE:%s"
588                           "%s\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n", p_sys->i_seglen,
589                           p_sys->b_caching ? "YES" : "NO",
590                           p_sys->i_numsegs > 0 ? "" : b_isend ? "\n#EXT-X-PLAYLIST-TYPE:VOD" : "\n#EXT-X-PLAYLIST-TYPE:EVENT",
591                           i_firstseg ) < 0 )
592         {
593             free( psz_idxTmp );
594             fclose( fp );
595             return -1;
596         }
597         char *psz_current_uri=NULL;
598
599
600         for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
601         {
602             //scale to i_index_offset..numsegs + i_index_offset
603             uint32_t index = i - i_firstseg + i_index_offset;
604
605             output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, index );
606             if( p_sys->key_uri &&
607                 ( !psz_current_uri ||  strcmp( psz_current_uri, segment->psz_key_uri ) )
608               )
609             {
610                 int ret = 0;
611                 free( psz_current_uri );
612                 psz_current_uri = strdup( segment->psz_key_uri );
613                 if( p_sys->b_generate_iv )
614                 {
615                     unsigned long long iv_hi = 0, iv_lo = 0;
616                     for( unsigned short i = 0; i < 8; i++ )
617                     {
618                         iv_hi |= segment->aes_ivs[i] & 0xff;
619                         iv_hi <<= 8;
620                         iv_lo |= segment->aes_ivs[8+i] & 0xff;
621                         iv_lo <<= 8;
622                     }
623                     ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\",IV=0X%16.16llx%16.16llx\n",
624                                    segment->psz_key_uri, iv_hi, iv_lo );
625
626                 } else {
627                     ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", segment->psz_key_uri );
628                 }
629                 if( ret < 0 )
630                 {
631                     free( psz_current_uri );
632                     free( psz_idxTmp );
633                     fclose( fp );
634                     return -1;
635                 }
636             }
637
638             val = fprintf( fp, "#EXTINF:%s,\n%s\n", segment->psz_duration, segment->psz_uri);
639             if ( val < 0 )
640             {
641                 free( psz_current_uri );
642                 free( psz_idxTmp );
643                 fclose( fp );
644                 return -1;
645             }
646         }
647         free( psz_current_uri );
648
649         if ( b_isend )
650         {
651             if ( fputs ( STR_ENDLIST, fp ) < 0)
652             {
653                 free( psz_idxTmp );
654                 fclose( fp ) ;
655                 return -1;
656             }
657
658         }
659         fclose( fp );
660
661         val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
662
663         if ( val < 0 )
664         {
665             vlc_unlink( psz_idxTmp );
666             msg_Err( p_access, "Error moving LiveHttp index file" );
667         }
668         else
669             msg_Dbg( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
670
671         free( psz_idxTmp );
672     }
673
674     // Then take care of deletion
675     // Try to follow pantos draft 11 section 6.2.2
676     while( p_sys->b_delsegs && p_sys->i_numsegs &&
677            isFirstItemRemovable( p_sys, i_firstseg, i_index_offset )
678          )
679     {
680          output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
681          msg_Dbg( p_access, "Removing segment number %d", segment->i_segment_number );
682          vlc_array_remove( p_sys->segments_t, 0 );
683
684          if ( segment->psz_filename )
685          {
686              vlc_unlink( segment->psz_filename );
687          }
688
689          destroySegment( segment );
690          i_index_offset -=1;
691     }
692
693
694     return 0;
695 }
696
697 /*****************************************************************************
698  * closeCurrentSegment: Close the segment file
699  *****************************************************************************/
700 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
701 {
702     if ( p_sys->i_handle >= 0 )
703     {
704         output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, vlc_array_count( p_sys->segments_t ) - 1 );
705
706         if( p_sys->key_uri )
707         {
708             size_t pad = 16 - p_sys->stuffing_size;
709             memset(&p_sys->stuffing_bytes[p_sys->stuffing_size], pad, pad);
710             gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx, p_sys->stuffing_bytes, 16, NULL, 0 );
711
712             if( err ) {
713                msg_Err( p_access, "Couldn't encrypt 16 bytes: %s", gpg_strerror(err) );
714             } else {
715             int ret = write( p_sys->i_handle, p_sys->stuffing_bytes, 16 );
716             if( ret != 16 )
717                 msg_Err( p_access, "Couldn't write 16 bytes" );
718             }
719             p_sys->stuffing_size = 0;
720         }
721
722
723         close( p_sys->i_handle );
724         p_sys->i_handle = -1;
725
726         if( ! ( us_asprintf( &segment->psz_duration, "%.2f", p_sys->f_seglen ) ) )
727         {
728             msg_Err( p_access, "Couldn't set duration on closed segment");
729             return;
730         }
731         segment->f_seglength = p_sys->f_seglen;
732
733         segment->i_segment_number = p_sys->i_segment;
734
735         if ( p_sys->psz_cursegPath )
736         {
737             msg_Dbg( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
738             free( p_sys->psz_cursegPath );
739             p_sys->psz_cursegPath = 0;
740             updateIndexAndDel( p_access, p_sys, b_isend );
741         }
742     }
743 }
744
745 /*****************************************************************************
746  * Close: close the target
747  *****************************************************************************/
748 static void Close( vlc_object_t * p_this )
749 {
750     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
751     sout_access_out_sys_t *p_sys = p_access->p_sys;
752     block_t *output_block = p_sys->block_buffer;
753     p_sys->block_buffer = NULL;
754
755     while( output_block )
756     {
757         block_t *p_next = output_block->p_next;
758         output_block->p_next = NULL;
759
760         /* Since we are flushing, check the segment change by hand and don't wait
761          * possible keyframe*/
762         if( ((float)(output_block->i_length * CLOCK_FREQ / INT64_C(1000000) ) +
763             (float)(output_block->i_dts - p_sys->i_opendts)) >= p_sys->i_seglenm )
764         {
765             closeCurrentSegment( p_access, p_sys, false );
766             if( unlikely(openNextFile( p_access, p_sys ) < 0 ) )
767             {
768                 block_ChainRelease( output_block );
769                 output_block = NULL;
770                 block_ChainRelease( p_next );
771
772                 /* Jump out of the loop so we can close rest of the stuff*/
773                 continue;
774             }
775             p_sys->i_opendts = p_sys->block_buffer ? p_sys->block_buffer->i_dts : output_block->i_dts;
776         }
777         Write( p_access, output_block );
778         output_block = p_next;
779     }
780
781     ssize_t writevalue = writeSegment( p_access );
782     msg_Dbg( p_access, "Writing.. %zd", writevalue );
783     if( unlikely( writevalue < 0 ) )
784     {
785         block_ChainRelease( p_sys->block_buffer );
786         p_sys->block_buffer = NULL;
787     }
788
789     closeCurrentSegment( p_access, p_sys, true );
790
791     if( p_sys->key_uri )
792     {
793         gcry_cipher_close( p_sys->aes_ctx );
794         free( p_sys->key_uri );
795     }
796
797     while( vlc_array_count( p_sys->segments_t ) > 0 )
798     {
799         output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
800         vlc_array_remove( p_sys->segments_t, 0 );
801         if( p_sys->b_delsegs && p_sys->i_numsegs && segment->psz_filename )
802         {
803             msg_Dbg( p_access, "Removing segment number %d name %s", segment->i_segment_number, segment->psz_filename );
804             vlc_unlink( segment->psz_filename );
805         }
806
807         destroySegment( segment );
808     }
809     vlc_array_destroy( p_sys->segments_t );
810
811     free( p_sys->psz_indexUrl );
812     free( p_sys->psz_indexPath );
813     free( p_sys );
814
815     msg_Dbg( p_access, "livehttp access output closed" );
816 }
817
818 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
819 {
820     sout_access_out_sys_t *p_sys = p_access->p_sys;
821
822     switch( i_query )
823     {
824         case ACCESS_OUT_CONTROLS_PACE:
825         {
826             bool *pb = va_arg( args, bool * );
827             *pb = !p_sys->b_ratecontrol;
828             //*pb = true;
829             break;
830         }
831
832         default:
833             return VLC_EGENERIC;
834     }
835     return VLC_SUCCESS;
836 }
837
838 /*****************************************************************************
839  * openNextFile: Open the segment file
840  *****************************************************************************/
841 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
842 {
843     int fd;
844
845     uint32_t i_newseg = p_sys->i_segment + 1;
846
847     /* Create segment and fill it info that we can (everything excluding duration */
848     output_segment_t *segment = (output_segment_t*)calloc(1, sizeof(output_segment_t));
849     if( unlikely( !segment ) )
850         return -1;
851
852     segment->i_segment_number = i_newseg;
853     segment->psz_filename = formatSegmentPath( p_access->psz_path, i_newseg, true );
854     char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
855     segment->psz_uri = formatSegmentPath( psz_idxFormat , i_newseg, false );
856
857     if ( unlikely( !segment->psz_filename ) )
858     {
859         msg_Err( p_access, "Format segmentpath failed");
860         destroySegment( segment );
861         return -1;
862     }
863
864     fd = vlc_open( segment->psz_filename, O_WRONLY | O_CREAT | O_LARGEFILE |
865                      O_TRUNC, 0666 );
866     if ( fd == -1 )
867     {
868         msg_Err( p_access, "cannot open `%s' (%m)", segment->psz_filename );
869         destroySegment( segment );
870         return -1;
871     }
872
873     vlc_array_append( p_sys->segments_t, segment);
874
875     if( p_sys->psz_keyfile )
876     {
877         LoadCryptFile( p_access );
878     }
879
880     if( p_sys->key_uri )
881     {
882         segment->psz_key_uri = strdup( p_sys->key_uri );
883         CryptKey( p_access, i_newseg );
884         if( p_sys->b_generate_iv )
885             memcpy( segment->aes_ivs, p_sys->aes_ivs, sizeof(uint8_t)*16 );
886     }
887     msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , segment->psz_filename, i_newseg );
888
889     p_sys->psz_cursegPath = strdup(segment->psz_filename);
890     p_sys->i_handle = fd;
891     p_sys->i_segment = i_newseg;
892     return fd;
893 }
894 /*****************************************************************************
895  * CheckSegmentChange: Check if segment needs to be closed and new opened
896  *****************************************************************************/
897 static int CheckSegmentChange( sout_access_out_t *p_access, block_t *p_buffer )
898 {
899     sout_access_out_sys_t *p_sys = p_access->p_sys;
900     block_t *output = p_sys->block_buffer;
901
902     if( p_sys->i_handle > 0 &&
903         ( ( p_buffer->i_dts - p_sys->i_opendts +
904           ( p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000) )
905         ) >= p_sys->i_seglenm ) )
906      {
907         closeCurrentSegment( p_access, p_sys, false );
908      }
909
910     if ( p_sys->i_handle < 0 )
911     {
912         p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
913         //For first segment we can get negative duration otherwise...?
914         if( ( p_sys->i_opendts != VLC_TS_INVALID ) &&
915             ( p_buffer->i_dts < p_sys->i_opendts ) )
916             p_sys->i_opendts = p_buffer->i_dts;
917
918         if ( openNextFile( p_access, p_sys ) < 0 )
919            return VLC_EGENERIC;
920     }
921     return VLC_SUCCESS;
922 }
923
924 static ssize_t writeSegment( sout_access_out_t *p_access )
925 {
926     sout_access_out_sys_t *p_sys = p_access->p_sys;
927     block_t *output = p_sys->block_buffer;
928     p_sys->block_buffer = NULL;
929     ssize_t i_write=0;
930     bool crypted = false;
931     while( output )
932     {
933         if( p_sys->key_uri && !crypted )
934         {
935             if( p_sys->stuffing_size )
936             {
937                 output = block_Realloc( output, p_sys->stuffing_size, output->i_buffer );
938                 if( unlikely(!output ) )
939                     return VLC_ENOMEM;
940                 memcpy( output->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
941                 p_sys->stuffing_size = 0;
942             }
943             size_t original = output->i_buffer;
944             size_t padded = (output->i_buffer + 15 ) & ~15;
945             size_t pad = padded - original;
946             if( pad )
947             {
948                 p_sys->stuffing_size = 16-pad;
949                 output->i_buffer -= p_sys->stuffing_size;
950                 memcpy(p_sys->stuffing_bytes, &output->p_buffer[output->i_buffer], p_sys->stuffing_size);
951             }
952
953             gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
954                                 output->p_buffer, output->i_buffer, NULL, 0 );
955             if( err )
956             {
957                 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
958                 return -1;
959             }
960             crypted=true;
961
962         }
963         ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
964         if ( val == -1 )
965         {
966            if ( errno == EINTR )
967               continue;
968            return -1;
969         }
970
971         p_sys->f_seglen =
972             (float)(output->i_length / INT64_C(1000000) ) +
973             (float)(output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
974
975         if ( (size_t)val >= output->i_buffer )
976         {
977            block_t *p_next = output->p_next;
978            block_Release (output);
979            output = p_next;
980            crypted=false;
981         }
982         else
983         {
984            output->p_buffer += val;
985            output->i_buffer -= val;
986         }
987         i_write += val;
988     }
989     return i_write;
990 }
991
992 /*****************************************************************************
993  * Write: standard write on a file descriptor.
994  *****************************************************************************/
995 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
996 {
997     size_t i_write = 0;
998     sout_access_out_sys_t *p_sys = p_access->p_sys;
999     block_t *p_temp;
1000     while( p_buffer )
1001     {
1002         if( ( p_sys->b_splitanywhere  || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
1003         {
1004             if( unlikely( CheckSegmentChange( p_access, p_buffer ) != VLC_SUCCESS ) )
1005             {
1006                 block_ChainRelease ( p_buffer );
1007                 return -1;
1008             }
1009
1010             ssize_t writevalue = writeSegment( p_access );
1011             if( unlikely( writevalue < 0 ) )
1012             {
1013                 block_ChainRelease ( p_buffer );
1014                 return -1;
1015             }
1016             i_write += writevalue;
1017         }
1018
1019         p_temp = p_buffer->p_next;
1020         p_buffer->p_next = NULL;
1021         block_ChainAppend( &p_sys->block_buffer, p_buffer );
1022         p_buffer = p_temp;
1023     }
1024
1025     return i_write;
1026 }
1027
1028 /*****************************************************************************
1029  * Seek: seek to a specific location in a file
1030  *****************************************************************************/
1031 static int Seek( sout_access_out_t *p_access, off_t i_pos )
1032 {
1033     (void) i_pos;
1034     msg_Err( p_access, "livehttp sout access cannot seek" );
1035     return -1;
1036 }