]> git.sesse.net Git - vlc/blob - modules/access_output/livehttp.c
livehttp: support static IV-use on encryption
[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 #define KEYURI_LONGTEXT N_("Location from where client will retrieve the stream decryption key")
96
97 #define KEYFILE_TEXT N_("AES key file")
98 #define KEYFILE_LONGTEXT N_("File containing the 16 bytes encryption key")
99
100 #define RANDOMIV_TEXT N_("Use randomized IV for encryption")
101 #define RANDOMIV_LONGTEXT N_("Generate IV instead using segment-number as IV")
102
103 vlc_module_begin ()
104     set_description( N_("HTTP Live streaming output") )
105     set_shortname( N_("LiveHTTP" ))
106     add_shortcut( "livehttp" )
107     set_capability( "sout access", 0 )
108     set_category( CAT_SOUT )
109     set_subcategory( SUBCAT_SOUT_ACO )
110     add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, false )
111     add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, false )
112     add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
113               SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
114     add_bool( SOUT_CFG_PREFIX "delsegs", true,
115               DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
116     add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
117               RATECONTROL_TEXT, RATECONTROL_TEXT, true )
118     add_bool( SOUT_CFG_PREFIX "caching", false,
119               NOCACHE_TEXT, NOCACHE_LONGTEXT, true )
120     add_bool( SOUT_CFG_PREFIX "generate-iv", false,
121               RANDOMIV_TEXT, RANDOMIV_LONGTEXT, true )
122     add_string( SOUT_CFG_PREFIX "index", NULL,
123                 INDEX_TEXT, INDEX_LONGTEXT, false )
124     add_string( SOUT_CFG_PREFIX "index-url", NULL,
125                 INDEXURL_TEXT, INDEXURL_LONGTEXT, false )
126     add_string( SOUT_CFG_PREFIX "key-uri", NULL,
127                 KEYURI_TEXT, KEYURI_TEXT, true )
128     add_loadfile( SOUT_CFG_PREFIX "key-file", NULL,
129                 KEYFILE_TEXT, KEYFILE_LONGTEXT, true )
130     set_callbacks( Open, Close )
131 vlc_module_end ()
132
133
134 /*****************************************************************************
135  * Exported prototypes
136  *****************************************************************************/
137 static const char *const ppsz_sout_options[] = {
138     "seglen",
139     "splitanywhere",
140     "numsegs",
141     "delsegs",
142     "index",
143     "index-url",
144     "ratecontrol",
145     "caching",
146     "key-uri",
147     "key-file",
148     "generate-iv",
149     NULL
150 };
151
152 static ssize_t Write( sout_access_out_t *, block_t * );
153 static int Seek ( sout_access_out_t *, off_t  );
154 static int Control( sout_access_out_t *, int, va_list );
155
156 struct sout_access_out_sys_t
157 {
158     char *psz_cursegPath;
159     char *psz_indexPath;
160     char *psz_indexUrl;
161     mtime_t i_opendts;
162     mtime_t  i_seglenm;
163     uint32_t i_segment;
164     size_t  i_seglen;
165     float   *p_seglens;
166     block_t *block_buffer;
167     int i_handle;
168     unsigned i_numsegs;
169     unsigned i_seglens;
170     bool b_delsegs;
171     bool b_ratecontrol;
172     bool b_splitanywhere;
173     bool b_caching;
174     bool b_generate_iv;
175     uint8_t aes_ivs[16];
176     gcry_cipher_hd_t aes_ctx;
177     char *key_uri;
178 };
179
180 static int CryptSetup( sout_access_out_t *p_access );
181 /*****************************************************************************
182  * Open: open the file
183  *****************************************************************************/
184 static int Open( vlc_object_t *p_this )
185 {
186     sout_access_out_t   *p_access = (sout_access_out_t*)p_this;
187     sout_access_out_sys_t *p_sys;
188     char *psz_idx;
189
190     config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
191
192     if( !p_access->psz_path )
193     {
194         msg_Err( p_access, "no file name specified" );
195         return VLC_EGENERIC;
196     }
197
198     if( unlikely( !( p_sys = malloc ( sizeof( *p_sys ) ) ) ) )
199         return VLC_ENOMEM;
200
201     p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
202     /* Try to get within asked segment length */
203     p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen;
204     p_sys->block_buffer = NULL;
205
206     p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
207     p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
208     p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
209     p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
210     p_sys->b_caching = var_GetBool( p_access, SOUT_CFG_PREFIX "caching") ;
211     p_sys->b_generate_iv = var_GetBool( p_access, SOUT_CFG_PREFIX "generate-iv") ;
212
213
214     /* 5 elements is from harrison-stetson algorithm to start from some number
215      * if we don't have numsegs defined
216      */
217     p_sys->i_seglens = 5;
218     if( p_sys->i_numsegs )
219         p_sys->i_seglens = p_sys->i_numsegs+1;
220     p_sys->p_seglens = malloc( sizeof(float) * p_sys->i_seglens  );
221     if( unlikely( !p_sys->p_seglens ) )
222     {
223         free( p_sys );
224         return VLC_ENOMEM;
225     }
226
227     p_sys->psz_indexPath = NULL;
228     psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
229     if ( psz_idx )
230     {
231         char *psz_tmp;
232         psz_tmp = str_format_time( psz_idx );
233         free( psz_idx );
234         if ( !psz_tmp )
235         {
236             free( p_sys->p_seglens );
237             free( p_sys );
238             return VLC_ENOMEM;
239         }
240         path_sanitize( psz_tmp );
241         p_sys->psz_indexPath = psz_tmp;
242         vlc_unlink( p_sys->psz_indexPath );
243     }
244
245     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
246
247     p_access->p_sys = p_sys;
248
249     if( CryptSetup( p_access ) < 0 )
250     {
251         free( p_sys->psz_indexUrl );
252         free( p_sys->psz_indexPath );
253         free( p_sys->p_seglens );
254         free( p_sys );
255         msg_Err( p_access, "Encryption init failed" );
256         return VLC_EGENERIC;
257     }
258
259     p_sys->i_handle = -1;
260     p_sys->i_segment = 0;
261     p_sys->psz_cursegPath = NULL;
262
263     p_access->pf_write = Write;
264     p_access->pf_seek  = Seek;
265     p_access->pf_control = Control;
266
267     return VLC_SUCCESS;
268 }
269
270 /************************************************************************
271  * CryptSetup: Initialize encryption
272  ************************************************************************/
273 static int CryptSetup( sout_access_out_t *p_access )
274 {
275     sout_access_out_sys_t *p_sys = p_access->p_sys;
276     uint8_t key[16];
277
278     p_sys->key_uri = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-uri" );
279     if( !p_sys->key_uri ) /*No key uri, assume no encryption wanted*/
280     {
281         msg_Dbg( p_access, "No key uri, no encryption");
282         return VLC_SUCCESS;
283     }
284     vlc_gcrypt_init();
285
286     /*Setup encryption cipher*/
287     gcry_error_t err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
288                                          GCRY_CIPHER_MODE_CBC, 0 );
289     if( err )
290     {
291         msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
292         return VLC_EGENERIC;
293     }
294
295     char *keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
296     if( unlikely(keyfile == NULL) )
297     {
298         msg_Err( p_access, "No key-file, no encryption" );
299         return VLC_EGENERIC;
300     }
301
302     int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
303     if( unlikely( keyfd == -1 ) )
304     {
305         msg_Err( p_access, "Unable to open keyfile %s: %m", keyfile );
306         free( keyfile );
307         return VLC_EGENERIC;
308     }
309     free( keyfile );
310
311     ssize_t keylen = read( keyfd, key, 16 );
312
313     close( keyfd );
314     if( keylen < 16 )
315     {
316         msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
317         return VLC_EGENERIC;
318     }
319
320     err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
321     if(err)
322     {
323         msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
324         gcry_cipher_close( p_sys->aes_ctx);
325         return VLC_EGENERIC;
326     }
327
328     if( p_sys->b_generate_iv )
329         vlc_rand_bytes( p_sys->aes_ivs, sizeof(uint8_t)*16);
330
331     return VLC_SUCCESS;
332 }
333
334 /************************************************************************
335  * CryptKey: Set encryption IV to current segment number
336  ************************************************************************/
337 static int CryptKey( sout_access_out_t *p_access, uint32_t i_segment )
338 {
339     sout_access_out_sys_t *p_sys = p_access->p_sys;
340
341     if( !p_sys->b_generate_iv )
342     {
343         /* Use segment number as IV if randomIV isn't selected*/
344         memset( p_sys->aes_ivs, 0, 16 * sizeof(uint8_t));
345         p_sys->aes_ivs[15] = i_segment & 0xff;
346         p_sys->aes_ivs[14] = (i_segment >> 8 ) & 0xff;
347         p_sys->aes_ivs[13] = (i_segment >> 16 ) & 0xff;
348         p_sys->aes_ivs[12] = (i_segment >> 24 ) & 0xff;
349     }
350
351     gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
352                                           p_sys->aes_ivs, 16);
353     if( err )
354     {
355         msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
356         gcry_cipher_close( p_sys->aes_ctx);
357         return VLC_EGENERIC;
358     }
359     return VLC_SUCCESS;
360 }
361
362
363 #define SEG_NUMBER_PLACEHOLDER "#"
364 /*****************************************************************************
365  * formatSegmentPath: create segment path name based on seg #
366  *****************************************************************************/
367 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
368 {
369     char *psz_result;
370     char *psz_firstNumSign;
371
372     if ( ! ( psz_result  = str_format_time( psz_path ) ) )
373         return NULL;
374
375     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
376     if ( *psz_firstNumSign )
377     {
378         char *psz_newResult;
379         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
380         int ret;
381
382         *psz_firstNumSign = '\0';
383         ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
384         free ( psz_result );
385         if ( ret < 0 )
386             return NULL;
387         psz_result = psz_newResult;
388     }
389
390     if ( b_sanitize )
391         path_sanitize( psz_result );
392
393     return psz_result;
394 }
395
396 /************************************************************************
397  * updateIndexAndDel: If necessary, update index file & delete old segments
398  ************************************************************************/
399 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
400 {
401
402     uint32_t i_firstseg;
403
404     if ( p_sys->i_numsegs == 0 || p_sys->i_segment < p_sys->i_numsegs )
405     {
406         i_firstseg = 1;
407
408         if( p_sys->i_segment >= (p_sys->i_seglens-1) )
409         {
410             p_sys->i_seglens <<= 1;
411             msg_Dbg( p_access, "Segment amount %u", p_sys->i_seglens );
412             p_sys->p_seglens = realloc( p_sys->p_seglens, sizeof(float) * p_sys->i_seglens );
413             if( unlikely( !p_sys->p_seglens ) )
414              return -1;
415         }
416     }
417     else
418         i_firstseg = ( p_sys->i_segment - p_sys->i_numsegs ) + 1;
419
420     // First update index
421     if ( p_sys->psz_indexPath )
422     {
423         int val;
424         FILE *fp;
425         char *psz_idxTmp;
426         if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
427             return -1;
428
429         fp = vlc_fopen( psz_idxTmp, "wt");
430         if ( !fp )
431         {
432             msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
433             free( psz_idxTmp );
434             return -1;
435         }
436
437         if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-VERSION:3\n#EXT-X-ALLOW-CACHE:%s\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n", p_sys->i_seglen, p_sys->b_caching ? "YES" : "NO",i_firstseg ) < 0 )
438         {
439             free( psz_idxTmp );
440             fclose( fp );
441             return -1;
442         }
443
444         if( p_sys->key_uri )
445         {
446             int ret = 0;
447             if( p_sys->b_generate_iv )
448             {
449                 unsigned long long iv_hi = 0, iv_lo = 0;
450                 for( unsigned short i = 0; i < 8; i++ )
451                 {
452                     iv_hi |= p_sys->aes_ivs[i] & 0xff;
453                     iv_hi <<= 8;
454                     iv_lo |= p_sys->aes_ivs[8+i] & 0xff;
455                     iv_lo <<= 8;
456                 }
457                 ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\",IV=0X%16.16llx%16.16llx\n",
458                                p_sys->key_uri, iv_hi, iv_lo );
459
460             } else {
461                 ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", p_sys->key_uri );
462             }
463             if( ret < 0 )
464             {
465                 free( psz_idxTmp );
466                 fclose( fp );
467                 return -1;
468             }
469         }
470
471         char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
472         for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
473         {
474             char *psz_name;
475             char *psz_duration = NULL;
476             if ( ! ( psz_name = formatSegmentPath( psz_idxFormat, i, false ) ) )
477             {
478                 free( psz_idxTmp );
479                 fclose( fp );
480                 return -1;
481             }
482             if( ! ( us_asprintf( &psz_duration, "%.2f", p_sys->p_seglens[i % p_sys->i_seglens ], psz_name ) ) )
483             {
484                 free( psz_idxTmp );
485                 fclose( fp );
486                 return -1;
487             }
488             val = fprintf( fp, "#EXTINF:%s,\n%s\n", psz_duration, psz_name );
489             free( psz_duration );
490             free( psz_name );
491             if ( val < 0 )
492             {
493                 free( psz_idxTmp );
494                 fclose( fp );
495                 return -1;
496             }
497         }
498
499         if ( b_isend )
500         {
501             if ( fputs ( STR_ENDLIST, fp ) < 0)
502             {
503                 free( psz_idxTmp );
504                 fclose( fp ) ;
505                 return -1;
506             }
507
508         }
509         fclose( fp );
510
511         val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
512
513         if ( val < 0 )
514         {
515             vlc_unlink( psz_idxTmp );
516             msg_Err( p_access, "Error moving LiveHttp index file" );
517         }
518         else
519             msg_Info( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
520
521         free( psz_idxTmp );
522     }
523
524     // Then take care of deletion
525     if ( p_sys->b_delsegs && i_firstseg > 1 )
526     {
527         char *psz_name = formatSegmentPath( p_access->psz_path, i_firstseg-1, true );
528          if ( psz_name )
529          {
530              vlc_unlink( psz_name );
531              free( psz_name );
532          }
533     }
534     return 0;
535 }
536
537 /*****************************************************************************
538  * closeCurrentSegment: Close the segment file
539  *****************************************************************************/
540 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
541 {
542     if ( p_sys->i_handle >= 0 )
543     {
544         close( p_sys->i_handle );
545         p_sys->i_handle = -1;
546         if ( p_sys->psz_cursegPath )
547         {
548             msg_Info( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
549             free( p_sys->psz_cursegPath );
550             p_sys->psz_cursegPath = 0;
551             updateIndexAndDel( p_access, p_sys, b_isend );
552         }
553     }
554 }
555
556 /*****************************************************************************
557  * Close: close the target
558  *****************************************************************************/
559 static void Close( vlc_object_t * p_this )
560 {
561     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
562     sout_access_out_sys_t *p_sys = p_access->p_sys;
563
564     msg_Dbg( p_access, "Flushing buffer to last file");
565     while( p_sys->block_buffer )
566     {
567         if( p_sys->key_uri )
568         {
569             size_t original = p_sys->block_buffer->i_buffer;
570             size_t padded = (p_sys->block_buffer->i_buffer + 15 ) & ~15;
571             if( padded == p_sys->block_buffer->i_buffer )
572                 padded += 16;
573             p_sys->block_buffer = block_Realloc( p_sys->block_buffer, 0, padded );
574             if( !p_sys->block_buffer )
575                 break;
576             int pad = padded - original;
577             memset( &p_sys->block_buffer->p_buffer[original], pad, pad );
578
579             gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
580                                 p_sys->block_buffer->p_buffer, padded, NULL, 0 );
581             if( err )
582             {
583                 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
584                 break;
585             }
586
587         }
588         ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
589         if ( val == -1 )
590         {
591            if ( errno == EINTR )
592               continue;
593            block_ChainRelease ( p_sys->block_buffer);
594            break;
595         }
596         if( !p_sys->block_buffer->p_next )
597         {
598             p_sys->p_seglens[p_sys->i_segment % p_sys->i_seglens ] =
599                 (float)( p_sys->block_buffer->i_length / (1000000)) +
600                 (float)(p_sys->block_buffer->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
601         }
602
603         if ( (size_t)val >= p_sys->block_buffer->i_buffer )
604         {
605            block_t *p_next = p_sys->block_buffer->p_next;
606            block_Release (p_sys->block_buffer);
607            p_sys->block_buffer = p_next;
608         }
609         else
610         {
611            p_sys->block_buffer->p_buffer += val;
612            p_sys->block_buffer->i_buffer -= val;
613         }
614     }
615
616     closeCurrentSegment( p_access, p_sys, true );
617     free( p_sys->psz_indexUrl );
618     free( p_sys->psz_indexPath );
619     free( p_sys->p_seglens );
620     free( p_sys );
621
622     if( p_sys->key_uri )
623     {
624         gcry_cipher_close( p_sys->aes_ctx );
625         free( p_sys->key_uri );
626     }
627     msg_Dbg( p_access, "livehttp access output closed" );
628 }
629
630 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
631 {
632     sout_access_out_sys_t *p_sys = p_access->p_sys;
633
634     switch( i_query )
635     {
636         case ACCESS_OUT_CONTROLS_PACE:
637         {
638             bool *pb = va_arg( args, bool * );
639             *pb = !p_sys->b_ratecontrol;
640             //*pb = true;
641             break;
642         }
643
644         default:
645             return VLC_EGENERIC;
646     }
647     return VLC_SUCCESS;
648 }
649
650 /*****************************************************************************
651  * openNextFile: Open the segment file
652  *****************************************************************************/
653 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
654 {
655     int fd;
656
657     uint32_t i_newseg = p_sys->i_segment + 1;
658
659     char *psz_seg = formatSegmentPath( p_access->psz_path, i_newseg, true );
660     if ( !psz_seg )
661         return -1;
662
663     fd = vlc_open( psz_seg, O_WRONLY | O_CREAT | O_LARGEFILE |
664                      O_TRUNC, 0666 );
665     if ( fd == -1 )
666     {
667         msg_Err( p_access, "cannot open `%s' (%m)", psz_seg );
668         free( psz_seg );
669         return -1;
670     }
671
672     CryptKey( p_access, i_newseg );
673     msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , psz_seg, i_newseg );
674
675     //free( psz_seg );
676     p_sys->psz_cursegPath = psz_seg;
677     p_sys->i_handle = fd;
678     p_sys->i_segment = i_newseg;
679     return fd;
680 }
681
682 /*****************************************************************************
683  * Write: standard write on a file descriptor.
684  *****************************************************************************/
685 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
686 {
687     size_t i_write = 0;
688     sout_access_out_sys_t *p_sys = p_access->p_sys;
689     block_t *p_temp;
690
691     while( p_buffer )
692     {
693         if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
694         {
695             block_t *output = p_sys->block_buffer;
696             p_sys->block_buffer = NULL;
697
698
699             if( p_sys->i_handle > 0 &&
700                 ( p_buffer->i_dts - p_sys->i_opendts +
701                   p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000)
702                 ) >= p_sys->i_seglenm )
703                 closeCurrentSegment( p_access, p_sys, false );
704
705             if ( p_sys->i_handle < 0 )
706             {
707                 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
708                 if ( openNextFile( p_access, p_sys ) < 0 )
709                    return -1;
710             }
711
712             while( output )
713             {
714                 if( p_sys->key_uri )
715                 {
716                     size_t original = output->i_buffer;
717                     size_t padded = (output->i_buffer + 15 ) & ~15;
718                     if( padded == output->i_buffer )
719                         padded += 16;
720                     output = block_Realloc( output, 0, padded );
721                     if( !output )
722                         return VLC_ENOMEM;
723                     int pad = padded - original;
724                     memset( &output->p_buffer[original], pad, pad );
725
726                     gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
727                                         output->p_buffer, padded, NULL, 0 );
728                     if( err )
729                     {
730                         msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
731                         return -1;
732                     }
733
734                 }
735                 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
736                 if ( val == -1 )
737                 {
738                    if ( errno == EINTR )
739                       continue;
740                    block_ChainRelease ( p_buffer );
741                    return -1;
742                 }
743                 p_sys->p_seglens[p_sys->i_segment % p_sys->i_seglens ] =
744                     (float)output->i_length / INT64_C(1000000) +
745                     (float)(output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
746
747                 if ( (size_t)val >= output->i_buffer )
748                 {
749                    block_t *p_next = output->p_next;
750                    block_Release (output);
751                    output = p_next;
752                 }
753                 else
754                 {
755                    output->p_buffer += val;
756                    output->i_buffer -= val;
757                 }
758                 i_write += val;
759             }
760         }
761
762         p_temp = p_buffer->p_next;
763         p_buffer->p_next = NULL;
764         block_ChainAppend( &p_sys->block_buffer, p_buffer );
765         p_buffer = p_temp;
766     }
767
768     return i_write;
769 }
770
771 /*****************************************************************************
772  * Seek: seek to a specific location in a file
773  *****************************************************************************/
774 static int Seek( sout_access_out_t *p_access, off_t i_pos )
775 {
776     (void) i_pos;
777     msg_Err( p_access, "livehttp sout access cannot seek" );
778     return -1;
779 }