]> git.sesse.net Git - vlc/blob - modules/access_filter/timeshift.c
e2e39bb686eb73982fb8deb1b34be16c73fbbb1e
[vlc] / modules / access_filter / timeshift.c
1 /*****************************************************************************
2  * timeshift.c: access filter implementing timeshifting capabilities
3  *****************************************************************************
4  * Copyright (C) 2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 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 General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34
35 #include <errno.h>
36
37 #include <vlc_access.h>
38 #include <vlc_charset.h>
39 #include <vlc_input.h>
40
41 #include <unistd.h>
42
43 #ifdef WIN32
44 #  include <direct.h>                                        /* _wgetcwd  */
45 #endif
46
47 /*****************************************************************************
48  * Module descriptor
49  *****************************************************************************/
50 static int  Open ( vlc_object_t * );
51 static void Close( vlc_object_t * );
52
53 #define GRANULARITY_TEXT N_("Timeshift granularity")
54 /// \bug [String] typo
55 #define GRANULARITY_LONGTEXT N_( "This is the size of the temporary files " \
56   "that will be used to store the timeshifted streams." )
57 #define DIR_TEXT N_("Timeshift directory")
58 #define DIR_LONGTEXT N_( "Directory used to store the timeshift temporary " \
59   "files." )
60 #define FORCE_TEXT N_("Force use of the timeshift module")
61 #define FORCE_LONGTEXT N_("Force use of the timeshift module even if the " \
62   "access declares that it can control pace or pause." )
63
64 vlc_module_begin();
65     set_shortname( N_("Timeshift") );
66     set_description( N_("Timeshift") );
67     set_category( CAT_INPUT );
68     set_subcategory( SUBCAT_INPUT_ACCESS_FILTER );
69     set_capability( "access_filter", 0 );
70     add_shortcut( "timeshift" );
71     set_callbacks( Open, Close );
72
73     add_integer( "timeshift-granularity", 50, NULL, GRANULARITY_TEXT,
74                  GRANULARITY_LONGTEXT, true );
75     add_directory( "timeshift-dir", 0, 0, DIR_TEXT, DIR_LONGTEXT, false );
76         change_unsafe();
77     add_bool( "timeshift-force", false, NULL, FORCE_TEXT, FORCE_LONGTEXT,
78               false );
79 vlc_module_end();
80
81 /*****************************************************************************
82  * Local prototypes
83  *****************************************************************************/
84
85 static int      Seek( access_t *, int64_t );
86 static block_t *Block  ( access_t *p_access );
87 static int      Control( access_t *, int i_query, va_list args );
88 static void*    Thread ( vlc_object_t *p_this );
89 static int      WriteBlockToFile( access_t *p_access, block_t *p_block );
90 static block_t *ReadBlockFromFile( access_t *p_access );
91 static char    *GetTmpFilePath( access_t *p_access );
92
93 #define TIMESHIFT_FIFO_MAX (10*1024*1024)
94 #define TIMESHIFT_FIFO_MIN (TIMESHIFT_FIFO_MAX/4)
95 #define TMP_FILE_MAX 256
96
97 typedef struct ts_entry_t
98 {
99     FILE *file;
100     struct ts_entry_t *p_next;
101
102 } ts_entry_t;
103
104 struct access_sys_t
105 {
106     block_fifo_t *p_fifo;
107
108     unsigned  i_files;
109     unsigned  i_file_size;
110     unsigned  i_write_size;
111
112     ts_entry_t *p_read_list;
113     ts_entry_t **pp_read_last;
114     ts_entry_t *p_write_list;
115     ts_entry_t **pp_write_last;
116
117     char *psz_filename_base;
118     char *psz_filename;
119
120     int64_t i_data;
121 };
122
123 /*****************************************************************************
124  * Open:
125  *****************************************************************************/
126 static int Open( vlc_object_t *p_this )
127 {
128     access_t *p_access = (access_t*)p_this;
129     access_t *p_src = p_access->p_source;
130     access_sys_t *p_sys;
131     bool b_bool;
132
133     var_Create( p_access, "timeshift-force", VLC_VAR_BOOL|VLC_VAR_DOINHERIT );
134     if( var_GetBool( p_access, "timeshift-force" ) )
135     {
136         msg_Dbg( p_access, "Forcing use of timeshift even if access can control pace or pause" );
137     }
138     else
139     {
140         /* Only work with not pace controled access */
141         if( access_Control( p_src, ACCESS_CAN_CONTROL_PACE, &b_bool ) ||
142             b_bool )
143         {
144             msg_Dbg( p_src, "ACCESS_CAN_CONTROL_PACE: timeshift useless" );
145             return VLC_EGENERIC;
146         }
147         /* Refuse access that can be paused */
148         if( access_Control( p_src, ACCESS_CAN_PAUSE, &b_bool ) || b_bool )
149         {
150             msg_Dbg( p_src, "ACCESS_CAN_PAUSE: timeshift useless" );
151             return VLC_EGENERIC;
152         }
153     }
154
155     /* */
156     p_access->pf_read = NULL;
157     p_access->pf_block = Block;
158     p_access->pf_seek = Seek;
159     p_access->pf_control = Control;
160     p_access->info = p_src->info;
161
162     p_access->p_sys = p_sys = malloc( sizeof( access_sys_t ) );
163     if( !p_sys )
164         return VLC_ENOMEM;
165
166     /* */
167     p_sys->p_fifo = block_FifoNew();
168     p_sys->i_write_size = 0;
169     p_sys->i_files = 0;
170     p_sys->i_data = 0;
171
172     p_sys->p_read_list = NULL;
173     p_sys->pp_read_last = &p_sys->p_read_list;
174     p_sys->p_write_list = NULL;
175     p_sys->pp_write_last = &p_sys->p_write_list;
176
177     var_Create( p_access, "timeshift-dir",
178                 VLC_VAR_DIRECTORY | VLC_VAR_DOINHERIT );
179     var_Create( p_access, "timeshift-granularity",
180                 VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
181     p_sys->i_file_size = var_GetInteger( p_access, "timeshift-granularity" );
182     if( p_sys->i_file_size < 1 ) p_sys->i_file_size = 1;
183     p_sys->i_file_size *= 1024 * 1024; /* In MBytes */
184
185     p_sys->psz_filename_base = GetTmpFilePath( p_access );
186     p_sys->psz_filename = malloc( strlen( p_sys->psz_filename_base ) + 1000 );
187
188     if( vlc_thread_create( p_access, "timeshift thread", Thread,
189                            VLC_THREAD_PRIORITY_LOW, false ) )
190     {
191         Close( p_this );
192         msg_Err( p_access, "cannot spawn timeshift access thread" );
193         return VLC_EGENERIC;
194     }
195
196     return VLC_SUCCESS;
197 }
198
199 /*****************************************************************************
200  * Close:
201  *****************************************************************************/
202 static void Close( vlc_object_t *p_this )
203 {
204     access_t     *p_access = (access_t*)p_this;
205     access_sys_t *p_sys = p_access->p_sys;
206     ts_entry_t *p_entry;
207     unsigned i;
208
209     msg_Dbg( p_access, "timeshift close called" );
210     vlc_thread_join( p_access );
211
212     for( p_entry = p_sys->p_write_list; p_entry; )
213     {
214         ts_entry_t *p_next = p_entry->p_next;
215         fclose( p_entry->file );
216         free( p_entry );
217         p_entry = p_next;
218     }
219     for( p_entry = p_sys->p_read_list; p_entry; )
220     {
221         ts_entry_t *p_next = p_entry->p_next;
222         fclose( p_entry->file );
223         free( p_entry );
224         p_entry = p_next;
225     }
226     for( i = 0; i < p_sys->i_files; i++ )
227     {
228         sprintf( p_sys->psz_filename, "%s%i.dat",
229                  p_sys->psz_filename_base, i );
230         unlink( p_sys->psz_filename );
231     }
232
233     free( p_sys->psz_filename );
234     free( p_sys->psz_filename_base );
235     block_FifoRelease( p_sys->p_fifo );
236     free( p_sys );
237 }
238
239 /*****************************************************************************
240  *
241  *****************************************************************************/
242 static block_t *Block( access_t *p_access )
243 {
244     access_sys_t *p_sys = p_access->p_sys;
245     access_t *p_src = p_access->p_source;
246     block_t *p_block = NULL;
247
248     /* Update info (we probably ought to be time caching that as well) */
249     if( p_src->info.i_update & INPUT_UPDATE_META )
250     {
251         p_src->info.i_update &= ~INPUT_UPDATE_META;
252         p_access->info.i_update |= INPUT_UPDATE_META;
253     }
254
255     /* Get data from timeshift fifo */
256     if( !p_access->info.b_eof )
257         p_block = block_FifoGet( p_sys->p_fifo );
258
259     if( p_block && !p_block->i_buffer ) /* Used to signal EOF */
260     { block_Release( p_block ); p_block = 0; }
261
262     if( p_block )
263     {
264         p_sys->i_data -= p_block->i_buffer;
265         return p_block;
266     }
267
268     p_access->info.b_eof = p_src->info.b_eof;
269     return NULL;
270 }
271
272 /*****************************************************************************
273  *
274  *****************************************************************************/
275 static void* Thread( vlc_object_t* p_this )
276 {
277     access_t *p_access = (access_t*)p_this;
278     access_sys_t *p_sys = p_access->p_sys;
279     access_t     *p_src = p_access->p_source;
280     block_t      *p_block;
281
282     while( vlc_object_alive (p_access) )
283     {
284         /* Get a new block from the source */
285         if( p_src->pf_block )
286         {
287             p_block = p_src->pf_block( p_src );
288         }
289         else
290         {
291             int i_read;
292
293             if( ( p_block = block_New( p_access, 2048 ) ) == NULL ) break;
294
295             i_read = p_src->pf_read( p_src, p_block->p_buffer, 2048 );
296             if( i_read <= 0 )
297             {
298               block_Release( p_block );
299               p_block = NULL;
300             }
301             p_block->i_buffer = i_read;
302         }
303
304         if( p_block == NULL )
305         {
306           if( p_src->info.b_eof ) break;
307           msleep( 10000 );
308           continue;
309         }
310
311         p_sys->i_data += p_block->i_buffer;
312
313         /* Write block */
314         if( !p_sys->p_write_list && !p_sys->p_read_list &&
315             block_FifoSize( p_sys->p_fifo ) < TIMESHIFT_FIFO_MAX )
316         {
317             /* If there isn't too much timeshifted data,
318              * write directly to FIFO */
319             block_FifoPut( p_sys->p_fifo, p_block );
320             continue;
321         }
322
323         WriteBlockToFile( p_access, p_block );
324         block_Release( p_block );
325
326         /* Read from file to fill up the fifo */
327         while( block_FifoSize( p_sys->p_fifo ) < TIMESHIFT_FIFO_MIN &&
328                vlc_object_alive (p_access) )
329         {
330             p_block = ReadBlockFromFile( p_access );
331             if( !p_block ) break;
332
333             block_FifoPut( p_sys->p_fifo, p_block );
334         }
335     }
336
337     msg_Dbg( p_access, "timeshift: no more input data" );
338
339     while( vlc_object_alive (p_access) &&
340            (p_sys->p_read_list || block_FifoSize( p_sys->p_fifo ) ) )
341     {
342         /* Read from file to fill up the fifo */
343         while( block_FifoSize( p_sys->p_fifo ) < TIMESHIFT_FIFO_MIN &&
344                vlc_object_alive (p_access) && p_sys->p_read_list )
345         {
346             p_block = ReadBlockFromFile( p_access );
347             if( !p_block ) break;
348
349             block_FifoPut( p_sys->p_fifo, p_block );
350         }
351
352         msleep( 100000 );
353     }
354
355     msg_Dbg( p_access, "timeshift: EOF" );
356     p_src->info.b_eof = true;
357
358     /* Send dummy packet to avoid deadlock in Block() */
359     block_FifoPut( p_sys->p_fifo, block_New( p_access, 0 ) );
360     return NULL;
361 }
362
363 /*****************************************************************************
364  * NextFileWrite:
365  *****************************************************************************/
366 static void NextFileWrite( access_t *p_access )
367 {
368     access_sys_t *p_sys = p_access->p_sys;
369     ts_entry_t   *p_next;
370
371     if( !p_sys->p_write_list )
372     {
373         p_sys->i_write_size = 0;
374         return;
375     }
376
377     p_next = p_sys->p_write_list->p_next;
378
379     /* Put written file in read list */
380     if( p_sys->i_write_size < p_sys->i_file_size )
381         if( ftruncate( fileno( p_sys->p_write_list->file ),
382                        p_sys->i_write_size ) == -1 )
383         {
384             msg_Dbg( p_access, "unable to truncate file: %m" );
385             /* return; */
386         }
387
388     fseek( p_sys->p_write_list->file, 0, SEEK_SET );
389     *p_sys->pp_read_last = p_sys->p_write_list;
390     p_sys->pp_read_last = &p_sys->p_write_list->p_next;
391     p_sys->p_write_list->p_next = 0;
392
393     /* Switch to next file to write */
394     p_sys->p_write_list = p_next;
395     if( !p_sys->p_write_list ) p_sys->pp_write_last = &p_sys->p_write_list;
396
397     p_sys->i_write_size = 0;
398 }
399
400 /*****************************************************************************
401  * NextFileRead:
402  *****************************************************************************/
403 static void NextFileRead( access_t *p_access )
404 {
405     access_sys_t *p_sys = p_access->p_sys;
406     ts_entry_t   *p_next;
407
408     if( !p_sys->p_read_list ) return;
409
410     p_next = p_sys->p_read_list->p_next;
411
412     /* Put read file in write list */
413     fseek( p_sys->p_read_list->file, 0, SEEK_SET );
414     *p_sys->pp_write_last = p_sys->p_read_list;
415     p_sys->pp_write_last = &p_sys->p_read_list->p_next;
416     p_sys->p_read_list->p_next = 0;
417
418     /* Switch to next file to read */
419     p_sys->p_read_list = p_next;
420     if( !p_sys->p_read_list ) p_sys->pp_read_last = &p_sys->p_read_list;
421 }
422
423 /*****************************************************************************
424  * WriteBlockToFile:
425  *****************************************************************************/
426 static int WriteBlockToFile( access_t *p_access, block_t *p_block )
427 {
428     access_sys_t *p_sys = p_access->p_sys;
429     int i_write, i_buffer;
430
431     if( p_sys->i_write_size == p_sys->i_file_size ) NextFileWrite( p_access );
432
433     /* Open new file if necessary */
434     if( !p_sys->p_write_list )
435     {
436         FILE *file;
437
438         sprintf( p_sys->psz_filename, "%s%u.dat",
439                  p_sys->psz_filename_base, p_sys->i_files );
440         file = utf8_fopen( p_sys->psz_filename, "w+b" );
441
442         if( !file && p_sys->i_files < 2 )
443         {
444             /* We just can't work with less than 2 buffer files */
445             msg_Err( p_access, "cannot open temporary file '%s' (%m)",
446                      p_sys->psz_filename );
447             return VLC_EGENERIC;
448         }
449         else if( !file ) return VLC_EGENERIC;
450
451         p_sys->p_write_list = malloc( sizeof(ts_entry_t) );
452         p_sys->p_write_list->p_next = 0;
453         p_sys->p_write_list->file = file;
454         p_sys->pp_write_last = &p_sys->p_write_list->p_next;
455
456         p_sys->i_files++;
457     }
458
459     /* Write to file */
460     i_buffer = __MIN( p_block->i_buffer,
461                       p_sys->i_file_size - p_sys->i_write_size );
462
463     i_write = fwrite( p_block->p_buffer, 1, i_buffer,
464                       p_sys->p_write_list->file );
465
466     if( i_write > 0 ) p_sys->i_write_size += i_write;
467
468     //p_access->info.i_size += i_write;
469     //p_access->info.i_update |= INPUT_UPDATE_SIZE;
470
471     if( i_write < i_buffer )
472     {
473         /* Looks like we're short of space */
474
475         if( !p_sys->p_write_list->p_next )
476         {
477             msg_Warn( p_access, "no more space, overwritting old data" );
478             NextFileRead( p_access );
479             NextFileRead( p_access );
480         }
481
482         /* Make sure we switch to next file in write list */
483         p_sys->i_write_size = p_sys->i_file_size;
484     }
485
486     p_block->p_buffer += i_write;
487     p_block->i_buffer -= i_write;
488
489     /* Check if we have some data left */
490     if( p_block->i_buffer ) return WriteBlockToFile( p_access, p_block );
491
492     return VLC_SUCCESS;
493 }
494
495 /*****************************************************************************
496  * ReadBlockFromFile:
497  *****************************************************************************/
498 static block_t *ReadBlockFromFile( access_t *p_access )
499 {
500     access_sys_t *p_sys = p_access->p_sys;
501     block_t *p_block;
502
503     if( !p_sys->p_read_list && p_sys->p_write_list )
504     {
505         /* Force switching to next write file, that should
506          * give us something to read */
507         NextFileWrite( p_access );
508     }
509
510     if( !p_sys->p_read_list ) return 0;
511
512     p_block = block_New( p_access, 4096 );
513     p_block->i_buffer = fread( p_block->p_buffer, 1, 4096,
514                                p_sys->p_read_list->file );
515
516     if( p_block->i_buffer == 0 ) NextFileRead( p_access );
517
518     //p_access->info.i_size -= p_block->i_buffer;
519     //p_access->info.i_update |= INPUT_UPDATE_SIZE;
520
521     return p_block;
522 }
523
524 /*****************************************************************************
525  * Seek: seek to a specific location in a file
526  *****************************************************************************/
527 static int Seek( access_t *p_access, int64_t i_pos )
528 {
529     //access_sys_t *p_sys = p_access->p_sys;
530     (void)p_access;
531     (void)i_pos;
532     return VLC_SUCCESS;
533 }
534
535 /*****************************************************************************
536  *
537  *****************************************************************************/
538 static int Control( access_t *p_access, int i_query, va_list args )
539 {
540     bool   *pb_bool;
541     int          *pi_int;
542
543     switch( i_query )
544     {
545     case ACCESS_CAN_SEEK:
546     case ACCESS_CAN_FASTSEEK:
547         pb_bool = (bool*)va_arg( args, bool* );
548         *pb_bool = true;
549         break;
550
551     case ACCESS_CAN_CONTROL_PACE:   /* Not really true */
552     case ACCESS_CAN_PAUSE:
553         pb_bool = (bool*)va_arg( args, bool* );
554         *pb_bool = true;
555         break;
556
557     case ACCESS_GET_MTU:
558         pi_int = (int*)va_arg( args, int * );
559         *pi_int = 0;
560         break;
561
562     case ACCESS_SET_PAUSE_STATE:
563         break;
564
565     /* Forward everything else to the source access */
566     default:
567         return access_vaControl( p_access->p_source, i_query, args );
568     }
569     return VLC_SUCCESS;
570 }
571
572 /*****************************************************************************
573  * GetTmpFilePath:
574  *****************************************************************************/
575 #ifdef WIN32
576 #define getpid() (int)GetCurrentProcessId()
577 #endif
578 static char *GetTmpFilePath( access_t *p_access )
579 {
580     char *psz_dir = var_GetNonEmptyString( p_access, "timeshift-dir" );
581     char *psz_filename_base;
582
583     if( psz_dir == NULL )
584     {
585 #ifdef WIN32
586         DWORD ret = GetTempPathW (0, NULL);
587         wchar_t wdir[ret + 3]; // can at least old "C:" + nul
588         const wchar_t *pwdir = wdir;
589         wchar_t *pwdir_free = NULL;
590
591         if (GetTempPathW (ret + 1, wdir) == 0)
592         {
593             pwdir_free = pwdir = _wgetcwd (NULL, 0);
594             if (pwdir == NULL)
595                 pwdir = L"C:";
596         }
597
598         psz_dir = FromWide (pwdir);
599         if (pwdir_free != NULL)
600             free (pwdir_free);
601
602         /* remove trailing antislash if any */
603         if (psz_dir[strlen (psz_dir) - 1] == '\\')
604             psz_dir[strlen (psz_dir) - 1] = '\0';
605 #else
606         psz_dir = strdup( "/tmp" );
607 #endif
608     }
609
610     if( asprintf( &psz_filename_base, "%s/vlc-timeshift-%d-%d-",
611               psz_dir, getpid(), p_access->i_object_id ) == -1 )
612         psz_filename_base = NULL;
613     free( psz_dir );
614
615     return psz_filename_base;
616 }