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