]> git.sesse.net Git - vlc/blob - modules/access_output/livehttp.c
livehttp: free p_sys->p_seglens if str_format_time fails
[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->p_seglens );
208             free( p_sys );
209             return VLC_ENOMEM;
210         }
211         path_sanitize( psz_tmp );
212         p_sys->psz_indexPath = psz_tmp;
213         vlc_unlink( p_sys->psz_indexPath );
214     }
215
216     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
217
218     p_access->p_sys = p_sys;
219     p_sys->i_handle = -1;
220     p_sys->i_segment = 0;
221     p_sys->psz_cursegPath = NULL;
222
223     p_access->pf_write = Write;
224     p_access->pf_seek  = Seek;
225     p_access->pf_control = Control;
226
227     return VLC_SUCCESS;
228 }
229
230 #define SEG_NUMBER_PLACEHOLDER "#"
231 /*****************************************************************************
232  * formatSegmentPath: create segment path name based on seg #
233  *****************************************************************************/
234 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
235 {
236     char *psz_result;
237     char *psz_firstNumSign;
238
239     if ( ! ( psz_result  = str_format_time( psz_path ) ) )
240         return NULL;
241
242     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
243     if ( *psz_firstNumSign ) {
244         char *psz_newResult;
245         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
246         int ret;
247
248         *psz_firstNumSign = '\0';
249         ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
250         free ( psz_result );
251         if ( ret < 0 )
252             return NULL;
253         psz_result = psz_newResult;
254     }
255
256     if ( b_sanitize )
257         path_sanitize( psz_result );
258
259     return psz_result;
260 }
261
262 /************************************************************************
263  * updateIndexAndDel: If necessary, update index file & delete old segments
264  ************************************************************************/
265 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
266 {
267
268     uint32_t i_firstseg;
269
270     if ( p_sys->i_numsegs == 0 || p_sys->i_segment < p_sys->i_numsegs )
271     {
272         i_firstseg = 1;
273
274         if( p_sys->i_segment >= (p_sys->i_seglens-1) )
275         {
276             p_sys->i_seglens <<= 1;
277             msg_Dbg( p_access, "Segment amount %u", p_sys->i_seglens );
278             p_sys->p_seglens = realloc( p_sys->p_seglens, sizeof(float) * p_sys->i_seglens );
279             if( unlikely( !p_sys->p_seglens ) )
280              return -1;
281         }
282     }
283     else
284         i_firstseg = ( p_sys->i_segment - p_sys->i_numsegs ) + 1;
285
286     // First update index
287     if ( p_sys->psz_indexPath )
288     {
289         int val;
290         FILE *fp;
291         char *psz_idxTmp;
292         if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
293             return -1;
294
295         fp = vlc_fopen( psz_idxTmp, "wt");
296         if ( !fp )
297         {
298             msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
299             free( psz_idxTmp );
300             return -1;
301         }
302
303         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 )
304         {
305             free( psz_idxTmp );
306             fclose( fp );
307             return -1;
308         }
309
310         char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
311         for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
312         {
313             char *psz_name;
314             char *psz_duration = NULL;
315             if ( ! ( psz_name = formatSegmentPath( psz_idxFormat, i, false ) ) )
316             {
317                 free( psz_idxTmp );
318                 fclose( fp );
319                 return -1;
320             }
321             if( ! ( us_asprintf( &psz_duration, "%.2f", p_sys->p_seglens[i % p_sys->i_seglens ], psz_name ) ) )
322             {
323                 free( psz_idxTmp );
324                 fclose( fp );
325                 return -1;
326             }
327             val = fprintf( fp, "#EXTINF:%s,\n%s\n", psz_duration, psz_name );
328             free( psz_duration );
329             free( psz_name );
330             if ( val < 0 )
331             {
332                 free( psz_idxTmp );
333                 fclose( fp );
334                 return -1;
335             }
336         }
337
338         if ( b_isend )
339         {
340             if ( fputs ( STR_ENDLIST, fp ) < 0)
341             {
342                 free( psz_idxTmp );
343                 fclose( fp ) ;
344                 return -1;
345             }
346
347         }
348         fclose( fp );
349
350         val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
351
352         if ( val < 0 )
353         {
354             vlc_unlink( psz_idxTmp );
355             msg_Err( p_access, "Error moving LiveHttp index file" );
356         }
357         else
358             msg_Info( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
359
360         free( psz_idxTmp );
361     }
362
363     // Then take care of deletion
364     if ( p_sys->b_delsegs && i_firstseg > 1 )
365     {
366         char *psz_name = formatSegmentPath( p_access->psz_path, i_firstseg-1, true );
367          if ( psz_name )
368          {
369              vlc_unlink( psz_name );
370              free( psz_name );
371          }
372     }
373     return 0;
374 }
375
376 /*****************************************************************************
377  * closeCurrentSegment: Close the segment file
378  *****************************************************************************/
379 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
380 {
381     if ( p_sys->i_handle >= 0 )
382     {
383         close( p_sys->i_handle );
384         p_sys->i_handle = -1;
385         if ( p_sys->psz_cursegPath )
386         {
387             msg_Info( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
388             free( p_sys->psz_cursegPath );
389             p_sys->psz_cursegPath = 0;
390             updateIndexAndDel( p_access, p_sys, b_isend );
391         }
392     }
393 }
394
395 /*****************************************************************************
396  * Close: close the target
397  *****************************************************************************/
398 static void Close( vlc_object_t * p_this )
399 {
400     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
401     sout_access_out_sys_t *p_sys = p_access->p_sys;
402
403     msg_Dbg( p_access, "Flushing buffer to last file");
404     while( p_sys->block_buffer )
405     {
406         ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
407         if ( val == -1 )
408         {
409            if ( errno == EINTR )
410               continue;
411            block_ChainRelease ( p_sys->block_buffer);
412            break;
413         }
414         if( !p_sys->block_buffer->p_next )
415         {
416             p_sys->p_seglens[p_sys->i_segment % p_sys->i_seglens ] =
417                 (float)( p_sys->block_buffer->i_length / (1000000)) +
418                 (float)(p_sys->block_buffer->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
419         }
420
421         if ( (size_t)val >= p_sys->block_buffer->i_buffer )
422         {
423            block_t *p_next = p_sys->block_buffer->p_next;
424            block_Release (p_sys->block_buffer);
425            p_sys->block_buffer = p_next;
426         }
427         else
428         {
429            p_sys->block_buffer->p_buffer += val;
430            p_sys->block_buffer->i_buffer -= val;
431         }
432     }
433
434     closeCurrentSegment( p_access, p_sys, true );
435     free( p_sys->psz_indexUrl );
436     free( p_sys->psz_indexPath );
437     free( p_sys->p_seglens );
438     free( p_sys );
439
440     msg_Dbg( p_access, "livehttp access output closed" );
441 }
442
443 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
444 {
445     sout_access_out_sys_t *p_sys = p_access->p_sys;
446
447     switch( i_query )
448     {
449         case ACCESS_OUT_CONTROLS_PACE:
450         {
451             bool *pb = va_arg( args, bool * );
452             *pb = !p_sys->b_ratecontrol;
453             //*pb = true;
454             break;
455         }
456
457         default:
458             return VLC_EGENERIC;
459     }
460     return VLC_SUCCESS;
461 }
462
463 /*****************************************************************************
464  * openNextFile: Open the segment file
465  *****************************************************************************/
466 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
467 {
468     int fd;
469
470     uint32_t i_newseg = p_sys->i_segment + 1;
471
472     char *psz_seg = formatSegmentPath( p_access->psz_path, i_newseg, true );
473     if ( !psz_seg )
474         return -1;
475
476     fd = vlc_open( psz_seg, O_WRONLY | O_CREAT | O_LARGEFILE |
477                      O_TRUNC, 0666 );
478     if ( fd == -1 )
479     {
480         msg_Err( p_access, "cannot open `%s' (%m)", psz_seg );
481         free( psz_seg );
482         return -1;
483     }
484
485     msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , psz_seg, i_newseg );
486
487     //free( psz_seg );
488     p_sys->psz_cursegPath = psz_seg;
489     p_sys->i_handle = fd;
490     p_sys->i_segment = i_newseg;
491     return fd;
492 }
493
494 /*****************************************************************************
495  * Write: standard write on a file descriptor.
496  *****************************************************************************/
497 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
498 {
499     size_t i_write = 0;
500     sout_access_out_sys_t *p_sys = p_access->p_sys;
501     block_t *p_temp;
502
503     while( p_buffer )
504     {
505         if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
506         {
507             block_t *output = p_sys->block_buffer;
508             p_sys->block_buffer = NULL;
509
510
511             if( p_sys->i_handle > 0 &&
512                 ( p_buffer->i_dts - p_sys->i_opendts +
513                   p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000)
514                 ) >= p_sys->i_seglenm )
515                 closeCurrentSegment( p_access, p_sys, false );
516
517             if ( p_sys->i_handle < 0 )
518             {
519                 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
520                 if ( openNextFile( p_access, p_sys ) < 0 )
521                    return -1;
522             }
523
524             while( output )
525             {
526                 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
527                 if ( val == -1 )
528                 {
529                    if ( errno == EINTR )
530                       continue;
531                    block_ChainRelease ( p_buffer );
532                    return -1;
533                 }
534                 p_sys->p_seglens[p_sys->i_segment % p_sys->i_seglens ] =
535                     (float)output->i_length / INT64_C(1000000) +
536                     (float)(output->i_dts - p_sys->i_opendts) / CLOCK_FREQ;
537
538                 if ( (size_t)val >= output->i_buffer )
539                 {
540                    block_t *p_next = output->p_next;
541                    block_Release (output);
542                    output = p_next;
543                 }
544                 else
545                 {
546                    output->p_buffer += val;
547                    output->i_buffer -= val;
548                 }
549                 i_write += val;
550             }
551         }
552
553         p_temp = p_buffer->p_next;
554         p_buffer->p_next = NULL;
555         block_ChainAppend( &p_sys->block_buffer, p_buffer );
556         p_buffer = p_temp;
557     }
558
559     return i_write;
560 }
561
562 /*****************************************************************************
563  * Seek: seek to a specific location in a file
564  *****************************************************************************/
565 static int Seek( sout_access_out_t *p_access, off_t i_pos )
566 {
567     (void) i_pos;
568     msg_Err( p_access, "livehttp sout access cannot seek" );
569     return -1;
570 }