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