es_out_timeshift.c 43.6 KB
Newer Older
1 2 3 4 5 6
/*****************************************************************************
 * es_out_timeshift.c: Es Out timeshift.
 *****************************************************************************
 * Copyright (C) 2008 Laurent Aimar
 * $Id$
 *
7
 * Authors: Laurent Aimar < fenrir _AT_ videolan _DOT_ org>
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#if defined (WIN32) && !defined (UNDER_CE)
#  include <direct.h>
#endif
#ifdef HAVE_SYS_STAT_H
#   include <sys/stat.h>
#endif

#include <vlc_common.h>
#include <vlc_charset.h>

#include <vlc_input.h>
#include <vlc_es_out.h>
#include <vlc_block.h>
#include "input_internal.h"
#include "es_out.h"
#include "es_out_timeshift.h"

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/

56 57 58 59 60 61 62
/* XXX attribute_packed is (and MUST be) used ONLY to reduce memory usage */
#ifdef HAVE_ATTRIBUTE_PACKED
#   define attribute_packed __attribute__((__packed__))
#else
#   define attribute_packed
#endif

63 64 65 66 67 68 69 70
enum
{
    C_ADD,
    C_SEND,
    C_DEL,
    C_CONTROL,
};

71
typedef struct attribute_packed
Laurent Aimar's avatar
Laurent Aimar committed
72 73 74
{
    es_out_id_t *p_es;
    es_format_t *p_fmt;
75
} ts_cmd_add_t;
Laurent Aimar's avatar
Laurent Aimar committed
76

77
typedef struct attribute_packed
Laurent Aimar's avatar
Laurent Aimar committed
78 79 80 81
{
    es_out_id_t *p_es;
} ts_cmd_del_t;

82
typedef struct attribute_packed
Laurent Aimar's avatar
Laurent Aimar committed
83 84 85
{
    es_out_id_t *p_es;
    block_t *p_block;
86
    int     i_offset;  /* We do not use file > INT_MAX */
Laurent Aimar's avatar
Laurent Aimar committed
87 88
} ts_cmd_send_t;

89
typedef struct attribute_packed
Laurent Aimar's avatar
Laurent Aimar committed
90 91 92
{
    int  i_query;

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    union
    {
        bool b_bool;
        int  i_int;
        int64_t i_i64;
        es_out_id_t *p_es;
        struct
        {
            int     i_int;
            int64_t i_i64;
        } int_i64;
        struct
        {
            int        i_int;
            vlc_meta_t *p_meta;
        } int_meta;
        struct
        {
            int       i_int;
            vlc_epg_t *p_epg;
        } int_epg;
        struct
        {
            es_out_id_t *p_es;
            bool        b_bool;
        } es_bool;
        struct
        {
            es_out_id_t *p_es;
            es_format_t *p_fmt;
        } es_fmt;
    };
Laurent Aimar's avatar
Laurent Aimar committed
125 126
} ts_cmd_control_t;

127
typedef struct attribute_packed
128
{
129
    int8_t  i_type;
130
    mtime_t i_date;
131 132
    union
    {
Laurent Aimar's avatar
Laurent Aimar committed
133 134 135 136
        ts_cmd_add_t     add;
        ts_cmd_del_t     del;
        ts_cmd_send_t    send;
        ts_cmd_control_t control;
137 138 139
    };
} ts_cmd_t;

140 141 142 143 144 145
typedef struct ts_storage_t ts_storage_t;
struct ts_storage_t
{
    ts_storage_t *p_next;

    /* */
146
    char    *psz_file;  /* Filename */
147
    size_t  i_file_max; /* Max size in bytes */
148 149 150
    int64_t i_file_size;/* Current size in bytes */
    FILE    *p_filew;   /* FILE handle for data writing */
    FILE    *p_filer;   /* FILE handle for data reading */
151 152 153 154 155 156 157 158

    /* */
    int      i_cmd_r;
    int      i_cmd_w;
    int      i_cmd_max;
    ts_cmd_t *p_cmd;
};

159 160 161 162 163 164 165
typedef struct
{
    VLC_COMMON_MEMBERS

    /* */
    input_thread_t *p_input;
    es_out_t       *p_out;
166 167
    int64_t        i_tmp_size_max;
    const char     *psz_tmp_path;
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

    /* Lock for all following fields */
    vlc_mutex_t    lock;
    vlc_cond_t     wait;

    /* */
    bool           b_paused;
    mtime_t        i_pause_date;

    /* */
    int            i_rate;
    int            i_rate_source;
    mtime_t        i_rate_date;
    mtime_t        i_rate_delay;

183 184 185
    /* */
    mtime_t        i_buffering_delay;

186
    /* */
187 188 189
    ts_storage_t   *p_storage_r;
    ts_storage_t   *p_storage_w;

190 191 192 193
    mtime_t        i_cmd_delay;

} ts_thread_t;

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
struct es_out_id_t
{
    es_out_id_t *p_es;
};

struct es_out_sys_t
{
    input_thread_t *p_input;
	es_out_t       *p_out;

    /* Configuration */
    int64_t        i_tmp_size_max;    /* Maximal temporary file size in byte */
    char           *psz_tmp_path;     /* Path for temporary files */

    /* Lock for all following fields */
    vlc_mutex_t    lock;

    /* */
    bool           b_delayed;
213
    ts_thread_t   *p_thread;
214

215 216 217 218 219
    /* */
    bool           b_input_paused;
    bool           b_input_paused_source;
    int            i_input_rate;
    int            i_input_rate_source;
220

221 222 223 224 225 226 227 228 229 230 231
    /* */
    int            i_es;
    es_out_id_t    **pp_es;
};

static es_out_id_t *Add    ( es_out_t *, const es_format_t * );
static int          Send   ( es_out_t *, es_out_id_t *, block_t * );
static void         Del    ( es_out_t *, es_out_id_t * );
static int          Control( es_out_t *, int i_query, va_list );
static void         Destroy( es_out_t * );

232
static int          TsStart( es_out_t * );
Laurent Aimar's avatar
Laurent Aimar committed
233 234
static void         TsAutoStop( es_out_t * );

235
static void         TsStop( ts_thread_t * );
236
static void         TsPushCmd( ts_thread_t *, ts_cmd_t * );
237
static int          TsPopCmdLocked( ts_thread_t *, ts_cmd_t *, bool b_flush );
238
static bool         TsHasCmd( ts_thread_t * );
Laurent Aimar's avatar
Laurent Aimar committed
239
static bool         TsIsUnused( ts_thread_t * );
240 241
static int          TsChangePause( ts_thread_t *, bool b_source_paused, bool b_paused, mtime_t i_date );
static int          TsChangeRate( ts_thread_t *, int i_src_rate, int i_rate );
242
static mtime_t      TsGetDelay( ts_thread_t * );
243

244 245
static void         *TsRun( vlc_object_t * );

246
static ts_storage_t *TsStorageNew( const char *psz_path, int64_t i_tmp_size_max );
247
static void         TsStorageDelete( ts_storage_t * );
248 249
static void         TsStoragePack( ts_storage_t *p_storage );
static bool         TsStorageIsFull( ts_storage_t *, const ts_cmd_t *p_cmd );
250
static bool         TsStorageIsEmpty( ts_storage_t * );
251
static void         TsStoragePushCmd( ts_storage_t *, const ts_cmd_t *p_cmd, bool b_flush );
252
static void         TsStoragePopCmd( ts_storage_t *p_storage, ts_cmd_t *p_cmd, bool b_flush );
253

254 255
static void CmdClean( ts_cmd_t * );
static void cmd_cleanup_routine( void *p ) { CmdClean( p ); }
256 257 258 259 260 261

static int  CmdInitAdd    ( ts_cmd_t *, es_out_id_t *, const es_format_t *, bool b_copy );
static void CmdInitSend   ( ts_cmd_t *, es_out_id_t *, block_t * );
static int  CmdInitDel    ( ts_cmd_t *, es_out_id_t * );
static int  CmdInitControl( ts_cmd_t *, int i_query, va_list, bool b_copy );

262 263 264 265 266 267
/* */
static void CmdCleanAdd    ( ts_cmd_t * );
static void CmdCleanSend   ( ts_cmd_t * );
static void CmdCleanControl( ts_cmd_t *p_cmd );

/* XXX these functions will take the destination es_out_t */
268 269 270 271 272
static void CmdExecuteAdd    ( es_out_t *, ts_cmd_t * );
static int  CmdExecuteSend   ( es_out_t *, ts_cmd_t * );
static void CmdExecuteDel    ( es_out_t *, ts_cmd_t * );
static int  CmdExecuteControl( es_out_t *, ts_cmd_t * );

273
/* File helpers */
274
static char *GetTmpPath( char *psz_path );
275
static FILE *GetTmpFile( char **ppsz_file, const char *psz_path );
276 277 278 279

/*****************************************************************************
 * input_EsOutTimeshiftNew:
 *****************************************************************************/
280
es_out_t *input_EsOutTimeshiftNew( input_thread_t *p_input, es_out_t *p_next_out, int i_rate )
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
{
    es_out_t *p_out = malloc( sizeof(*p_out) );
    if( !p_out )
        return NULL;

    es_out_sys_t *p_sys = malloc( sizeof(*p_sys) );
    if( !p_sys )
    {
        free( p_out );
        return NULL;
    }

    /* */
    p_out->pf_add     = Add;
    p_out->pf_send    = Send;
    p_out->pf_del     = Del;
    p_out->pf_control = Control;
    p_out->pf_destroy = Destroy;
    p_out->p_sys      = p_sys;
    p_out->b_sout     = p_input->p->p_sout != NULL;

    /* */
303 304
    p_sys->b_input_paused = false;
    p_sys->b_input_paused_source = false;
305
    p_sys->p_input = p_input;
306 307 308
    p_sys->i_input_rate = i_rate;
    p_sys->i_input_rate_source = i_rate;

309 310
    p_sys->p_out = p_next_out;
    vlc_mutex_init_recursive( &p_sys->lock );
311

312
    p_sys->b_delayed = false;
313
    p_sys->p_thread = NULL;
314 315 316

    TAB_INIT( p_sys->i_es, p_sys->pp_es );

317 318 319 320 321 322 323 324 325 326 327 328
    /* */
    const int i_tmp_size_max = var_CreateGetInteger( p_input, "input-timeshift-granularity" );
    if( i_tmp_size_max < 0 )
        p_sys->i_tmp_size_max = 50*1024*1024;
    else
        p_sys->i_tmp_size_max = __MAX( i_tmp_size_max, 1*1024*1024 );
    msg_Dbg( p_input, "using timeshift granularity of %d bytes",
             (int)p_sys->i_tmp_size_max );

    char *psz_tmp_path = var_CreateGetNonEmptyString( p_input, "input-timeshift-path" );
    p_sys->psz_tmp_path = GetTmpPath( psz_tmp_path );
    msg_Dbg( p_input, "using timeshift  path '%s'", p_sys->psz_tmp_path );
329

330 331 332 333 334 335 336 337 338 339
#if 0
#define S(t) msg_Err( p_input, "SIZEOF("#t")=%d", sizeof(t) )
    S(ts_cmd_t);
    S(ts_cmd_control_t);
    S(ts_cmd_send_t);
    S(ts_cmd_del_t);
    S(ts_cmd_add_t);
#undef S
#endif

340 341 342 343 344 345 346 347 348 349
    return p_out;
}

/*****************************************************************************
 * Internal functions
 *****************************************************************************/
static void Destroy( es_out_t *p_out )
{
    es_out_sys_t *p_sys = p_out->p_sys;

350
    if( p_sys->b_delayed )
351 352 353 354
    {
        TsStop( p_sys->p_thread );
        p_sys->b_delayed = false;
    }
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

    while( p_sys->i_es > 0 )
        Del( p_out, p_sys->pp_es[0] );
    TAB_CLEAN( p_sys->i_es, p_sys->pp_es  );

    free( p_sys->psz_tmp_path );
    vlc_mutex_destroy( &p_sys->lock );
    free( p_sys );
    free( p_out );
}

static es_out_id_t *Add( es_out_t *p_out, const es_format_t *p_fmt )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    ts_cmd_t cmd;

    es_out_id_t *p_es = malloc( sizeof( *p_es ) );
    if( !p_es )
        return NULL;

    vlc_mutex_lock( &p_sys->lock );

Laurent Aimar's avatar
Laurent Aimar committed
377 378
    TsAutoStop( p_out );

379 380 381 382 383 384 385 386 387 388
    if( CmdInitAdd( &cmd, p_es, p_fmt, p_sys->b_delayed ) )
    {
        vlc_mutex_unlock( &p_sys->lock );
        free( p_es );
        return NULL;
    }

    TAB_APPEND( p_sys->i_es, p_sys->pp_es, p_es );

    if( p_sys->b_delayed )
389
        TsPushCmd( p_sys->p_thread, &cmd );
390
    else
391
        CmdExecuteAdd( p_sys->p_out, &cmd );
392 393 394 395 396 397 398 399 400 401 402 403 404

    vlc_mutex_unlock( &p_sys->lock );

    return p_es;
}
static int Send( es_out_t *p_out, es_out_id_t *p_es, block_t *p_block )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    ts_cmd_t cmd;
    int i_ret = VLC_SUCCESS;

    vlc_mutex_lock( &p_sys->lock );

Laurent Aimar's avatar
Laurent Aimar committed
405 406
    TsAutoStop( p_out );

407 408
    CmdInitSend( &cmd, p_es, p_block );
    if( p_sys->b_delayed )
409
        TsPushCmd( p_sys->p_thread, &cmd );
410
    else
411
        i_ret = CmdExecuteSend( p_sys->p_out, &cmd) ;
412 413 414 415 416 417 418 419 420 421 422 423

    vlc_mutex_unlock( &p_sys->lock );

    return i_ret;
}
static void Del( es_out_t *p_out, es_out_id_t *p_es )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    ts_cmd_t cmd;

    vlc_mutex_lock( &p_sys->lock );

Laurent Aimar's avatar
Laurent Aimar committed
424 425
    TsAutoStop( p_out );

426 427
    CmdInitDel( &cmd, p_es );
    if( p_sys->b_delayed )
428
        TsPushCmd( p_sys->p_thread, &cmd );
429
    else
430
        CmdExecuteDel( p_sys->p_out, &cmd );
431 432 433 434 435

    TAB_REMOVE( p_sys->i_es, p_sys->pp_es, p_es );

    vlc_mutex_unlock( &p_sys->lock );
}
436 437 438 439 440

static int ControlLockedGetEmpty( es_out_t *p_out, bool *pb_empty )
{
    es_out_sys_t *p_sys = p_out->p_sys;

441
    if( p_sys->b_delayed && TsHasCmd( p_sys->p_thread ) )
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        *pb_empty = false;
    else
        *pb_empty = es_out_GetEmpty( p_sys->p_out );

    return VLC_SUCCESS;
}
static int ControlLockedGetWakeup( es_out_t *p_out, mtime_t *pi_wakeup )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( p_sys->b_delayed )
    {
        assert( !p_sys->p_input->b_can_pace_control );
        *pi_wakeup = 0;
    }
    else
    {
        *pi_wakeup = es_out_GetWakeup( p_sys->p_out );
    }

    return VLC_SUCCESS;
}
464
static int ControlLockedGetBuffering( es_out_t *p_out, bool *pb_buffering, mtime_t *pi_delay )
465 466 467 468
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( p_sys->b_delayed )
469 470 471 472
    {
        mtime_t i_delay;
        es_out_GetBuffering( p_sys->p_out, &i_delay );

473
        *pb_buffering = true;
474 475
        *pi_delay = i_delay + TsGetDelay( p_sys->p_thread );
    }
476
    else
477 478 479
    {
        *pb_buffering = es_out_GetBuffering( p_sys->p_out, pi_delay );
    }
480 481 482 483 484 485

    return VLC_SUCCESS;
}
static int ControlLockedSetPauseState( es_out_t *p_out, bool b_source_paused, bool b_paused, mtime_t i_date )
{
    es_out_sys_t *p_sys = p_out->p_sys;
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    int i_ret;

    if( !p_sys->b_delayed && !b_source_paused == !b_paused )
    {
        i_ret = es_out_SetPauseState( p_sys->p_out, b_source_paused, b_paused, i_date );
    }
    else
    {
        i_ret = VLC_EGENERIC;
        if( !p_sys->p_input->b_can_pace_control )
        {
            if( !p_sys->b_delayed )
                TsStart( p_out );
            if( p_sys->b_delayed )
                i_ret = TsChangePause( p_sys->p_thread, b_source_paused, b_paused, i_date );
        }
        else
        {
            /* XXX we may do it BUT it would be better to finish the clock clean up+improvments
             * and so be able to advertize correctly pace control property in access
             * module */
            msg_Err( p_sys->p_input, "EsOutTimeshift does not work with streams that have space control" );
        }
    }
510

511
    if( !i_ret )
512
    {
513 514
        p_sys->b_input_paused_source = b_source_paused;
        p_sys->b_input_paused = b_paused;
515
    }
516
    return i_ret;
517 518 519 520
}
static int ControlLockedSetRate( es_out_t *p_out, int i_src_rate, int i_rate )
{
    es_out_sys_t *p_sys = p_out->p_sys;
521
    int i_ret;
522

523 524 525 526 527
    if( !p_sys->b_delayed && i_src_rate == i_rate )
    {
        i_ret = es_out_SetRate( p_sys->p_out, i_src_rate, i_rate );
    }
    else
528
    {
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        i_ret = VLC_EGENERIC;
        if( !p_sys->p_input->b_can_pace_control )
        {
            if( !p_sys->b_delayed )
                TsStart( p_out );
            if( p_sys->b_delayed )
                i_ret = TsChangeRate( p_sys->p_thread, i_src_rate, i_rate );
        }
        else
        {
            /* XXX we may do it BUT it would be better to finish the clock clean up+improvments
             * and so be able to advertize correctly pace control property in access
             * module */
            msg_Err( p_sys->p_input, "EsOutTimeshift does not work with streams that have space control" );
        }

545
    }
546 547 548 549 550 551 552

    if( !i_ret )
    {
        p_sys->i_input_rate_source = i_src_rate;
        p_sys->i_input_rate = i_rate;
    }
    return i_ret;
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
}
static int ControlLockedSetTime( es_out_t *p_out, mtime_t i_date )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( !p_sys->b_delayed )
        return es_out_SetTime( p_sys->p_out, i_date );

    /* TODO */
    msg_Err( p_sys->p_input, "EsOutTimeshift does not yet support time change" );
    return VLC_EGENERIC;
}
static int ControlLockedSetFrameNext( es_out_t *p_out )
{
    es_out_sys_t *p_sys = p_out->p_sys;

Laurent Aimar's avatar
Laurent Aimar committed
569
    return es_out_SetFrameNext( p_sys->p_out );
570 571
}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
static int ControlLocked( es_out_t *p_out, int i_query, va_list args )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    switch( i_query )
    {
    /* Invalid query for this es_out level */
    case ES_OUT_SET_ES_BY_ID:
    case ES_OUT_RESTART_ES_BY_ID:
    case ES_OUT_SET_ES_DEFAULT_BY_ID:
    case ES_OUT_SET_DELAY:
    case ES_OUT_SET_RECORD_STATE:
        assert(0);
        return VLC_EGENERIC;

    /* TODO ? or to remove ? */
    case ES_OUT_GET_TS:
        return VLC_EGENERIC;

    /* Pass-through control */
    case ES_OUT_SET_ACTIVE:
    case ES_OUT_SET_MODE:
    case ES_OUT_SET_GROUP:
    case ES_OUT_SET_PCR:
    case ES_OUT_SET_GROUP_PCR:
    case ES_OUT_RESET_PCR:
    case ES_OUT_SET_NEXT_DISPLAY_TIME:
    case ES_OUT_SET_GROUP_META:
    case ES_OUT_SET_GROUP_EPG:
    case ES_OUT_DEL_GROUP:
    case ES_OUT_SET_ES:
    case ES_OUT_RESTART_ES:
    case ES_OUT_SET_ES_DEFAULT:
    case ES_OUT_SET_ES_STATE:
    case ES_OUT_SET_ES_FMT:
    {
        ts_cmd_t cmd;
        if( CmdInitControl( &cmd, i_query, args, p_sys->b_delayed ) )
            return VLC_EGENERIC;
        if( p_sys->b_delayed )
        {
613
            TsPushCmd( p_sys->p_thread, &cmd );
614 615
            return VLC_SUCCESS;
        }
616
        return CmdExecuteControl( p_sys->p_out, &cmd );
617 618
    }

619 620 621 622 623 624 625 626 627 628 629
    /* Special control when delayed */
    case ES_OUT_GET_ES_STATE:
    {
        es_out_id_t *p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
        bool *pb_enabled = (bool*)va_arg( args, bool* );

        if( p_sys->b_delayed )
        {
            *pb_enabled = true;
            return VLC_SUCCESS;
        }
630
        return es_out_Control( p_sys->p_out, ES_OUT_GET_ES_STATE, p_es->p_es, pb_enabled );
631 632 633
    }

    /* Special internal input control */
634 635 636 637 638
    case ES_OUT_GET_EMPTY:
    {
        bool *pb_empty = (bool*)va_arg( args, bool* );
        return ControlLockedGetEmpty( p_out, pb_empty );
    }
639
    case ES_OUT_GET_WAKE_UP: /* TODO ? */
640 641 642 643
    {
        mtime_t *pi_wakeup = (mtime_t*)va_arg( args, mtime_t* );
        return ControlLockedGetWakeup( p_out, pi_wakeup );
    }
644
    case ES_OUT_GET_BUFFERING:
645 646
    {
        bool *pb_buffering = (bool *)va_arg( args, bool* );
647 648
        mtime_t *pi_delay = (mtime_t*)va_arg( args, mtime_t* );
        return ControlLockedGetBuffering( p_out, pb_buffering, pi_delay );
649
    }
650
    case ES_OUT_SET_PAUSE_STATE:
651 652 653 654 655 656 657
    {
        const bool b_source_paused = (bool)va_arg( args, int );
        const bool b_paused = (bool)va_arg( args, int );
        const mtime_t i_date = (mtime_t) va_arg( args, mtime_t );

        return ControlLockedSetPauseState( p_out, b_source_paused, b_paused, i_date );
    }
658
    case ES_OUT_SET_RATE:
659 660 661 662 663 664
    {
        const int i_src_rate = (int)va_arg( args, int );
        const int i_rate = (int)va_arg( args, int );

        return ControlLockedSetRate( p_out, i_src_rate, i_rate );
    }
665
    case ES_OUT_SET_TIME:
666 667 668 669 670
    {
        const mtime_t i_date = (mtime_t)va_arg( args, mtime_t );

        return ControlLockedSetTime( p_out, i_date );
    }
671
    case ES_OUT_SET_FRAME_NEXT:
672 673 674
    {
        return ControlLockedSetFrameNext( p_out );
    }
675 676 677 678 679 680 681 682 683 684 685 686 687

    default:
        msg_Err( p_sys->p_input, "Unknown es_out_Control query !" );
        assert(0);
        return VLC_EGENERIC;
    }
}
static int Control( es_out_t *p_out, int i_query, va_list args )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    int i_ret;

    vlc_mutex_lock( &p_sys->lock );
Laurent Aimar's avatar
Laurent Aimar committed
688 689 690

    TsAutoStop( p_out );

691
    i_ret = ControlLocked( p_out, i_query, args );
Laurent Aimar's avatar
Laurent Aimar committed
692

693 694 695 696 697
    vlc_mutex_unlock( &p_sys->lock );

    return i_ret;
}

698 699 700
/*****************************************************************************
 *
 *****************************************************************************/
701 702 703 704 705 706 707
static void TsDestructor( vlc_object_t *p_this )
{
    ts_thread_t *p_ts = (ts_thread_t*)p_this;

    vlc_cond_destroy( &p_ts->wait );
    vlc_mutex_destroy( &p_ts->lock );
}
708 709 710
static int TsStart( es_out_t *p_out )
{
    es_out_sys_t *p_sys = p_out->p_sys;
711
    ts_thread_t *p_ts;
712 713 714

    assert( !p_sys->b_delayed );

715 716 717
    p_sys->p_thread = p_ts = vlc_custom_create( p_sys->p_input, sizeof(ts_thread_t),
                                                VLC_OBJECT_GENERIC, "es out timeshift" );
    if( !p_ts )
718 719
        return VLC_EGENERIC;

720 721
    p_ts->i_tmp_size_max = p_sys->i_tmp_size_max;
    p_ts->psz_tmp_path = p_sys->psz_tmp_path;
722 723 724 725 726 727 728 729 730 731
    p_ts->p_input = p_sys->p_input;
    p_ts->p_out = p_sys->p_out;
    vlc_mutex_init( &p_ts->lock );
    vlc_cond_init( &p_ts->wait );
    p_ts->b_paused = p_sys->b_input_paused && !p_sys->b_input_paused_source;
    p_ts->i_pause_date = p_ts->b_paused ? mdate() : -1;
    p_ts->i_rate_source = p_sys->i_input_rate_source;
    p_ts->i_rate        = p_sys->i_input_rate;
    p_ts->i_rate_date = -1;
    p_ts->i_rate_delay = 0;
732
    p_ts->i_buffering_delay = 0;
733
    p_ts->i_cmd_delay = 0;
734 735
    p_ts->p_storage_r = NULL;
    p_ts->p_storage_w = NULL;
736 737 738

    vlc_object_set_destructor( p_ts, TsDestructor );

739
    p_sys->b_delayed = true;
Laurent Aimar's avatar
Laurent Aimar committed
740
    if( vlc_thread_create( p_ts, "es out timeshift",
741 742 743
                           TsRun, VLC_THREAD_PRIORITY_INPUT, false ) )
    {
        msg_Err( p_sys->p_input, "cannot create input thread" );
744

Laurent Aimar's avatar
Laurent Aimar committed
745
        vlc_object_release( p_ts );
746 747 748 749 750 751 752

        p_sys->b_delayed = false;
        return VLC_EGENERIC;
    }

    return VLC_SUCCESS;
}
Laurent Aimar's avatar
Laurent Aimar committed
753 754 755 756 757 758 759 760 761 762 763 764
static void TsAutoStop( es_out_t *p_out )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( !p_sys->b_delayed || !TsIsUnused( p_sys->p_thread ) )
        return;

    msg_Warn( p_sys->p_input, "es out timeshift: auto stop" );
    TsStop( p_sys->p_thread );

    p_sys->b_delayed = false;
}
765
static void TsStop( ts_thread_t *p_ts )
766
{
767 768
    vlc_object_kill( p_ts );
    vlc_thread_join( p_ts );
769

770
    vlc_mutex_lock( &p_ts->lock );
Laurent Aimar's avatar
Laurent Aimar committed
771 772 773 774
    for( ;; )
    {
        ts_cmd_t cmd;

775
        if( TsPopCmdLocked( p_ts, &cmd, true ) )
Laurent Aimar's avatar
Laurent Aimar committed
776 777 778 779
            break;

        CmdClean( &cmd );
    }
780 781 782
    assert( !p_ts->p_storage_r || !p_ts->p_storage_r->p_next );
    if( p_ts->p_storage_r )
        TsStorageDelete( p_ts->p_storage_r );
783
    vlc_mutex_unlock( &p_ts->lock );
Laurent Aimar's avatar
Laurent Aimar committed
784

785
    vlc_object_release( p_ts );
786
}
787
static void TsPushCmd( ts_thread_t *p_ts, ts_cmd_t *p_cmd )
788
{
789
    vlc_mutex_lock( &p_ts->lock );
790

791
    if( !p_ts->p_storage_w || TsStorageIsFull( p_ts->p_storage_w, p_cmd ) )
792
    {
793
        ts_storage_t *p_storage = TsStorageNew( p_ts->psz_tmp_path, p_ts->i_tmp_size_max );
794

795 796 797
        if( !p_storage )
        {
            CmdClean( p_cmd );
798 799
            vlc_mutex_unlock( &p_ts->lock );
            /* TODO warn the user (but only once) */
800 801
            return;
        }
802

803 804 805 806 807 808
        if( !p_ts->p_storage_w )
        {
            p_ts->p_storage_r = p_ts->p_storage_w = p_storage;
        }
        else
        {
809
            TsStoragePack( p_ts->p_storage_w );
810 811 812
            p_ts->p_storage_w->p_next = p_storage;
            p_ts->p_storage_w = p_storage;
        }
813
    }
814

815
    /* TODO return error and warn the user (but only once) */
816
    TsStoragePushCmd( p_ts->p_storage_w, p_cmd, p_ts->p_storage_r == p_ts->p_storage_w );
817 818 819 820

    vlc_cond_signal( &p_ts->wait );

    vlc_mutex_unlock( &p_ts->lock );
821
}
822
static int TsPopCmdLocked( ts_thread_t *p_ts, ts_cmd_t *p_cmd, bool b_flush )
823
{
824
    vlc_assert_locked( &p_ts->lock );
825

826
    if( TsStorageIsEmpty( p_ts->p_storage_r ) )
827 828
        return VLC_EGENERIC;

829
    TsStoragePopCmd( p_ts->p_storage_r, p_cmd, b_flush );
830 831 832 833 834 835 836 837 838 839

    while( p_ts->p_storage_r && TsStorageIsEmpty( p_ts->p_storage_r ) )
    {
        ts_storage_t *p_next = p_ts->p_storage_r->p_next;
        if( !p_next )
            break;

        TsStorageDelete( p_ts->p_storage_r );
        p_ts->p_storage_r = p_next;
    }
840 841 842

    return VLC_SUCCESS;
}
843
static bool TsHasCmd( ts_thread_t *p_ts )
844
{
845
    bool b_cmd;
846

847
    vlc_mutex_lock( &p_ts->lock );
848
    b_cmd =  TsStorageIsEmpty( p_ts->p_storage_r );
849 850 851 852
    vlc_mutex_unlock( &p_ts->lock );

    return b_cmd;
}
Laurent Aimar's avatar
Laurent Aimar committed
853 854 855 856 857 858 859
static bool TsIsUnused( ts_thread_t *p_ts )
{
    bool b_unused;

    vlc_mutex_lock( &p_ts->lock );
    b_unused = !p_ts->b_paused &&
               p_ts->i_rate == p_ts->i_rate_source &&
860
               TsStorageIsEmpty( p_ts->p_storage_r );
Laurent Aimar's avatar
Laurent Aimar committed
861 862 863 864
    vlc_mutex_unlock( &p_ts->lock );

    return b_unused;
}
865 866 867
static int TsChangePause( ts_thread_t *p_ts, bool b_source_paused, bool b_paused, mtime_t i_date )
{
    vlc_mutex_lock( &p_ts->lock );
868 869 870 871 872

    int i_ret;
    if( b_paused )
    {
        assert( !b_source_paused );
873
        i_ret = es_out_SetPauseState( p_ts->p_out, true, true, i_date );
874 875 876
    }
    else
    {
877
        i_ret = es_out_SetPauseState( p_ts->p_out, false, false, i_date );
878 879 880 881 882 883
    }

    if( !i_ret )
    {
        if( !b_paused )
        {
884
            assert( p_ts->i_pause_date > 0 );
885

886
            p_ts->i_cmd_delay += i_date - p_ts->i_pause_date;
887 888
        }

889 890
        p_ts->b_paused = b_paused;
        p_ts->i_pause_date = i_date;
891

892
        vlc_cond_signal( &p_ts->wait );
893
    }
894
    vlc_mutex_unlock( &p_ts->lock );
895 896
    return i_ret;
}
897
static int TsChangeRate( ts_thread_t *p_ts, int i_src_rate, int i_rate )
898
{
899
    int i_ret;
900

901 902
    vlc_mutex_lock( &p_ts->lock );
    p_ts->i_cmd_delay += p_ts->i_rate_delay;
903

904 905 906 907
    p_ts->i_rate_date = -1;
    p_ts->i_rate_delay = 0;
    p_ts->i_rate = i_rate;
    p_ts->i_rate_source = i_src_rate;
908

909 910
    i_ret = es_out_SetRate( p_ts->p_out, i_rate, i_rate );
    vlc_mutex_unlock( &p_ts->lock );
911

912
    return i_ret;
913
}
914 915 916 917 918 919 920 921 922 923 924 925 926
static mtime_t TsGetDelay( ts_thread_t *p_ts )
{
    mtime_t i_delay;

    vlc_mutex_lock( &p_ts->lock );
    i_delay = p_ts->i_cmd_delay + p_ts->i_rate_delay + p_ts->i_buffering_delay;
    if( p_ts->b_paused )
        i_delay += mdate() - p_ts->i_pause_date;
    vlc_mutex_unlock( &p_ts->lock );

    return i_delay;
}

927

928 929
static void *TsRun( vlc_object_t *p_thread )
{
930
    ts_thread_t *p_ts = (ts_thread_t*)p_thread;
931
    mtime_t i_buffering_date = -1;
932 933 934 935

    for( ;; )
    {
        ts_cmd_t cmd;
936
        mtime_t  i_deadline;
937
        bool b_buffering;
938

939
        /* Pop a command to execute */
940 941
        vlc_mutex_lock( &p_ts->lock );
        mutex_cleanup_push( &p_ts->lock );
942

943 944 945
        for( ;; )
        {
            const int canc = vlc_savecancel();
946
            b_buffering = es_out_GetBuffering( p_ts->p_out, NULL );
947

948
            if( ( !p_ts->b_paused || b_buffering ) && !TsPopCmdLocked( p_ts, &cmd, false ) )
949 950
            {
                vlc_restorecancel( canc );
951
                break;
952 953
            }
            vlc_restorecancel( canc );
954

955
            vlc_cond_wait( &p_ts->wait, &p_ts->lock );
956 957 958 959 960 961 962 963 964 965 966 967 968 969
        }

        if( b_buffering && i_buffering_date < 0 )
        {
            i_buffering_date = cmd.i_date;
        }
        else if( i_buffering_date > 0 )
        {
            p_ts->i_buffering_delay += i_buffering_date - cmd.i_date; /* It is < 0 */
            if( b_buffering )
                i_buffering_date = cmd.i_date;
            else
                i_buffering_date = -1;
        }
970

971 972
        if( p_ts->i_rate_date < 0 )
            p_ts->i_rate_date = cmd.i_date;
973

974 975
        p_ts->i_rate_delay = 0;
        if( p_ts->i_rate_source != p_ts->i_rate )
976
        {
977 978
            const mtime_t i_duration = cmd.i_date - p_ts->i_rate_date;
            p_ts->i_rate_delay = i_duration * p_ts->i_rate / p_ts->i_rate_source - i_duration;
979
        }
980
        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 )
981
        {
982 983
            const int canc = vlc_savecancel();

984
            /* Auto reset to rate 1.0 */
985
            msg_Warn( p_ts->p_input, "es out timeshift: auto reset rate to %d", p_ts->i_rate_source );
986

987
            p_ts->i_cmd_delay = 0;
988
            p_ts->i_buffering_delay = 0;
989

990
            p_ts->i_rate_delay = 0;
991
            p_ts->i_rate_date = -1;
992
            p_ts->i_rate = p_ts->i_rate_source;
993

994
            if( !es_out_SetRate( p_ts->p_out, p_ts->i_rate_source, p_ts->i_rate ) )
995
            {
996
                vlc_value_t val = { .i_int = p_ts->i_rate };
997 998 999
                /* Warn back input
                 * FIXME it is perfectly safe BUT it is ugly as it may hide a
                 * rate change requested by user */
1000
                input_ControlPush( p_ts->p_input, INPUT_CONTROL_SET_RATE, &val );
1001
            }
1002 1003

            vlc_restorecancel( canc );
1004
        }
1005
        i_deadline = cmd.i_date + p_ts->i_cmd_delay + p_ts->i_rate_delay + p_ts->i_buffering_delay;
1006 1007

        vlc_cleanup_run();
1008 1009 1010 1011 1012

        /* Regulate the speed of command processing to the same one than
         * reading  */
        vlc_cleanup_push( cmd_cleanup_routine, &cmd );

1013
        mwait( i_deadline );
1014 1015

        vlc_cleanup_pop();
1016

1017
        /* Execute the command  */
1018 1019 1020 1021
        const int canc = vlc_savecancel();
        switch( cmd.i_type )
        {
        case C_ADD:
1022
            CmdExecuteAdd( p_ts->p_out, &cmd );
1023 1024 1025
            CmdCleanAdd( &cmd );
            break;
        case C_SEND:
1026
            CmdExecuteSend( p_ts->p_out, &cmd );
1027 1028 1029
            CmdCleanSend( &cmd );
            break;
        case C_CONTROL:
1030
            CmdExecuteControl( p_ts->p_out, &cmd );
1031 1032 1033
            CmdCleanControl( &cmd );
            break;
        case C_DEL:
1034
            CmdExecuteDel( p_ts->p_out, &cmd );
1035 1036 1037 1038 1039
            break;
        default:
            assert(0);
            break;
        }
1040
        vlc_restorecancel( canc );
1041 1042 1043 1044 1045
    }

    return NULL;
}

1046 1047 1048
/*****************************************************************************
 *
 *****************************************************************************/
1049
static ts_storage_t *TsStorageNew( const char *psz_tmp_path, int64_t i_tmp_size_max )
1050
{
1051
    ts_storage_t *p_storage = calloc( 1, sizeof(ts_storage_t) );
1052 1053 1054 1055 1056 1057
    if( !p_storage )
        return NULL;

    /* */
    p_storage->p_next = NULL;

1058 1059 1060 1061 1062 1063 1064
    /* */
    p_storage->i_file_max = i_tmp_size_max;
    p_storage->i_file_size = 0;
    p_storage->p_filew = GetTmpFile( &p_storage->psz_file, psz_tmp_path );
    if( p_storage->psz_file )
        p_storage->p_filer = utf8_fopen( p_storage->psz_file, "rb" );

1065 1066 1067
    /* */
    p_storage->i_cmd_w = 0;
    p_storage->i_cmd_r = 0;
1068
    p_storage->i_cmd_max = 30000;
1069
    p_storage->p_cmd = malloc( p_storage->i_cmd_max * sizeof(*p_storage->p_cmd) );
1070
    //fprintf( stderr, "\nSTORAGE name=%s size=%d kbytes\n", p_storage->psz_file, p_storage->i_cmd_max * sizeof(*p_storage->p_cmd) /1024 );
1071

1072
    if( !p_storage->p_cmd || !p_storage->p_filew || !p_storage->p_filer )
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    {
        TsStorageDelete( p_storage );
        return NULL;
    }
    return p_storage;
}
static void TsStorageDelete( ts_storage_t *p_storage )
{
    while( p_storage->i_cmd_r < p_storage->i_cmd_w )
    {
        ts_cmd_t cmd;

1085
        TsStoragePopCmd( p_storage, &cmd, true );
1086 1087 1088 1089 1090

        CmdClean( &cmd );
    }
    free( p_storage->p_cmd );

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    if( p_storage->p_filer )
        fclose( p_storage->p_filer );
    if( p_storage->p_filew )
        fclose( p_storage->p_filew );

    if( p_storage->psz_file )
    {
        utf8_unlink( p_storage->psz_file );
        free( p_storage->psz_file );
    }

1102 1103
    free( p_storage );
}
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
static void TsStoragePack( ts_storage_t *p_storage )
{
    /* Try to release a bit of memory */
    if( p_storage->i_cmd_w >= p_storage->i_cmd_max )
        return;

    p_storage->i_cmd_max = __MAX( p_storage->i_cmd_w, 1 );

    ts_cmd_t *p_new = realloc( p_storage->p_cmd, p_storage->i_cmd_max * sizeof(*p_storage->p_cmd) );
    if( p_new )
        p_storage->p_cmd = p_new;
}
static bool TsStorageIsFull( ts_storage_t *p_storage, const ts_cmd_t *p_cmd )
1117
{
1118 1119 1120 1121 1122 1123 1124