]> git.sesse.net Git - vlc/blob - modules/demux/ty.c
A bit of headers cleanup
[vlc] / modules / demux / ty.c
1 /*****************************************************************************
2  * ty.c - TiVo ty stream video demuxer for VLC
3  *****************************************************************************
4  * Copyright (C) 2005 the VideoLAN team
5  * Copyright (C) 2005 by Neal Symms (tivo@freakinzoo.com) - February 2005
6  * based on code by Christopher Wingert for tivo-mplayer
7  * tivo(at)wingert.org, February 2003
8  *
9  * $Id$
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *
25  * CODE CHANGES:
26  * v1.0.0 - 24-Feb-2005 - Initial release - Series 1 support ONLY!
27  * v1.0.1 - 25-Feb-2005 - Added fix for bad GOP headers - Neal
28  * v1.0.2 - 26-Feb-2005 - No longer require "seekable" input stream - Neal
29  *****************************************************************************/
30
31 /*****************************************************************************
32  * Preamble
33  *****************************************************************************/
34
35 #include <stdlib.h>
36 #include <vlc/vlc.h>
37 #include <vlc_demux.h>
38 #include "vlc_codec.h"
39
40 #define SERIES1_PES_LENGTH  (11)
41 #define SERIES2_PES_LENGTH  (16)
42 #define AC3_PES_LENGTH      (14)
43 #define DTIVO_PTS_OFFSET    (6)
44 #define SA_PTS_OFFSET       (9)
45 #define AC3_PTS_OFFSET      (9)
46 static const unsigned char ty_VideoPacket[] = { 0x00, 0x00, 0x01, 0xe0 };
47 static const unsigned char ty_MPEGAudioPacket[] = { 0x00, 0x00, 0x01, 0xc0 };
48 static const unsigned char ty_AC3AudioPacket[] = { 0x00, 0x00, 0x01, 0xbd };
49
50 /*****************************************************************************
51  * Local prototypes
52  *****************************************************************************/
53 static int get_chunk_header(demux_t *);
54 static void setup_audio_streams(char, demux_t *);
55 static mtime_t get_pts( unsigned char *buf );
56 static int find_es_header( unsigned const char *header,
57    unsigned char *buffer, int bufferSize, int *esOffset1 );
58 static int ty_stream_seek(demux_t *p_demux, double seek_pct);
59
60 static int TyOpen (vlc_object_t *);
61 static void TyClose(vlc_object_t *);
62 static int TyDemux(demux_t *);
63 static int Control(demux_t *, int, va_list);
64
65 /*****************************************************************************
66  * Module descriptor
67  *****************************************************************************/
68 vlc_module_begin();
69     set_shortname( "TY" );
70     set_description(_("TY Stream audio/video demux"));
71     set_category( CAT_INPUT );
72     set_subcategory( SUBCAT_INPUT_DEMUX );
73     set_capability("demux2", 8);
74     /* FIXME: there seems to be a segfault when using PVR access
75      * and TY demux has a bigger priority than PS
76      * Something must be wrong.
77      */
78     set_callbacks(TyOpen, TyClose);
79     add_shortcut("ty");
80     add_shortcut("tivo");
81 vlc_module_end();
82
83 /* packet types for reference:
84  2/c0: audio data continued
85  3/c0: audio packet header (PES header)
86  4/c0: audio data (S/A only?)
87  9/c0: audio packet header, AC-3 audio
88  2/e0: video data continued
89  6/e0: video packet header (PES header)
90  7/e0: video sequence header start
91  8/e0: video I-frame header start
92  a/e0: video P-frame header start
93  b/e0: video B-frame header start
94  c/e0: video GOP header start
95  e/01: closed-caption data
96  e/02: Extended data services data 
97  e/03: ipreview data ("thumbs up to record" signal)
98 */
99
100 #define TIVO_PES_FILEID   ( 0xf5467abd )
101 #define TIVO_PART_LENGTH  ( 0x20000000 )    /* 536,870,912 bytes */
102 #define CHUNK_SIZE        ( 128 * 1024 )
103
104 typedef struct
105 {
106   long l_rec_size;
107   unsigned char ex1, ex2;
108   unsigned char rec_type;
109   unsigned char subrec_type;
110   char b_ext;
111 } ty_rec_hdr_t;
112
113 struct demux_sys_t
114 {
115   es_out_id_t *p_video;               /* ptr to video codec */
116   es_out_id_t *p_audio;               /* holds either ac3 or mpeg codec ptr */
117
118   int             i_chunk_count;
119   int             i_stuff_cnt;
120   size_t          i_stream_size;      /* size of input stream (if known) */
121   vlc_bool_t      b_seekable;         /* is this stream seekable? */
122   int             tivoType;           /* 1 = SA, 2 = DTiVo */
123   vlc_bool_t      b_mpeg_audio;       /* true if we're using MPEG audio */
124   uint8_t         pes_buffer[20];     /* holds incomplete pes headers */
125   int             i_pes_buf_cnt;      /* how many bytes in our buffer */
126
127   mtime_t         firstAudioPTS;
128   mtime_t         lastAudioPTS;
129   mtime_t         lastVideoPTS;
130
131   ty_rec_hdr_t    *rec_hdrs;          /* record headers array */
132   int             i_cur_rec;          /* current record in this chunk */
133   int             i_num_recs;         /* number of recs in this chunk */
134   int             i_seq_rec;          /* record number where seq start is */
135   vlc_bool_t      eof;
136   vlc_bool_t      b_first_chunk;
137 };
138
139
140 /*
141  * TyOpen: check file and initialize demux structures
142  *
143  * here's what we do:
144  * 1. peek at the first 12 bytes of the stream for the
145  *    magic TiVo PART header & stream type & chunk size
146  * 2. if it's not there, error with VLC_EGENERIC
147  * 3. set up video (mpgv) codec
148  * 4. return VLC_SUCCESS
149  */
150 static int TyOpen(vlc_object_t *p_this)
151 {
152     demux_t *p_demux = (demux_t *)p_this;
153     demux_sys_t *p_sys;
154     es_format_t fmt;
155     uint8_t *p_peek;
156
157     /* peek at the first 12 bytes. */
158     /* for TY streams, they're always the same */
159     if( stream_Peek( p_demux->s, &p_peek, 12 ) < 12 )
160         return VLC_EGENERIC;
161
162     if ( U32_AT(p_peek) != TIVO_PES_FILEID ||
163          U32_AT(&p_peek[4]) != 0x02 ||
164          U32_AT(&p_peek[8]) != CHUNK_SIZE )
165     {
166         /* doesn't look like a TY file... */
167         char *psz_ext = strrchr(p_demux->psz_path, '.');
168
169         if( !p_demux->b_force &&
170             (!psz_ext || strcasecmp(psz_ext, ".ty")) ) return VLC_EGENERIC;
171         msg_Warn( p_demux, "this does not look like a TY file, "
172                   "continuing anyway..." );
173     }
174
175     /* at this point, we assume we have a valid TY stream */  
176     msg_Dbg( p_demux, "valid TY stream detected" );
177
178     /* Set exported functions */
179     p_demux->pf_demux = TyDemux;
180     p_demux->pf_control = Control;
181
182     /* create our structure that will hold all data */
183     p_demux->p_sys = p_sys = malloc(sizeof(demux_sys_t));
184     memset(p_sys, 0, sizeof(demux_sys_t));
185
186     /* set up our struct (most were zero'd out with the memset above) */
187     p_sys->b_first_chunk = VLC_TRUE;
188     p_sys->firstAudioPTS = -1;
189     p_sys->i_stream_size = stream_Size(p_demux->s);
190     p_sys->b_mpeg_audio = VLC_FALSE;
191
192     /* see if this stream is seekable */
193     stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
194
195     /* TODO: read first chunk & parse first audio PTS, then (if seekable)
196      *       seek to last chunk & last record; read its PTS and compute
197      *       overall program time.  Also determine Tivo type.   */
198
199     /* NOTE: we wait to create the audio ES until we know what
200      * audio type we have.   */
201     p_sys->p_audio = NULL;
202
203     /* register the video stream */
204     es_format_Init( &fmt, VIDEO_ES, VLC_FOURCC( 'm', 'p', 'g', 'v' ) );
205     p_sys->p_video = es_out_Add( p_demux->out, &fmt );
206
207 #if 0
208     /* register the CC decoder */
209     es_format_Init( &fmt, SPU_ES, VLC_FOURCC('s', 'u', 'b', 't'));
210     p_sys->p_subt_es = es_out_Add(p_demux->out, &fmt);
211 #endif
212
213     return VLC_SUCCESS;
214 }
215
216
217 /* set up audio codec.
218  * this will be called once we determine audio type */
219 static void setup_audio_streams(char stream_type, demux_t *p_demux)
220 {
221     demux_sys_t *p_sys = p_demux->p_sys;
222     es_format_t  fmt;
223
224     if (stream_type == 'A') {
225         /* AC3 audio detected */
226         es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC( 'a', '5', '2', ' ' ) );
227         p_sys->tivoType = 2;      /* AC3 is only on dtivo */
228     } else {
229         /* assume MPEG */
230         es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC( 'm', 'p', 'g', 'a' ) );
231         p_sys->b_mpeg_audio = VLC_TRUE;
232     }
233     /* register the chosen audio output codec */
234     p_sys->p_audio = es_out_Add( p_demux->out, &fmt );
235 }
236
237
238 /* =========================================================================== */
239 /* Compute Presentation Time Stamp (PTS)
240  * Assume buf points to beginning of PTS */
241 static mtime_t get_pts( unsigned char *buf )
242 {
243     mtime_t i_pts;
244
245     i_pts = ((mtime_t)(buf[0]&0x0e ) << 29)|
246              (mtime_t)(buf[1] << 22)|
247             ((mtime_t)(buf[2]&0xfe) << 14)|
248              (mtime_t)(buf[3] << 7)|
249              (mtime_t)(buf[4] >> 1);
250     i_pts *= 100 / 9;   /* convert PTS (90Khz clock) to microseconds */
251     return i_pts;
252 }
253
254
255 /* =========================================================================== */
256 static int find_es_header( unsigned const char *header,
257    unsigned char *buffer, int bufferSize, int *esOffset1 )
258 {
259     int count;
260
261     *esOffset1 = -1;
262     for( count = 0 ; count < bufferSize ; count++ )
263     {
264         if ( ( buffer[ count + 0 ] == header[ 0 ] ) &&
265              ( buffer[ count + 1 ] == header[ 1 ] ) &&
266              ( buffer[ count + 2 ] == header[ 2 ] ) &&
267              ( buffer[ count + 3 ] == header[ 3 ] ) )
268         {
269             *esOffset1 = count;
270             return 1;
271         }
272     }
273     return( -1 );
274 }
275
276
277 /* =========================================================================== */
278 /* check if we have a full PES header, if not, then save what we have.
279  * this is called when audio-start packets are encountered.
280  * Returns:
281  *     1 partial PES hdr found, some audio data found (buffer adjusted),
282  *    -1 partial PES hdr found, no audio data found
283  *     0 otherwise (complete PES found, pts extracted, pts set, buffer adjusted) */
284 /* TODO: fix it so it works with S2 / SA / DTivo / HD etc... */
285 static int check_sync_pes( demux_t *p_demux, block_t *p_block,
286                            int32_t offset, int32_t rec_len )
287 {
288     demux_sys_t *p_sys = p_demux->p_sys;
289     int pts_offset;
290     int pes_length = p_sys->b_mpeg_audio?SERIES1_PES_LENGTH:AC3_PES_LENGTH;
291
292     if( p_sys->tivoType == 1 )
293     {
294         /* SA tivo */
295         pts_offset = SA_PTS_OFFSET;
296     }
297     else
298     {
299         /* DTivo */
300         pts_offset = p_sys->b_mpeg_audio?DTIVO_PTS_OFFSET:AC3_PTS_OFFSET;
301     }
302     if ( offset < 0 || offset + pes_length > rec_len )
303     {
304         /* entire PES header not present */
305         msg_Dbg( p_demux, "PES header at %d not complete in record. storing.",
306                  offset );
307         /* save the partial pes header */
308         if( offset < 0 )
309         {
310             /* no header found, fake some 00's (this works, believe me) */
311             memset( p_sys->pes_buffer, 0, 4 );
312             p_sys->i_pes_buf_cnt = 4;
313             if( rec_len > 4 )
314                 msg_Err( p_demux, "PES header not found in record of %d bytes!",
315                          rec_len );
316             return -1;
317         }
318         /* copy the partial pes header we found */
319         memcpy( p_sys->pes_buffer, p_block->p_buffer + offset,
320                 rec_len - offset );
321         p_sys->i_pes_buf_cnt = rec_len - offset;
322
323         if( offset > 0 )
324         {
325             /* PES Header was found, but not complete, so trim the end of this record */
326             p_block->i_buffer -= rec_len - offset;
327             return 1;
328         }
329         return -1;    /* partial PES, no audio data */
330     }
331     /* full PES header present, extract PTS */
332     p_sys->lastAudioPTS = get_pts( &p_block->p_buffer[ offset + pts_offset ] );
333     if (p_sys->firstAudioPTS < 0)
334         p_sys->firstAudioPTS = p_sys->lastAudioPTS;
335     p_block->i_pts = p_sys->lastAudioPTS;
336     /*msg_Dbg(p_demux, "Audio PTS %lld", p_sys->lastAudioPTS );*/
337     /* adjust audio record to remove PES header */
338     memmove(p_block->p_buffer + offset, p_block->p_buffer + offset + pes_length,
339             rec_len - pes_length);
340     p_block->i_buffer -= pes_length;
341     return 0;
342 }
343
344
345 /* =========================================================================== */
346 /* TyDemux: Read & Demux one record from the chunk
347  *
348  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
349  *
350  * NOTE: I think we can return the number of packets sent instead of just 1.
351  * that means we can demux an entire chunk and shoot it back (may be more efficient)
352  * -- should try that some day :) --
353  */
354 int TyDemux(demux_t *p_demux)
355 {
356     int              invalidType = 0;
357     int              recordsDecoded = 0;
358
359     int              rec_type;
360     long             l_rec_size;
361     int              i_cur_rec;
362     int              subrec_type;
363     ty_rec_hdr_t     *rec_hdr;
364
365     block_t          *p_block_in = NULL;
366     int              esOffset1;
367
368     unsigned char    lastCC[ 16 ];
369     unsigned char    lastXDS[ 16 ];
370
371     demux_sys_t      *p_sys = p_demux->p_sys;
372
373     /*msg_Dbg(p_demux, "ty demux processing" );*/
374
375     /* did we hit EOF earlier? */
376     if (p_sys->eof) return 0;
377
378     /*
379      * what we do (1 record now.. maybe more later):
380     * - use stream_Read() to read the chunk header & record headers
381     * - discard entire chunk if it is a PART header chunk
382     * - parse all the headers into record header array
383     * - keep a pointer of which record we're on
384     * - use stream_Block() to fetch each record
385     * - parse out PTS from PES headers
386     * - set PTS for data packets
387     * - pass the data on to the proper codec via es_out_Send()
388
389     * if this is the first time or
390     * if we're at the end of this chunk, start a new one
391     */
392     /* parse the next chunk's record headers */
393     if (p_sys->b_first_chunk || p_sys->i_cur_rec >= p_sys->i_num_recs)
394         if (get_chunk_header(p_demux) == 0)
395             return 0;
396
397     /*======================================================================
398      * parse & send one record of the chunk
399      *====================================================================== */
400     i_cur_rec = p_sys->i_cur_rec;
401     recordsDecoded++;
402     rec_hdr = &p_sys->rec_hdrs[ i_cur_rec ];
403     subrec_type = rec_hdr->subrec_type;
404     rec_type = rec_hdr->rec_type;
405     l_rec_size = rec_hdr->l_rec_size;
406
407     if (!rec_hdr->b_ext)
408     {
409         /*msg_Dbg(p_demux, "Record Type 0x%x/%02x %ld bytes",
410                     subrec_type, rec_type, l_rec_size );*/
411   
412         /* some normal records are 0 length, so check for that... */
413         if (l_rec_size > 0)
414         {
415             /* read in this record's payload */
416             if( !( p_block_in = stream_Block( p_demux->s, l_rec_size ) ) )
417             {
418                 /* EOF */
419                 p_sys->eof = 1;
420                 return 0;
421             }
422             /* set these as 'unknown' for now */
423             p_block_in->i_pts = p_block_in->i_dts = 0;
424         }
425         else
426         {
427             /* no data in payload; we're done */
428             p_sys->i_cur_rec++;
429             return 1;
430         }
431     }
432     /*else
433     {
434         -- don't read any data from the stream, data was in the record header --
435         msg_Dbg(p_demux,
436                "Record Type 0x%02x/%02x, ext data = %02x, %02x", subrec_type,
437                 rec_type, rec_hdr->ex1, rec_hdr->ex2);
438     }*/
439
440     /*================================================================*
441      * Video Parsing
442      *================================================================*/
443     if ( rec_type == 0xe0 )
444     {
445         if( subrec_type == 0x06 )
446         {
447             /* get the PTS from this packet.
448              * Do NOT Pass this packet (a PES Header) on to the MPEG2 codec */
449             find_es_header( ty_VideoPacket, p_block_in->p_buffer,
450                             l_rec_size, &esOffset1 );
451             if ( esOffset1 != -1 )
452             {
453                 /* msg_Dbg(p_demux, "Video PES hdr at offset %d", esOffset1); */
454                 p_sys->lastVideoPTS = get_pts( &p_block_in->p_buffer[ esOffset1 + 9 ] );
455                 /*msg_Dbg(p_demux, "Video rec %d PTS "I64Fd, p_sys->i_cur_rec,
456                             p_sys->lastVideoPTS );*/
457             }
458             block_Release(p_block_in);
459         }
460         else
461         {
462 #if 0
463             msg_Dbg(p_demux, "packet buffer has "
464                     "%02x %02x %02x %02x %02x %02x %02x %02x "
465                     "%02x %02x %02x %02x %02x %02x %02x %02x",
466                     p_block_in->p_buffer[0], p_block_in->p_buffer[1],
467                     p_block_in->p_buffer[2], p_block_in->p_buffer[3],
468                     p_block_in->p_buffer[4], p_block_in->p_buffer[5],
469                     p_block_in->p_buffer[6], p_block_in->p_buffer[7],
470                     p_block_in->p_buffer[8], p_block_in->p_buffer[9],
471                     p_block_in->p_buffer[10], p_block_in->p_buffer[11],
472                     p_block_in->p_buffer[12], p_block_in->p_buffer[13],
473                     p_block_in->p_buffer[14], p_block_in->p_buffer[15]);
474 #endif
475             /* if it's not a continue blk, then set PTS */
476             if (subrec_type != 0x02)
477             {
478                 /*msg_Dbg(p_demux, "Video rec %d type 0x%02X", p_sys->i_cur_rec,
479                            subrec_type);*/
480                 /* if it's a GOP header, make sure it's legal
481                  * (if we have enough data) */
482                 /* Some ty files don't have this bit set
483                  * and it causes problems */
484                 if (subrec_type == 0x0c && l_rec_size >= 6)
485                     p_block_in->p_buffer[5] |= 0x08;
486                 /* set PTS for this block before we send */
487                 if (p_sys->lastVideoPTS > 0)
488                 {
489                     p_block_in->i_pts = p_sys->lastVideoPTS;
490                     /* PTS gets used ONCE. 
491                      * Any subsequent frames we get BEFORE next PES
492                      * header will have their PTS computed in the codec */
493                     p_sys->lastVideoPTS = 0;
494                 }
495             } 
496             es_out_Send(p_demux->out, p_sys->p_video, p_block_in);
497         }
498     } /* end if video rec type */
499     /* ================================================================
500      * Audio Parsing
501      * ================================================================
502      * parse PES headers and send the rest to the codec
503      */
504     else if ( rec_type == 0xc0 )
505     {
506 #if 0
507         int i;
508         printf( "Audio Packet Header " );
509         for( i = 0 ; i < 24 ; i++ )
510             printf( "%2.2x ", p_block_in->p_buffer[i] );
511         printf( "\n" );
512 #endif
513         /* load a codec if we haven't yet */
514         if ( p_sys->p_audio == NULL )
515         {
516             if ( subrec_type == 0x09 )
517             {
518                 /* set up for AC-3 audio */
519                 msg_Dbg(p_demux, "detected AC-3 Audio" );
520                         setup_audio_streams('A', p_demux);
521             }
522             else
523             {
524                 /* set up for MPEG audio */
525                 msg_Dbg(p_demux, "detected MPEG Audio" );
526                 setup_audio_streams('M', p_demux);
527             }
528         }
529
530         /* SA or DTiVo Audio Data, no PES (continued block)
531          * ================================================
532          */
533         if ( subrec_type == 2 )
534         {
535             /* continue PES if previous was incomplete */
536             /* TODO: Make this work for all series & types of tivos */
537             if (p_sys->i_pes_buf_cnt > 0)
538             {
539                 int i_need = SERIES1_PES_LENGTH - p_sys->i_pes_buf_cnt;
540
541                 msg_Dbg(p_demux, "continuing PES header");
542                 /* do we have enough data to complete? */
543                 if (i_need < l_rec_size)
544                 {
545                     /* we have enough; reconstruct this p_frame with the new hdr */
546                     memcpy(&p_sys->pes_buffer[p_sys->i_pes_buf_cnt],
547                            p_block_in->p_buffer, i_need);
548                     /* advance the block past the PES header (don't want to send it) */
549                     p_block_in->p_buffer += i_need;
550                     p_block_in->i_buffer -= i_need;
551                     /* get the PTS out of this PES header (MPEG or AC3) */
552                     if (p_sys->b_mpeg_audio)
553                         find_es_header(ty_MPEGAudioPacket, p_sys->pes_buffer,
554                                         10, &esOffset1);
555                     else
556                         find_es_header(ty_AC3AudioPacket, p_sys->pes_buffer,
557                                         10, &esOffset1);
558                     if (esOffset1 < 0)
559                     {
560                         /* god help us; something's really wrong */
561                         msg_Err(p_demux, "can't find audio PES header in packet");
562                     }
563                     else
564                     {
565                         p_sys->lastAudioPTS = get_pts( 
566                             &p_sys->pes_buffer[ esOffset1 + DTIVO_PTS_OFFSET ] );
567                         p_block_in->i_pts = p_sys->lastAudioPTS;
568                     }
569                     p_sys->i_pes_buf_cnt = 0;
570                 }
571                 else
572                 {
573                     /* don't have complete PES hdr; save what we have and return */
574                     memcpy(&p_sys->pes_buffer[p_sys->i_pes_buf_cnt],
575                             p_block_in->p_buffer, l_rec_size);
576                     p_sys->i_pes_buf_cnt += l_rec_size;
577                     p_sys->i_cur_rec++;
578                     block_Release(p_block_in);
579                     return 1;
580                 }
581             }
582             /* set PCR before we send */
583             /*es_out_Control( p_demux->out, ES_OUT_SET_PCR,
584                               p_block_in->i_pts );*/
585             es_out_Send( p_demux->out, p_sys->p_audio, p_block_in );
586         } /* subrec == 2 */
587
588         /* MPEG Audio with PES Header, either SA or DTiVo   */
589         /* ================================================ */
590         if ( subrec_type == 0x03 )
591         {
592             find_es_header( ty_MPEGAudioPacket, p_block_in->p_buffer,
593             l_rec_size, &esOffset1 );
594
595             /*msg_Dbg(p_demux, "buffer has %#02x %#02x %#02x %#02x",
596                p_block_in->p_buffer[0], p_block_in->p_buffer[1],
597                p_block_in->p_buffer[2], p_block_in->p_buffer[3]);
598             msg_Dbg(p_demux, "audio ES hdr at offset %d", esOffset1);*/
599
600             /* SA PES Header, No Audio Data                     */
601             /* ================================================ */
602             if ( ( esOffset1 == 0 ) && ( l_rec_size == 16 ) )
603             {
604                 p_sys->tivoType = 1;
605                 p_sys->lastAudioPTS = get_pts( &p_block_in->p_buffer[
606                             SA_PTS_OFFSET ] );
607                 if (p_sys->firstAudioPTS < 0)
608                     p_sys->firstAudioPTS = p_sys->lastAudioPTS;
609                 block_Release(p_block_in);
610                 /*msg_Dbg(p_demux, "SA Audio PTS %lld",
611                            p_sys->lastAudioPTS );*/
612             }
613             else
614             /* DTiVo Audio with PES Header                      */
615             /* ================================================ */
616             {
617                 p_sys->tivoType = 2;
618
619                 /* Check for complete PES
620                  * (TODO: handle proper size for tivo version) */
621                 if (check_sync_pes(p_demux, p_block_in, esOffset1,
622                                     l_rec_size) == -1)
623                 {
624                     /* partial PES header found, nothing else. 
625                      * we're done. */
626                     p_sys->i_cur_rec++;
627                     block_Release(p_block_in);
628                     return 1;
629                 }
630 #if 0
631                 msg_Dbg(p_demux, "packet buffer has "
632                          "%02x %02x %02x %02x %02x %02x %02x %02x "
633                          "%02x %02x %02x %02x %02x %02x %02x %02x",
634                          p_block_in->p_buffer[0], p_block_in->p_buffer[1],
635                          p_block_in->p_buffer[2], p_block_in->p_buffer[3],
636                          p_block_in->p_buffer[4], p_block_in->p_buffer[5],
637                          p_block_in->p_buffer[6], p_block_in->p_buffer[7],
638                          p_block_in->p_buffer[8], p_block_in->p_buffer[9],
639                          p_block_in->p_buffer[10], p_block_in->p_buffer[11],
640                          p_block_in->p_buffer[12], p_block_in->p_buffer[13],
641                          p_block_in->p_buffer[14], p_block_in->p_buffer[15]);
642 #endif
643                 /* set PCR before we send */
644                 if( p_block_in->i_pts > 0 )
645                     es_out_Control( p_demux->out, ES_OUT_SET_PCR,
646                                     p_block_in->i_pts );
647                 es_out_Send( p_demux->out, p_sys->p_audio, p_block_in );
648             }   /* if DTiVo */
649         }   /* if subrec == 0x03 */
650
651         /* SA Audio with no PES Header                      */
652         /* ================================================ */
653         if ( subrec_type == 0x04 )
654         {
655             /*msg_Dbg(p_demux,
656                     "Adding SA Audio Packet Size %ld", l_rec_size ); */
657
658             /* set PCR before we send */
659             if (p_sys->lastAudioPTS > 0)
660             {
661                 p_block_in->i_pts = p_sys->lastAudioPTS;
662                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
663                                 p_block_in->i_pts );
664             }
665             es_out_Send( p_demux->out, p_sys->p_audio, p_block_in );
666         }
667
668         /* DTiVo AC3 Audio Data with PES Header             */
669         /* ================================================ */
670         if ( subrec_type == 0x09 )
671         {
672             find_es_header( ty_AC3AudioPacket, p_block_in->p_buffer,
673                             l_rec_size, &esOffset1 );
674
675             /*msg_Dbg(p_demux, "buffer has %#02x %#02x %#02x %#02x",
676                        p_block_in->p_buffer[0], p_block_in->p_buffer[1],
677                        p_block_in->p_buffer[2], p_block_in->p_buffer[3]);
678             msg_Dbg(p_demux, "audio ES AC3 hdr at offset %d", esOffset1);*/
679
680             /* Check for complete PES */
681             if (check_sync_pes(p_demux, p_block_in, esOffset1,
682                                 l_rec_size) == -1)
683             {
684                 /* partial PES header found, nothing else.  we're done. */
685                 p_sys->i_cur_rec++;
686                 return 1;
687             }
688             /* set PCR before we send (if PTS found) */
689             if( p_block_in->i_pts > 0 )
690             {
691                 es_out_Control( p_demux->out, ES_OUT_SET_PCR,
692                                 p_block_in->i_pts );
693             }
694             es_out_Send( p_demux->out, p_sys->p_audio, p_block_in );
695         }
696     } /* end "if audio" */
697     /* ================================================================ */
698     /* Closed Caption                                                   */
699     /* ================================================================ */
700     else if ( rec_type == 0x01 )
701     {
702         /*msg_Dbg(p_demux, "CC1 %02x %02x [%c%c]", rec_hdr->ex1,
703                    rec_hdr->ex2, rec_hdr->ex1, rec_hdr->ex2 );*/
704
705         /* construct a 'user-data' MPEG packet */
706         lastCC[ 0x00 ] = 0x00;
707         lastCC[ 0x01 ] = 0x00;
708         lastCC[ 0x02 ] = 0x01;
709         lastCC[ 0x03 ] = 0xb2;
710         lastCC[ 0x04 ] = 'T';    /* vcdimager code says this byte should be 0x11 */
711         lastCC[ 0x05 ] = 'Y';    /* (no other notes there) */
712         lastCC[ 0x06 ] = 0x01;
713         lastCC[ 0x07 ] = rec_hdr->ex1;
714         lastCC[ 0x08 ] = rec_hdr->ex2;
715         /* not sure what to send, because VLC doesn't yet support
716          * teletext type of subtitles (only supports the full-sentence type) */
717         /*p_block_in = block_NewEmpty(); ????
718         es_out_Send( p_demux->out, p_sys->p_subt_es, p_block_in );*/
719     }
720     else if ( rec_type == 0x02 )
721     {
722         /*msg_Dbg(p_demux, "CC2 %02x %02x", rec_hdr->ex1, rec_hdr->ex2 );*/
723
724         /* construct a 'user-data' MPEG packet */
725         lastXDS[ 0x00 ] = 0x00;
726         lastXDS[ 0x01 ] = 0x00;
727         lastXDS[ 0x02 ] = 0x01;
728         lastXDS[ 0x03 ] = 0xb2;
729         lastXDS[ 0x04 ] = 'T';    /* vcdimager code says this byte should be 0x11 */
730         lastXDS[ 0x05 ] = 'Y';    /* (no other notes there) */
731         lastXDS[ 0x06 ] = 0x02;
732         lastXDS[ 0x07 ] = rec_hdr->ex1;
733         lastXDS[ 0x08 ] = rec_hdr->ex2;
734         /* not sure what to send, because VLC doesn't support this?? */
735         /*p_block_in = block_NewEmpty(); ????
736         es_out_Send( p_demux->out, p_sys->p_audio, p_block_in );*/
737     }
738     /* ================================================================ */
739     /* Tivo data services (e.g. "thumbs-up to record!")  useless for us */
740     /* ================================================================ */
741     else if ( rec_type == 0x03 )
742     {
743     }
744     /* ================================================================ */
745     /* Unknown, but seen regularly */
746     /* ================================================================ */
747     else if ( rec_type == 0x05 )
748     {
749     }
750     else
751     {
752         msg_Dbg(p_demux, "Invalid record type 0x%02x", rec_type );
753         if (p_block_in) block_Release(p_block_in);
754             invalidType++;
755     }
756     p_sys->i_cur_rec++;
757     return 1;
758 }
759
760
761 /* seek to a position within the stream, if possible */
762 static int ty_stream_seek(demux_t *p_demux, double seek_pct)
763 {
764     demux_sys_t *p_sys = p_demux->p_sys;
765     int64_t seek_pos = p_sys->i_stream_size * seek_pct;
766     int i;
767     long l_skip_amt;
768
769     /* if we're not seekable, there's nothing to do */
770     if (!p_sys->b_seekable)
771         return VLC_EGENERIC;
772
773     /* figure out which chunk we want & go there */
774     p_sys->i_chunk_count = seek_pos / CHUNK_SIZE;
775
776     if ( stream_Seek( p_demux->s, p_sys->i_chunk_count * CHUNK_SIZE))
777     {
778         /* can't seek stream */
779         return VLC_EGENERIC;
780     }
781     /* load the chunk */
782     get_chunk_header(p_demux);
783   
784     /* seek within the chunk to get roughly to where we want */
785     p_sys->i_cur_rec = (int)
786       ((double) ((seek_pos % CHUNK_SIZE) / (double) (CHUNK_SIZE)) * p_sys->i_num_recs);
787     msg_Dbg(p_demux, "seeked to file pos " I64Fd, seek_pos);
788     msg_Dbg(p_demux, " (chunk %d, record %d)",
789              p_sys->i_chunk_count - 1, p_sys->i_cur_rec);
790
791     /* seek to the start of this record's data.
792      * to do that, we have to skip past all prior records */
793     l_skip_amt = 0;
794     for (i=0; i<p_sys->i_cur_rec; i++)
795         l_skip_amt += p_sys->rec_hdrs[i].l_rec_size;
796     stream_Seek(p_demux->s, ((p_sys->i_chunk_count-1) * CHUNK_SIZE) +
797                  (p_sys->i_num_recs * 16) + l_skip_amt + 4);
798
799     /* to hell with syncing any audio or video, just start reading records... :) */
800     /*p_sys->lastAudioPTS = p_sys->lastVideoPTS = 0;*/
801     es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
802     return VLC_SUCCESS;
803 }
804
805
806 static int Control(demux_t *p_demux, int i_query, va_list args)
807 {
808     demux_sys_t *p_sys = p_demux->p_sys;
809     double f, *pf;
810     int64_t i64, *p_i64;
811   
812     /*msg_Info(p_demux, "control cmd %d", i_query);*/
813     switch( i_query )
814     {
815     case DEMUX_GET_POSITION:
816         /* arg is 0.0 - 1.0 percent of overall file position */
817         if( ( i64 = p_sys->i_stream_size ) > 0 )
818         {
819             pf = (double*) va_arg( args, double* );
820             *pf = (double)stream_Tell( p_demux->s ) / (double) i64;
821             return VLC_SUCCESS;
822         }
823         return VLC_EGENERIC;
824
825     case DEMUX_SET_POSITION:
826         /* arg is 0.0 - 1.0 percent of overall file position */
827         f = (double) va_arg( args, double );
828         //msg_Dbg(p_demux, "Control - set position to %2.3f", f);
829         if ((i64 = p_sys->i_stream_size) > 0)
830             return ty_stream_seek(p_demux, f);
831         return VLC_EGENERIC;
832     case DEMUX_GET_TIME:
833         /* return latest PTS - start PTS */
834         p_i64 = (int64_t *) va_arg(args, int64_t *);
835         *p_i64 = p_sys->lastAudioPTS - p_sys->firstAudioPTS;
836         return VLC_SUCCESS;
837     case DEMUX_SET_TIME:      /* arg is time in microsecs */
838     case DEMUX_GET_LENGTH:    /* length of program in microseconds, 0 if unk */
839     case DEMUX_GET_FPS:
840     default:
841         return VLC_EGENERIC;
842     }
843 }
844
845
846 /* =========================================================================== */
847 static void TyClose( vlc_object_t *p_this )
848 {
849     demux_sys_t *p_sys = ((demux_t *) p_this)->p_sys;
850
851     free(p_sys->rec_hdrs);
852     free(p_sys);
853 }
854
855
856 /* =========================================================================== */
857 static int get_chunk_header(demux_t *p_demux)
858 {
859     int i_readSize, i_num_recs, i;
860     uint8_t packet_header[4];
861     uint8_t record_header[16];
862     ty_rec_hdr_t *p_rec_hdr;
863     demux_sys_t *p_sys = p_demux->p_sys;
864     int i_payload_size = 0;         /* sum of all records */
865
866     msg_Dbg(p_demux, "parsing ty chunk #%d", p_sys->i_chunk_count );
867
868     /* if we have left-over filler space from the last chunk, get that */
869     if (p_sys->i_stuff_cnt > 0)
870         stream_Read( p_demux->s, NULL, p_sys->i_stuff_cnt);
871
872     /* read the TY packet header */
873     i_readSize = stream_Read( p_demux->s, packet_header, 4 );
874     p_sys->i_chunk_count++;
875   
876     if ( i_readSize < 4 )
877     {
878         /* EOF */
879         p_sys->eof = 1;
880         return 0;
881     }
882   
883     /* if it's a PART Header, then try again. */
884     if( U32_AT( &packet_header[ 0 ] ) == TIVO_PES_FILEID )
885     {
886         msg_Dbg( p_demux, "skipping TY PART Header" );
887         /* TODO: if stream is seekable, should we seek() instead of read() ?? */
888         stream_Read( p_demux->s, NULL, CHUNK_SIZE - 4 );
889         return get_chunk_header(p_demux);
890     }
891
892     /* number of records in chunk (8- or 16-bit number) */
893     if (packet_header[3] & 0x80)
894     {
895         /* 16 bit rec cnt */
896         p_sys->i_num_recs = i_num_recs = (packet_header[1] << 8) + packet_header[0];
897         p_sys->i_seq_rec = (packet_header[3] << 8) + packet_header[2];
898         if (p_sys->i_seq_rec != 0xffff)
899         {
900             p_sys->i_seq_rec &= ~0x8000;
901         }
902     }
903     else
904     {
905         /* 8 bit reclen - tivo 1.3 format */
906         p_sys->i_num_recs = i_num_recs = packet_header[0];
907         p_sys->i_seq_rec = packet_header[1];
908     }
909     p_sys->i_cur_rec = 0;
910     p_sys->b_first_chunk = VLC_FALSE;
911   
912     /*msg_Dbg( p_demux, "chunk has %d records", i_num_recs );*/
913
914     /* parse headers into array */
915     if (p_sys->rec_hdrs)
916         free(p_sys->rec_hdrs);
917     p_sys->rec_hdrs = malloc(i_num_recs * sizeof(ty_rec_hdr_t));
918     for (i = 0; i < i_num_recs; i++)
919     {
920         i_readSize = stream_Read( p_demux->s, record_header, 16 );
921         if (i_readSize < 16)
922         {
923             /* EOF */
924             p_sys->eof = VLC_TRUE;
925             return 0;
926         }
927         p_rec_hdr = &p_sys->rec_hdrs[i];     /* for brevity */
928         p_rec_hdr->rec_type = record_header[3];
929         p_rec_hdr->subrec_type = record_header[2] & 0x0f;
930         if ((record_header[ 0 ] & 0x80) == 0x80)
931         {
932             unsigned char b1, b2;
933             /* marker bit 2 set, so read extended data */
934             b1 = ( ( ( record_header[ 0 ] & 0x0f ) << 4 ) | 
935                    ( ( record_header[ 1 ] & 0xf0 ) >> 4 ) );
936             b1 &= 0x7f;
937             b2 = ( ( ( record_header[ 1 ] & 0x0f ) << 4 ) | 
938                    ( ( record_header[ 2 ] & 0xf0 ) >> 4 ) );
939             b2 &= 0x7f;
940
941             p_rec_hdr->ex1 = b1;
942             p_rec_hdr->ex2 = b2;
943             p_rec_hdr->l_rec_size = 0;
944             p_rec_hdr->b_ext = VLC_TRUE;
945         }
946         else
947         {
948             p_rec_hdr->l_rec_size = ( record_header[ 0 ] << 8 |
949                 record_header[ 1 ] ) << 4 | ( record_header[ 2 ] >> 4 );
950             i_payload_size += p_rec_hdr->l_rec_size;
951             p_rec_hdr->b_ext = VLC_FALSE;
952         }
953     } /* end of record-header loop */
954     p_sys->i_stuff_cnt = CHUNK_SIZE - 4 -
955         (p_sys->i_num_recs * 16) - i_payload_size;
956     if (p_sys->i_stuff_cnt > 0)
957         msg_Dbg( p_demux, "chunk has %d stuff bytes at end",
958                  p_sys->i_stuff_cnt );
959     return 1;
960 }