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