es_out_timeshift.c 32 KB
Newer Older
1 2 3 4 5 6 7 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 56 57 58 59 60 61 62 63
/*****************************************************************************
 * es_out_timeshift.c: Es Out timeshift.
 *****************************************************************************
 * Copyright (C) 2008 Laurent Aimar
 * $Id$
 *
 * Authors: Laurent Aimar < fenrir _AT_ via _DOT_ ecp _DOT_ fr>
 *
 * 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
 *****************************************************************************/

enum
{
    C_ADD,
    C_SEND,
    C_DEL,
    C_CONTROL,
};

Laurent Aimar's avatar
Laurent Aimar committed
64 65 66 67
typedef struct
{
    es_out_id_t *p_es;
    es_format_t *p_fmt;
68
} ts_cmd_add_t;
Laurent Aimar's avatar
Laurent Aimar committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

typedef struct
{
    es_out_id_t *p_es;
} ts_cmd_del_t;

typedef struct
{
    es_out_id_t *p_es;
    block_t *p_block;
} ts_cmd_send_t;

typedef struct
{
    int  i_query;

    bool b_bool;
    bool *pb_bool;
    int  i_int;
    int  *pi_int;
    int64_t i_i64;
    vlc_meta_t *p_meta;
    vlc_epg_t *p_epg;
    es_out_id_t *p_es;
    es_format_t *p_fmt;
} ts_cmd_control_t;

96 97
typedef struct
{
98 99
    int     i_type;
    mtime_t i_date;
100 101
    union
    {
Laurent Aimar's avatar
Laurent Aimar committed
102 103 104 105
        ts_cmd_add_t     add;
        ts_cmd_del_t     del;
        ts_cmd_send_t    send;
        ts_cmd_control_t control;
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    };
} ts_cmd_t;

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;
125
    vlc_cond_t     wait;
126 127 128

    /* */
    bool           b_delayed;
129
    vlc_object_t   *p_thread;
130

131 132 133
    bool           b_paused;
    mtime_t        i_pause_date;

134 135 136 137 138
    int            i_rate;
    int            i_rate_source;
    mtime_t        i_rate_date;
    mtime_t        i_rate_delay;

139 140 141 142 143 144 145
    /* */
    int            i_es;
    es_out_id_t    **pp_es;

    /* */
    int            i_cmd;
    ts_cmd_t       **pp_cmd;
146
    mtime_t        i_cmd_delay;
147 148 149 150 151 152 153 154
};

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 * );

155 156
static int          TsStart( es_out_t * );
static void         TsStop( es_out_t * );
157 158 159 160 161
static void         TsPushCmd( es_out_t *, const ts_cmd_t * );
static int          TsPopCmd( es_out_t *, ts_cmd_t * );
static int          TsChangePause( es_out_t *, bool b_source_paused, bool b_paused, mtime_t i_date );
static int          TsChangeRate( es_out_t *, int i_src_rate, int i_rate );

162 163
static void         *TsRun( vlc_object_t * );

164 165
static void CmdClean( ts_cmd_t * );
static void cmd_cleanup_routine( void *p ) { CmdClean( p ); }
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

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 );

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 * );

static void CmdCleanAdd    ( ts_cmd_t * );
static void CmdCleanSend   ( ts_cmd_t * );
static void CmdCleanControl( ts_cmd_t *p_cmd );

static char *GetTmpPath( char *psz_path );
static FILE *GetTmpFile( const char *psz_path );

/*****************************************************************************
 * input_EsOutTimeshiftNew:
 *****************************************************************************/
187
es_out_t *input_EsOutTimeshiftNew( input_thread_t *p_input, es_out_t *p_next_out, int i_rate )
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
{
    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;

    /* */
    p_sys->p_input = p_input;
    p_sys->p_out = p_next_out;
    vlc_mutex_init_recursive( &p_sys->lock );
213 214
    vlc_cond_init( &p_sys->wait );

215
    p_sys->b_delayed = false;
216
    p_sys->p_thread = NULL;
217 218
    p_sys->b_paused = false;
    p_sys->i_pause_date = -1;
219 220 221 222
    p_sys->i_rate_source =
    p_sys->i_rate        = i_rate;
    p_sys->i_rate_date = -1;
    p_sys->i_rate_delay = 0;
223
    p_sys->i_cmd_delay = 0;
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

    /* TODO config
     * timeshift-granularity
     * timeshift-path
     */
    p_sys->i_tmp_size_max = 50 * 1024*1024;
    p_sys->psz_tmp_path = GetTmpPath( NULL );

    return p_out;
}

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

245 246 247
    if( p_sys->b_delayed )
        TsStop( p_out );

248 249 250 251 252 253 254
    TAB_CLEAN( p_sys->i_cmd, p_sys->pp_cmd  );

    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 );
255
    vlc_cond_destroy( &p_sys->wait );
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    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 );

    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 )
282
        TsPushCmd( p_out, &cmd );
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    else
        CmdExecuteAdd( p_out, &cmd );

    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 );

    CmdInitSend( &cmd, p_es, p_block );
    if( p_sys->b_delayed )
300
        TsPushCmd( p_out, &cmd );
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    else
        i_ret = CmdExecuteSend( p_out, &cmd) ;

    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 );

    CmdInitDel( &cmd, p_es );
    if( p_sys->b_delayed )
317
        TsPushCmd( p_out, &cmd );
318 319 320 321 322 323 324
    else
        CmdExecuteDel( p_out, &cmd );

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

    vlc_mutex_unlock( &p_sys->lock );
}
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

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

    if( p_sys->b_delayed && p_sys->i_cmd > 0 )
        *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;
}
static int ControlLockedGetBuffering( es_out_t *p_out, bool *pb_buffering )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( p_sys->b_delayed )
        *pb_buffering = true;
    else
        *pb_buffering = es_out_GetBuffering( p_sys->p_out );

    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;

    if( !p_sys->b_delayed &&
        !b_source_paused == !b_paused )
    {
        return es_out_SetPauseState( p_sys->p_out, b_source_paused, b_paused, i_date );
    }
373
    return TsChangePause( p_out, b_source_paused, b_paused, i_date );
374 375 376 377 378 379 380 381 382 383
}
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;

    if( !p_sys->b_delayed &&
        i_src_rate == i_rate )
    {
        return es_out_SetRate( p_sys->p_out, i_src_rate, i_rate );
    }
384
    return TsChangeRate( p_out, i_src_rate, i_rate );
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
}
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;

    if( !p_sys->b_delayed )
        return es_out_SetFrameNext( p_sys->p_out );

    /* TODO */
    msg_Err( p_sys->p_input, "EsOutTimeshift does not yet support frame next" );
    return VLC_EGENERIC;
}

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
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_GET_ACTIVE:
    case ES_OUT_SET_MODE:
    case ES_OUT_GET_MODE:
    case ES_OUT_SET_GROUP:
    case ES_OUT_GET_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_GET_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 )
        {
454
            TsPushCmd( p_out, &cmd );
455 456 457 458 459 460
            return VLC_SUCCESS;
        }
        return CmdExecuteControl( p_out, &cmd );
    }

    /* Special control */
461 462 463 464 465
    case ES_OUT_GET_EMPTY:
    {
        bool *pb_empty = (bool*)va_arg( args, bool* );
        return ControlLockedGetEmpty( p_out, pb_empty );
    }
466
    case ES_OUT_GET_WAKE_UP: /* TODO ? */
467 468 469 470
    {
        mtime_t *pi_wakeup = (mtime_t*)va_arg( args, mtime_t* );
        return ControlLockedGetWakeup( p_out, pi_wakeup );
    }
471
    case ES_OUT_GET_BUFFERING:
472 473 474 475
    {
        bool *pb_buffering = (bool *)va_arg( args, bool* );
        return ControlLockedGetBuffering( p_out, pb_buffering );
    }
476
    case ES_OUT_SET_PAUSE_STATE:
477 478 479 480 481 482 483
    {
        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 );
    }
484
    case ES_OUT_SET_RATE:
485 486 487 488 489 490
    {
        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 );
    }
491
    case ES_OUT_SET_TIME:
492 493 494 495 496
    {
        const mtime_t i_date = (mtime_t)va_arg( args, mtime_t );

        return ControlLockedSetTime( p_out, i_date );
    }
497
    case ES_OUT_SET_FRAME_NEXT:
498 499 500
    {
        return ControlLockedSetFrameNext( p_out );
    }
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

    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 );
    i_ret = ControlLocked( p_out, i_query, args );
    vlc_mutex_unlock( &p_sys->lock );

    return i_ret;
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
/*****************************************************************************
 *
 *****************************************************************************/
static int TsStart( es_out_t *p_out )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    assert( !p_sys->b_delayed );

    p_sys->p_thread = vlc_custom_create( p_sys->p_input, sizeof(vlc_object_t),
                                         VLC_OBJECT_GENERIC, "es out timeshift" );
    if( !p_sys->p_thread )
        return VLC_EGENERIC;

    p_sys->b_delayed = true;
    p_sys->p_thread->p_private = p_out;
    if( vlc_thread_create( p_sys->p_thread, "es out timeshift",
                           TsRun, VLC_THREAD_PRIORITY_INPUT, false ) )
    {
        msg_Err( p_sys->p_input, "cannot create input thread" );
        vlc_object_release( p_sys->p_thread );

        p_sys->b_delayed = false;
        return VLC_EGENERIC;
    }

    return VLC_SUCCESS;
}
static void TsStop( es_out_t *p_out )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    assert( p_sys->b_delayed );

    vlc_object_kill( p_sys->p_thread );
    vlc_thread_join( p_sys->p_thread );

Laurent Aimar's avatar
Laurent Aimar committed
557 558 559 560
    for( ;; )
    {
        ts_cmd_t cmd;

561
        if( TsPopCmd( p_out, &cmd ) )
Laurent Aimar's avatar
Laurent Aimar committed
562 563 564 565 566
            break;

        CmdClean( &cmd );
    }

567 568
    p_sys->b_delayed = false;
}
569 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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
static void TsPushCmd( es_out_t *p_out, const ts_cmd_t *p_cmd )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    ts_cmd_t *p_dup = malloc( sizeof(*p_dup) );

    if( p_dup )
    {
        *p_dup = *p_cmd;
        TAB_APPEND( p_sys->i_cmd, p_sys->pp_cmd, p_dup );

        vlc_cond_signal( &p_sys->wait );
    }
}
static int TsPopCmd( es_out_t *p_out, ts_cmd_t *p_cmd )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( p_sys->i_cmd <= 0 )
        return VLC_EGENERIC;

    *p_cmd = *p_sys->pp_cmd[0];

    free( p_sys->pp_cmd[0] );
    TAB_REMOVE( p_sys->i_cmd, p_sys->pp_cmd, p_sys->pp_cmd[0] );
    return VLC_SUCCESS;
}
static int TsChangePause( 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;

    if( p_sys->p_input->b_can_pace_control )
    {
        /* 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" );
        return VLC_EGENERIC;
    }

    int i_ret;
    if( b_paused )
    {
        assert( !b_source_paused );

        if( !p_sys->b_delayed )
            TsStart( p_out );

        i_ret = es_out_SetPauseState( p_sys->p_out, true, true, i_date );
    }
    else
    {
        i_ret = es_out_SetPauseState( p_sys->p_out, false, false, i_date );
    }

    if( !i_ret )
    {
        if( !b_paused )
        {
            assert( p_sys->i_pause_date > 0 );

            p_sys->i_cmd_delay += i_date - p_sys->i_pause_date;
        }

        p_sys->b_paused = b_paused;
        p_sys->i_pause_date = i_date;

        vlc_cond_signal( &p_sys->wait );
    }
    return i_ret;
}
static int TsChangeRate( es_out_t *p_out, int i_src_rate, int i_rate )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( p_sys->p_input->b_can_pace_control )
    {
        /* 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" );
        return VLC_EGENERIC;
    }

    p_sys->i_cmd_delay += p_sys->i_rate_delay;

    p_sys->i_rate_date = -1;
    p_sys->i_rate_delay = 0;
    p_sys->i_rate = i_rate;
    p_sys->i_rate_source = i_src_rate;

    if( !p_sys->b_delayed )
        TsStart( p_out );

    return es_out_SetRate( p_sys->p_out, i_rate, i_rate );
}

665 666 667 668 669 670 671 672
static void *TsRun( vlc_object_t *p_thread )
{
    es_out_t *p_out = p_thread->p_private;
    es_out_sys_t *p_sys = p_out->p_sys;

    for( ;; )
    {
        ts_cmd_t cmd;
673
        mtime_t  i_deadline;
674

675
        /* Pop a command to execute */
676 677 678
        vlc_mutex_lock( &p_sys->lock );
        mutex_cleanup_push( &p_sys->lock );

679
        while( p_sys->b_paused || TsPopCmd( p_out, &cmd ) )
680 681
            vlc_cond_wait( &p_sys->wait, &p_sys->lock );

682 683 684 685 686 687 688 689 690 691 692
        if( p_sys->i_rate_date < 0 )
            p_sys->i_rate_date = cmd.i_date;

        p_sys->i_rate_delay = 0;
        if( p_sys->i_rate_source != p_sys->i_rate )
        {
            const mtime_t i_duration = cmd.i_date - p_sys->i_rate_date;
            p_sys->i_rate_delay = i_duration * p_sys->i_rate / p_sys->i_rate_source - i_duration;
        }
        if( p_sys->i_cmd_delay + p_sys->i_rate_delay < 0 )
        {
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
            /* Auto reset to rate 1.0 */
            msg_Warn( p_sys->p_input, "es out timeshift: auto reset rate to %d", p_sys->i_rate_source );

            p_sys->i_cmd_delay = 0;

            p_sys->i_rate_date = -1;
            p_sys->i_rate_delay = 0;
            p_sys->i_rate = p_sys->i_rate_source;

            if( !es_out_SetRate( p_sys->p_out, p_sys->i_rate_source, p_sys->i_rate ) )
            {
                vlc_value_t val = { .i_int = p_sys->i_rate };
                /* Warn back input
                 * FIXME it is perfectly safe BUT it is ugly as it may hide a
                 * rate change requested by user */
                input_ControlPush( p_sys->p_input, INPUT_CONTROL_SET_RATE, &val );
            }
710
        }
711
        i_deadline = cmd.i_date + p_sys->i_cmd_delay + p_sys->i_rate_delay;
712 713

        vlc_cleanup_run();
714 715 716 717 718 719

        /* Regulate the speed of command processing to the same one than
         * reading  */
        //fprintf( stderr, "d=%d - %d\n", (int)(p_sys->i_cmd_delay/1000), (int)( (mdate() - cmd.i_date - p_sys->i_cmd_delay)/1000) );
        vlc_cleanup_push( cmd_cleanup_routine, &cmd );

720
        mwait( i_deadline );
721 722

        vlc_cleanup_pop();
723

724
        /* Execute the command */
725
        const int canc = vlc_savecancel();
726 727

        vlc_mutex_lock( &p_sys->lock );
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        switch( cmd.i_type )
        {
        case C_ADD:
            CmdExecuteAdd( p_out, &cmd );
            CmdCleanAdd( &cmd );
            break;
        case C_SEND:
            CmdExecuteSend( p_out, &cmd );
            CmdCleanSend( &cmd );
            break;
        case C_CONTROL:
            CmdExecuteControl( p_out, &cmd );
            CmdCleanControl( &cmd );
            break;
        case C_DEL:
            CmdExecuteDel( p_out, &cmd );
            break;
        default:
            assert(0);
            break;
        }
        vlc_mutex_unlock( &p_sys->lock );
750 751

        vlc_restorecancel( canc );
752 753 754 755 756
    }

    return NULL;
}

757 758 759
/*****************************************************************************
 *
 *****************************************************************************/
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
static void CmdClean( ts_cmd_t *p_cmd )
{
    switch( p_cmd->i_type )
    {
    case C_ADD:
        CmdCleanAdd( p_cmd );
        break;
    case C_SEND:
        CmdCleanSend( p_cmd );
        break;
    case C_CONTROL:
        CmdCleanControl( p_cmd );
        break;
    case C_DEL:
        break;
    default:
        assert(0);
        break;
    }
}

781 782 783
static int CmdInitAdd( ts_cmd_t *p_cmd, es_out_id_t *p_es, const es_format_t *p_fmt, bool b_copy )
{
    p_cmd->i_type = C_ADD;
784
    p_cmd->i_date = mdate();
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    p_cmd->add.p_es = p_es;
    if( b_copy )
    {
        p_cmd->add.p_fmt = malloc( sizeof(*p_fmt) );
        if( !p_cmd->add.p_fmt )
            return VLC_EGENERIC;
        es_format_Copy( p_cmd->add.p_fmt, p_fmt );
    }
    else
    {
        p_cmd->add.p_fmt = (es_format_t*)p_fmt;
    }
    return VLC_SUCCESS;
}
static void CmdExecuteAdd( es_out_t *p_out, ts_cmd_t *p_cmd )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    p_cmd->add.p_es->p_es = es_out_Add( p_sys->p_out, p_cmd->add.p_fmt );
}
static void CmdCleanAdd( ts_cmd_t *p_cmd )
{
    es_format_Clean( p_cmd->add.p_fmt );
    free( p_cmd->add.p_fmt );
}

static void CmdInitSend( ts_cmd_t *p_cmd, es_out_id_t *p_es, block_t *p_block )
{
    p_cmd->i_type = C_SEND;
814
    p_cmd->i_date = mdate();
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    p_cmd->send.p_es = p_es;
    p_cmd->send.p_block = p_block;
}
static int CmdExecuteSend( es_out_t *p_out, ts_cmd_t *p_cmd )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    block_t *p_block = p_cmd->send.p_block;

    p_cmd->send.p_block = NULL;

    if( p_block )
    {
        if( p_cmd->send.p_es->p_es )
            return es_out_Send( p_sys->p_out, p_cmd->send.p_es->p_es, p_block );
        block_Release( p_block );
    }
    return VLC_EGENERIC;
}
static void CmdCleanSend( ts_cmd_t *p_cmd )
{
    if( p_cmd->send.p_block )
        block_Release( p_cmd->send.p_block );
}

static int CmdInitDel( ts_cmd_t *p_cmd, es_out_id_t *p_es )
{
    p_cmd->i_type = C_DEL;
842
    p_cmd->i_date = mdate();
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
    p_cmd->del.p_es = p_es;
    return VLC_SUCCESS;
}
static void CmdExecuteDel( es_out_t *p_out, ts_cmd_t *p_cmd )
{
    es_out_sys_t *p_sys = p_out->p_sys;

    if( p_cmd->del.p_es->p_es )
        es_out_Del( p_sys->p_out, p_cmd->del.p_es->p_es );
    free( p_cmd->del.p_es );
}

static int CmdInitControl( ts_cmd_t *p_cmd, int i_query, va_list args, bool b_copy )
{
    p_cmd->i_type = C_CONTROL;
858
    p_cmd->i_date = mdate();
859
    p_cmd->control.i_query = i_query;
860 861 862
    p_cmd->control.p_meta  = NULL;
    p_cmd->control.p_epg = NULL;
    p_cmd->control.p_fmt = NULL;
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

    switch( i_query )
    {
    /* Pass-through control */
    case ES_OUT_SET_ACTIVE:  /* arg1= bool                     */
        p_cmd->control.b_bool = (bool)va_arg( args, int );
        break;

    case ES_OUT_GET_ACTIVE:  /* arg1= bool*                    */
        p_cmd->control.pb_bool = (bool*)va_arg( args, bool * );
        break;

    case ES_OUT_SET_MODE:    /* arg1= int                            */
    case ES_OUT_SET_GROUP:   /* arg1= int                            */
    case ES_OUT_DEL_GROUP:   /* arg1=int i_group */
        p_cmd->control.i_int = (int)va_arg( args, int );
        break;

    case ES_OUT_GET_MODE:    /* arg2= int*                           */
    case ES_OUT_GET_GROUP:   /* arg1= int*                           */
        p_cmd->control.pi_int = (int*)va_arg( args, int * );
        break;

    case ES_OUT_SET_PCR:                /* arg1=int64_t i_pcr(microsecond!) (using default group 0)*/
    case ES_OUT_SET_NEXT_DISPLAY_TIME:  /* arg1=int64_t i_pts(microsecond) */
        p_cmd->control.i_i64 = (int64_t)va_arg( args, int64_t );
        break;

    case ES_OUT_SET_GROUP_PCR:          /* arg1= int i_group, arg2=int64_t i_pcr(microsecond!)*/
        p_cmd->control.i_int = (int)va_arg( args, int );
        p_cmd->control.i_i64 = (int64_t)va_arg( args, int64_t );
        break;

    case ES_OUT_RESET_PCR:           /* no arg */
        break;

    case ES_OUT_SET_GROUP_META:  /* arg1=int i_group arg2=vlc_meta_t* */
    {
        p_cmd->control.i_int = (int)va_arg( args, int );
        vlc_meta_t *p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t * );

        if( b_copy )
        {
            p_cmd->control.p_meta = vlc_meta_New();
            if( !p_cmd->control.p_meta )
                return VLC_EGENERIC;
            vlc_meta_Merge( p_cmd->control.p_meta, p_meta );
        }
        else
        {
            p_cmd->control.p_meta = p_meta;
        }
        break;
    }

    case ES_OUT_SET_GROUP_EPG:   /* arg1=int i_group arg2=vlc_epg_t* */
    {
        p_cmd->control.i_int = (int)va_arg( args, int );
        vlc_epg_t *p_epg = (vlc_epg_t*)va_arg( args, vlc_epg_t * );

        if( b_copy )
        {
            p_cmd->control.p_epg = vlc_epg_New( p_epg->psz_name );
            if( !p_cmd->control.p_epg )
                return VLC_EGENERIC;
            for( int i = 0; i < p_epg->i_event; i++ )
            {
                vlc_epg_event_t *p_evt = p_epg->pp_event[i];

                vlc_epg_AddEvent( p_cmd->control.p_epg,
                                  p_evt->i_start, p_evt->i_duration,
                                  p_evt->psz_name,
                                  p_evt->psz_short_description, p_evt->psz_description );
            }
            vlc_epg_SetCurrent( p_cmd->control.p_epg,
                                p_epg->p_current ? p_epg->p_current->i_start : -1 );
        }
        else
        {
            p_cmd->control.p_epg = p_epg;
        }
        break;
    }

    /* Modified control */
    case ES_OUT_SET_ES:      /* arg1= es_out_id_t*                   */
    case ES_OUT_RESTART_ES:  /* arg1= es_out_id_t*                   */
    case ES_OUT_SET_ES_DEFAULT: /* arg1= es_out_id_t*                */
        p_cmd->control.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
        break;

    case ES_OUT_SET_ES_STATE:/* arg1= es_out_id_t* arg2=bool   */
        p_cmd->control.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
        p_cmd->control.b_bool = (bool)va_arg( args, int );
        break;

    case ES_OUT_GET_ES_STATE:/* arg1= es_out_id_t* arg2=bool*  */
        p_cmd->control.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
        p_cmd->control.pb_bool = (bool*)va_arg( args, bool * );
        break;

    case ES_OUT_SET_ES_FMT:     /* arg1= es_out_id_t* arg2=es_format_t* */
    {
        p_cmd->control.p_es = (es_out_id_t*)va_arg( args, es_out_id_t * );
        es_format_t *p_fmt = (es_format_t*)va_arg( args, es_format_t * );

        if( b_copy )
        {
            p_cmd->control.p_fmt = malloc( sizeof(*p_fmt) );
            if( !p_cmd->control.p_fmt )
                return VLC_EGENERIC;
            es_format_Copy( p_cmd->control.p_fmt, p_fmt );
        }
        else
        {
            p_cmd->control.p_fmt = p_fmt;
        }
        break;
    }

    default:
        assert(0);
        return VLC_EGENERIC;
    }

    return VLC_SUCCESS;
}
static int CmdExecuteControl( es_out_t *p_out, ts_cmd_t *p_cmd )
{
    es_out_sys_t *p_sys = p_out->p_sys;
    const int i_query = p_cmd->control.i_query;

    switch( i_query )
    {
    /* Pass-through control */
    case ES_OUT_SET_ACTIVE:  /* arg1= bool                     */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.b_bool );

    case ES_OUT_GET_ACTIVE:  /* arg1= bool*                    */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.pb_bool );

    case ES_OUT_SET_MODE:    /* arg1= int                            */
    case ES_OUT_SET_GROUP:   /* arg1= int                            */
    case ES_OUT_DEL_GROUP:   /* arg1=int i_group */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.i_int );

    case ES_OUT_GET_MODE:    /* arg2= int*                           */
    case ES_OUT_GET_GROUP:   /* arg1= int*                           */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.pi_int );

    case ES_OUT_SET_PCR:                /* arg1=int64_t i_pcr(microsecond!) (using default group 0)*/
    case ES_OUT_SET_NEXT_DISPLAY_TIME:  /* arg1=int64_t i_pts(microsecond) */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.i_i64 );

    case ES_OUT_SET_GROUP_PCR:          /* arg1= int i_group, arg2=int64_t i_pcr(microsecond!)*/
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.i_int, p_cmd->control.i_i64 );

    case ES_OUT_RESET_PCR:           /* no arg */
        return es_out_Control( p_sys->p_out, i_query );

    case ES_OUT_SET_GROUP_META:  /* arg1=int i_group arg2=vlc_meta_t* */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.i_int, p_cmd->control.p_meta );

    case ES_OUT_SET_GROUP_EPG:   /* arg1=int i_group arg2=vlc_epg_t* */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.i_int, p_cmd->control.p_epg );

    /* Modified control */
    case ES_OUT_SET_ES:      /* arg1= es_out_id_t*                   */
    case ES_OUT_RESTART_ES:  /* arg1= es_out_id_t*                   */
    case ES_OUT_SET_ES_DEFAULT: /* arg1= es_out_id_t*                */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.p_es->p_es );

    case ES_OUT_SET_ES_STATE:/* arg1= es_out_id_t* arg2=bool   */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.p_es->p_es, p_cmd->control.b_bool );

    case ES_OUT_GET_ES_STATE:/* arg1= es_out_id_t* arg2=bool*  */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.p_es->p_es, p_cmd->control.pb_bool );

    case ES_OUT_SET_ES_FMT:     /* arg1= es_out_id_t* arg2=es_format_t* */
        return es_out_Control( p_sys->p_out, i_query, p_cmd->control.p_es->p_es, p_cmd->control.p_fmt );

    default:
        assert(0);
        msg_Err( p_sys->p_input, "Unknown es_out_Control query in CmdExecuteControl!" );
        return VLC_EGENERIC;
    }
}
static void CmdCleanControl( ts_cmd_t *p_cmd )
{
    if( p_cmd->control.p_meta )
        vlc_meta_Delete( p_cmd->control.p_meta );
    if( p_cmd->control.p_epg )
        vlc_epg_Delete( p_cmd->control.p_epg );
    if( p_cmd->control.p_fmt )
    {
        es_format_Clean( p_cmd->control.p_fmt );
        free( p_cmd->control.p_fmt );
    }
}


/*****************************************************************************
 * GetTmpFile/Path:
 *****************************************************************************/
static char *GetTmpPath( char *psz_path )
{
    if( psz_path && *psz_path )
    {
        /* Make sure that the path exists and is a directory */
        struct stat s;
        const int i_ret = utf8_stat( psz_path, &s );

        if( i_ret < 0 && !utf8_mkdir( psz_path, 0600 ) )
            return psz_path;
        else if( i_ret == 0 && ( s.st_mode & S_IFDIR ) )
            return psz_path;
    }
    free( psz_path );

    /* Create a suitable path */
#if defined (WIN32) && !defined (UNDER_CE)
    const DWORD dwCount = GetTempPathW( 0, NULL );
    wchar_t *psw_path = calloc( dwCount + 1, sizeof(wchar_t) );
    if( psw_path )
    {
        if( GetTempPathW( dwCount + 1, psw_path ) <= 0 )
        {
            free( psw_path );

            psw_path = _wgetcwd( NULL, 0 );
        }
    }

    psz_path = NULL;
    if( psw_path )
    {
        psz_path = FromWide( psw_path );
        while( psz_path && *psz_path && psz_path[strlen( psz_path ) - 1] == '\\' )
            psz_path[strlen( psz_path ) - 1] = '\0';

        free( psw_path );
    }

    if( !psz_path || *psz_path == '\0' )
    {
        free( psz_path );
        return strdup( "C:" );
    }
#else
    psz_path = strdup( "/tmp" );
#endif

    return psz_path;
}

static FILE *GetTmpFile( const char *psz_path )
{
    char *psz_name;
    int fd;
    FILE *f;

    /* */
    if( asprintf( &psz_name, "%s/vlc-timeshift.XXXXXX", psz_path ) < 0 )
        return NULL;

    /* */
    fd = mkstemp( psz_name );
    free( psz_name );

    if( fd < 0 )
        return NULL;

    /* */
    f = fdopen( fd, "rw+" );
    if( !f )
        close( fd );

    return f;
}