vdr.c 29.6 KB
Newer Older
1 2 3 4 5
/*****************************************************************************
 * vdr.c: VDR recordings access plugin
 *****************************************************************************
 * Copyright (C) 2010 Tobias Güntner
 *
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
6 7 8
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
9 10 11 12
 * (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
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
13 14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
15
 *
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
16 17 18
 * You should have received a copy of the GNU Lesser 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.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *****************************************************************************/

/***
VDR splits recordings into multiple files and stores each recording in a
separate directory. If VLC opens a normal directory, the filesystem module
will add all files to the playlist. If, however, VLC opens a VDR recording,
this module will join all files within that directory and provide a single
continuous stream instead.

VDR recordings have either of two directory layouts:
    1) PES format:
        /path/to/0000-00-00.00.00.00.00.rec/
            001.vdr, 002.vdr, 003.vdr, ...
            index.vdr, info.vdr, marks.vdr, ...
    2) TS format:
34 35
        /path/to/0000-00-00.00.00.0-0.rec/
            00001.ts, 00002.ts, 00003.ts, ...
36 37 38 39 40 41 42 43 44 45 46 47
            index, info, marks, ...
See http://www.vdr-wiki.de/ and http://www.tvdr.de/ for more information.
***/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

48
#include <sys/types.h>
49
#include <sys/stat.h>
50
#include <fcntl.h>
51
#include <unistd.h>
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

#include <ctype.h>
#include <time.h>
#include <errno.h>

#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_access.h>
#include <vlc_input.h>
#include <vlc_fs.h>
#include <vlc_charset.h>
#include <vlc_dialog.h>
#include <vlc_configuration.h>

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );

#define HELP_TEXT N_("Support for VDR recordings (http://www.tvdr.de/).")

#define CHAPTER_OFFSET_TEXT N_("Chapter offset in ms")
#define CHAPTER_OFFSET_LONGTEXT N_( \
    "Move all chapters. This value should be set in milliseconds." )

#define FPS_TEXT N_("Frame rate")
#define FPS_LONGTEXT N_( \
    "Default frame rate for chapter import." )

vlc_module_begin ()
    set_category( CAT_INPUT )
    set_shortname( N_("VDR") )
    set_help( HELP_TEXT )
    set_subcategory( SUBCAT_INPUT_ACCESS )
    set_description( N_("VDR recordings") )
88
    add_integer( "vdr-chapter-offset", 0,
89
        CHAPTER_OFFSET_TEXT, CHAPTER_OFFSET_LONGTEXT, true )
90
    add_float_with_range( "vdr-fps", 25, 1, 1000,
91 92 93 94 95 96 97 98 99 100 101 102 103
        FPS_TEXT, FPS_LONGTEXT, true )
    set_capability( "access", 60 )
    add_shortcut( "vdr" )
    add_shortcut( "directory" )
    add_shortcut( "dir" )
    add_shortcut( "file" )
    set_callbacks( Open, Close )
vlc_module_end ()

/*****************************************************************************
 * Local prototypes, constants, structures
 *****************************************************************************/

104 105 106
/* minimum chapter size in seconds */
#define MIN_CHAPTER_SIZE 5

107 108 109 110 111 112
TYPEDEF_ARRAY( uint64_t, size_array_t );

struct access_sys_t
{
    /* file sizes of all parts */
    size_array_t file_sizes;
113
    uint64_t offset;
114
    uint64_t size; /* total size */
115 116 117 118 119 120 121 122 123 124

    /* index and fd of current open file */
    unsigned i_current_file;
    int fd;

    /* meta data */
    vlc_meta_t *p_meta;

    /* cut marks */
    input_title_t *p_marks;
125
    uint64_t *offsets;
126
    unsigned cur_seekpoint;
127 128 129 130 131 132 133 134 135 136 137
    float fps;

    /* file format: true=TS, false=PES */
    bool b_ts_format;
};

#define CURRENT_FILE_SIZE ARRAY_VAL(p_sys->file_sizes, p_sys->i_current_file)
#define FILE_SIZE(pos)    ARRAY_VAL(p_sys->file_sizes, pos)
#define FILE_COUNT        (unsigned)p_sys->file_sizes.i_size

static int Control( access_t *, int, va_list );
138
static ssize_t Read( access_t *p_access, void *p_buffer, size_t i_len );
139 140
static int Seek( access_t *p_access, uint64_t i_pos);
static void FindSeekpoint( access_t *p_access );
141
static bool ScanDirectory( access_t *p_access );
142 143 144 145 146 147 148 149 150 151 152 153
static char *GetFilePath( access_t *p_access, unsigned i_file );
static bool ImportNextFile( access_t *p_access );
static bool SwitchFile( access_t *p_access, unsigned i_file );
static void OptimizeForRead( int fd );
static void UpdateFileSize( access_t *p_access );
static FILE *OpenRelativeFile( access_t *p_access, const char *psz_file );
static bool ReadLine( char **ppsz_line, size_t *pi_size, FILE *p_file );
static void ImportMeta( access_t *p_access );
static void ImportMarks( access_t *p_access );
static bool ReadIndexRecord( FILE *p_file, bool b_ts, int64_t i_frame,
                            uint64_t *pi_offset, uint16_t *pi_file_num );
static int64_t ParseFrameNumber( const char *psz_line, float fps );
154
static const char *BaseName( const char *psz_path );
155 156 157 158 159 160 161 162 163 164 165 166 167 168

/*****************************************************************************
 * Open a directory
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    access_t *p_access = (access_t*)p_this;

    if( !p_access->psz_filepath )
        return VLC_EGENERIC;

    /* Some tests can be skipped if this module was explicitly requested.
     * That way, the user can play "corrupt" recordings if necessary
     * and we can avoid false positives in the general case. */
169
    bool b_strict = strcmp( p_access->psz_name, "vdr" );
170

171
    /* Do a quick test based on the directory name to see if this
172 173 174 175
     * directory might contain a VDR recording. We can be reasonably
     * sure if ScanDirectory() actually finds files. */
    if( b_strict )
    {
176 177 178 179 180 181
        char psz_extension[4];
        int i_length = 0;
        const char *psz_name = BaseName( p_access->psz_filepath );
        if( sscanf( psz_name, "%*u-%*u-%*u.%*u.%*u.%*u%*[-.]%*u.%3s%n",
            psz_extension, &i_length ) != 1 || strcasecmp( psz_extension, "rec" ) ||
            ( psz_name[i_length] != DIR_SEP_CHAR && psz_name[i_length] != '\0' ) )
182 183 184 185 186 187 188 189 190
            return VLC_EGENERIC;
    }

    /* Only directories can be recordings */
    struct stat st;
    if( vlc_stat( p_access->psz_filepath, &st ) ||
        !S_ISDIR( st.st_mode ) )
        return VLC_EGENERIC;

191
    access_sys_t *p_sys = vlc_calloc( p_this, 1, sizeof( *p_sys ) );
192 193 194 195 196

    if( unlikely(p_sys == NULL) )
        return VLC_ENOMEM;

    p_access->p_sys = p_sys;
197
    p_sys->fd = -1;
198
    p_sys->cur_seekpoint = 0;
199 200 201 202
    p_sys->fps = var_InheritFloat( p_access, "vdr-fps" );
    ARRAY_INIT( p_sys->file_sizes );

    /* Import all files and prepare playback. */
203
    if( !ScanDirectory( p_access ) ||
204 205 206 207 208 209
        !SwitchFile( p_access, 0 ) )
    {
        Close( p_this );
        return VLC_EGENERIC;
    }

210
    ACCESS_SET_CALLBACKS( Read, NULL, Control, Seek );
211 212 213 214 215 216 217 218 219 220 221 222
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Close files and free resources
 *****************************************************************************/
static void Close( vlc_object_t * p_this )
{
    access_t *p_access = (access_t*)p_this;
    access_sys_t *p_sys = p_access->p_sys;

    if( p_sys->fd != -1 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
223
        vlc_close( p_sys->fd );
224 225 226 227 228
    ARRAY_RESET( p_sys->file_sizes );

    if( p_sys->p_meta )
        vlc_meta_Delete( p_sys->p_meta );

229 230
    size_t count = p_sys->p_marks->i_seekpoint;
    TAB_CLEAN( count, p_sys->offsets );
231 232 233 234 235 236
    vlc_input_title_Delete( p_sys->p_marks );
}

/*****************************************************************************
 * Determine format and import files
 *****************************************************************************/
237
static bool ScanDirectory( access_t *p_access )
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
{
    access_sys_t *p_sys = p_access->p_sys;

    /* find first part and determine directory format */
    p_sys->b_ts_format = true;
    if( !ImportNextFile( p_access ) )
    {
        p_sys->b_ts_format = !p_sys->b_ts_format;
        if( !ImportNextFile( p_access ) )
            return false;
    }

    /* get all remaining parts */
    while( ImportNextFile( p_access ) )
        continue;

    /* import meta data etc. */
    ImportMeta( p_access );

    /* cut marks depend on meta data and file sizes */
    ImportMarks( p_access );

    return true;
}

/*****************************************************************************
 * Control input stream
 *****************************************************************************/
static int Control( access_t *p_access, int i_query, va_list args )
{
    access_sys_t *p_sys = p_access->p_sys;
    input_title_t ***ppp_title;
    int i;
    int64_t *pi64;
    vlc_meta_t *p_meta;

    switch( i_query )
    {
276 277 278 279
        case STREAM_CAN_SEEK:
        case STREAM_CAN_FASTSEEK:
        case STREAM_CAN_PAUSE:
        case STREAM_CAN_CONTROL_PACE:
280 281 282
            *va_arg( args, bool* ) = true;
            break;

283
        case STREAM_GET_SIZE:
284 285 286
            *va_arg( args, uint64_t* ) = p_sys->size;
            break;

287
        case STREAM_GET_PTS_DELAY:
288
            pi64 = va_arg( args, int64_t * );
289 290
            *pi64 = INT64_C(1000)
                  * var_InheritInteger( p_access, "file-caching" );
291 292
            break;

293
        case STREAM_SET_PAUSE_STATE:
294 295 296
            /* nothing to do */
            break;

297
        case STREAM_GET_TITLE_INFO:
298 299 300 301 302
            /* return a copy of our seek points */
            if( !p_sys->p_marks )
                return VLC_EGENERIC;
            ppp_title = va_arg( args, input_title_t*** );
            *va_arg( args, int* ) = 1;
303
            *ppp_title = malloc( sizeof( **ppp_title ) );
304 305 306 307 308
            if( !*ppp_title )
                return VLC_ENOMEM;
            **ppp_title = vlc_input_title_Duplicate( p_sys->p_marks );
            break;

309
        case STREAM_GET_TITLE:
310 311 312
            *va_arg( args, unsigned * ) = 0;
            break;

313
        case STREAM_GET_SEEKPOINT:
314 315 316
            *va_arg( args, unsigned * ) = p_sys->cur_seekpoint;
            break;

317
        case STREAM_GET_CONTENT_TYPE:
318
            *va_arg( args, char ** ) =
319
                strdup( p_sys->b_ts_format ? "video/MP2T" : "video/MP2P" );
320 321
            break;

322
        case STREAM_SET_TITLE:
323 324 325
            /* ignore - only one title */
            break;

326
        case STREAM_SET_SEEKPOINT:
327
            i = va_arg( args, int );
328
            return Seek( p_access, p_sys->offsets[i] );
329

330
        case STREAM_GET_META:
331 332 333 334 335 336 337 338 339 340 341 342 343
            p_meta = va_arg( args, vlc_meta_t* );
            vlc_meta_Merge( p_meta, p_sys->p_meta );
            break;

        default:
            return VLC_EGENERIC;
    }
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Read and concatenate files
 *****************************************************************************/
344
static ssize_t Read( access_t *p_access, void *p_buffer, size_t i_len )
345 346 347 348 349 350 351 352 353 354 355 356
{
    access_sys_t *p_sys = p_access->p_sys;

    if( p_sys->fd == -1 )
        /* no more data */
        return 0;

    ssize_t i_ret = read( p_sys->fd, p_buffer, i_len );

    if( i_ret > 0 )
    {
        /* success */
357
        p_sys->offset += i_ret;
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        UpdateFileSize( p_access );
        FindSeekpoint( p_access );
        return i_ret;
    }
    else if( i_ret == 0 )
    {
        /* check for new files in case the recording is still active */
        if( p_sys->i_current_file >= FILE_COUNT - 1 )
            ImportNextFile( p_access );
        /* play next file */
        SwitchFile( p_access, p_sys->i_current_file + 1 );
        return -1;
    }
    else if( errno == EINTR )
    {
        /* try again later */
        return -1;
    }
    else
    {
        /* abort on read error */
379
        msg_Err( p_access, "failed to read (%s)", vlc_strerror_c(errno) );
Thomas Guillem's avatar
Thomas Guillem committed
380 381 382
        vlc_dialog_display_error( p_access, _("File reading failed"),
            _("VLC could not read the file (%s)."),
            vlc_strerror(errno) );
383 384 385 386 387 388 389 390 391 392 393 394
        SwitchFile( p_access, -1 );
        return 0;
    }
}

/*****************************************************************************
 * Seek to a specific location in a file
 *****************************************************************************/
static int Seek( access_t *p_access, uint64_t i_pos )
{
    access_sys_t *p_sys = p_access->p_sys;

395
    /* might happen if called by STREAM_SET_SEEKPOINT */
396
    i_pos = __MIN( i_pos, p_sys->size );
397

398
    p_sys->offset = i_pos;
399 400 401 402 403 404

    /* find correct chapter */
    FindSeekpoint( p_access );

    /* find correct file */
    unsigned i_file = 0;
405 406
    while( i_file < FILE_COUNT - 1 &&
           i_pos >= FILE_SIZE( i_file ) )
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    {
        i_pos -= FILE_SIZE( i_file );
        i_file++;
    }
    if( !SwitchFile( p_access, i_file ) )
        return VLC_EGENERIC;

    /* adjust position within that file */
    return lseek( p_sys->fd, i_pos, SEEK_SET ) != -1 ?
        VLC_SUCCESS : VLC_EGENERIC;
}

/*****************************************************************************
 * Change the chapter index to match the current position
 *****************************************************************************/
static void FindSeekpoint( access_t *p_access )
{
    access_sys_t *p_sys = p_access->p_sys;
    if( !p_sys->p_marks )
        return;

428
    int new_seekpoint = p_sys->cur_seekpoint;
429
    if( p_sys->offset < p_sys->offsets[p_sys->cur_seekpoint] )
430 431
    {
        /* i_pos moved backwards, start fresh */
432
        new_seekpoint = 0;
433 434 435
    }

    /* only need to check the following seekpoints */
436
    while( new_seekpoint + 1 < p_sys->p_marks->i_seekpoint &&
437
        p_sys->offset >= p_sys->offsets[new_seekpoint + 1] )
438
    {
439
        new_seekpoint++;
440 441
    }

442
    p_sys->cur_seekpoint = new_seekpoint;
443 444 445 446 447 448 449
}

/*****************************************************************************
 * Returns the path of a certain part
 *****************************************************************************/
static char *GetFilePath( access_t *p_access, unsigned i_file )
{
450
    access_sys_t *sys = p_access->p_sys;
451
    char *psz_path;
452 453

    if( asprintf( &psz_path, sys->b_ts_format ?
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
        "%s" DIR_SEP "%05u.ts" : "%s" DIR_SEP "%03u.vdr",
        p_access->psz_filepath, i_file + 1 ) == -1 )
        return NULL;
    else
        return psz_path;
}

/*****************************************************************************
 * Check if another part exists and import it
 *****************************************************************************/
static bool ImportNextFile( access_t *p_access )
{
    access_sys_t *p_sys = p_access->p_sys;

    char *psz_path = GetFilePath( p_access, FILE_COUNT );
    if( !psz_path )
        return false;

    struct stat st;
    if( vlc_stat( psz_path, &st ) )
    {
475 476
        msg_Dbg( p_access, "could not stat %s: %s", psz_path,
                 vlc_strerror_c(errno) );
477 478 479 480 481 482 483 484 485 486 487 488 489
        free( psz_path );
        return false;
    }
    if( !S_ISREG( st.st_mode ) )
    {
        msg_Dbg( p_access, "%s is not a regular file", psz_path );
        free( psz_path );
        return false;
    }
    msg_Dbg( p_access, "%s exists", psz_path );
    free( psz_path );

    ARRAY_APPEND( p_sys->file_sizes, st.st_size );
490
    p_sys->size += st.st_size;
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

    return true;
}

/*****************************************************************************
 * Close the current file and open another
 *****************************************************************************/
static bool SwitchFile( access_t *p_access, unsigned i_file )
{
    access_sys_t *p_sys = p_access->p_sys;

    /* requested file already open? */
    if( p_sys->fd != -1 && p_sys->i_current_file == i_file )
        return true;

    /* close old file */
    if( p_sys->fd != -1 )
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
509
        vlc_close( p_sys->fd );
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
        p_sys->fd = -1;
    }

    /* switch */
    if( i_file >= FILE_COUNT )
        return false;
    p_sys->i_current_file = i_file;

    /* open new file */
    char *psz_path = GetFilePath( p_access, i_file );
    if( !psz_path )
        return false;
    p_sys->fd = vlc_open( psz_path, O_RDONLY );

    if( p_sys->fd == -1 )
    {
526 527
        msg_Err( p_access, "Failed to open %s: %s", psz_path,
                 vlc_strerror_c(errno) );
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        goto error;
    }

    /* cannot handle anything except normal files */
    struct stat st;
    if( fstat( p_sys->fd, &st ) || !S_ISREG( st.st_mode ) )
    {
        msg_Err( p_access, "%s is not a regular file", psz_path );
        goto error;
    }

    OptimizeForRead( p_sys->fd );

    msg_Dbg( p_access, "opened %s", psz_path );
    free( psz_path );
    return true;

error:
Thomas Guillem's avatar
Thomas Guillem committed
546
    vlc_dialog_display_error (p_access, _("File reading failed"), _("VLC could not"
547
        " open the file \"%s\" (%s)."), psz_path, vlc_strerror(errno) );
548 549
    if( p_sys->fd != -1 )
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
550
        vlc_close( p_sys->fd );
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        p_sys->fd = -1;
    }
    free( psz_path );
    return false;
}

/*****************************************************************************
 * Some tweaks to speed up read()
 *****************************************************************************/
static void OptimizeForRead( int fd )
{
    /* cf. Open() in file access module */
    VLC_UNUSED(fd);
#ifdef HAVE_POSIX_FADVISE
    posix_fadvise( fd, 0, 4096, POSIX_FADV_WILLNEED );
    posix_fadvise( fd, 0, 0, POSIX_FADV_NOREUSE );
#endif
#ifdef F_RDAHEAD
    fcntl( fd, F_RDAHEAD, 1 );
#endif
#ifdef F_NOCACHE
572
    fcntl( fd, F_NOCACHE, 0 );
573 574 575 576 577 578 579 580 581 582 583
#endif
}

/*****************************************************************************
 * Fix size if the (last) part is still growing
 *****************************************************************************/
static void UpdateFileSize( access_t *p_access )
{
    access_sys_t *p_sys = p_access->p_sys;
    struct stat st;

584
    if( p_sys->size >= p_sys->offset )
585 586 587 588 589 590 591 592
        return;

    /* TODO: not sure if this can happen or what to do in this case */
    if( fstat( p_sys->fd, &st ) )
        return;
    if( (uint64_t)st.st_size <= CURRENT_FILE_SIZE )
        return;

593
    p_sys->size -= CURRENT_FILE_SIZE;
594
    CURRENT_FILE_SIZE = st.st_size;
595
    p_sys->size += CURRENT_FILE_SIZE;
596 597 598 599 600 601 602
}

/*****************************************************************************
 * Open file relative to base directory for reading.
 *****************************************************************************/
static FILE *OpenRelativeFile( access_t *p_access, const char *psz_file )
{
603 604
    access_sys_t *sys = p_access->p_sys;

605 606
    /* build path and add extension */
    char *psz_path;
607 608
    if( asprintf( &psz_path, "%s" DIR_SEP "%s%s", p_access->psz_filepath,
                  psz_file, sys->b_ts_format ? "" : ".vdr" ) == -1 )
609 610 611 612
        return NULL;

    FILE *file = vlc_fopen( psz_path, "rb" );
    if( !file )
613 614
        msg_Warn( p_access, "Failed to open %s: %s", psz_path,
                  vlc_strerror_c(errno) );
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 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    free( psz_path );

    return file;
}

/*****************************************************************************
 * Read a line of text. Returns false on error or EOF.
 *****************************************************************************/
static bool ReadLine( char **ppsz_line, size_t *pi_size, FILE *p_file )
{
    ssize_t read = getline( ppsz_line, pi_size, p_file );

    if( read == -1 )
    {
        /* automatically free buffer on eof */
        free( *ppsz_line );
        *ppsz_line = NULL;
        return false;
    }

    if( read > 0 && (*ppsz_line)[ read - 1 ] == '\n' )
        (*ppsz_line)[ read - 1 ] = '\0';
    EnsureUTF8( *ppsz_line );

    return true;
}

/*****************************************************************************
 * Import meta data
 *****************************************************************************/
static void ImportMeta( access_t *p_access )
{
    access_sys_t *p_sys = p_access->p_sys;

    FILE *infofile = OpenRelativeFile( p_access, "info" );
    if( !infofile )
        return;

    vlc_meta_t *p_meta = vlc_meta_New();
    p_sys->p_meta = p_meta;
    if( !p_meta )
    {
        fclose( infofile );
        return;
    }

    char *line = NULL;
    size_t line_len;
    char *psz_title = NULL, *psz_smalltext = NULL, *psz_date = NULL;

    while( ReadLine( &line, &line_len, infofile ) )
    {
        if( !isalpha( (unsigned char)line[0] ) || line[1] != ' ' )
            continue;

        char tag = line[0];
        char *text = line + 2;

        if( tag == 'C' )
        {
            char *psz_name = strchr( text, ' ' );
            if( psz_name )
            {
                *psz_name = '\0';
                vlc_meta_AddExtra( p_meta, "Channel", psz_name + 1 );
            }
            vlc_meta_AddExtra( p_meta, "Transponder", text );
        }

        else if( tag == 'E' )
        {
            unsigned i_id, i_start, i_length;
            if( sscanf( text, "%u %u %u", &i_id, &i_start, &i_length ) == 3 )
            {
                char str[50];
                struct tm tm;
                time_t start = i_start;
                localtime_r( &start, &tm );

                /* TODO: locale */
                strftime( str, sizeof(str), "%Y-%m-%d %H:%M", &tm );
                vlc_meta_AddExtra( p_meta, "Date", str );
                free( psz_date );
                psz_date = strdup( str );

                /* display in minutes */
                i_length = ( i_length + 59 ) / 60;
                snprintf( str, sizeof(str), "%u:%02u", i_length / 60, i_length % 60 );
                vlc_meta_AddExtra( p_meta, "Duration", str );
            }
        }

        else if( tag == 'T' )
        {
            free( psz_title );
            psz_title = strdup( text );
            vlc_meta_AddExtra( p_meta, "Title", text );
        }

        else if( tag == 'S' )
        {
            free( psz_smalltext );
            psz_smalltext = strdup( text );
            vlc_meta_AddExtra( p_meta, "Info", text );
        }

        else if( tag == 'D' )
        {
            for( char *p = text; *p; ++p )
            {
                if( *p == '|' )
                    *p = '\n';
            }
            vlc_meta_SetDescription( p_meta, text );
        }

        /* FPS are required to convert between timestamps and frames */
        else if( tag == 'F' )
        {
            float fps = atof( text );
            if( fps >= 1 )
                p_sys->fps = fps;
            vlc_meta_AddExtra( p_meta, "Frame Rate", text );
        }

        else if( tag == 'P' )
        {
            vlc_meta_AddExtra( p_meta, "Priority", text );
        }

        else if( tag == 'L' )
        {
            vlc_meta_AddExtra( p_meta, "Lifetime", text );
        }
    }

    /* create a meaningful title */
    int i_len = 10 +
        ( psz_title ? strlen( psz_title ) : 0 ) +
        ( psz_smalltext ? strlen( psz_smalltext ) : 0 ) +
        ( psz_date ? strlen( psz_date ) : 0 );
    char *psz_display = malloc( i_len );

    if( psz_display )
    {
        *psz_display = '\0';
        if( psz_title )
            strcat( psz_display, psz_title );
        if( psz_title && psz_smalltext )
            strcat( psz_display, " - " );
        if( psz_smalltext )
            strcat( psz_display, psz_smalltext );
        if( ( psz_title || psz_smalltext ) && psz_date )
        {
            strcat( psz_display, " (" );
            strcat( psz_display, psz_date );
            strcat( psz_display, ")" );
        }
        if( *psz_display )
            vlc_meta_SetTitle( p_meta, psz_display );
    }

    free( psz_display );
    free( psz_title );
    free( psz_smalltext );
    free( psz_date );

    fclose( infofile );
}

/*****************************************************************************
 * Import cut marks and convert them to seekpoints (chapters).
 *****************************************************************************/
static void ImportMarks( access_t *p_access )
{
    access_sys_t *p_sys = p_access->p_sys;

    FILE *marksfile = OpenRelativeFile( p_access, "marks" );
    if( !marksfile )
        return;

    FILE *indexfile = OpenRelativeFile( p_access, "index" );
    if( !indexfile )
    {
        fclose( marksfile );
        return;
    }

803 804 805 806 807 808 809 810 811 812
    /* get the length of this recording (index stores 8 bytes per frame) */
    struct stat st;
    if( fstat( fileno( indexfile ), &st ) )
    {
        fclose( marksfile );
        fclose( indexfile );
        return;
    }
    int64_t i_frame_count = st.st_size / 8;

813 814 815 816 817 818 819 820 821
    /* Put all cut marks in a "dummy" title */
    input_title_t *p_marks = vlc_input_title_New();
    if( !p_marks )
    {
        fclose( marksfile );
        fclose( indexfile );
        return;
    }
    p_marks->psz_name = strdup( _("VDR Cut Marks") );
822
    p_marks->i_length = i_frame_count * (int64_t)( CLOCK_FREQ / p_sys->fps );
823

824 825 826
    uint64_t *offsetv = NULL;
    size_t offsetc = 0;

827 828 829 830
    /* offset for chapter positions */
    int i_chapter_offset = p_sys->fps / 1000 *
        var_InheritInteger( p_access, "vdr-chapter-offset" );

831 832 833 834 835 836 837
    /* minimum chapter size in frames */
    int i_min_chapter_size = p_sys->fps * MIN_CHAPTER_SIZE;

    /* the last chapter started at this frame (init to 0 so
     * we skip useless chapters near the beginning as well) */
    int64_t i_prev_chapter = 0;

838 839 840 841 842 843 844
    /* parse lines of the form "0:00:00.00 foobar" */
    char *line = NULL;
    size_t line_len;
    while( ReadLine( &line, &line_len, marksfile ) )
    {
        int64_t i_frame = ParseFrameNumber( line, p_sys->fps );

845 846 847 848 849 850
        /* skip chapters which are near the end or too close to each other */
        if( i_frame - i_prev_chapter < i_min_chapter_size ||
            i_frame >= i_frame_count - i_min_chapter_size )
            continue;
        i_prev_chapter = i_frame;

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
        /* move chapters (simple workaround for inaccurate cut marks) */
        if( i_frame > -i_chapter_offset )
            i_frame += i_chapter_offset;
        else
            i_frame = 0;

        uint64_t i_offset;
        uint16_t i_file_number;
        if( !ReadIndexRecord( indexfile, p_sys->b_ts_format,
            i_frame, &i_offset, &i_file_number ) )
            continue;
        if( i_file_number < 1 || i_file_number > FILE_COUNT )
            continue;

        /* add file sizes to get the "global" offset */
        seekpoint_t *sp = vlc_seekpoint_New();
        if( !sp )
            continue;
        sp->i_time_offset = i_frame * (int64_t)( CLOCK_FREQ / p_sys->fps );
        sp->psz_name = strdup( line );

        TAB_APPEND( p_marks->i_seekpoint, p_marks->seekpoint, sp );
873 874 875 876
        TAB_APPEND( offsetc, offsetv, i_offset );

        for( int i = 0; i + 1 < i_file_number; ++i )
            offsetv[offsetc - 1] += FILE_SIZE( i );
877 878
    }

879
    /* add a chapter at the beginning if missing */
880
    if( p_marks->i_seekpoint > 0 && offsetv[0] > 0 )
881 882 883 884 885 886 887
    {
        seekpoint_t *sp = vlc_seekpoint_New();
        if( sp )
        {
            sp->i_time_offset = 0;
            sp->psz_name = strdup( _("Start") );
            TAB_INSERT( p_marks->i_seekpoint, p_marks->seekpoint, sp, 0 );
888
            TAB_INSERT( offsetc, offsetv, UINT64_C(0), 0 );
889 890
        }
    }
891 892

    if( p_marks->i_seekpoint > 0 )
893
    {
894
        p_sys->p_marks = p_marks;
895 896
        p_sys->offsets = offsetv;
    }
897
    else
898
    {
899
        vlc_input_title_Delete( p_marks );
900 901
        TAB_CLEAN( offsetc, offsetv );
    }
902 903 904 905 906 907 908 909 910 911 912 913 914 915

    fclose( marksfile );
    fclose( indexfile );
}

/*****************************************************************************
 * Lookup frame offset in index file
 *****************************************************************************/
static bool ReadIndexRecord( FILE *p_file, bool b_ts, int64_t i_frame,
                            uint64_t *pi_offset, uint16_t *pi_file_num )
{
    uint8_t index_record[8];
    if( fseek( p_file, sizeof(index_record) * i_frame, SEEK_SET ) != 0 )
        return false;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
916
    if( fread( &index_record, sizeof(index_record), 1, p_file ) < 1 )
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
        return false;

    /* VDR usually (only?) runs on little endian machines, but VLC has a
     * broader audience. See recording.* in VDR source for data layout. */
    if( b_ts )
    {
        uint64_t i_index_entry = GetQWLE( &index_record );
        *pi_offset = i_index_entry & UINT64_C(0xFFFFFFFFFF);
        *pi_file_num = i_index_entry >> 48;
    }
    else
    {
        *pi_offset = GetDWLE( &index_record );
        *pi_file_num = index_record[5];
    }

    return true;
}

/*****************************************************************************
 * Convert time stamp from file to frame number
 *****************************************************************************/
static int64_t ParseFrameNumber( const char *psz_line, float fps )
{
    unsigned h, m, s, f, n;

    /* hour:min:sec.frame (frame is optional) */
    n = sscanf( psz_line, "%u:%u:%u.%u", &h, &m, &s, &f );
    if( n >= 3 )
    {
        if( n < 4 )
            f = 1;
        int64_t i_seconds = (int64_t)h * 3600 + (int64_t)m * 60 + s;
        return (int64_t)( i_seconds * (double)fps ) + __MAX(1, f) - 1;
    }

    /* only a frame number */
    int64_t i_frame = strtoll( psz_line, NULL, 10 );
    return __MAX(1, i_frame) - 1;
}
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

/*****************************************************************************
 * Return the last path component (including trailing separators)
 *****************************************************************************/
static const char *BaseName( const char *psz_path )
{
    const char *psz_name = psz_path + strlen( psz_path );

    /* skip superfluous separators at the end */
    while( psz_name > psz_path && psz_name[-1] == DIR_SEP_CHAR )
        --psz_name;

    /* skip last component */
    while( psz_name > psz_path && psz_name[-1] != DIR_SEP_CHAR )
        --psz_name;

    return psz_name;
}