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