]> git.sesse.net Git - vlc/blob - modules/access_output/livehttp.c
livehttp: set caching disabled for default
[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 #ifndef O_LARGEFILE
50 #   define O_LARGEFILE 0
51 #endif
52
53 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
54
55 #define MAX_RENAME_RETRIES        10
56
57 /*****************************************************************************
58  * Module descriptor
59  *****************************************************************************/
60 static int  Open ( vlc_object_t * );
61 static void Close( vlc_object_t * );
62
63 #define SOUT_CFG_PREFIX "sout-livehttp-"
64 #define SEGLEN_TEXT N_("Segment length")
65 #define SEGLEN_LONGTEXT N_("Length of TS stream segments")
66
67 #define SPLITANYWHERE_TEXT N_("Split segments anywhere")
68 #define SPLITANYWHERE_LONGTEXT N_("Don't require a keyframe before splitting "\
69                                 "a segment. Needed for audio only.")
70
71 #define NUMSEGS_TEXT N_("Number of segments")
72 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
73
74 #define NOCACHE_TEXT N_("Allow cache")
75 #define NOCACHE_LONGTEXT N_("Add EXT-X-ALLOW-CACHE:NO directive in playlist-file if this is disabled")
76
77 #define INDEX_TEXT N_("Index file")
78 #define INDEX_LONGTEXT N_("Path to the index file to create")
79
80 #define INDEXURL_TEXT N_("Full URL to put in index file")
81 #define INDEXURL_LONGTEXT N_("Full URL to put in index file. "\
82                           "Use #'s to represent segment number")
83
84 #define DELSEGS_TEXT N_("Delete segments")
85 #define DELSEGS_LONGTEXT N_("Delete segments when they are no longer needed")
86
87 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
88
89 vlc_module_begin ()
90     set_description( N_("HTTP Live streaming output") )
91     set_shortname( N_("LiveHTTP" ))
92     add_shortcut( "livehttp" )
93     set_capability( "sout access", 0 )
94     set_category( CAT_SOUT )
95     set_subcategory( SUBCAT_SOUT_ACO )
96     add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, false )
97     add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, false )
98     add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
99               SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
100     add_bool( SOUT_CFG_PREFIX "delsegs", true,
101               DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
102     add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
103               RATECONTROL_TEXT, RATECONTROL_TEXT, true )
104     add_bool( SOUT_CFG_PREFIX "caching", false,
105               NOCACHE_TEXT, NOCACHE_LONGTEXT, true )
106     add_string( SOUT_CFG_PREFIX "index", NULL,
107                 INDEX_TEXT, INDEX_LONGTEXT, false )
108     add_string( SOUT_CFG_PREFIX "index-url", NULL,
109                 INDEXURL_TEXT, INDEXURL_LONGTEXT, false )
110     set_callbacks( Open, Close )
111 vlc_module_end ()
112
113
114 /*****************************************************************************
115  * Exported prototypes
116  *****************************************************************************/
117 static const char *const ppsz_sout_options[] = {
118     "seglen",
119     "splitanywhere",
120     "numsegs",
121     "delsegs",
122     "index",
123     "index-url",
124     "ratecontrol",
125     "caching",
126     NULL
127 };
128
129 static ssize_t Write( sout_access_out_t *, block_t * );
130 static int Seek ( sout_access_out_t *, off_t  );
131 static int Control( sout_access_out_t *, int, va_list );
132
133 struct sout_access_out_sys_t
134 {
135     char *psz_cursegPath;
136     char *psz_indexPath;
137     char *psz_indexUrl;
138     mtime_t i_opendts;
139     mtime_t  i_seglenm;
140     uint32_t i_segment;
141     size_t  i_seglen;
142     float   *p_seglens;
143     block_t *block_buffer;
144     int i_handle;
145     unsigned i_numsegs;
146     unsigned i_seglens;
147     bool b_delsegs;
148     bool b_ratecontrol;
149     bool b_splitanywhere;
150     bool b_caching;
151 };
152
153 /*****************************************************************************
154  * Open: open the file
155  *****************************************************************************/
156 static int Open( vlc_object_t *p_this )
157 {
158     sout_access_out_t   *p_access = (sout_access_out_t*)p_this;
159     sout_access_out_sys_t *p_sys;
160     char *psz_idx;
161
162     config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
163
164     if( !p_access->psz_path )
165     {
166         msg_Err( p_access, "no file name specified" );
167         return VLC_EGENERIC;
168     }
169
170     if( unlikely( !( p_sys = malloc ( sizeof( *p_sys ) ) ) ) )
171         return VLC_ENOMEM;
172
173     p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
174     /* Try to get within asked segment length */
175     p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen;
176     p_sys->block_buffer = NULL;
177
178     p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
179     p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
180     p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
181     p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
182     p_sys->b_caching = var_GetBool( p_access, SOUT_CFG_PREFIX "caching") ;
183
184
185     /* 5 elements is from harrison-stetson algorithm to start from some number
186      * if we don't have numsegs defined
187      */
188     p_sys->i_seglens = 5;
189     if( p_sys->i_numsegs )
190         p_sys->i_seglens = p_sys->i_numsegs+1;
191     p_sys->p_seglens = malloc( sizeof(float) * p_sys->i_seglens  );
192     if( unlikely( !p_sys->p_seglens ) )
193     {
194         free( p_sys );
195         return VLC_ENOMEM;
196     }
197
198     p_sys->psz_indexPath = NULL;
199     psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
200     if ( psz_idx )
201     {
202         char *psz_tmp;
203         psz_tmp = str_format_time( psz_idx );
204         free( psz_idx );
205         if ( !psz_tmp )
206         {
207             free( p_sys );
208             return VLC_ENOMEM;
209         }
210         path_sanitize( psz_tmp );
211         p_sys->psz_indexPath = psz_tmp;
212         vlc_unlink( p_sys->psz_indexPath );
213     }
214
215     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
216
217     p_access->p_sys = p_sys;
218     p_sys->i_handle = -1;
219     p_sys->i_segment = 0;
220     p_sys->psz_cursegPath = NULL;
221
222     p_access->pf_write = Write;
223     p_access->pf_seek  = Seek;
224     p_access->pf_control = Control;
225
226     return VLC_SUCCESS;
227 }
228
229 #define SEG_NUMBER_PLACEHOLDER "#"
230 /*****************************************************************************
231  * formatSegmentPath: create segment path name based on seg #
232  *****************************************************************************/
233 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
234 {
235     char *psz_result;
236     char *psz_firstNumSign;
237
238     if ( ! ( psz_result  = str_format_time( psz_path ) ) )
239         return NULL;
240
241     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
242     if ( *psz_firstNumSign ) {
243         char *psz_newResult;
244         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
245         int ret;
246
247         *psz_firstNumSign = '\0';
248         ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
249         free ( psz_result );
250         if ( ret < 0 )
251             return NULL;
252         psz_result = psz_newResult;
253     }
254
255     if ( b_sanitize )
256         path_sanitize( psz_result );
257
258     return psz_result;
259 }
260
261 /************************************************************************
262  * updateIndexAndDel: If necessary, update index file & delete old segments
263  ************************************************************************/
264 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
265 {
266
267     uint32_t i_firstseg;
268
269     if ( p_sys->i_numsegs == 0 || p_sys->i_segment < p_sys->i_numsegs )
270     {
271         i_firstseg = 1;
272
273         if( p_sys->i_segment >= (p_sys->i_seglens-1) )
274         {
275             p_sys->i_seglens <<= 1;
276             msg_Dbg( p_access, "Segment amount %u", p_sys->i_seglens );
277             p_sys->p_seglens = realloc( p_sys->p_seglens, sizeof(float) * p_sys->i_seglens );
278             if( unlikely( !p_sys->p_seglens ) )
279              return -1;
280         }
281     }
282     else
283         i_firstseg = ( p_sys->i_segment - p_sys->i_numsegs ) + 1;
284
285     // First update index
286     if ( p_sys->psz_indexPath )
287     {
288         int val;
289         FILE *fp;
290         char *psz_idxTmp;
291         if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
292             return -1;
293
294         fp = vlc_fopen( psz_idxTmp, "wt");
295         if ( !fp )
296         {
297             msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
298             free( psz_idxTmp );
299             return -1;
300         }
301
302         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 )
303         {
304             free( psz_idxTmp );
305             fclose( fp );
306             return -1;
307         }
308
309         char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
310         for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
311         {
312             char *psz_name;
313             char *psz_duration = NULL;
314             if ( ! ( psz_name = formatSegmentPath( psz_idxFormat, i, false ) ) )
315             {
316                 free( psz_idxTmp );
317                 fclose( fp );
318                 return -1;
319             }
320             if( ! ( us_asprintf( &psz_duration, "%.2f", p_sys->p_seglens[i % p_sys->i_seglens ], psz_name ) ) )
321             {
322                 free( psz_idxTmp );
323                 fclose( fp );
324                 return -1;
325             }
326             val = fprintf( fp, "#EXTINF:%s,\n%s\n", psz_duration, psz_name );
327             free( psz_duration );
328             free( psz_name );
329             if ( val < 0 )
330             {
331                 free( psz_idxTmp );
332                 fclose( fp );
333                 return -1;
334             }
335         }
336
337         if ( b_isend )
338         {
339             if ( fputs ( STR_ENDLIST, fp ) < 0)
340             {
341                 free( psz_idxTmp );
342                 fclose( fp ) ;
343                 return -1;
344             }
345
346         }
347         fclose( fp );
348
349         val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
350
351         if ( val < 0 )
352         {
353             vlc_unlink( psz_idxTmp );
354             msg_Err( p_access, "Error moving LiveHttp index file" );
355         }
356         else
357             msg_Info( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
358
359         free( psz_idxTmp );
360     }
361
362     // Then take care of deletion
363     if ( p_sys->b_delsegs && i_firstseg > 1 )
364     {
365         char *psz_name = formatSegmentPath( p_access->psz_path, i_firstseg-1, true );
366          if ( psz_name )
367          {
368              vlc_unlink( psz_name );
369              free( psz_name );
370          }
371     }
372     return 0;
373 }
374
375 /*****************************************************************************
376  * closeCurrentSegment: Close the segment file
377  *****************************************************************************/
378 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
379 {
380     if ( p_sys->i_handle >= 0 )
381     {
382         close( p_sys->i_handle );
383         p_sys->i_handle = -1;
384         if ( p_sys->psz_cursegPath )
385         {
386             msg_Info( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
387             free( p_sys->psz_cursegPath );
388             p_sys->psz_cursegPath = 0;
389             updateIndexAndDel( p_access, p_sys, b_isend );
390         }
391     }
392 }
393
394 /*****************************************************************************
395  * Close: close the target
396  *****************************************************************************/
397 static void Close( vlc_object_t * p_this )
398 {
399     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
400     sout_access_out_sys_t *p_sys = p_access->p_sys;
401
402     msg_Dbg( p_access, "Flushing buffer to last file");
403     while( p_sys->block_buffer )
404     {
405         ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
406         if ( val == -1 )
407         {
408            if ( errno == EINTR )
409               continue;
410            block_ChainRelease ( p_sys->block_buffer);
411            break;
412         }
413         if( !p_sys->block_buffer->p_next )
414         {
415             p_sys->p_seglens[p_sys->i_segment % p_sys->i_seglens ] =
416                 (float)( p_sys->block_buffer->i_length / (1000000)) +
417                 (float)(p_sys->block_buffer->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
418         }
419
420         if ( (size_t)val >= p_sys->block_buffer->i_buffer )
421         {
422            block_t *p_next = p_sys->block_buffer->p_next;
423            block_Release (p_sys->block_buffer);
424            p_sys->block_buffer = p_next;
425         }
426         else
427         {
428            p_sys->block_buffer->p_buffer += val;
429            p_sys->block_buffer->i_buffer -= val;
430         }
431     }
432
433     closeCurrentSegment( p_access, p_sys, true );
434     free( p_sys->psz_indexUrl );
435     free( p_sys->psz_indexPath );
436     free( p_sys->p_seglens );
437     free( p_sys );
438
439     msg_Dbg( p_access, "livehttp access output closed" );
440 }
441
442 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
443 {
444     sout_access_out_sys_t *p_sys = p_access->p_sys;
445
446     switch( i_query )
447     {
448         case ACCESS_OUT_CONTROLS_PACE:
449         {
450             bool *pb = va_arg( args, bool * );
451             *pb = !p_sys->b_ratecontrol;
452             //*pb = true;
453             break;
454         }
455
456         default:
457             return VLC_EGENERIC;
458     }
459     return VLC_SUCCESS;
460 }
461
462 /*****************************************************************************
463  * openNextFile: Open the segment file
464  *****************************************************************************/
465 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
466 {
467     int fd;
468
469     uint32_t i_newseg = p_sys->i_segment + 1;
470
471     char *psz_seg = formatSegmentPath( p_access->psz_path, i_newseg, true );
472     if ( !psz_seg )
473         return -1;
474
475     fd = vlc_open( psz_seg, O_WRONLY | O_CREAT | O_LARGEFILE |
476                      O_TRUNC, 0666 );
477     if ( fd == -1 )
478     {
479         msg_Err( p_access, "cannot open `%s' (%m)", psz_seg );
480         free( psz_seg );
481         return -1;
482     }
483
484     msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , psz_seg, i_newseg );
485
486     //free( psz_seg );
487     p_sys->psz_cursegPath = psz_seg;
488     p_sys->i_handle = fd;
489     p_sys->i_segment = i_newseg;
490     return fd;
491 }
492
493 /*****************************************************************************
494  * Write: standard write on a file descriptor.
495  *****************************************************************************/
496 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
497 {
498     size_t i_write = 0;
499     sout_access_out_sys_t *p_sys = p_access->p_sys;
500     block_t *p_temp;
501
502     while( p_buffer )
503     {
504         if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
505         {
506             block_t *output = p_sys->block_buffer;
507             p_sys->block_buffer = NULL;
508
509
510             if( p_sys->i_handle > 0 &&
511                 ( p_buffer->i_dts - p_sys->i_opendts +
512                   p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000)
513                 ) >= p_sys->i_seglenm )
514                 closeCurrentSegment( p_access, p_sys, false );
515
516             if ( p_sys->i_handle < 0 )
517             {
518                 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
519                 if ( openNextFile( p_access, p_sys ) < 0 )
520                    return -1;
521             }
522
523             while( output )
524             {
525                 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
526                 if ( val == -1 )
527                 {
528                    if ( errno == EINTR )
529                       continue;
530                    block_ChainRelease ( p_buffer );
531                    return -1;
532                 }
533                 p_sys->p_seglens[p_sys->i_segment % p_sys->i_seglens ] =
534                     (float)output->i_length / INT64_C(1000000) +
535                     (float)(output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
536
537                 if ( (size_t)val >= output->i_buffer )
538                 {
539                    block_t *p_next = output->p_next;
540                    block_Release (output);
541                    output = p_next;
542                 }
543                 else
544                 {
545                    output->p_buffer += val;
546                    output->i_buffer -= val;
547                 }
548                 i_write += val;
549             }
550         }
551
552         p_temp = p_buffer->p_next;
553         p_buffer->p_next = NULL;
554         block_ChainAppend( &p_sys->block_buffer, p_buffer );
555         p_buffer = p_temp;
556     }
557
558     return i_write;
559 }
560
561 /*****************************************************************************
562  * Seek: seek to a specific location in a file
563  *****************************************************************************/
564 static int Seek( sout_access_out_t *p_access, off_t i_pos )
565 {
566     (void) i_pos;
567     msg_Err( p_access, "livehttp sout access cannot seek" );
568     return -1;
569 }