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