]> git.sesse.net Git - vlc/blobdiff - modules/access_output/livehttp.c
livehttp: use vlc_array to store segment info
[vlc] / modules / access_output / livehttp.c
index 52a383d4a23975d0c0a1e69fb208cb886533e739..677b92cd6a0dede8640e22a80a5465f69d9a490f 100644 (file)
@@ -1,10 +1,11 @@
 /*****************************************************************************
  * livehttp.c: Live HTTP Streaming
  *****************************************************************************
- * Copyright © 2001, 2002 VLC authors and VideoLAN
+ * Copyright © 2001, 2002, 2013 VLC authors and VideoLAN
  * Copyright © 2009-2010 by Keary Griffin
  *
  * Authors: Keary Griffin <kearygriffin at gmail.com>
+ *          Ilkka Ollakka <ileoo at videolan dot org>
  *
  * This program is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as published by
@@ -33,6 +34,9 @@
 #include <time.h>
 #include <fcntl.h>
 #include <errno.h>
+#ifdef HAVE_UNISTD_H
+# include <unistd.h>
+#endif
 
 #include <vlc_common.h>
 #include <vlc_plugin.h>
 #include <vlc_strings.h>
 #include <vlc_charset.h>
 
+#include <gcrypt.h>
+#include <vlc_gcrypt.h>
+
+#include <vlc_rand.h>
+
 #ifndef O_LARGEFILE
 #   define O_LARGEFILE 0
 #endif
@@ -67,6 +76,9 @@ static void Close( vlc_object_t * );
 #define NUMSEGS_TEXT N_("Number of segments")
 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
 
+#define NOCACHE_TEXT N_("Allow cache")
+#define NOCACHE_LONGTEXT N_("Add EXT-X-ALLOW-CACHE:NO directive in playlist-file if this is disabled")
+
 #define INDEX_TEXT N_("Index file")
 #define INDEX_LONGTEXT N_("Path to the index file to create")
 
@@ -79,6 +91,15 @@ static void Close( vlc_object_t * );
 
 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
 
+#define KEYURI_TEXT N_("AES key URI to place in playlist")
+#define KEYURI_LONGTEXT N_("Location from where client will retrieve the stream decryption key")
+
+#define KEYFILE_TEXT N_("AES key file")
+#define KEYFILE_LONGTEXT N_("File containing the 16 bytes encryption key")
+
+#define RANDOMIV_TEXT N_("Use randomized IV for encryption")
+#define RANDOMIV_LONGTEXT N_("Generate IV instead using segment-number as IV")
+
 vlc_module_begin ()
     set_description( N_("HTTP Live streaming output") )
     set_shortname( N_("LiveHTTP" ))
@@ -86,18 +107,26 @@ vlc_module_begin ()
     set_capability( "sout access", 0 )
     set_category( CAT_SOUT )
     set_subcategory( SUBCAT_SOUT_ACO )
-    add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, true )
-    add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, true )
+    add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, false )
+    add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, false )
     add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
               SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
     add_bool( SOUT_CFG_PREFIX "delsegs", true,
               DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
     add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
               RATECONTROL_TEXT, RATECONTROL_TEXT, true )
+    add_bool( SOUT_CFG_PREFIX "caching", false,
+              NOCACHE_TEXT, NOCACHE_LONGTEXT, true )
+    add_bool( SOUT_CFG_PREFIX "generate-iv", false,
+              RANDOMIV_TEXT, RANDOMIV_LONGTEXT, true )
     add_string( SOUT_CFG_PREFIX "index", NULL,
-                INDEX_TEXT, INDEX_LONGTEXT, true )
+                INDEX_TEXT, INDEX_LONGTEXT, false )
     add_string( SOUT_CFG_PREFIX "index-url", NULL,
-                INDEXURL_TEXT, INDEXURL_LONGTEXT, true )
+                INDEXURL_TEXT, INDEXURL_LONGTEXT, false )
+    add_string( SOUT_CFG_PREFIX "key-uri", NULL,
+                KEYURI_TEXT, KEYURI_TEXT, true )
+    add_loadfile( SOUT_CFG_PREFIX "key-file", NULL,
+                KEYFILE_TEXT, KEYFILE_LONGTEXT, true )
     set_callbacks( Open, Close )
 vlc_module_end ()
 
@@ -113,6 +142,10 @@ static const char *const ppsz_sout_options[] = {
     "index",
     "index-url",
     "ratecontrol",
+    "caching",
+    "key-uri",
+    "key-file",
+    "generate-iv",
     NULL
 };
 
@@ -120,6 +153,15 @@ static ssize_t Write( sout_access_out_t *, block_t * );
 static int Seek ( sout_access_out_t *, off_t  );
 static int Control( sout_access_out_t *, int, va_list );
 
+typedef struct output_segment
+{
+    char *psz_filename;
+    char *psz_uri;
+    char *psz_key_uri;
+    char *psz_duration;
+    uint32_t i_segment_number;
+} output_segment_t;
+
 struct sout_access_out_sys_t
 {
     char *psz_cursegPath;
@@ -129,13 +171,24 @@ struct sout_access_out_sys_t
     mtime_t  i_seglenm;
     uint32_t i_segment;
     size_t  i_seglen;
+    float   f_seglen;
+    block_t *block_buffer;
     int i_handle;
     unsigned i_numsegs;
     bool b_delsegs;
     bool b_ratecontrol;
     bool b_splitanywhere;
+    bool b_caching;
+    bool b_generate_iv;
+    uint8_t aes_ivs[16];
+    gcry_cipher_hd_t aes_ctx;
+    char *key_uri;
+    uint8_t stuffing_bytes[16];
+    ssize_t stuffing_size;
+    vlc_array_t *segments_t;
 };
 
+static int CryptSetup( sout_access_out_t *p_access );
 /*****************************************************************************
  * Open: open the file
  *****************************************************************************/
@@ -153,23 +206,31 @@ static int Open( vlc_object_t *p_this )
         return VLC_EGENERIC;
     }
 
-    if( !( p_sys = malloc ( sizeof( *p_sys ) ) ) )
+    if( unlikely( !( p_sys = malloc ( sizeof( *p_sys ) ) ) ) )
         return VLC_ENOMEM;
 
     p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
+    /* Try to get within asked segment length */
     p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen;
+    p_sys->block_buffer = NULL;
 
     p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
     p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
     p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
     p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
+    p_sys->b_caching = var_GetBool( p_access, SOUT_CFG_PREFIX "caching") ;
+    p_sys->b_generate_iv = var_GetBool( p_access, SOUT_CFG_PREFIX "generate-iv") ;
+
+    p_sys->segments_t = vlc_array_new();
+
+    p_sys->stuffing_size = 0;
 
     p_sys->psz_indexPath = NULL;
     psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
     if ( psz_idx )
     {
         char *psz_tmp;
-        psz_tmp = str_format( p_access, psz_idx );
+        psz_tmp = str_format_time( psz_idx );
         free( psz_idx );
         if ( !psz_tmp )
         {
@@ -184,6 +245,16 @@ static int Open( vlc_object_t *p_this )
     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
 
     p_access->p_sys = p_sys;
+
+    if( CryptSetup( p_access ) < 0 )
+    {
+        free( p_sys->psz_indexUrl );
+        free( p_sys->psz_indexPath );
+        free( p_sys );
+        msg_Err( p_access, "Encryption init failed" );
+        return VLC_EGENERIC;
+    }
+
     p_sys->i_handle = -1;
     p_sys->i_segment = 0;
     p_sys->psz_cursegPath = NULL;
@@ -195,20 +266,114 @@ static int Open( vlc_object_t *p_this )
     return VLC_SUCCESS;
 }
 
+/************************************************************************
+ * CryptSetup: Initialize encryption
+ ************************************************************************/
+static int CryptSetup( sout_access_out_t *p_access )
+{
+    sout_access_out_sys_t *p_sys = p_access->p_sys;
+    uint8_t key[16];
+
+    p_sys->key_uri = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "key-uri" );
+    if( !p_sys->key_uri ) /*No key uri, assume no encryption wanted*/
+    {
+        msg_Dbg( p_access, "No key uri, no encryption");
+        return VLC_SUCCESS;
+    }
+    vlc_gcrypt_init();
+
+    /*Setup encryption cipher*/
+    gcry_error_t err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
+                                         GCRY_CIPHER_MODE_CBC, 0 );
+    if( err )
+    {
+        msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
+        return VLC_EGENERIC;
+    }
+
+    char *keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
+    if( unlikely(keyfile == NULL) )
+    {
+        msg_Err( p_access, "No key-file, no encryption" );
+        return VLC_EGENERIC;
+    }
+
+    int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
+    if( unlikely( keyfd == -1 ) )
+    {
+        msg_Err( p_access, "Unable to open keyfile %s: %m", keyfile );
+        free( keyfile );
+        return VLC_EGENERIC;
+    }
+    free( keyfile );
+
+    ssize_t keylen = read( keyfd, key, 16 );
+
+    close( keyfd );
+    if( keylen < 16 )
+    {
+        msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
+        return VLC_EGENERIC;
+    }
+
+    err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
+    if(err)
+    {
+        msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
+        gcry_cipher_close( p_sys->aes_ctx);
+        return VLC_EGENERIC;
+    }
+
+    if( p_sys->b_generate_iv )
+        vlc_rand_bytes( p_sys->aes_ivs, sizeof(uint8_t)*16);
+
+    return VLC_SUCCESS;
+}
+
+/************************************************************************
+ * CryptKey: Set encryption IV to current segment number
+ ************************************************************************/
+static int CryptKey( sout_access_out_t *p_access, uint32_t i_segment )
+{
+    sout_access_out_sys_t *p_sys = p_access->p_sys;
+
+    if( !p_sys->b_generate_iv )
+    {
+        /* Use segment number as IV if randomIV isn't selected*/
+        memset( p_sys->aes_ivs, 0, 16 * sizeof(uint8_t));
+        p_sys->aes_ivs[15] = i_segment & 0xff;
+        p_sys->aes_ivs[14] = (i_segment >> 8 ) & 0xff;
+        p_sys->aes_ivs[13] = (i_segment >> 16 ) & 0xff;
+        p_sys->aes_ivs[12] = (i_segment >> 24 ) & 0xff;
+    }
+
+    gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
+                                          p_sys->aes_ivs, 16);
+    if( err )
+    {
+        msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
+        gcry_cipher_close( p_sys->aes_ctx);
+        return VLC_EGENERIC;
+    }
+    return VLC_SUCCESS;
+}
+
+
 #define SEG_NUMBER_PLACEHOLDER "#"
 /*****************************************************************************
  * formatSegmentPath: create segment path name based on seg #
  *****************************************************************************/
-static char *formatSegmentPath( sout_access_out_t *p_access, char *psz_path, uint32_t i_seg, bool b_sanitize )
+static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
 {
     char *psz_result;
     char *psz_firstNumSign;
 
-    if ( ! ( psz_result  = str_format( p_access, psz_path ) ) )
+    if ( ! ( psz_result  = str_format_time( psz_path ) ) )
         return NULL;
 
     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
-    if ( *psz_firstNumSign ) {
+    if ( *psz_firstNumSign )
+    {
         char *psz_newResult;
         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
         int ret;
@@ -227,6 +392,15 @@ static char *formatSegmentPath( sout_access_out_t *p_access, char *psz_path, uin
     return psz_result;
 }
 
+static void destroySegment( output_segment_t *segment )
+{
+    free( segment->psz_filename );
+    free( segment->psz_duration );
+    free( segment->psz_uri );
+    free( segment->psz_key_uri );
+    free( segment );
+}
+
 /************************************************************************
  * updateIndexAndDel: If necessary, update index file & delete old segments
  ************************************************************************/
@@ -257,28 +431,54 @@ static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t
             return -1;
         }
 
-        if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n", p_sys->i_seglen, i_firstseg ) < 0 )
+        if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-VERSION:3\n#EXT-X-ALLOW-CACHE:%s"
+                          "%s\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n", p_sys->i_seglen,
+                          p_sys->b_caching ? "YES" : "NO",
+                          p_sys->i_numsegs > 0 ? "" : b_isend ? "\n#EXT-X-PLAYLIST-TYPE:VOD" : "\n#EXT-X-PLAYLIST-TYPE:EVENT",
+                          i_firstseg ) < 0 )
         {
             free( psz_idxTmp );
             fclose( fp );
             return -1;
         }
 
-        char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
-        for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
+        if( p_sys->key_uri )
         {
-            char *psz_name;
-            if ( ! ( psz_name = formatSegmentPath( p_access, psz_idxFormat, i, false ) ) )
+            int ret = 0;
+            if( p_sys->b_generate_iv )
+            {
+                unsigned long long iv_hi = 0, iv_lo = 0;
+                for( unsigned short i = 0; i < 8; i++ )
+                {
+                    iv_hi |= p_sys->aes_ivs[i] & 0xff;
+                    iv_hi <<= 8;
+                    iv_lo |= p_sys->aes_ivs[8+i] & 0xff;
+                    iv_lo <<= 8;
+                }
+                ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\",IV=0X%16.16llx%16.16llx\n",
+                               p_sys->key_uri, iv_hi, iv_lo );
+
+            } else {
+                ret = fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", p_sys->key_uri );
+            }
+            if( ret < 0 )
             {
                 free( psz_idxTmp );
                 fclose( fp );
                 return -1;
             }
-            val = fprintf( fp, "#EXTINF:%zu,\n%s\n", p_sys->i_seglen, psz_name );
-            free( psz_name );
+        }
+
+        for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
+        {
+            //scale to 0..numsegs-1
+            uint32_t index = i-i_firstseg;
+
+            output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, index );
+
+            val = fprintf( fp, "#EXTINF:%s,\n%s\n", segment->psz_duration, segment->psz_uri);
             if ( val < 0 )
             {
-                free( psz_idxTmp );
                 fclose( fp );
                 return -1;
             }
@@ -304,21 +504,24 @@ static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t
             msg_Err( p_access, "Error moving LiveHttp index file" );
         }
         else
-            msg_Info( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
+            msg_Dbg( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
 
         free( psz_idxTmp );
     }
 
     // Then take care of deletion
-    if ( p_sys->b_delsegs && i_firstseg > 1 )
+    while( p_sys->b_delsegs && p_sys->i_numsegs && ( (vlc_array_count( p_sys->segments_t ) ) >= p_sys->i_numsegs ) )
     {
-        char *psz_name = formatSegmentPath( p_access, p_access->psz_path, i_firstseg-1, true );
-         if ( psz_name )
+         output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
+         vlc_array_remove( p_sys->segments_t, 0 );
+         if ( segment->psz_filename )
          {
-             vlc_unlink( psz_name );
-             free( psz_name );
+             vlc_unlink( segment->psz_filename );
          }
+         destroySegment( segment );
     }
+
+
     return 0;
 }
 
@@ -329,11 +532,39 @@ static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sy
 {
     if ( p_sys->i_handle >= 0 )
     {
+        output_segment_t *segment = (output_segment_t *)vlc_array_item_at_index( p_sys->segments_t, vlc_array_count( p_sys->segments_t ) - 1 );
+
+        if( p_sys->key_uri )
+        {
+            size_t pad = 16 - p_sys->stuffing_size;
+            memset(&p_sys->stuffing_bytes[p_sys->stuffing_size], pad, pad);
+            gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx, p_sys->stuffing_bytes, 16, NULL, 0 );
+
+            if( err ) {
+               msg_Err( p_access, "Couldn't encrypt 16 bytes: %s", gpg_strerror(err) );
+            } else {
+            int ret = write( p_sys->i_handle, p_sys->stuffing_bytes, 16 );
+            if( ret != 16 )
+                msg_Err( p_access, "Couldn't write 16 bytes" );
+            }
+            p_sys->stuffing_size = 0;
+        }
+
+
         close( p_sys->i_handle );
         p_sys->i_handle = -1;
+
+        if( ! ( us_asprintf( &segment->psz_duration, "%.2f", p_sys->f_seglen ) ) )
+        {
+            msg_Err( p_access, "Couldn't set duration on closed segment");
+            return;
+        }
+
+        segment->i_segment_number = p_sys->i_segment;
+
         if ( p_sys->psz_cursegPath )
         {
-            msg_Info( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
+            msg_Dbg( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
             free( p_sys->psz_cursegPath );
             p_sys->psz_cursegPath = 0;
             updateIndexAndDel( p_access, p_sys, b_isend );
@@ -349,8 +580,83 @@ static void Close( vlc_object_t * p_this )
     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
     sout_access_out_sys_t *p_sys = p_access->p_sys;
 
+    msg_Dbg( p_access, "Flushing buffer to last file");
+    bool crypted = false;
+    while( p_sys->block_buffer )
+    {
+        if( p_sys->key_uri && !crypted)
+        {
+            if( p_sys->stuffing_size )
+            {
+                p_sys->block_buffer = block_Realloc( p_sys->block_buffer, p_sys->stuffing_size, p_sys->block_buffer->i_buffer );
+                if( unlikely(!p_sys->block_buffer) )
+                    return;
+                memcpy( p_sys->block_buffer->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
+                p_sys->stuffing_size = 0;
+            }
+            size_t original = p_sys->block_buffer->i_buffer;
+            size_t padded = (original + 15 ) & ~15;
+            size_t pad = padded - original;
+            if( pad )
+            {
+                p_sys->stuffing_size = 16 - pad;
+                p_sys->block_buffer->i_buffer -= p_sys->stuffing_size;
+                memcpy( p_sys->stuffing_bytes, &p_sys->block_buffer->p_buffer[p_sys->block_buffer->i_buffer], p_sys->stuffing_size );
+            }
+
+            gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
+                                p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer, NULL, 0 );
+            if( err )
+            {
+                msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
+                break;
+            }
+            crypted = true;
+        }
+        ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
+        if ( val == -1 )
+        {
+           if ( errno == EINTR )
+              continue;
+           block_ChainRelease ( p_sys->block_buffer);
+           break;
+        }
+        if( !p_sys->block_buffer->p_next )
+        {
+            p_sys->f_seglen = (float)( p_sys->block_buffer->i_length / (1000000)) +
+                               (float)(p_sys->block_buffer->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
+        }
+
+        if ( likely( (size_t)val >= p_sys->block_buffer->i_buffer ) )
+        {
+           block_t *p_next = p_sys->block_buffer->p_next;
+           block_Release (p_sys->block_buffer);
+           p_sys->block_buffer = p_next;
+           crypted=false;
+        }
+        else
+        {
+           p_sys->block_buffer->p_buffer += val;
+           p_sys->block_buffer->i_buffer -= val;
+        }
+    }
 
     closeCurrentSegment( p_access, p_sys, true );
+
+    if( p_sys->key_uri )
+    {
+        gcry_cipher_close( p_sys->aes_ctx );
+        free( p_sys->key_uri );
+    }
+
+    while( vlc_array_count( p_sys->segments_t ) > 0 )
+    {
+        output_segment_t *segment = vlc_array_item_at_index( p_sys->segments_t, 0 );
+        vlc_array_remove( p_sys->segments_t, 0 );
+        destroySegment( segment );
+    }
+    vlc_array_destroy( p_sys->segments_t );
+
     free( p_sys->psz_indexUrl );
     free( p_sys->psz_indexPath );
     free( p_sys );
@@ -387,23 +693,45 @@ static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t
 
     uint32_t i_newseg = p_sys->i_segment + 1;
 
-    char *psz_seg = formatSegmentPath( p_access, p_access->psz_path, i_newseg, true );
-    if ( !psz_seg )
+    /* Create segment and fill it info that we can (everything excluding duration */
+    output_segment_t *segment = (output_segment_t*)malloc(sizeof(output_segment_t));
+    if( unlikely( !segment ) )
         return -1;
 
-    fd = vlc_open( psz_seg, O_WRONLY | O_CREAT | O_LARGEFILE |
+    memset( segment, 0 , sizeof( output_segment_t ) );
+
+    segment->i_segment_number = i_newseg;
+    segment->psz_filename = formatSegmentPath( p_access->psz_path, i_newseg, true );
+    char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
+    segment->psz_uri = formatSegmentPath( psz_idxFormat , i_newseg, true );
+
+    if ( unlikely( !segment->psz_filename ) )
+    {
+        msg_Err( p_access, "Format segmentpath failed");
+        return -1;
+    }
+
+
+
+    fd = vlc_open( segment->psz_filename, O_WRONLY | O_CREAT | O_LARGEFILE |
                      O_TRUNC, 0666 );
     if ( fd == -1 )
     {
-        msg_Err( p_access, "cannot open `%s' (%m)", psz_seg );
-        free( psz_seg );
+        msg_Err( p_access, "cannot open `%s' (%m)", segment->psz_filename );
+        destroySegment( segment );
         return -1;
     }
 
-    msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , psz_seg, i_newseg );
+    vlc_array_append( p_sys->segments_t, segment);
 
-    //free( psz_seg );
-    p_sys->psz_cursegPath = psz_seg;
+    if( p_sys->key_uri )
+    {
+        segment->psz_key_uri = strdup( p_sys->key_uri );
+        CryptKey( p_access, i_newseg );
+    }
+    msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , segment->psz_filename, i_newseg );
+
+    p_sys->psz_cursegPath = strdup(segment->psz_filename);
     p_sys->i_handle = fd;
     p_sys->i_segment = i_newseg;
     return fd;
@@ -416,42 +744,96 @@ static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
 {
     size_t i_write = 0;
     sout_access_out_sys_t *p_sys = p_access->p_sys;
+    block_t *p_temp;
 
     while( p_buffer )
     {
-        if ( p_sys->i_handle >= 0 && ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_TYPE_I ) ) && ( p_buffer->i_dts-p_sys->i_opendts ) > p_sys->i_seglenm )
-        {
-            closeCurrentSegment( p_access, p_sys, false );
-        }
-        if ( p_buffer->i_buffer > 0 && p_sys->i_handle < 0 )
+        if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
         {
-            p_sys->i_opendts = p_buffer->i_dts;
-            if ( openNextFile( p_access, p_sys ) < 0 )
-                return -1;
-        }
-        ssize_t val = write ( p_sys->i_handle,
-                             p_buffer->p_buffer, p_buffer->i_buffer );
-        if ( val == -1 )
-        {
-            if ( errno == EINTR )
-                continue;
-            block_ChainRelease ( p_buffer );
-            return -1;
-        }
+            bool crypted = false;
+            block_t *output = p_sys->block_buffer;
+            p_sys->block_buffer = NULL;
 
-        if ( (size_t)val >= p_buffer->i_buffer )
-        {
-            block_t *p_next = p_buffer->p_next;
-            block_Release (p_buffer);
-            p_buffer = p_next;
-        }
-        else
-        {
-            p_buffer->p_buffer += val;
-            p_buffer->i_buffer -= val;
+
+            if( p_sys->i_handle > 0 &&
+                ( p_buffer->i_dts - p_sys->i_opendts +
+                  p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000)
+                ) >= p_sys->i_seglenm )
+                closeCurrentSegment( p_access, p_sys, false );
+
+            if ( p_sys->i_handle < 0 )
+            {
+                p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
+                if ( openNextFile( p_access, p_sys ) < 0 )
+                   return -1;
+            }
+
+            while( output )
+            {
+                if( p_sys->key_uri && !crypted )
+                {
+                    if( p_sys->stuffing_size )
+                    {
+                        output = block_Realloc( output, p_sys->stuffing_size, output->i_buffer );
+                        if( unlikely(!output ) )
+                            return VLC_ENOMEM;
+                        memcpy( output->p_buffer, p_sys->stuffing_bytes, p_sys->stuffing_size );
+                        p_sys->stuffing_size = 0;
+                    }
+                    size_t original = output->i_buffer;
+                    size_t padded = (output->i_buffer + 15 ) & ~15;
+                    size_t pad = padded - original;
+                    if( pad )
+                    {
+                        p_sys->stuffing_size = 16-pad;
+                        output->i_buffer -= p_sys->stuffing_size;
+                        memcpy(p_sys->stuffing_bytes, &output->p_buffer[output->i_buffer], p_sys->stuffing_size);
+                    }
+
+                    gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
+                                        output->p_buffer, output->i_buffer, NULL, 0 );
+                    if( err )
+                    {
+                        msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
+                        return -1;
+                    }
+                    crypted=true;
+
+                }
+                ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
+                if ( val == -1 )
+                {
+                   if ( errno == EINTR )
+                      continue;
+                   block_ChainRelease ( p_buffer );
+                   return -1;
+                }
+                p_sys->f_seglen =
+                    (float)output->i_length / INT64_C(1000000) +
+                    (float)(output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
+
+                if ( (size_t)val >= output->i_buffer )
+                {
+                   block_t *p_next = output->p_next;
+                   block_Release (output);
+                   output = p_next;
+                   crypted=false;
+                }
+                else
+                {
+                   output->p_buffer += val;
+                   output->i_buffer -= val;
+                }
+                i_write += val;
+            }
         }
-        i_write += val;
+
+        p_temp = p_buffer->p_next;
+        p_buffer->p_next = NULL;
+        block_ChainAppend( &p_sys->block_buffer, p_buffer );
+        p_buffer = p_temp;
     }
+
     return i_write;
 }