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