]> git.sesse.net Git - vlc/blob - src/input/es_out_timeshift.c
block_t.i_samples -> block_t.i_nb_samples (as aout_buffer_t)
[vlc] / src / input / es_out_timeshift.c
1 /*****************************************************************************
2  * es_out_timeshift.c: Es Out timeshift.
3  *****************************************************************************
4  * Copyright (C) 2008 Laurent Aimar
5  * $Id$
6  *
7  * Authors: Laurent Aimar < fenrir _AT_ videolan _DOT_ org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 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 General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <errno.h>
34 #include <assert.h>
35 #if defined (WIN32) && !defined (UNDER_CE)
36 #  include <direct.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 #   include <sys/stat.h>
40 #endif
41
42 #include <vlc_common.h>
43 #include <vlc_charset.h>
44
45 #include <vlc_input.h>
46 #include <vlc_es_out.h>
47 #include <vlc_block.h>
48 #include "input_internal.h"
49 #include "es_out.h"
50 #include "es_out_timeshift.h"
51
52 /*****************************************************************************
53  * Local prototypes
54  *****************************************************************************/
55
56 /* XXX attribute_packed is (and MUST be) used ONLY to reduce memory usage */
57 #ifdef HAVE_ATTRIBUTE_PACKED
58 #   define attribute_packed __attribute__((__packed__))
59 #else
60 #   define attribute_packed
61 #endif
62
63 enum
64 {
65     C_ADD,
66     C_SEND,
67     C_DEL,
68     C_CONTROL,
69 };
70
71 typedef struct attribute_packed
72 {
73     es_out_id_t *p_es;
74     es_format_t *p_fmt;
75 } ts_cmd_add_t;
76
77 typedef struct attribute_packed
78 {
79     es_out_id_t *p_es;
80 } ts_cmd_del_t;
81
82 typedef struct attribute_packed
83 {
84     es_out_id_t *p_es;
85     block_t *p_block;
86     int     i_offset;  /* We do not use file > INT_MAX */
87 } ts_cmd_send_t;
88
89 typedef struct attribute_packed
90 {
91     int  i_query;
92
93     union
94     {
95         bool b_bool;
96         int  i_int;
97         int64_t i_i64;
98         es_out_id_t *p_es;
99         struct
100         {
101             int     i_int;
102             int64_t i_i64;
103         } int_i64;
104         struct
105         {
106             int        i_int;
107             vlc_meta_t *p_meta;
108         } int_meta;
109         struct
110         {
111             int       i_int;
112             vlc_epg_t *p_epg;
113         } int_epg;
114         struct
115         {
116             es_out_id_t *p_es;
117             bool        b_bool;
118         } es_bool;
119         struct
120         {
121             es_out_id_t *p_es;
122             es_format_t *p_fmt;
123         } es_fmt;
124         struct
125         {
126             /* FIXME Really too big (double make the whole thing too big) */
127             double  f_position;
128             mtime_t i_time;
129             mtime_t i_length;
130         } times;
131         struct
132         {
133             mtime_t i_pts_delay;
134             int     i_cr_average;
135         } jitter;
136     };
137 } ts_cmd_control_t;
138
139 typedef struct attribute_packed
140 {
141     int8_t  i_type;
142     mtime_t i_date;
143     union
144     {
145         ts_cmd_add_t     add;
146         ts_cmd_del_t     del;
147         ts_cmd_send_t    send;
148         ts_cmd_control_t control;
149     };
150 } ts_cmd_t;
151
152 typedef struct ts_storage_t ts_storage_t;
153 struct ts_storage_t
154 {
155     ts_storage_t *p_next;
156
157     /* */
158     char    *psz_file;  /* Filename */
159     size_t  i_file_max; /* Max size in bytes */
160     int64_t i_file_size;/* Current size in bytes */
161     FILE    *p_filew;   /* FILE handle for data writing */
162     FILE    *p_filer;   /* FILE handle for data reading */
163
164     /* */
165     int      i_cmd_r;
166     int      i_cmd_w;
167     int      i_cmd_max;
168     ts_cmd_t *p_cmd;
169 };
170
171 typedef struct
172 {
173     VLC_COMMON_MEMBERS
174
175     /* */
176     input_thread_t *p_input;
177     es_out_t       *p_out;
178     int64_t        i_tmp_size_max;
179     const char     *psz_tmp_path;
180
181     /* Lock for all following fields */
182     vlc_mutex_t    lock;
183     vlc_cond_t     wait;
184
185     /* */
186     bool           b_paused;
187     mtime_t        i_pause_date;
188
189     /* */
190     int            i_rate;
191     int            i_rate_source;
192     mtime_t        i_rate_date;
193     mtime_t        i_rate_delay;
194
195     /* */
196     mtime_t        i_buffering_delay;
197
198     /* */
199     ts_storage_t   *p_storage_r;
200     ts_storage_t   *p_storage_w;
201
202     mtime_t        i_cmd_delay;
203
204 } ts_thread_t;
205
206 struct es_out_id_t
207 {
208     es_out_id_t *p_es;
209 };
210
211 struct es_out_sys_t
212 {
213     input_thread_t *p_input;
214         es_out_t       *p_out;
215
216     /* Configuration */
217     int64_t        i_tmp_size_max;    /* Maximal temporary file size in byte */
218     char           *psz_tmp_path;     /* Path for temporary files */
219
220     /* Lock for all following fields */
221     vlc_mutex_t    lock;
222
223     /* */
224     bool           b_delayed;
225     ts_thread_t   *p_thread;
226
227     /* */
228     bool           b_input_paused;
229     bool           b_input_paused_source;
230     int            i_input_rate;
231     int            i_input_rate_source;
232
233     /* */
234     int            i_es;
235     es_out_id_t    **pp_es;
236 };
237
238 static es_out_id_t *Add    ( es_out_t *, const es_format_t * );
239 static int          Send   ( es_out_t *, es_out_id_t *, block_t * );
240 static void         Del    ( es_out_t *, es_out_id_t * );
241 static int          Control( es_out_t *, int i_query, va_list );
242 static void         Destroy( es_out_t * );
243
244 static int          TsStart( es_out_t * );
245 static void         TsAutoStop( es_out_t * );
246
247 static void         TsStop( ts_thread_t * );
248 static void         TsPushCmd( ts_thread_t *, ts_cmd_t * );
249 static int          TsPopCmdLocked( ts_thread_t *, ts_cmd_t *, bool b_flush );
250 static bool         TsHasCmd( ts_thread_t * );
251 static bool         TsIsUnused( ts_thread_t * );
252 static int          TsChangePause( ts_thread_t *, bool b_source_paused, bool b_paused, mtime_t i_date );
253 static int          TsChangeRate( ts_thread_t *, int i_src_rate, int i_rate );
254
255 static void         *TsRun( vlc_object_t * );
256
257 static ts_storage_t *TsStorageNew( const char *psz_path, int64_t i_tmp_size_max );
258 static void         TsStorageDelete( ts_storage_t * );
259 static void         TsStoragePack( ts_storage_t *p_storage );
260 static bool         TsStorageIsFull( ts_storage_t *, const ts_cmd_t *p_cmd );
261 static bool         TsStorageIsEmpty( ts_storage_t * );
262 static void         TsStoragePushCmd( ts_storage_t *, const ts_cmd_t *p_cmd, bool b_flush );
263 static void         TsStoragePopCmd( ts_storage_t *p_storage, ts_cmd_t *p_cmd, bool b_flush );
264
265 static void CmdClean( ts_cmd_t * );
266 static void cmd_cleanup_routine( void *p ) { CmdClean( p ); }
267
268 static int  CmdInitAdd    ( ts_cmd_t *, es_out_id_t *, const es_format_t *, bool b_copy );
269 static void CmdInitSend   ( ts_cmd_t *, es_out_id_t *, block_t * );
270 static int  CmdInitDel    ( ts_cmd_t *, es_out_id_t * );
271 static int  CmdInitControl( ts_cmd_t *, int i_query, va_list, bool b_copy );
272
273 /* */
274 static void CmdCleanAdd    ( ts_cmd_t * );
275 static void CmdCleanSend   ( ts_cmd_t * );
276 static void CmdCleanControl( ts_cmd_t *p_cmd );
277
278 /* XXX these functions will take the destination es_out_t */
279 static void CmdExecuteAdd    ( es_out_t *, ts_cmd_t * );
280 static int  CmdExecuteSend   ( es_out_t *, ts_cmd_t * );
281 static void CmdExecuteDel    ( es_out_t *, ts_cmd_t * );
282 static int  CmdExecuteControl( es_out_t *, ts_cmd_t * );
283
284 /* File helpers */
285 static char *GetTmpPath( char *psz_path );
286 static FILE *GetTmpFile( char **ppsz_file, const char *psz_path );
287
288 /*****************************************************************************
289  * input_EsOutTimeshiftNew:
290  *****************************************************************************/
291 es_out_t *input_EsOutTimeshiftNew( input_thread_t *p_input, es_out_t *p_next_out, int i_rate )
292 {
293     es_out_t *p_out = malloc( sizeof(*p_out) );
294     if( !p_out )
295         return NULL;
296
297     es_out_sys_t *p_sys = malloc( sizeof(*p_sys) );
298     if( !p_sys )
299     {
300         free( p_out );
301         return NULL;
302     }
303
304     /* */
305     p_out->pf_add     = Add;
306     p_out->pf_send    = Send;
307     p_out->pf_del     = Del;
308     p_out->pf_control = Control;
309     p_out->pf_destroy = Destroy;
310     p_out->p_sys      = p_sys;
311     p_out->b_sout     = p_input->p->p_sout != NULL;
312
313     /* */
314     p_sys->b_input_paused = false;
315     p_sys->b_input_paused_source = false;
316     p_sys->p_input = p_input;
317     p_sys->i_input_rate = i_rate;
318     p_sys->i_input_rate_source = i_rate;
319
320     p_sys->p_out = p_next_out;
321     vlc_mutex_init_recursive( &p_sys->lock );
322
323     p_sys->b_delayed = false;
324     p_sys->p_thread = NULL;
325
326     TAB_INIT( p_sys->i_es, p_sys->pp_es );
327
328     /* */
329     const int i_tmp_size_max = var_CreateGetInteger( p_input, "input-timeshift-granularity" );
330     if( i_tmp_size_max < 0 )
331         p_sys->i_tmp_size_max = 50*1024*1024;
332     else
333         p_sys->i_tmp_size_max = __MAX( i_tmp_size_max, 1*1024*1024 );
334     msg_Dbg( p_input, "using timeshift granularity of %d MBytes",
335              (int)p_sys->i_tmp_size_max/(1024*1024) );
336
337     char *psz_tmp_path = var_CreateGetNonEmptyString( p_input, "input-timeshift-path" );
338     p_sys->psz_tmp_path = GetTmpPath( psz_tmp_path );
339     msg_Dbg( p_input, "using timeshift path '%s'", p_sys->psz_tmp_path );
340
341 #if 0
342 #define S(t) msg_Err( p_input, "SIZEOF("#t")=%d", sizeof(t) )
343     S(ts_cmd_t);
344     S(ts_cmd_control_t);
345     S(ts_cmd_send_t);
346     S(ts_cmd_del_t);
347     S(ts_cmd_add_t);
348 #undef S
349 #endif
350
351     return p_out;
352 }
353
354 /*****************************************************************************
355  * Internal functions
356  *****************************************************************************/
357 static void Destroy( es_out_t *p_out )
358 {
359     es_out_sys_t *p_sys = p_out->p_sys;
360
361     if( p_sys->b_delayed )
362     {
363         TsStop( p_sys->p_thread );
364         p_sys->b_delayed = false;
365     }
366
367     while( p_sys->i_es > 0 )
368         Del( p_out, p_sys->pp_es[0] );
369     TAB_CLEAN( p_sys->i_es, p_sys->pp_es  );
370
371     free( p_sys->psz_tmp_path );
372     vlc_mutex_destroy( &p_sys->lock );
373     free( p_sys );
374     free( p_out );
375 }
376
377 static es_out_id_t *Add( es_out_t *p_out, const es_format_t *p_fmt )
378 {
379     es_out_sys_t *p_sys = p_out->p_sys;
380     ts_cmd_t cmd;
381
382     es_out_id_t *p_es = malloc( sizeof( *p_es ) );
383     if( !p_es )
384         return NULL;
385
386     vlc_mutex_lock( &p_sys->lock );
387
388     TsAutoStop( p_out );
389
390     if( CmdInitAdd( &cmd, p_es, p_fmt, p_sys->b_delayed ) )
391     {
392         vlc_mutex_unlock( &p_sys->lock );
393         free( p_es );
394         return NULL;
395     }
396
397     TAB_APPEND( p_sys->i_es, p_sys->pp_es, p_es );
398
399     if( p_sys->b_delayed )
400         TsPushCmd( p_sys->p_thread, &cmd );
401     else
402         CmdExecuteAdd( p_sys->p_out, &cmd );
403
404     vlc_mutex_unlock( &p_sys->lock );
405
406     return p_es;
407 }
408 static int Send( es_out_t *p_out, es_out_id_t *p_es, block_t *p_block )
409 {
410     es_out_sys_t *p_sys = p_out->p_sys;
411     ts_cmd_t cmd;
412     int i_ret = VLC_SUCCESS;
413
414     vlc_mutex_lock( &p_sys->lock );
415
416     TsAutoStop( p_out );
417
418     CmdInitSend( &cmd, p_es, p_block );
419     if( p_sys->b_delayed )
420         TsPushCmd( p_sys->p_thread, &cmd );
421     else
422         i_ret = CmdExecuteSend( p_sys->p_out, &cmd) ;
423
424     vlc_mutex_unlock( &p_sys->lock );
425
426     return i_ret;
427 }
428 static void Del( es_out_t *p_out, es_out_id_t *p_es )
429 {
430     es_out_sys_t *p_sys = p_out->p_sys;
431     ts_cmd_t cmd;
432
433     vlc_mutex_lock( &p_sys->lock );
434
435     TsAutoStop( p_out );
436
437     CmdInitDel( &cmd, p_es );
438     if( p_sys->b_delayed )
439         TsPushCmd( p_sys->p_thread, &cmd );
440     else
441         CmdExecuteDel( p_sys->p_out, &cmd );
442
443     TAB_REMOVE( p_sys->i_es, p_sys->pp_es, p_es );
444
445     vlc_mutex_unlock( &p_sys->lock );
446 }
447
448 static int ControlLockedGetEmpty( es_out_t *p_out, bool *pb_empty )
449 {
450     es_out_sys_t *p_sys = p_out->p_sys;
451
452     if( p_sys->b_delayed && TsHasCmd( p_sys->p_thread ) )
453         *pb_empty = false;
454     else
455         *pb_empty = es_out_GetEmpty( p_sys->p_out );
456
457     return VLC_SUCCESS;
458 }
459 static int ControlLockedGetWakeup( es_out_t *p_out, mtime_t *pi_wakeup )
460 {
461     es_out_sys_t *p_sys = p_out->p_sys;
462
463     if( p_sys->b_delayed )
464     {
465         assert( !p_sys->p_input->p->b_can_pace_control );
466         *pi_wakeup = 0;
467     }
468     else
469     {
470         *pi_wakeup = es_out_GetWakeup( p_sys->p_out );
471     }
472
473     return VLC_SUCCESS;
474 }
475 static int ControlLockedGetBuffering( es_out_t *p_out, bool *pb_buffering )
476 {
477     es_out_sys_t *p_sys = p_out->p_sys;
478
479     if( p_sys->b_delayed )
480         *pb_buffering = true;
481     else
482         *pb_buffering = es_out_GetBuffering( p_sys->p_out );
483
484     return VLC_SUCCESS;
485 }
486 static int ControlLockedSetPauseState( es_out_t *p_out, bool b_source_paused, bool b_paused, mtime_t i_date )
487 {
488     es_out_sys_t *p_sys = p_out->p_sys;
489     int i_ret;
490
491     if( !p_sys->b_delayed && !b_source_paused == !b_paused )
492     {
493         i_ret = es_out_SetPauseState( p_sys->p_out, b_source_paused, b_paused, i_date );
494     }
495     else
496     {
497         i_ret = VLC_EGENERIC;
498         if( !p_sys->p_input->p->b_can_pace_control )
499         {
500             if( !p_sys->b_delayed )
501                 TsStart( p_out );
502             if( p_sys->b_delayed )
503                 i_ret = TsChangePause( p_sys->p_thread, b_source_paused, b_paused, i_date );
504         }
505         else
506         {
507             /* XXX we may do it BUT it would be better to finish the clock clean up+improvments
508              * and so be able to advertize correctly pace control property in access
509              * module */
510             msg_Err( p_sys->p_input, "EsOutTimeshift does not work with streams that have space control" );
511         }
512     }
513
514     if( !i_ret )
515     {
516         p_sys->b_input_paused_source = b_source_paused;
517         p_sys->b_input_paused = b_paused;
518     }
519     return i_ret;
520 }
521 static int ControlLockedSetRate( es_out_t *p_out, int i_src_rate, int i_rate )
522 {
523     es_out_sys_t *p_sys = p_out->p_sys;
524     int i_ret;
525
526     if( !p_sys->b_delayed && i_src_rate == i_rate )
527     {
528         i_ret = es_out_SetRate( p_sys->p_out, i_src_rate, i_rate );
529     }
530     else
531     {
532         i_ret = VLC_EGENERIC;
533         if( !p_sys->p_input->p->b_can_pace_control )
534         {
535             if( !p_sys->b_delayed )
536                 TsStart( p_out );
537             if( p_sys->b_delayed )
538                 i_ret = TsChangeRate( p_sys->p_thread, i_src_rate, i_rate );
539         }
540         else
541         {
542             /* XXX we may do it BUT it would be better to finish the clock clean up+improvments
543              * and so be able to advertize correctly pace control property in access
544              * module */
545             msg_Err( p_sys->p_input, "EsOutTimeshift does not work with streams that have space control" );
546         }
547
548     }
549
550     if( !i_ret )
551     {
552         p_sys->i_input_rate_source = i_src_rate;
553         p_sys->i_input_rate = i_rate;
554     }
555     return i_ret;
556 }
557 static int ControlLockedSetTime( es_out_t *p_out, mtime_t i_date )
558 {
559     es_out_sys_t *p_sys = p_out->p_sys;
560
561     if( !p_sys->b_delayed )
562         return es_out_SetTime( p_sys->p_out, i_date );
563
564     /* TODO */
565     msg_Err( p_sys->p_input, "EsOutTimeshift does not yet support time change" );
566     return VLC_EGENERIC;
567 }
568 static int ControlLockedSetFrameNext( es_out_t *p_out )
569 {
570     es_out_sys_t *p_sys = p_out->p_sys;
571
572     return es_out_SetFrameNext( p_sys->p_out );
573 }
574
575 static int ControlLocked( es_out_t *p_out, int i_query, va_list args )
576 {
577     es_out_sys_t *p_sys = p_out->p_sys;
578
579     switch( i_query )
580     {
581     /* Invalid query for this es_out level */
582     case ES_OUT_SET_ES_BY_ID:
583     case ES_OUT_RESTART_ES_BY_ID:
584     case ES_OUT_SET_ES_DEFAULT_BY_ID:
585     case ES_OUT_SET_DELAY:
586     case ES_OUT_SET_RECORD_STATE:
587         assert(0);
588         return VLC_EGENERIC;
589
590     /* Pass-through control */
591     case ES_OUT_SET_ACTIVE:
592     case ES_OUT_SET_MODE:
593     case ES_OUT_SET_GROUP:
594     case ES_OUT_SET_PCR:
595     case ES_OUT_SET_GROUP_PCR:
596     case ES_OUT_RESET_PCR:
597     case ES_OUT_SET_NEXT_DISPLAY_TIME:
598     case ES_OUT_SET_GROUP_META:
599     case ES_OUT_SET_GROUP_EPG:
600     case ES_OUT_SET_ES_SCRAMBLED_STATE:
601     case ES_OUT_DEL_GROUP:
602     case ES_OUT_SET_META:
603     case ES_OUT_SET_ES:
604     case ES_OUT_RESTART_ES:
605     case ES_OUT_SET_ES_DEFAULT:
606     case ES_OUT_SET_ES_STATE:
607     case ES_OUT_SET_ES_FMT:
608     case ES_OUT_SET_TIMES:
609     case ES_OUT_SET_JITTER:
610     {
611         ts_cmd_t cmd;
612         if( CmdInitControl( &cmd, i_query, args, p_sys->b_delayed ) )
613             return VLC_EGENERIC;
614         if( p_sys->b_delayed )
615         {
616             TsPushCmd( p_sys->p_thread, &cmd );
617             return VLC_SUCCESS;
618         }
619         return CmdExecuteControl( p_sys->p_out, &cmd );
620     }
621
622     /* Special control when delayed */
623     case ES_OUT_GET_ES_STATE:
624     {
625         es_out_id_t *p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
626         bool *pb_enabled = (bool*)va_arg( args, bool* );
627
628         if( p_sys->b_delayed )
629         {
630             *pb_enabled = true;
631             return VLC_SUCCESS;
632         }
633         return es_out_Control( p_sys->p_out, ES_OUT_GET_ES_STATE, p_es->p_es, pb_enabled );
634     }
635
636     /* Special internal input control */
637     case ES_OUT_GET_EMPTY:
638     {
639         bool *pb_empty = (bool*)va_arg( args, bool* );
640         return ControlLockedGetEmpty( p_out, pb_empty );
641     }
642     case ES_OUT_GET_WAKE_UP: /* TODO ? */
643     {
644         mtime_t *pi_wakeup = (mtime_t*)va_arg( args, mtime_t* );
645         return ControlLockedGetWakeup( p_out, pi_wakeup );
646     }
647     case ES_OUT_GET_BUFFERING:
648     {
649         bool *pb_buffering = (bool *)va_arg( args, bool* );
650         return ControlLockedGetBuffering( p_out, pb_buffering );
651     }
652     case ES_OUT_SET_PAUSE_STATE:
653     {
654         const bool b_source_paused = (bool)va_arg( args, int );
655         const bool b_paused = (bool)va_arg( args, int );
656         const mtime_t i_date = (mtime_t) va_arg( args, mtime_t );
657
658         return ControlLockedSetPauseState( p_out, b_source_paused, b_paused, i_date );
659     }
660     case ES_OUT_SET_RATE:
661     {
662         const int i_src_rate = (int)va_arg( args, int );
663         const int i_rate = (int)va_arg( args, int );
664
665         return ControlLockedSetRate( p_out, i_src_rate, i_rate );
666     }
667     case ES_OUT_SET_TIME:
668     {
669         const mtime_t i_date = (mtime_t)va_arg( args, mtime_t );
670
671         return ControlLockedSetTime( p_out, i_date );
672     }
673     case ES_OUT_SET_FRAME_NEXT:
674     {
675         return ControlLockedSetFrameNext( p_out );
676     }
677
678     default:
679         msg_Err( p_sys->p_input, "Unknown es_out_Control query !" );
680         assert(0);
681         return VLC_EGENERIC;
682     }
683 }
684 static int Control( es_out_t *p_out, int i_query, va_list args )
685 {
686     es_out_sys_t *p_sys = p_out->p_sys;
687     int i_ret;
688
689     vlc_mutex_lock( &p_sys->lock );
690
691     TsAutoStop( p_out );
692
693     i_ret = ControlLocked( p_out, i_query, args );
694
695     vlc_mutex_unlock( &p_sys->lock );
696
697     return i_ret;
698 }
699
700 /*****************************************************************************
701  *
702  *****************************************************************************/
703 static void TsDestructor( vlc_object_t *p_this )
704 {
705     ts_thread_t *p_ts = (ts_thread_t*)p_this;
706
707     vlc_cond_destroy( &p_ts->wait );
708     vlc_mutex_destroy( &p_ts->lock );
709 }
710 static int TsStart( es_out_t *p_out )
711 {
712     es_out_sys_t *p_sys = p_out->p_sys;
713     ts_thread_t *p_ts;
714
715     assert( !p_sys->b_delayed );
716
717     p_sys->p_thread = p_ts = vlc_custom_create( p_sys->p_input, sizeof(ts_thread_t),
718                                                 VLC_OBJECT_GENERIC, "es out timeshift" );
719     if( !p_ts )
720         return VLC_EGENERIC;
721
722     p_ts->i_tmp_size_max = p_sys->i_tmp_size_max;
723     p_ts->psz_tmp_path = p_sys->psz_tmp_path;
724     p_ts->p_input = p_sys->p_input;
725     p_ts->p_out = p_sys->p_out;
726     vlc_mutex_init( &p_ts->lock );
727     vlc_cond_init( &p_ts->wait );
728     p_ts->b_paused = p_sys->b_input_paused && !p_sys->b_input_paused_source;
729     p_ts->i_pause_date = p_ts->b_paused ? mdate() : -1;
730     p_ts->i_rate_source = p_sys->i_input_rate_source;
731     p_ts->i_rate        = p_sys->i_input_rate;
732     p_ts->i_rate_date = -1;
733     p_ts->i_rate_delay = 0;
734     p_ts->i_buffering_delay = 0;
735     p_ts->i_cmd_delay = 0;
736     p_ts->p_storage_r = NULL;
737     p_ts->p_storage_w = NULL;
738
739     vlc_object_set_destructor( p_ts, TsDestructor );
740
741     p_sys->b_delayed = true;
742     if( vlc_thread_create( p_ts, "es out timeshift",
743                            TsRun, VLC_THREAD_PRIORITY_INPUT ) )
744     {
745         msg_Err( p_sys->p_input, "cannot create input thread" );
746
747         vlc_object_release( p_ts );
748
749         p_sys->b_delayed = false;
750         return VLC_EGENERIC;
751     }
752
753     return VLC_SUCCESS;
754 }
755 static void TsAutoStop( es_out_t *p_out )
756 {
757     es_out_sys_t *p_sys = p_out->p_sys;
758
759     if( !p_sys->b_delayed || !TsIsUnused( p_sys->p_thread ) )
760         return;
761
762     msg_Warn( p_sys->p_input, "es out timeshift: auto stop" );
763     TsStop( p_sys->p_thread );
764
765     p_sys->b_delayed = false;
766 }
767 static void TsStop( ts_thread_t *p_ts )
768 {
769     vlc_object_kill( p_ts );
770     vlc_thread_join( p_ts );
771
772     vlc_mutex_lock( &p_ts->lock );
773     for( ;; )
774     {
775         ts_cmd_t cmd;
776
777         if( TsPopCmdLocked( p_ts, &cmd, true ) )
778             break;
779
780         CmdClean( &cmd );
781     }
782     assert( !p_ts->p_storage_r || !p_ts->p_storage_r->p_next );
783     if( p_ts->p_storage_r )
784         TsStorageDelete( p_ts->p_storage_r );
785     vlc_mutex_unlock( &p_ts->lock );
786
787     vlc_object_release( p_ts );
788 }
789 static void TsPushCmd( ts_thread_t *p_ts, ts_cmd_t *p_cmd )
790 {
791     vlc_mutex_lock( &p_ts->lock );
792
793     if( !p_ts->p_storage_w || TsStorageIsFull( p_ts->p_storage_w, p_cmd ) )
794     {
795         ts_storage_t *p_storage = TsStorageNew( p_ts->psz_tmp_path, p_ts->i_tmp_size_max );
796
797         if( !p_storage )
798         {
799             CmdClean( p_cmd );
800             vlc_mutex_unlock( &p_ts->lock );
801             /* TODO warn the user (but only once) */
802             return;
803         }
804
805         if( !p_ts->p_storage_w )
806         {
807             p_ts->p_storage_r = p_ts->p_storage_w = p_storage;
808         }
809         else
810         {
811             TsStoragePack( p_ts->p_storage_w );
812             p_ts->p_storage_w->p_next = p_storage;
813             p_ts->p_storage_w = p_storage;
814         }
815     }
816
817     /* TODO return error and warn the user (but only once) */
818     TsStoragePushCmd( p_ts->p_storage_w, p_cmd, p_ts->p_storage_r == p_ts->p_storage_w );
819
820     vlc_cond_signal( &p_ts->wait );
821
822     vlc_mutex_unlock( &p_ts->lock );
823 }
824 static int TsPopCmdLocked( ts_thread_t *p_ts, ts_cmd_t *p_cmd, bool b_flush )
825 {
826     vlc_assert_locked( &p_ts->lock );
827
828     if( TsStorageIsEmpty( p_ts->p_storage_r ) )
829         return VLC_EGENERIC;
830
831     TsStoragePopCmd( p_ts->p_storage_r, p_cmd, b_flush );
832
833     while( p_ts->p_storage_r && TsStorageIsEmpty( p_ts->p_storage_r ) )
834     {
835         ts_storage_t *p_next = p_ts->p_storage_r->p_next;
836         if( !p_next )
837             break;
838
839         TsStorageDelete( p_ts->p_storage_r );
840         p_ts->p_storage_r = p_next;
841     }
842
843     return VLC_SUCCESS;
844 }
845 static bool TsHasCmd( ts_thread_t *p_ts )
846 {
847     bool b_cmd;
848
849     vlc_mutex_lock( &p_ts->lock );
850     b_cmd =  TsStorageIsEmpty( p_ts->p_storage_r );
851     vlc_mutex_unlock( &p_ts->lock );
852
853     return b_cmd;
854 }
855 static bool TsIsUnused( ts_thread_t *p_ts )
856 {
857     bool b_unused;
858
859     vlc_mutex_lock( &p_ts->lock );
860     b_unused = !p_ts->b_paused &&
861                p_ts->i_rate == p_ts->i_rate_source &&
862                TsStorageIsEmpty( p_ts->p_storage_r );
863     vlc_mutex_unlock( &p_ts->lock );
864
865     return b_unused;
866 }
867 static int TsChangePause( ts_thread_t *p_ts, bool b_source_paused, bool b_paused, mtime_t i_date )
868 {
869     vlc_mutex_lock( &p_ts->lock );
870
871     int i_ret;
872     if( b_paused )
873     {
874         assert( !b_source_paused );
875         i_ret = es_out_SetPauseState( p_ts->p_out, true, true, i_date );
876     }
877     else
878     {
879         i_ret = es_out_SetPauseState( p_ts->p_out, false, false, i_date );
880     }
881
882     if( !i_ret )
883     {
884         if( !b_paused )
885         {
886             assert( p_ts->i_pause_date > 0 );
887
888             p_ts->i_cmd_delay += i_date - p_ts->i_pause_date;
889         }
890
891         p_ts->b_paused = b_paused;
892         p_ts->i_pause_date = i_date;
893
894         vlc_cond_signal( &p_ts->wait );
895     }
896     vlc_mutex_unlock( &p_ts->lock );
897     return i_ret;
898 }
899 static int TsChangeRate( ts_thread_t *p_ts, int i_src_rate, int i_rate )
900 {
901     int i_ret;
902
903     vlc_mutex_lock( &p_ts->lock );
904     p_ts->i_cmd_delay += p_ts->i_rate_delay;
905
906     p_ts->i_rate_date = -1;
907     p_ts->i_rate_delay = 0;
908     p_ts->i_rate = i_rate;
909     p_ts->i_rate_source = i_src_rate;
910
911     i_ret = es_out_SetRate( p_ts->p_out, i_rate, i_rate );
912     vlc_mutex_unlock( &p_ts->lock );
913
914     return i_ret;
915 }
916
917 static void *TsRun( vlc_object_t *p_thread )
918 {
919     ts_thread_t *p_ts = (ts_thread_t*)p_thread;
920     mtime_t i_buffering_date = -1;
921
922     for( ;; )
923     {
924         ts_cmd_t cmd;
925         mtime_t  i_deadline;
926         bool b_buffering;
927
928         /* Pop a command to execute */
929         vlc_mutex_lock( &p_ts->lock );
930         mutex_cleanup_push( &p_ts->lock );
931
932         for( ;; )
933         {
934             const int canc = vlc_savecancel();
935             b_buffering = es_out_GetBuffering( p_ts->p_out );
936
937             if( ( !p_ts->b_paused || b_buffering ) && !TsPopCmdLocked( p_ts, &cmd, false ) )
938             {
939                 vlc_restorecancel( canc );
940                 break;
941             }
942             vlc_restorecancel( canc );
943
944             vlc_cond_wait( &p_ts->wait, &p_ts->lock );
945         }
946
947         if( b_buffering && i_buffering_date < 0 )
948         {
949             i_buffering_date = cmd.i_date;
950         }
951         else if( i_buffering_date > 0 )
952         {
953             p_ts->i_buffering_delay += i_buffering_date - cmd.i_date; /* It is < 0 */
954             if( b_buffering )
955                 i_buffering_date = cmd.i_date;
956             else
957                 i_buffering_date = -1;
958         }
959
960         if( p_ts->i_rate_date < 0 )
961             p_ts->i_rate_date = cmd.i_date;
962
963         p_ts->i_rate_delay = 0;
964         if( p_ts->i_rate_source != p_ts->i_rate )
965         {
966             const mtime_t i_duration = cmd.i_date - p_ts->i_rate_date;
967             p_ts->i_rate_delay = i_duration * p_ts->i_rate / p_ts->i_rate_source - i_duration;
968         }
969         if( p_ts->i_cmd_delay + p_ts->i_rate_delay + p_ts->i_buffering_delay < 0 && p_ts->i_rate != p_ts->i_rate_source )
970         {
971             const int canc = vlc_savecancel();
972
973             /* Auto reset to rate 1.0 */
974             msg_Warn( p_ts->p_input, "es out timeshift: auto reset rate to %d", p_ts->i_rate_source );
975
976             p_ts->i_cmd_delay = 0;
977             p_ts->i_buffering_delay = 0;
978
979             p_ts->i_rate_delay = 0;
980             p_ts->i_rate_date = -1;
981             p_ts->i_rate = p_ts->i_rate_source;
982
983             if( !es_out_SetRate( p_ts->p_out, p_ts->i_rate_source, p_ts->i_rate ) )
984             {
985                 vlc_value_t val = { .i_int = p_ts->i_rate };
986                 /* Warn back input
987                  * FIXME it is perfectly safe BUT it is ugly as it may hide a
988                  * rate change requested by user */
989                 input_ControlPush( p_ts->p_input, INPUT_CONTROL_SET_RATE, &val );
990             }
991
992             vlc_restorecancel( canc );
993         }
994         i_deadline = cmd.i_date + p_ts->i_cmd_delay + p_ts->i_rate_delay + p_ts->i_buffering_delay;
995
996         vlc_cleanup_run();
997
998         /* Regulate the speed of command processing to the same one than
999          * reading  */
1000         vlc_cleanup_push( cmd_cleanup_routine, &cmd );
1001
1002         mwait( i_deadline );
1003
1004         vlc_cleanup_pop();
1005
1006         /* Execute the command  */
1007         const int canc = vlc_savecancel();
1008         switch( cmd.i_type )
1009         {
1010         case C_ADD:
1011             CmdExecuteAdd( p_ts->p_out, &cmd );
1012             CmdCleanAdd( &cmd );
1013             break;
1014         case C_SEND:
1015             CmdExecuteSend( p_ts->p_out, &cmd );
1016             CmdCleanSend( &cmd );
1017             break;
1018         case C_CONTROL:
1019             CmdExecuteControl( p_ts->p_out, &cmd );
1020             CmdCleanControl( &cmd );
1021             break;
1022         case C_DEL:
1023             CmdExecuteDel( p_ts->p_out, &cmd );
1024             break;
1025         default:
1026             assert(0);
1027             break;
1028         }
1029         vlc_restorecancel( canc );
1030     }
1031
1032     return NULL;
1033 }
1034
1035 /*****************************************************************************
1036  *
1037  *****************************************************************************/
1038 static ts_storage_t *TsStorageNew( const char *psz_tmp_path, int64_t i_tmp_size_max )
1039 {
1040     ts_storage_t *p_storage = calloc( 1, sizeof(ts_storage_t) );
1041     if( !p_storage )
1042         return NULL;
1043
1044     /* */
1045     p_storage->p_next = NULL;
1046
1047     /* */
1048     p_storage->i_file_max = i_tmp_size_max;
1049     p_storage->i_file_size = 0;
1050     p_storage->p_filew = GetTmpFile( &p_storage->psz_file, psz_tmp_path );
1051     if( p_storage->psz_file )
1052         p_storage->p_filer = utf8_fopen( p_storage->psz_file, "rb" );
1053
1054     /* */
1055     p_storage->i_cmd_w = 0;
1056     p_storage->i_cmd_r = 0;
1057     p_storage->i_cmd_max = 30000;
1058     p_storage->p_cmd = malloc( p_storage->i_cmd_max * sizeof(*p_storage->p_cmd) );
1059     //fprintf( stderr, "\nSTORAGE name=%s size=%d kbytes\n", p_storage->psz_file, p_storage->i_cmd_max * sizeof(*p_storage->p_cmd) /1024 );
1060
1061     if( !p_storage->p_cmd || !p_storage->p_filew || !p_storage->p_filer )
1062     {
1063         TsStorageDelete( p_storage );
1064         return NULL;
1065     }
1066     return p_storage;
1067 }
1068 static void TsStorageDelete( ts_storage_t *p_storage )
1069 {
1070     while( p_storage->i_cmd_r < p_storage->i_cmd_w )
1071     {
1072         ts_cmd_t cmd;
1073
1074         TsStoragePopCmd( p_storage, &cmd, true );
1075
1076         CmdClean( &cmd );
1077     }
1078     free( p_storage->p_cmd );
1079
1080     if( p_storage->p_filer )
1081         fclose( p_storage->p_filer );
1082     if( p_storage->p_filew )
1083         fclose( p_storage->p_filew );
1084
1085     if( p_storage->psz_file )
1086     {
1087         utf8_unlink( p_storage->psz_file );
1088         free( p_storage->psz_file );
1089     }
1090
1091     free( p_storage );
1092 }
1093 static void TsStoragePack( ts_storage_t *p_storage )
1094 {
1095     /* Try to release a bit of memory */
1096     if( p_storage->i_cmd_w >= p_storage->i_cmd_max )
1097         return;
1098
1099     p_storage->i_cmd_max = __MAX( p_storage->i_cmd_w, 1 );
1100
1101     ts_cmd_t *p_new = realloc( p_storage->p_cmd, p_storage->i_cmd_max * sizeof(*p_storage->p_cmd) );
1102     if( p_new )
1103         p_storage->p_cmd = p_new;
1104 }
1105 static bool TsStorageIsFull( ts_storage_t *p_storage, const ts_cmd_t *p_cmd )
1106 {
1107     if( p_cmd && p_cmd->i_type == C_SEND && p_storage->i_cmd_w > 0 )
1108     {
1109         size_t i_size = sizeof(*p_cmd->send.p_block) + p_cmd->send.p_block->i_buffer;
1110
1111         if( p_storage->i_file_size + i_size >= p_storage->i_file_max )
1112             return true;
1113     }
1114     return p_storage->i_cmd_w >= p_storage->i_cmd_max;
1115 }
1116 static bool TsStorageIsEmpty( ts_storage_t *p_storage )
1117 {
1118     return !p_storage || p_storage->i_cmd_r >= p_storage->i_cmd_w;
1119 }
1120 static void TsStoragePushCmd( ts_storage_t *p_storage, const ts_cmd_t *p_cmd, bool b_flush )
1121 {
1122     ts_cmd_t cmd = *p_cmd;
1123
1124     assert( !TsStorageIsFull( p_storage, p_cmd ) );
1125
1126     if( cmd.i_type == C_SEND )
1127     {
1128         block_t *p_block = cmd.send.p_block;
1129
1130         cmd.send.p_block = NULL;
1131         cmd.send.i_offset = ftell( p_storage->p_filew );
1132
1133         if( fwrite( p_block, sizeof(*p_block), 1, p_storage->p_filew ) != 1 )
1134         {
1135             block_Release( p_block );
1136             return;
1137         }
1138         p_storage->i_file_size += sizeof(*p_block);
1139         if( p_block->i_buffer > 0 )
1140         {
1141             if( fwrite( p_block->p_buffer, p_block->i_buffer, 1, p_storage->p_filew ) != 1 )
1142             {
1143                 block_Release( p_block );
1144                 return;
1145             }
1146         }
1147         p_storage->i_file_size += p_block->i_buffer;
1148         block_Release( p_block );
1149
1150         if( b_flush )
1151             fflush( p_storage->p_filew );
1152     }
1153     p_storage->p_cmd[p_storage->i_cmd_w++] = cmd;
1154 }
1155 static void TsStoragePopCmd( ts_storage_t *p_storage, ts_cmd_t *p_cmd, bool b_flush )
1156 {
1157     assert( !TsStorageIsEmpty( p_storage ) );
1158
1159     *p_cmd = p_storage->p_cmd[p_storage->i_cmd_r++];
1160     if( p_cmd->i_type == C_SEND )
1161     {
1162         block_t block;
1163
1164         if( !b_flush &&
1165             !fseek( p_storage->p_filer, p_cmd->send.i_offset, SEEK_SET ) &&
1166             fread( &block, sizeof(block), 1, p_storage->p_filer ) == 1 )
1167         {
1168             block_t *p_block = block_Alloc( block.i_buffer );
1169             if( p_block )
1170             {
1171                 p_block->i_dts      = block.i_dts;
1172                 p_block->i_pts      = block.i_pts;
1173                 p_block->i_flags    = block.i_flags;
1174                 p_block->i_length   = block.i_length;
1175                 p_block->i_rate     = block.i_rate;
1176                 p_block->i_nb_samples = block.i_nb_samples;
1177                 p_block->i_buffer = fread( p_block->p_buffer, 1, block.i_buffer, p_storage->p_filer );
1178             }
1179             p_cmd->send.p_block = p_block;
1180         }
1181         else
1182         {
1183             //fprintf( stderr, "TsStoragePopCmd: %m\n" );
1184             p_cmd->send.p_block = block_Alloc( 1 );
1185         }
1186     }
1187 }
1188
1189 /*****************************************************************************
1190  *
1191  *****************************************************************************/
1192 static void CmdClean( ts_cmd_t *p_cmd )
1193 {
1194     switch( p_cmd->i_type )
1195     {
1196     case C_ADD:
1197         CmdCleanAdd( p_cmd );
1198         break;
1199     case C_SEND:
1200         CmdCleanSend( p_cmd );
1201         break;
1202     case C_CONTROL:
1203         CmdCleanControl( p_cmd );
1204         break;
1205     case C_DEL:
1206         break;
1207     default:
1208         assert(0);
1209         break;
1210     }
1211 }
1212
1213 static int CmdInitAdd( ts_cmd_t *p_cmd, es_out_id_t *p_es, const es_format_t *p_fmt, bool b_copy )
1214 {
1215     p_cmd->i_type = C_ADD;
1216     p_cmd->i_date = mdate();
1217     p_cmd->add.p_es = p_es;
1218     if( b_copy )
1219     {
1220         p_cmd->add.p_fmt = malloc( sizeof(*p_fmt) );
1221         if( !p_cmd->add.p_fmt )
1222             return VLC_EGENERIC;
1223         es_format_Copy( p_cmd->add.p_fmt, p_fmt );
1224     }
1225     else
1226     {
1227         p_cmd->add.p_fmt = (es_format_t*)p_fmt;
1228     }
1229     return VLC_SUCCESS;
1230 }
1231 static void CmdExecuteAdd( es_out_t *p_out, ts_cmd_t *p_cmd )
1232 {
1233     p_cmd->add.p_es->p_es = es_out_Add( p_out, p_cmd->add.p_fmt );
1234 }
1235 static void CmdCleanAdd( ts_cmd_t *p_cmd )
1236 {
1237     es_format_Clean( p_cmd->add.p_fmt );
1238     free( p_cmd->add.p_fmt );
1239 }
1240
1241 static void CmdInitSend( ts_cmd_t *p_cmd, es_out_id_t *p_es, block_t *p_block )
1242 {
1243     p_cmd->i_type = C_SEND;
1244     p_cmd->i_date = mdate();
1245     p_cmd->send.p_es = p_es;
1246     p_cmd->send.p_block = p_block;
1247 }
1248 static int CmdExecuteSend( es_out_t *p_out, ts_cmd_t *p_cmd )
1249 {
1250     block_t *p_block = p_cmd->send.p_block;
1251
1252     p_cmd->send.p_block = NULL;
1253
1254     if( p_block )
1255     {
1256         if( p_cmd->send.p_es->p_es )
1257             return es_out_Send( p_out, p_cmd->send.p_es->p_es, p_block );
1258         block_Release( p_block );
1259     }
1260     return VLC_EGENERIC;
1261 }
1262 static void CmdCleanSend( ts_cmd_t *p_cmd )
1263 {
1264     if( p_cmd->send.p_block )
1265         block_Release( p_cmd->send.p_block );
1266 }
1267
1268 static int CmdInitDel( ts_cmd_t *p_cmd, es_out_id_t *p_es )
1269 {
1270     p_cmd->i_type = C_DEL;
1271     p_cmd->i_date = mdate();
1272     p_cmd->del.p_es = p_es;
1273     return VLC_SUCCESS;
1274 }
1275 static void CmdExecuteDel( es_out_t *p_out, ts_cmd_t *p_cmd )
1276 {
1277     if( p_cmd->del.p_es->p_es )
1278         es_out_Del( p_out, p_cmd->del.p_es->p_es );
1279     free( p_cmd->del.p_es );
1280 }
1281
1282 static int CmdInitControl( ts_cmd_t *p_cmd, int i_query, va_list args, bool b_copy )
1283 {
1284     p_cmd->i_type = C_CONTROL;
1285     p_cmd->i_date = mdate();
1286     p_cmd->control.i_query = i_query;
1287
1288     switch( i_query )
1289     {
1290     /* Pass-through control */
1291     case ES_OUT_SET_ACTIVE:  /* arg1= bool                     */
1292         p_cmd->control.b_bool = (bool)va_arg( args, int );
1293         break;
1294
1295     case ES_OUT_SET_MODE:    /* arg1= int                            */
1296     case ES_OUT_SET_GROUP:   /* arg1= int                            */
1297     case ES_OUT_DEL_GROUP:   /* arg1=int i_group */
1298         p_cmd->control.i_int = (int)va_arg( args, int );
1299         break;
1300
1301     case ES_OUT_SET_PCR:                /* arg1=int64_t i_pcr(microsecond!) (using default group 0)*/
1302     case ES_OUT_SET_NEXT_DISPLAY_TIME:  /* arg1=int64_t i_pts(microsecond) */
1303         p_cmd->control.i_i64 = (int64_t)va_arg( args, int64_t );
1304         break;
1305
1306     case ES_OUT_SET_GROUP_PCR:          /* arg1= int i_group, arg2=int64_t i_pcr(microsecond!)*/
1307         p_cmd->control.int_i64.i_int = (int)va_arg( args, int );
1308         p_cmd->control.int_i64.i_i64 = (int64_t)va_arg( args, int64_t );
1309         break;
1310
1311     case ES_OUT_SET_ES_SCRAMBLED_STATE:
1312         p_cmd->control.es_bool.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
1313         p_cmd->control.es_bool.b_bool = (bool)va_arg( args, int );
1314         break;
1315
1316     case ES_OUT_RESET_PCR:           /* no arg */
1317         break;
1318
1319     case ES_OUT_SET_META:        /* arg1=const vlc_meta_t* */
1320     case ES_OUT_SET_GROUP_META:  /* arg1=int i_group arg2=const vlc_meta_t* */
1321     {
1322         if( i_query == ES_OUT_SET_GROUP_META )
1323             p_cmd->control.int_meta.i_int = (int)va_arg( args, int );
1324         const vlc_meta_t *p_meta = va_arg( args, const vlc_meta_t * );
1325
1326         if( b_copy )
1327         {
1328             p_cmd->control.int_meta.p_meta = vlc_meta_New();
1329             if( !p_cmd->control.int_meta.p_meta )
1330                 return VLC_EGENERIC;
1331             vlc_meta_Merge( p_cmd->control.int_meta.p_meta, p_meta );
1332         }
1333         else
1334         {
1335             /* The cast is only needed to avoid warning */
1336             p_cmd->control.int_meta.p_meta = (vlc_meta_t*)p_meta;
1337         }
1338         break;
1339     }
1340
1341     case ES_OUT_SET_GROUP_EPG:   /* arg1=int i_group arg2=const vlc_epg_t* */
1342     {
1343         p_cmd->control.int_epg.i_int = (int)va_arg( args, int );
1344         const vlc_epg_t *p_epg = va_arg( args, const vlc_epg_t * );
1345
1346         if( b_copy )
1347         {
1348             p_cmd->control.int_epg.p_epg = vlc_epg_New( p_epg->psz_name );
1349             if( !p_cmd->control.int_epg.p_epg )
1350                 return VLC_EGENERIC;
1351             for( int i = 0; i < p_epg->i_event; i++ )
1352             {
1353                 vlc_epg_event_t *p_evt = p_epg->pp_event[i];
1354
1355                 vlc_epg_AddEvent( p_cmd->control.int_epg.p_epg,
1356                                   p_evt->i_start, p_evt->i_duration,
1357                                   p_evt->psz_name,
1358                                   p_evt->psz_short_description, p_evt->psz_description );
1359             }
1360             vlc_epg_SetCurrent( p_cmd->control.int_epg.p_epg,
1361                                 p_epg->p_current ? p_epg->p_current->i_start : -1 );
1362         }
1363         else
1364         {
1365             /* The cast is only needed to avoid warning */
1366             p_cmd->control.int_epg.p_epg = (vlc_epg_t*)p_epg;
1367         }
1368         break;
1369     }
1370
1371     /* Modified control */
1372     case ES_OUT_SET_ES:      /* arg1= es_out_id_t*                   */
1373     case ES_OUT_RESTART_ES:  /* arg1= es_out_id_t*                   */
1374     case ES_OUT_SET_ES_DEFAULT: /* arg1= es_out_id_t*                */
1375         p_cmd->control.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
1376         break;
1377
1378     case ES_OUT_SET_ES_STATE:/* arg1= es_out_id_t* arg2=bool   */
1379         p_cmd->control.es_bool.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
1380         p_cmd->control.es_bool.b_bool = (bool)va_arg( args, int );
1381         break;
1382
1383     case ES_OUT_SET_ES_FMT:     /* arg1= es_out_id_t* arg2=es_format_t* */
1384     {
1385         p_cmd->control.es_fmt.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
1386         es_format_t *p_fmt = (es_format_t*)va_arg( args, es_format_t * );
1387
1388         if( b_copy )
1389         {
1390             p_cmd->control.es_fmt.p_fmt = malloc( sizeof(*p_fmt) );
1391             if( !p_cmd->control.es_fmt.p_fmt )
1392                 return VLC_EGENERIC;
1393             es_format_Copy( p_cmd->control.es_fmt.p_fmt, p_fmt );
1394         }
1395         else
1396         {
1397             p_cmd->control.es_fmt.p_fmt = p_fmt;
1398         }
1399         break;
1400     }
1401     case ES_OUT_SET_TIMES:
1402     {
1403         double f_position = (double)va_arg( args, double );
1404         mtime_t i_time = (mtime_t)va_arg( args, mtime_t );
1405         mtime_t i_length = (mtime_t)va_arg( args, mtime_t );
1406
1407         p_cmd->control.times.f_position = f_position;
1408         p_cmd->control.times.i_time = i_time;
1409         p_cmd->control.times.i_length = i_length;
1410         break;
1411     }
1412     case ES_OUT_SET_JITTER:
1413     {
1414         mtime_t i_pts_delay = (mtime_t)va_arg( args, mtime_t );
1415         int     i_cr_average = (int)va_arg( args, int );
1416
1417         p_cmd->control.jitter.i_pts_delay = i_pts_delay;
1418         p_cmd->control.jitter.i_cr_average = i_cr_average;
1419         break;
1420     }
1421
1422     default:
1423         assert(0);
1424         return VLC_EGENERIC;
1425     }
1426
1427     return VLC_SUCCESS;
1428 }
1429 static int CmdExecuteControl( es_out_t *p_out, ts_cmd_t *p_cmd )
1430 {
1431     const int i_query = p_cmd->control.i_query;
1432
1433     switch( i_query )
1434     {
1435     /* Pass-through control */
1436     case ES_OUT_SET_ACTIVE:  /* arg1= bool                     */
1437         return es_out_Control( p_out, i_query, p_cmd->control.b_bool );
1438
1439     case ES_OUT_SET_MODE:    /* arg1= int                            */
1440     case ES_OUT_SET_GROUP:   /* arg1= int                            */
1441     case ES_OUT_DEL_GROUP:   /* arg1=int i_group */
1442         return es_out_Control( p_out, i_query, p_cmd->control.i_int );
1443
1444     case ES_OUT_SET_PCR:                /* arg1=int64_t i_pcr(microsecond!) (using default group 0)*/
1445     case ES_OUT_SET_NEXT_DISPLAY_TIME:  /* arg1=int64_t i_pts(microsecond) */
1446         return es_out_Control( p_out, i_query, p_cmd->control.i_i64 );
1447
1448     case ES_OUT_SET_GROUP_PCR:          /* arg1= int i_group, arg2=int64_t i_pcr(microsecond!)*/
1449         return es_out_Control( p_out, i_query, p_cmd->control.int_i64.i_int,
1450                                                p_cmd->control.int_i64.i_i64 );
1451
1452     case ES_OUT_RESET_PCR:           /* no arg */
1453         return es_out_Control( p_out, i_query );
1454
1455     case ES_OUT_SET_GROUP_META:  /* arg1=int i_group arg2=const vlc_meta_t* */
1456         return es_out_Control( p_out, i_query, p_cmd->control.int_meta.i_int,
1457                                                p_cmd->control.int_meta.p_meta );
1458
1459     case ES_OUT_SET_GROUP_EPG:   /* arg1=int i_group arg2=const vlc_epg_t* */
1460         return es_out_Control( p_out, i_query, p_cmd->control.int_epg.i_int,
1461                                                p_cmd->control.int_epg.p_epg );
1462
1463     case ES_OUT_SET_ES_SCRAMBLED_STATE: /* arg1=int es_out_id_t* arg2=bool */
1464         return es_out_Control( p_out, i_query, p_cmd->control.es_bool.p_es->p_es,
1465                                                p_cmd->control.es_bool.b_bool );
1466
1467     case ES_OUT_SET_META:  /* arg1=const vlc_meta_t* */
1468         return es_out_Control( p_out, i_query, p_cmd->control.int_meta.p_meta );
1469
1470     /* Modified control */
1471     case ES_OUT_SET_ES:      /* arg1= es_out_id_t*                   */
1472     case ES_OUT_RESTART_ES:  /* arg1= es_out_id_t*                   */
1473     case ES_OUT_SET_ES_DEFAULT: /* arg1= es_out_id_t*                */
1474         return es_out_Control( p_out, i_query, p_cmd->control.p_es->p_es );
1475
1476     case ES_OUT_SET_ES_STATE:/* arg1= es_out_id_t* arg2=bool   */
1477         return es_out_Control( p_out, i_query, p_cmd->control.es_bool.p_es->p_es,
1478                                                p_cmd->control.es_bool.b_bool );
1479
1480     case ES_OUT_SET_ES_FMT:     /* arg1= es_out_id_t* arg2=es_format_t* */
1481         return es_out_Control( p_out, i_query, p_cmd->control.es_fmt.p_es->p_es,
1482                                                p_cmd->control.es_fmt.p_fmt );
1483
1484     case ES_OUT_SET_TIMES:
1485         return es_out_Control( p_out, i_query, p_cmd->control.times.f_position,
1486                                                p_cmd->control.times.i_time,
1487                                                p_cmd->control.times.i_length );
1488     case ES_OUT_SET_JITTER:
1489         return es_out_Control( p_out, i_query, p_cmd->control.jitter.i_pts_delay,
1490                                                p_cmd->control.jitter.i_cr_average );
1491
1492     default:
1493         assert(0);
1494         return VLC_EGENERIC;
1495     }
1496 }
1497 static void CmdCleanControl( ts_cmd_t *p_cmd )
1498 {
1499     if( ( p_cmd->control.i_query == ES_OUT_SET_GROUP_META ||
1500           p_cmd->control.i_query == ES_OUT_SET_META ) &&
1501         p_cmd->control.int_meta.p_meta )
1502     {
1503         vlc_meta_Delete( p_cmd->control.int_meta.p_meta );
1504     }
1505     else if( p_cmd->control.i_query == ES_OUT_SET_GROUP_EPG &&
1506              p_cmd->control.int_epg.p_epg )
1507     {
1508         vlc_epg_Delete( p_cmd->control.int_epg.p_epg );
1509     }
1510     else if( p_cmd->control.i_query == ES_OUT_SET_ES_FMT &&
1511              p_cmd->control.es_fmt.p_fmt )
1512     {
1513         es_format_Clean( p_cmd->control.es_fmt.p_fmt );
1514         free( p_cmd->control.es_fmt.p_fmt );
1515     }
1516 }
1517
1518
1519 /*****************************************************************************
1520  * GetTmpFile/Path:
1521  *****************************************************************************/
1522 static char *GetTmpPath( char *psz_path )
1523 {
1524     if( psz_path && *psz_path )
1525     {
1526         /* Make sure that the path exists and is a directory */
1527         struct stat s;
1528         const int i_ret = utf8_stat( psz_path, &s );
1529
1530         if( i_ret < 0 && !utf8_mkdir( psz_path, 0600 ) )
1531             return psz_path;
1532         else if( i_ret == 0 && ( s.st_mode & S_IFDIR ) )
1533             return psz_path;
1534     }
1535     free( psz_path );
1536
1537     /* Create a suitable path */
1538 #if defined (WIN32) && !defined (UNDER_CE)
1539     const DWORD dwCount = GetTempPathW( 0, NULL );
1540     wchar_t *psw_path = calloc( dwCount + 1, sizeof(wchar_t) );
1541     if( psw_path )
1542     {
1543         if( GetTempPathW( dwCount + 1, psw_path ) <= 0 )
1544         {
1545             free( psw_path );
1546
1547             psw_path = _wgetcwd( NULL, 0 );
1548         }
1549     }
1550
1551     psz_path = NULL;
1552     if( psw_path )
1553     {
1554         psz_path = FromWide( psw_path );
1555         while( psz_path && *psz_path && psz_path[strlen( psz_path ) - 1] == '\\' )
1556             psz_path[strlen( psz_path ) - 1] = '\0';
1557
1558         free( psw_path );
1559     }
1560
1561     if( !psz_path || *psz_path == '\0' )
1562     {
1563         free( psz_path );
1564         return strdup( "C:" );
1565     }
1566 #else
1567     psz_path = strdup( "/tmp" );
1568 #endif
1569
1570     return psz_path;
1571 }
1572
1573 static FILE *GetTmpFile( char **ppsz_file, const char *psz_path )
1574 {
1575     char *psz_name;
1576     int fd;
1577     FILE *f;
1578
1579     /* */
1580     *ppsz_file = NULL;
1581     if( asprintf( &psz_name, "%s/vlc-timeshift.XXXXXX", psz_path ) < 0 )
1582         return NULL;
1583
1584     /* */
1585     fd = utf8_mkstemp( psz_name );
1586     *ppsz_file = psz_name;
1587
1588     if( fd < 0 )
1589         return NULL;
1590
1591     /* */
1592     f = fdopen( fd, "w+b" );
1593     if( !f )
1594         close( fd );
1595
1596     return f;
1597 }
1598