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