1 /*****************************************************************************
2 * livehttp.c: Live HTTP Streaming
3 *****************************************************************************
4 * Copyright © 2001, 2002, 2013 VLC authors and VideoLAN
5 * Copyright © 2009-2010 by Keary Griffin
7 * Authors: Keary Griffin <kearygriffin at gmail.com>
8 * Ilkka Ollakka <ileoo at videolan dot org>
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.
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.
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 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
33 #include <sys/types.h>
41 #include <vlc_common.h>
42 #include <vlc_plugin.h>
44 #include <vlc_block.h>
46 #include <vlc_strings.h>
47 #include <vlc_charset.h>
50 #include <vlc_gcrypt.h>
53 # define O_LARGEFILE 0
56 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
58 #define MAX_RENAME_RETRIES 10
60 /*****************************************************************************
62 *****************************************************************************/
63 static int Open ( vlc_object_t * );
64 static void Close( vlc_object_t * );
66 #define SOUT_CFG_PREFIX "sout-livehttp-"
67 #define SEGLEN_TEXT N_("Segment length")
68 #define SEGLEN_LONGTEXT N_("Length of TS stream segments")
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.")
74 #define NUMSEGS_TEXT N_("Number of segments")
75 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
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")
80 #define INDEX_TEXT N_("Index file")
81 #define INDEX_LONGTEXT N_("Path to the index file to create")
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")
87 #define DELSEGS_TEXT N_("Delete segments")
88 #define DELSEGS_LONGTEXT N_("Delete segments when they are no longer needed")
90 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
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")
95 #define KEYFILE_TEXT N_("AES key file")
96 #define KEYFILE_LONGTEXT N_("File containing the 16 bytes encryption key")
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 )
127 /*****************************************************************************
128 * Exported prototypes
129 *****************************************************************************/
130 static const char *const ppsz_sout_options[] = {
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 );
148 struct sout_access_out_sys_t
150 char *psz_cursegPath;
158 block_t *block_buffer;
164 bool b_splitanywhere;
167 gcry_cipher_hd_t aes_ctx;
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 )
177 sout_access_out_t *p_access = (sout_access_out_t*)p_this;
178 sout_access_out_sys_t *p_sys;
181 config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
183 if( !p_access->psz_path )
185 msg_Err( p_access, "no file name specified" );
189 if( unlikely( !( p_sys = malloc ( sizeof( *p_sys ) ) ) ) )
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;
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") ;
204 /* 5 elements is from harrison-stetson algorithm to start from some number
205 * if we don't have numsegs defined
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 ) )
217 p_sys->psz_indexPath = NULL;
218 psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
222 psz_tmp = str_format_time( psz_idx );
226 free( p_sys->p_seglens );
230 path_sanitize( psz_tmp );
231 p_sys->psz_indexPath = psz_tmp;
232 vlc_unlink( p_sys->psz_indexPath );
235 p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
237 p_access->p_sys = p_sys;
239 if( CryptSetup( p_access ) < 0 )
241 free( p_sys->psz_indexUrl );
242 free( p_sys->psz_indexPath );
243 free( p_sys->p_seglens );
245 msg_Err( p_access, "Encryption init failed" );
249 p_sys->i_handle = -1;
250 p_sys->i_segment = 0;
251 p_sys->psz_cursegPath = NULL;
253 p_access->pf_write = Write;
254 p_access->pf_seek = Seek;
255 p_access->pf_control = Control;
260 /************************************************************************
261 * CryptSetup: Initialize encryption
262 ************************************************************************/
263 static int CryptSetup( sout_access_out_t *p_access )
265 sout_access_out_sys_t *p_sys = p_access->p_sys;
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*/
271 msg_Dbg( p_access, "No key uri, no encryption");
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 );
281 msg_Err( p_access, "Openin AES Cipher failed: %s", gpg_strerror(err));
285 char *keyfile = var_InheritString( p_access, SOUT_CFG_PREFIX "key-file" );
286 if( unlikely(keyfile == NULL) )
288 msg_Err( p_access, "No key-file, no encryption" );
292 int keyfd = vlc_open( keyfile, O_RDONLY | O_NONBLOCK );
293 if( unlikely( keyfd == -1 ) )
295 msg_Err( p_access, "Unable to open keyfile %s: %m", keyfile );
301 ssize_t keylen = read( keyfd, key, 16 );
306 msg_Err( p_access, "No key at least 16 octects (you provided %zd), no encryption", keylen );
310 err = gcry_cipher_setkey( p_sys->aes_ctx, key, 16 );
313 msg_Err(p_access, "Setting AES key failed: %s", gpg_strerror(err));
314 gcry_cipher_close( p_sys->aes_ctx);
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 )
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;
333 gcry_error_t err = gcry_cipher_setiv( p_sys->aes_ctx,
337 msg_Err(p_access, "Setting AES IVs failed: %s", gpg_strerror(err) );
338 gcry_cipher_close( p_sys->aes_ctx);
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 )
352 char *psz_firstNumSign;
354 if ( ! ( psz_result = str_format_time( psz_path ) ) )
357 psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
358 if ( *psz_firstNumSign )
361 int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
364 *psz_firstNumSign = '\0';
365 ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
369 psz_result = psz_newResult;
373 path_sanitize( psz_result );
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 )
386 if ( p_sys->i_numsegs == 0 || p_sys->i_segment < p_sys->i_numsegs )
390 if( p_sys->i_segment >= (p_sys->i_seglens-1) )
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 ) )
400 i_firstseg = ( p_sys->i_segment - p_sys->i_numsegs ) + 1;
402 // First update index
403 if ( p_sys->psz_indexPath )
408 if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
411 fp = vlc_fopen( psz_idxTmp, "wt");
414 msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
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 )
428 if( fprintf( fp, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"\n", p_sys->key_uri ) < 0 )
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++ )
440 char *psz_duration = NULL;
441 if ( ! ( psz_name = formatSegmentPath( psz_idxFormat, i, false ) ) )
447 if( ! ( us_asprintf( &psz_duration, "%.2f", p_sys->p_seglens[i % p_sys->i_seglens ], psz_name ) ) )
453 val = fprintf( fp, "#EXTINF:%s,\n%s\n", psz_duration, psz_name );
454 free( psz_duration );
466 if ( fputs ( STR_ENDLIST, fp ) < 0)
476 val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
480 vlc_unlink( psz_idxTmp );
481 msg_Err( p_access, "Error moving LiveHttp index file" );
484 msg_Info( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
489 // Then take care of deletion
490 if ( p_sys->b_delsegs && i_firstseg > 1 )
492 char *psz_name = formatSegmentPath( p_access->psz_path, i_firstseg-1, true );
495 vlc_unlink( psz_name );
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 )
507 if ( p_sys->i_handle >= 0 )
509 close( p_sys->i_handle );
510 p_sys->i_handle = -1;
511 if ( p_sys->psz_cursegPath )
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 );
521 /*****************************************************************************
522 * Close: close the target
523 *****************************************************************************/
524 static void Close( vlc_object_t * p_this )
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;
529 msg_Dbg( p_access, "Flushing buffer to last file");
530 while( p_sys->block_buffer )
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 )
538 p_sys->block_buffer = block_Realloc( p_sys->block_buffer, 0, padded );
539 if( !p_sys->block_buffer )
541 int pad = padded - original;
542 memset( &p_sys->block_buffer->p_buffer[original], pad, pad );
544 gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
545 p_sys->block_buffer->p_buffer, padded, NULL, 0 );
548 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
553 ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
556 if ( errno == EINTR )
558 block_ChainRelease ( p_sys->block_buffer);
561 if( !p_sys->block_buffer->p_next )
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;
568 if ( (size_t)val >= p_sys->block_buffer->i_buffer )
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;
576 p_sys->block_buffer->p_buffer += val;
577 p_sys->block_buffer->i_buffer -= val;
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 );
589 gcry_cipher_close( p_sys->aes_ctx );
590 free( p_sys->key_uri );
592 msg_Dbg( p_access, "livehttp access output closed" );
595 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
597 sout_access_out_sys_t *p_sys = p_access->p_sys;
601 case ACCESS_OUT_CONTROLS_PACE:
603 bool *pb = va_arg( args, bool * );
604 *pb = !p_sys->b_ratecontrol;
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 )
622 uint32_t i_newseg = p_sys->i_segment + 1;
624 char *psz_seg = formatSegmentPath( p_access->psz_path, i_newseg, true );
628 fd = vlc_open( psz_seg, O_WRONLY | O_CREAT | O_LARGEFILE |
632 msg_Err( p_access, "cannot open `%s' (%m)", psz_seg );
637 CryptKey( p_access, i_newseg );
638 msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , psz_seg, i_newseg );
641 p_sys->psz_cursegPath = psz_seg;
642 p_sys->i_handle = fd;
643 p_sys->i_segment = i_newseg;
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 )
653 sout_access_out_sys_t *p_sys = p_access->p_sys;
658 if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
660 block_t *output = p_sys->block_buffer;
661 p_sys->block_buffer = NULL;
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 );
670 if ( p_sys->i_handle < 0 )
672 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
673 if ( openNextFile( p_access, p_sys ) < 0 )
681 size_t original = output->i_buffer;
682 size_t padded = (output->i_buffer + 15 ) & ~15;
683 if( padded == output->i_buffer )
685 output = block_Realloc( output, 0, padded );
688 int pad = padded - original;
689 memset( &output->p_buffer[original], pad, pad );
691 gcry_error_t err = gcry_cipher_encrypt( p_sys->aes_ctx,
692 output->p_buffer, padded, NULL, 0 );
695 msg_Err( p_access, "Encryption failure: %s ", gpg_strerror(err) );
700 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
703 if ( errno == EINTR )
705 block_ChainRelease ( p_buffer );
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;
712 if ( (size_t)val >= output->i_buffer )
714 block_t *p_next = output->p_next;
715 block_Release (output);
720 output->p_buffer += val;
721 output->i_buffer -= val;
727 p_temp = p_buffer->p_next;
728 p_buffer->p_next = NULL;
729 block_ChainAppend( &p_sys->block_buffer, p_buffer );
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 )
742 msg_Err( p_access, "livehttp sout access cannot seek" );