]> git.sesse.net Git - vlc/blob - modules/access_output/livehttp.c
livehttp: take block length in account when checking segment length
[vlc] / modules / access_output / livehttp.c
1 /*****************************************************************************
2  * livehttp.c: Live HTTP Streaming
3  *****************************************************************************
4  * Copyright © 2001, 2002 VLC authors and VideoLAN
5  * Copyright © 2009-2010 by Keary Griffin
6  *
7  * Authors: Keary Griffin <kearygriffin at gmail.com>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <sys/types.h>
33 #include <time.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39
40 #include <vlc_common.h>
41 #include <vlc_plugin.h>
42 #include <vlc_sout.h>
43 #include <vlc_block.h>
44 #include <vlc_fs.h>
45 #include <vlc_strings.h>
46 #include <vlc_charset.h>
47
48 #ifndef O_LARGEFILE
49 #   define O_LARGEFILE 0
50 #endif
51
52 #define STR_ENDLIST "#EXT-X-ENDLIST\n"
53
54 #define MAX_RENAME_RETRIES        10
55
56 /*****************************************************************************
57  * Module descriptor
58  *****************************************************************************/
59 static int  Open ( vlc_object_t * );
60 static void Close( vlc_object_t * );
61
62 #define SOUT_CFG_PREFIX "sout-livehttp-"
63 #define SEGLEN_TEXT N_("Segment length")
64 #define SEGLEN_LONGTEXT N_("Length of TS stream segments")
65
66 #define SPLITANYWHERE_TEXT N_("Split segments anywhere")
67 #define SPLITANYWHERE_LONGTEXT N_("Don't require a keyframe before splitting "\
68                                 "a segment. Needed for audio only.")
69
70 #define NUMSEGS_TEXT N_("Number of segments")
71 #define NUMSEGS_LONGTEXT N_("Number of segments to include in index")
72
73 #define INDEX_TEXT N_("Index file")
74 #define INDEX_LONGTEXT N_("Path to the index file to create")
75
76 #define INDEXURL_TEXT N_("Full URL to put in index file")
77 #define INDEXURL_LONGTEXT N_("Full URL to put in index file. "\
78                           "Use #'s to represent segment number")
79
80 #define DELSEGS_TEXT N_("Delete segments")
81 #define DELSEGS_LONGTEXT N_("Delete segments when they are no longer needed")
82
83 #define RATECONTROL_TEXT N_("Use muxers rate control mechanism")
84
85 vlc_module_begin ()
86     set_description( N_("HTTP Live streaming output") )
87     set_shortname( N_("LiveHTTP" ))
88     add_shortcut( "livehttp" )
89     set_capability( "sout access", 0 )
90     set_category( CAT_SOUT )
91     set_subcategory( SUBCAT_SOUT_ACO )
92     add_integer( SOUT_CFG_PREFIX "seglen", 10, SEGLEN_TEXT, SEGLEN_LONGTEXT, true )
93     add_integer( SOUT_CFG_PREFIX "numsegs", 0, NUMSEGS_TEXT, NUMSEGS_LONGTEXT, true )
94     add_bool( SOUT_CFG_PREFIX "splitanywhere", false,
95               SPLITANYWHERE_TEXT, SPLITANYWHERE_LONGTEXT, true )
96     add_bool( SOUT_CFG_PREFIX "delsegs", true,
97               DELSEGS_TEXT, DELSEGS_LONGTEXT, true )
98     add_bool( SOUT_CFG_PREFIX "ratecontrol", false,
99               RATECONTROL_TEXT, RATECONTROL_TEXT, true )
100     add_string( SOUT_CFG_PREFIX "index", NULL,
101                 INDEX_TEXT, INDEX_LONGTEXT, true )
102     add_string( SOUT_CFG_PREFIX "index-url", NULL,
103                 INDEXURL_TEXT, INDEXURL_LONGTEXT, true )
104     set_callbacks( Open, Close )
105 vlc_module_end ()
106
107
108 /*****************************************************************************
109  * Exported prototypes
110  *****************************************************************************/
111 static const char *const ppsz_sout_options[] = {
112     "seglen",
113     "splitanywhere",
114     "numsegs",
115     "delsegs",
116     "index",
117     "index-url",
118     "ratecontrol",
119     NULL
120 };
121
122 static ssize_t Write( sout_access_out_t *, block_t * );
123 static int Seek ( sout_access_out_t *, off_t  );
124 static int Control( sout_access_out_t *, int, va_list );
125
126 struct sout_access_out_sys_t
127 {
128     char *psz_cursegPath;
129     char *psz_indexPath;
130     char *psz_indexUrl;
131     mtime_t i_opendts;
132     mtime_t  i_seglenm;
133     uint32_t i_segment;
134     size_t  i_seglen;
135     block_t *block_buffer;
136     int i_handle;
137     unsigned i_numsegs;
138     bool b_delsegs;
139     bool b_ratecontrol;
140     bool b_splitanywhere;
141 };
142
143 /*****************************************************************************
144  * Open: open the file
145  *****************************************************************************/
146 static int Open( vlc_object_t *p_this )
147 {
148     sout_access_out_t   *p_access = (sout_access_out_t*)p_this;
149     sout_access_out_sys_t *p_sys;
150     char *psz_idx;
151
152     config_ChainParse( p_access, SOUT_CFG_PREFIX, ppsz_sout_options, p_access->p_cfg );
153
154     if( !p_access->psz_path )
155     {
156         msg_Err( p_access, "no file name specified" );
157         return VLC_EGENERIC;
158     }
159
160     if( !( p_sys = malloc ( sizeof( *p_sys ) ) ) )
161         return VLC_ENOMEM;
162
163     p_sys->i_seglen = var_GetInteger( p_access, SOUT_CFG_PREFIX "seglen" );
164     /* Try to get within +-10% of asked segment length, so limit is +10% of segment length*/
165     p_sys->i_seglenm = CLOCK_FREQ * p_sys->i_seglen * 1.10;
166     p_sys->block_buffer = NULL;
167
168     p_sys->i_numsegs = var_GetInteger( p_access, SOUT_CFG_PREFIX "numsegs" );
169     p_sys->b_splitanywhere = var_GetBool( p_access, SOUT_CFG_PREFIX "splitanywhere" );
170     p_sys->b_delsegs = var_GetBool( p_access, SOUT_CFG_PREFIX "delsegs" );
171     p_sys->b_ratecontrol = var_GetBool( p_access, SOUT_CFG_PREFIX "ratecontrol") ;
172
173     p_sys->psz_indexPath = NULL;
174     psz_idx = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index" );
175     if ( psz_idx )
176     {
177         char *psz_tmp;
178         psz_tmp = str_format_time( psz_idx );
179         free( psz_idx );
180         if ( !psz_tmp )
181         {
182             free( p_sys );
183             return VLC_ENOMEM;
184         }
185         path_sanitize( psz_tmp );
186         p_sys->psz_indexPath = psz_tmp;
187         vlc_unlink( p_sys->psz_indexPath );
188     }
189
190     p_sys->psz_indexUrl = var_GetNonEmptyString( p_access, SOUT_CFG_PREFIX "index-url" );
191
192     p_access->p_sys = p_sys;
193     p_sys->i_handle = -1;
194     p_sys->i_segment = 0;
195     p_sys->psz_cursegPath = NULL;
196
197     p_access->pf_write = Write;
198     p_access->pf_seek  = Seek;
199     p_access->pf_control = Control;
200
201     return VLC_SUCCESS;
202 }
203
204 #define SEG_NUMBER_PLACEHOLDER "#"
205 /*****************************************************************************
206  * formatSegmentPath: create segment path name based on seg #
207  *****************************************************************************/
208 static char *formatSegmentPath( char *psz_path, uint32_t i_seg, bool b_sanitize )
209 {
210     char *psz_result;
211     char *psz_firstNumSign;
212
213     if ( ! ( psz_result  = str_format_time( psz_path ) ) )
214         return NULL;
215
216     psz_firstNumSign = psz_result + strcspn( psz_result, SEG_NUMBER_PLACEHOLDER );
217     if ( *psz_firstNumSign ) {
218         char *psz_newResult;
219         int i_cnt = strspn( psz_firstNumSign, SEG_NUMBER_PLACEHOLDER );
220         int ret;
221
222         *psz_firstNumSign = '\0';
223         ret = asprintf( &psz_newResult, "%s%0*d%s", psz_result, i_cnt, i_seg, psz_firstNumSign + i_cnt );
224         free ( psz_result );
225         if ( ret < 0 )
226             return NULL;
227         psz_result = psz_newResult;
228     }
229
230     if ( b_sanitize )
231         path_sanitize( psz_result );
232
233     return psz_result;
234 }
235
236 /************************************************************************
237  * updateIndexAndDel: If necessary, update index file & delete old segments
238  ************************************************************************/
239 static int updateIndexAndDel( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
240 {
241
242     uint32_t i_firstseg;
243
244     if ( p_sys->i_numsegs == 0 || p_sys->i_segment < p_sys->i_numsegs )
245         i_firstseg = 1;
246     else
247         i_firstseg = ( p_sys->i_segment - p_sys->i_numsegs ) + 1;
248
249     // First update index
250     if ( p_sys->psz_indexPath )
251     {
252         int val;
253         FILE *fp;
254         char *psz_idxTmp;
255         if ( asprintf( &psz_idxTmp, "%s.tmp", p_sys->psz_indexPath ) < 0)
256             return -1;
257
258         fp = vlc_fopen( psz_idxTmp, "wt");
259         if ( !fp )
260         {
261             msg_Err( p_access, "cannot open index file `%s'", psz_idxTmp );
262             free( psz_idxTmp );
263             return -1;
264         }
265
266         if ( fprintf( fp, "#EXTM3U\n#EXT-X-TARGETDURATION:%zu\n#EXT-X-MEDIA-SEQUENCE:%"PRIu32"\n", p_sys->i_seglen, i_firstseg ) < 0 )
267         {
268             free( psz_idxTmp );
269             fclose( fp );
270             return -1;
271         }
272
273         char *psz_idxFormat = p_sys->psz_indexUrl ? p_sys->psz_indexUrl : p_access->psz_path;
274         for ( uint32_t i = i_firstseg; i <= p_sys->i_segment; i++ )
275         {
276             char *psz_name;
277             if ( ! ( psz_name = formatSegmentPath( psz_idxFormat, i, false ) ) )
278             {
279                 free( psz_idxTmp );
280                 fclose( fp );
281                 return -1;
282             }
283             val = fprintf( fp, "#EXTINF:%zu,\n%s\n", p_sys->i_seglen, psz_name );
284             free( psz_name );
285             if ( val < 0 )
286             {
287                 free( psz_idxTmp );
288                 fclose( fp );
289                 return -1;
290             }
291         }
292
293         if ( b_isend )
294         {
295             if ( fputs ( STR_ENDLIST, fp ) < 0)
296             {
297                 free( psz_idxTmp );
298                 fclose( fp ) ;
299                 return -1;
300             }
301
302         }
303         fclose( fp );
304
305         val = vlc_rename ( psz_idxTmp, p_sys->psz_indexPath);
306
307         if ( val < 0 )
308         {
309             vlc_unlink( psz_idxTmp );
310             msg_Err( p_access, "Error moving LiveHttp index file" );
311         }
312         else
313             msg_Info( p_access, "LiveHttpIndexComplete: %s" , p_sys->psz_indexPath );
314
315         free( psz_idxTmp );
316     }
317
318     // Then take care of deletion
319     if ( p_sys->b_delsegs && i_firstseg > 1 )
320     {
321         char *psz_name = formatSegmentPath( p_access->psz_path, i_firstseg-1, true );
322          if ( psz_name )
323          {
324              vlc_unlink( psz_name );
325              free( psz_name );
326          }
327     }
328     return 0;
329 }
330
331 /*****************************************************************************
332  * closeCurrentSegment: Close the segment file
333  *****************************************************************************/
334 static void closeCurrentSegment( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys, bool b_isend )
335 {
336     if ( p_sys->i_handle >= 0 )
337     {
338         close( p_sys->i_handle );
339         p_sys->i_handle = -1;
340         if ( p_sys->psz_cursegPath )
341         {
342             msg_Info( p_access, "LiveHttpSegmentComplete: %s (%"PRIu32")" , p_sys->psz_cursegPath, p_sys->i_segment );
343             free( p_sys->psz_cursegPath );
344             p_sys->psz_cursegPath = 0;
345             updateIndexAndDel( p_access, p_sys, b_isend );
346         }
347     }
348 }
349
350 /*****************************************************************************
351  * Close: close the target
352  *****************************************************************************/
353 static void Close( vlc_object_t * p_this )
354 {
355     sout_access_out_t *p_access = (sout_access_out_t*)p_this;
356     sout_access_out_sys_t *p_sys = p_access->p_sys;
357
358     msg_Dbg( p_access, "Flushing buffer to last file");
359     while( p_sys->block_buffer )
360     {
361         ssize_t val = write( p_sys->i_handle, p_sys->block_buffer->p_buffer, p_sys->block_buffer->i_buffer );
362         if ( val == -1 )
363         {
364            if ( errno == EINTR )
365               continue;
366            block_ChainRelease ( p_sys->block_buffer);
367            break;
368         }
369
370         if ( (size_t)val >= p_sys->block_buffer->i_buffer )
371         {
372            block_t *p_next = p_sys->block_buffer->p_next;
373            block_Release (p_sys->block_buffer);
374            p_sys->block_buffer = p_next;
375         }
376         else
377         {
378            p_sys->block_buffer->p_buffer += val;
379            p_sys->block_buffer->i_buffer -= val;
380         }
381     }
382
383     closeCurrentSegment( p_access, p_sys, true );
384     free( p_sys->psz_indexUrl );
385     free( p_sys->psz_indexPath );
386     free( p_sys );
387
388     msg_Dbg( p_access, "livehttp access output closed" );
389 }
390
391 static int Control( sout_access_out_t *p_access, int i_query, va_list args )
392 {
393     sout_access_out_sys_t *p_sys = p_access->p_sys;
394
395     switch( i_query )
396     {
397         case ACCESS_OUT_CONTROLS_PACE:
398         {
399             bool *pb = va_arg( args, bool * );
400             *pb = !p_sys->b_ratecontrol;
401             //*pb = true;
402             break;
403         }
404
405         default:
406             return VLC_EGENERIC;
407     }
408     return VLC_SUCCESS;
409 }
410
411 /*****************************************************************************
412  * openNextFile: Open the segment file
413  *****************************************************************************/
414 static ssize_t openNextFile( sout_access_out_t *p_access, sout_access_out_sys_t *p_sys )
415 {
416     int fd;
417
418     uint32_t i_newseg = p_sys->i_segment + 1;
419
420     char *psz_seg = formatSegmentPath( p_access->psz_path, i_newseg, true );
421     if ( !psz_seg )
422         return -1;
423
424     fd = vlc_open( psz_seg, O_WRONLY | O_CREAT | O_LARGEFILE |
425                      O_TRUNC, 0666 );
426     if ( fd == -1 )
427     {
428         msg_Err( p_access, "cannot open `%s' (%m)", psz_seg );
429         free( psz_seg );
430         return -1;
431     }
432
433     msg_Dbg( p_access, "Successfully opened livehttp file: %s (%"PRIu32")" , psz_seg, i_newseg );
434
435     //free( psz_seg );
436     p_sys->psz_cursegPath = psz_seg;
437     p_sys->i_handle = fd;
438     p_sys->i_segment = i_newseg;
439     return fd;
440 }
441
442 /*****************************************************************************
443  * Write: standard write on a file descriptor.
444  *****************************************************************************/
445 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
446 {
447     size_t i_write = 0;
448     sout_access_out_sys_t *p_sys = p_access->p_sys;
449     block_t *p_temp;
450
451     while( p_buffer )
452     {
453         if ( ( p_sys->b_splitanywhere || ( p_buffer->i_flags & BLOCK_FLAG_HEADER ) ) )
454         {
455             block_t *output = p_sys->block_buffer;
456             p_sys->block_buffer = NULL;
457
458
459             if( p_sys->i_handle > 0 &&
460                 ( p_buffer->i_dts - p_sys->i_opendts +
461                   p_buffer->i_length * CLOCK_FREQ / INT64_C(1000000)
462                 ) >= p_sys->i_seglenm )
463                 closeCurrentSegment( p_access, p_sys, false );
464
465             if ( p_sys->i_handle < 0 )
466             {
467                 p_sys->i_opendts = output ? output->i_dts : p_buffer->i_dts;
468                 if ( openNextFile( p_access, p_sys ) < 0 )
469                    return -1;
470             }
471
472             while( output )
473             {
474                 ssize_t val = write( p_sys->i_handle, output->p_buffer, output->i_buffer );
475                 if ( val == -1 )
476                 {
477                    if ( errno == EINTR )
478                       continue;
479                    block_ChainRelease ( p_buffer );
480                    return -1;
481                 }
482
483                 if ( (size_t)val >= output->i_buffer )
484                 {
485                    block_t *p_next = output->p_next;
486                    block_Release (output);
487                    output = p_next;
488                 }
489                 else
490                 {
491                    output->p_buffer += val;
492                    output->i_buffer -= val;
493                 }
494                 i_write += val;
495             }
496         }
497
498         p_temp = p_buffer->p_next;
499         p_buffer->p_next = NULL;
500         block_ChainAppend( &p_sys->block_buffer, p_buffer );
501         p_buffer = p_temp;
502     }
503
504     return i_write;
505 }
506
507 /*****************************************************************************
508  * Seek: seek to a specific location in a file
509  *****************************************************************************/
510 static int Seek( sout_access_out_t *p_access, off_t i_pos )
511 {
512     (void) i_pos;
513     msg_Err( p_access, "livehttp sout access cannot seek" );
514     return -1;
515 }