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