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