OSDN Git Service

Changes to support unstructured program streams (such as those produced by a Tivo...
[handbrake-jp/handbrake-jp-git.git] / libhb / stream.c
1 /* $Id$
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include "hb.h"
8 #include "lang.h"
9 #include "a52dec/a52.h"
10
11 #include <string.h>
12
13 #define min(a, b) a < b ? a : b
14
15 typedef enum {
16     hb_stream_type_unknown = 0,
17     transport,
18     program,
19     dvd_program
20 } hb_stream_type_t;
21
22 #define kMaxNumberVideoPIDS 1
23 #define kMaxNumberAudioPIDS 15
24 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
25 #define kMaxNumberPMTStreams 32
26
27
28 struct hb_stream_s
29 {
30     int     frames;             /* video frames so far */
31     int     errors;             /* total errors so far */
32     int     last_error_frame;   /* frame # at last error message */
33     int     last_error_count;   /* # errors at last error message */
34     int     packetsize;         /* Transport Stream packet size */
35
36     int64_t ts_lastpcr;         /* the last pcr we found in the TS stream */
37     int64_t ts_nextpcr;         /* the next pcr to put in a PS packet */
38
39     uint8_t *ts_packet;         /* buffer for one TS packet */
40     uint8_t *ts_buf[kMaxNumberDecodeStreams];
41     int     ts_pos[kMaxNumberDecodeStreams];
42     int8_t  ts_foundfirst[kMaxNumberDecodeStreams];
43     int8_t  ts_skipbad[kMaxNumberDecodeStreams];
44     int8_t  ts_streamcont[kMaxNumberDecodeStreams];
45     int8_t  ts_start[kMaxNumberDecodeStreams];
46
47     uint8_t *fwrite_buf;        /* PS buffer (set by hb_ts_stream_decode) */
48     uint8_t *fwrite_buf_orig;   /* PS buffer start (set by hb_ts_stream_decode) */
49
50     /*
51      * Stuff before this point is dynamic state updated as we read the
52      * stream. Stuff after this point is stream description state that
53      * we learn during the initial scan but cache so it can be
54      * reused during the conversion read.
55      */
56     uint8_t ts_number_video_pids;
57     uint8_t ts_number_audio_pids;
58
59     int16_t ts_video_pids[kMaxNumberVideoPIDS];
60     int16_t ts_audio_pids[kMaxNumberAudioPIDS];
61
62     uint8_t ts_streamid[kMaxNumberDecodeStreams];
63     uint8_t ts_stream_type[kMaxNumberDecodeStreams];
64
65     char    *path;
66     FILE    *file_handle;
67     hb_stream_type_t hb_stream_type;
68     int     opentype;
69
70     struct {
71         int lang_code;
72         int flags;
73         int rate;
74         int bitrate;
75     } a52_info[kMaxNumberAudioPIDS];
76
77     struct
78     {
79         unsigned short program_number;
80         unsigned short program_map_PID;
81     } pat_info[kMaxNumberPMTStreams];
82     int     ts_number_pat_entries;
83
84     struct
85     {
86         int reading;
87         unsigned char *tablebuf;
88         unsigned int tablepos;
89         unsigned char current_continuity_counter;
90
91         int section_length;
92         int program_number;
93         unsigned int PCR_PID;
94         int program_info_length;
95         unsigned char *progam_info_descriptor_data;
96         struct
97         {
98             unsigned char stream_type;
99             unsigned short elementary_PID;
100             unsigned short ES_info_length;
101             unsigned char *es_info_descriptor_data;
102         } pmt_stream_info[kMaxNumberPMTStreams];
103     } pmt_info;
104 };
105
106 /***********************************************************************
107  * Local prototypes
108  **********************************************************************/
109 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
110 static void hb_ts_stream_init(hb_stream_t *stream);
111 static void hb_ts_stream_find_pids(hb_stream_t *stream);
112 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
113 static void hb_ts_stream_reset(hb_stream_t *stream);
114 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
115                                                        int aud_pid_index);
116 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
117 static off_t align_to_next_packet(hb_stream_t *stream);
118
119 /*
120  * streams have a bunch of state that's learned during the scan. We don't
121  * want to throw away the state when scan does a close then relearn
122  * everything when reader does an open. So we save the stream state on
123  * the close following a scan and reuse it when 'reader' does an open.
124  */
125 static hb_list_t *stream_state_list;
126
127 static hb_stream_t *hb_stream_lookup( const char *path )
128 {
129     if ( stream_state_list == NULL )
130         return NULL;
131
132     hb_stream_t *ss;
133     int i = 0;
134
135     while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
136     {
137         if ( strcmp( path, ss->path ) == 0 )
138         {
139             break;
140         }
141     }
142     return ss;
143 }
144
145 static void hb_stream_state_delete( hb_stream_t *ss )
146 {
147     hb_list_rem( stream_state_list, ss );
148     free( ss->path );
149     free( ss );
150 }
151
152 /*
153  * logging routines.
154  * these frontend hb_log because transport streams can have a lot of errors
155  * so we want to rate limit messages. this routine limits the number of
156  * messages to at most one per minute of video. other errors that occur
157  * during the minute are counted & the count is output with the next
158  * error msg we print.
159  */
160 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
161 {
162     // limit error printing to at most one per minute of video (at 30fps)
163     ++stream->errors;
164     if ( stream->frames - stream->last_error_frame >= 30*60 )
165     {
166         char msg[256];
167
168         vsnprintf( msg, sizeof(msg), log, args );
169
170         if ( stream->errors - stream->last_error_count < 10 )
171         {
172             hb_log( "stream: error near frame %d: %s", stream->frames, msg );
173         }
174         else
175         {
176             int Edelta = stream->errors - stream->last_error_count;
177             double Epcnt = (double)Edelta * 100. /
178                             (stream->frames - stream->last_error_frame);
179             hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
180                     Edelta, Epcnt, stream->frames, msg );
181         }
182         stream->last_error_frame = stream->frames;
183         stream->last_error_count = stream->errors;
184     }
185 }
186
187 static void ts_warn( hb_stream_t *stream, char *log, ... )
188 {
189     va_list     args;
190     va_start( args, log );
191     ts_warn_helper( stream, log, args );
192     va_end( args );
193 }
194
195 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
196 {
197     va_list     args;
198     va_start( args, log );
199     ts_warn_helper( stream, log, args );
200     va_end( args );
201
202     stream->ts_skipbad[curstream] = 1;
203     stream->ts_pos[curstream] = 0;
204     stream->ts_streamcont[curstream] = -1;
205 }
206
207 static int check_ps_sync(const uint8_t *buf)
208 {
209     // a legal MPEG program stream must start with a Pack header in the
210     // first four bytes.
211     return (buf[0] == 0x00) && (buf[1] == 0x00) &&
212            (buf[2] == 0x01) && (buf[3] == 0xba);
213 }
214
215 static int check_ps_sys(const uint8_t *buf)
216 {
217     // a legal MPEG program stream must start with a Pack followed by a
218     // SYS. If we've already verified the pack, this skips over it and checks
219     // for the sys header.
220     int pos = 14 + ( buf[13] & 0x7 );   // skip over the PACK
221     return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
222            (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
223 }
224
225 static int check_ts_sync(const uint8_t *buf)
226 {
227     // must have initial sync byte, no scrambling & a legal adaptation ctrl
228     return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
229 }
230
231 static int have_ts_sync(const uint8_t *buf, int psize)
232 {
233     return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
234            check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
235            check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
236            check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
237 }
238
239 static int hb_stream_check_for_ts(const uint8_t *buf)
240 {
241     // transport streams should have a sync byte every 188 bytes.
242     // search the first 8KB of buf looking for at least 8 consecutive
243     // correctly located sync patterns.
244     int offset = 0;
245
246     for ( offset = 0; offset < 8*1024-8*188; ++offset )
247     {
248         if ( have_ts_sync( &buf[offset], 188) )
249             return 188 | (offset << 8);
250         if ( have_ts_sync( &buf[offset], 192) )
251             return 192 | (offset << 8);
252         if ( have_ts_sync( &buf[offset], 204) )
253             return 204 | (offset << 8);
254         if ( have_ts_sync( &buf[offset], 208) )
255             return 208 | (offset << 8);
256     }
257     return 0;
258 }
259
260 static int hb_stream_check_for_ps(const uint8_t *buf)
261 {
262     // program streams should start with a PACK then a SYS header.
263     return check_ps_sync(buf) && check_ps_sys(buf);
264 }
265
266 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
267 {
268     // DVD program streams should have a Pack header every 2048 bytes.
269     // check that we have 4 of these in a row.
270     return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
271            check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
272 }
273
274 static int hb_stream_get_type(hb_stream_t *stream)
275 {
276     uint8_t buf[2048*4];
277
278     if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
279     {
280         int psize;
281         if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
282         {
283             int offset = psize >> 8;
284             psize &= 0xff;
285             hb_log("file is MPEG Transport Stream with %d byte packets"
286                    " offset %d bytes", psize, offset);
287             stream->packetsize = psize;
288             stream->hb_stream_type = transport;
289             hb_ts_stream_init(stream);
290             return 1;
291         }
292         if ( hb_stream_check_for_dvd_ps(buf) != 0 )
293         {
294             hb_log("file is MPEG DVD Program Stream");
295             stream->hb_stream_type = dvd_program;
296             return 1;
297         }
298         if ( hb_stream_check_for_ps(buf) != 0 )
299         {
300             hb_log("file is MPEG Program Stream");
301             stream->hb_stream_type = program;
302             return 1;
303         }
304     }
305     return 0;
306 }
307
308 static void hb_stream_delete_dynamic( hb_stream_t *d )
309 {
310     if( d->file_handle )
311     {
312         fclose( d->file_handle );
313                 d->file_handle = NULL;
314     }
315
316         int i=0;
317
318     if ( d->ts_packet )
319     {
320         free( d->ts_packet );
321         d->ts_packet = NULL;
322     }
323         for (i = 0; i < kMaxNumberDecodeStreams; i++)
324         {
325                 if (d->ts_buf[i])
326                 {
327                         free(d->ts_buf[i]);
328                         d->ts_buf[i] = NULL;
329                 }
330         }
331 }
332
333 static void hb_stream_delete( hb_stream_t *d )
334 {
335     hb_stream_delete_dynamic( d );
336     free( d->path );
337     free( d );
338 }
339
340 /***********************************************************************
341  * hb_stream_open
342  ***********************************************************************
343  *
344  **********************************************************************/
345 hb_stream_t * hb_stream_open( char *path, int opentype )
346 {
347
348     FILE *f = fopen( path, "r" );
349     if ( f == NULL )
350     {
351         hb_log( "hb_stream_open: open %s failed", path );
352         return NULL;
353     }
354
355     hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
356     if ( d == NULL )
357     {
358         fclose( f );
359         hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
360         return NULL;
361     }
362
363     /*
364      * if we're opening the stream to read & convert, we need
365      * the state we saved when we scanned the stream. if we're
366      * opening the stream to scan it we want to rebuild the state
367      * (even if we have saved state, the stream may have changed).
368      */
369     hb_stream_t *ss = hb_stream_lookup( path );
370     if ( opentype == 1 )
371     {
372         /* opening to read - we must have saved state */
373         if ( ss == NULL )
374         {
375             hb_log( "hb_stream_open: error: re-opening %s but no scan state", path );
376             fclose( f );
377             free( d );
378             return NULL;
379         }
380         /*
381          * copy the saved state since we might be encoding the same stream
382          * multiple times.
383          */
384         memcpy( d, ss, sizeof(*d) );
385         d->file_handle = f;
386         d->opentype = opentype;
387         d->path = strdup( path );
388
389         if ( d->hb_stream_type == transport )
390         {
391             d->ts_packet = malloc( d->packetsize );
392
393             int i = 0;
394             for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
395             {
396                 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
397             }
398             hb_stream_seek( d, 0. );
399         }
400         return d;
401     }
402
403     /*
404      * opening for scan - delete any saved state then (re)scan the stream.
405      * If it's something we can deal with (MPEG2 PS or TS) return a stream
406      * reference structure & null otherwise.
407      */
408     if ( ss != NULL )
409     {
410         hb_stream_state_delete( ss );
411     }
412     d->file_handle = f;
413     d->opentype = opentype;
414     d->path = strdup( path );
415     if (d->path != NULL &&  hb_stream_get_type( d ) != 0 )
416     {
417         return d;
418     }
419     fclose( d->file_handle );
420     if (d->path)
421     {
422         free( d->path );
423     }
424     hb_log( "hb_stream_open: open %s failed", path );
425     free( d );
426     return NULL;
427 }
428
429 /***********************************************************************
430  * hb_stream_close
431  ***********************************************************************
432  * Closes and frees everything
433  **********************************************************************/
434 void hb_stream_close( hb_stream_t ** _d )
435 {
436     hb_stream_t *stream = * _d;
437     if ( stream->frames )
438     {
439         hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
440                 stream->errors, (double)stream->errors * 100. /
441                 (double)stream->frames );
442     }
443     /*
444      * if the stream was opened for a scan, cache the result, otherwise delete
445      * the state.
446      */
447     if ( stream->opentype == 0 )
448     {
449         hb_stream_delete_dynamic( stream );
450         if ( stream_state_list == NULL )
451         {
452             stream_state_list = hb_list_init();
453         }
454         hb_list_add( stream_state_list, stream );
455     }
456     else
457     {
458         hb_stream_delete( stream );
459     }
460     *_d = NULL;
461 }
462
463 /* when the file was first opened we made entries for all the audio elementary
464  * streams we found in it. Streams that were later found during the preview scan
465  * now have an audio codec, type, rate, etc., associated with them. At the end
466  * of the scan we delete all the audio entries that weren't found by the scan
467  * or don't have a format we support. This routine deletes audio entry 'indx'
468  * by copying all later entries down one slot. */
469 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
470 {
471     int i;
472
473     for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
474     {
475         stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
476         stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
477         stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
478         ++indx;
479     }
480     --stream->ts_number_audio_pids;
481 }
482
483 static int index_of_pid(int pid, hb_stream_t *stream)
484 {
485     int i;
486
487     if ( pid == stream->ts_video_pids[0] )
488         return 0;
489
490     for ( i = 0; i < stream->ts_number_audio_pids; ++i )
491         if ( pid == stream->ts_audio_pids[i] )
492             return i + 1;
493
494     return -1;
495 }
496
497 /***********************************************************************
498  * hb_ps_stream_title_scan
499  ***********************************************************************
500  *
501  **********************************************************************/
502 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
503 {
504     // 'Barebones Title'
505     hb_title_t *aTitle = hb_title_init( stream->path, 0 );
506     aTitle->index = 1;
507
508         // Copy part of the stream path to the title name
509         char *sep = strrchr(stream->path, '/');
510         if (sep)
511                 strcpy(aTitle->name, sep+1);
512         char *dot_term = strrchr(aTitle->name, '.');
513         if (dot_term)
514                 *dot_term = '\0';
515
516     // Height, width,  rate and aspect ratio information is filled in when the previews are built
517
518     hb_stream_duration(stream, aTitle);
519
520     // One Chapter
521     hb_chapter_t * chapter;
522     chapter = calloc( sizeof( hb_chapter_t ), 1 );
523     chapter->index = 1;
524     chapter->duration = aTitle->duration;
525     chapter->hours = aTitle->hours;
526     chapter->minutes = aTitle->minutes;
527     chapter->seconds = aTitle->seconds;
528     hb_list_add( aTitle->list_chapter, chapter );
529
530     // Figure out how many audio streams we really have:
531     // - For transport streams, for each PID listed in the PMT (whether
532     //   or not it was an audio stream type) read the bitstream until we
533     //   find an packet from that PID containing a PES header and see if
534     //   the elementary stream is an audio type.
535     // - For program streams read the first 4MB and take every unique
536     //   audio stream we find.
537         if (stream->hb_stream_type == transport)
538         {
539         int i;
540
541         for (i=0; i < stream->ts_number_audio_pids; i++)
542         {
543             hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
544             if (audio->config.in.codec)
545                 hb_list_add( aTitle->list_audio, audio );
546             else
547             {
548                 free(audio);
549                 hb_stream_delete_audio_entry(stream, i);
550                 --i;
551             }
552         }
553
554         // add the PCR PID if we don't already have it
555         if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
556         {
557             stream->ts_audio_pids[stream->ts_number_audio_pids++] =
558                 stream->pmt_info.PCR_PID;
559         }
560         }
561     else
562     {
563         hb_ps_stream_find_audio_ids(stream, aTitle);
564     }
565
566   return aTitle;
567 }
568
569 /*
570  * read the next transport stream packet from 'stream'. Return NULL if
571  * we hit eof & a pointer to the sync byte otherwise.
572  */
573 static const uint8_t *next_packet( hb_stream_t *stream )
574 {
575     uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
576
577     while ( 1 )
578     {
579         if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
580              stream->packetsize )
581         {
582             return NULL;
583         }
584         if (buf[0] == 0x47)
585         {
586             return buf;
587         }
588         // lost sync - back up to where we started then try to re-establish.
589         off_t pos = ftello(stream->file_handle) - stream->packetsize;
590         off_t pos2 = align_to_next_packet(stream);
591         if ( pos2 == 0 )
592         {
593             hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
594             return NULL;
595         }
596         ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
597                  pos, pos2 );
598     }
599 }
600
601 /*
602  * skip to the start of the next PACK header in program stream src_stream.
603  */
604 static void skip_to_next_pack( hb_stream_t *src_stream )
605 {
606     // scan forward until we find the start of the next pack
607     uint32_t strt_code = -1;
608     int c;
609
610     flockfile( src_stream->file_handle );
611     while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
612     {
613         strt_code = ( strt_code << 8 ) | c;
614         if ( strt_code == 0x000001ba )
615             // we found the start of the next pack
616             break;
617     }
618     funlockfile( src_stream->file_handle );
619
620     // if we didn't terminate on an eof back up so the next read
621     // starts on the pack boundary.
622     if ( c != EOF )
623     {
624         fseeko( src_stream->file_handle, -4, SEEK_CUR );
625     }
626 }
627
628 /*
629  * scan the next MB of 'stream' to find the next start packet for
630  * the Packetized Elementary Stream associated with TS PID 'pid'.
631  */
632 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
633 {
634     int npack = 100000; // max packets to read
635
636     while (--npack >= 0)
637     {
638         const uint8_t *buf = next_packet( stream );
639         if ( buf == NULL )
640         {
641             hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
642             return 0;
643         }
644
645         /*
646          * The PES header is only in TS packets with 'start' set so we check
647          * that first then check for the right PID.
648          */
649         if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
650             buf[2] != (pid & 0xff))
651         {
652             // not a start packet or not the pid we want
653             continue;
654         }
655
656         /* skip over the TS hdr to return a pointer to the PES hdr */
657         int udata = 4;
658         switch (buf[3] & 0x30)
659         {
660             case 0x00: // illegal
661             case 0x20: // fill packet
662                 continue;
663
664             case 0x30: // adaptation
665                 if (buf[4] > 182)
666                 {
667                     hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
668                     continue;
669                 }
670                 udata += buf[4] + 1;
671                 break;
672         }
673         return &buf[udata];
674     }
675
676     /* didn't find it */
677     return 0;
678 }
679
680 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
681 {
682     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
683     hb_list_t *list = hb_list_init();
684     // how many blocks we read while searching for a video PES header
685     int blksleft = 1024;
686     uint64_t pts = 0;
687
688     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
689     {
690         hb_buffer_t *es;
691
692         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
693         hb_demux_ps( buf, list, 0 );
694
695         while ( ( es = hb_list_item( list, 0 ) ) )
696         {
697             hb_list_rem( list, es );
698             if ( es->id == 0xe0 )
699             {
700                 // this PES contains video - if there's a PTS we're done
701                 // hb_demux_ps left the PTS in buf_es->start.
702                 if ( es->start != ~0 )
703                 {
704                     pts = es->start;
705                     blksleft = 0;
706                     break;
707                 }
708             }
709             hb_buffer_close( &es );
710         }
711     }
712     hb_list_empty( &list );
713     hb_buffer_close(&buf);
714     return pts;
715 }
716
717 /***********************************************************************
718  * hb_stream_duration
719  ***********************************************************************
720  *
721  * Finding stream duration is difficult.  One issue is that the video file
722  * may have chunks from several different program fragments (main feature,
723  * commercials, station id, trailers, etc.) all with their own base pts
724  * value.  We can't find the piece boundaries without reading the entire
725  * file but if we compute a rate based on time stamps from two different
726  * pieces the result will be meaningless.  The second issue is that the
727  * data rate of compressed video normally varies by 5-10x over the length
728  * of the video. This says that we want to compute the rate over relatively
729  * long segments to get a representative average but long segments increase
730  * the likelihood that we'll cross a piece boundary.
731  *
732  * What we do is take time stamp samples at several places in the file
733  * (currently 16) then compute the average rate (i.e., ticks of video per
734  * byte of the file) for all pairs of samples (N^2 rates computed for N
735  * samples). Some of those rates will be absurd because the samples came
736  * from different segments. Some will be way low or high because the
737  * samples came from a low or high motion part of the segment. But given
738  * that we're comparing *all* pairs the majority of the computed rates
739  * should be near the overall average.  So we median filter the computed
740  * rates to pick the most representative value.
741  *
742  **********************************************************************/
743 struct pts_pos {
744     uint64_t pos;   /* file position of this PTS sample */
745     uint64_t pts;   /* PTS from video stream */
746 };
747
748 #define NDURSAMPLES 16
749
750 // get one (position, timestamp) sampple from a transport or program
751 // stream.
752 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
753 {
754     struct pts_pos pp = { 0, 0 };
755
756     if ( stream->hb_stream_type == transport )
757     {
758         const uint8_t *buf;
759         fseeko( stream->file_handle, fpos, SEEK_SET );
760         align_to_next_packet( stream );
761         buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
762         if ( buf == NULL )
763         {
764             hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
765             return pp;
766         }
767         if ( ( buf[7] >> 7 ) != 1 )
768         {
769             hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
770             return pp;
771         }
772         pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
773                  ( (uint64_t)buf[10] << 22 ) |
774                  ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
775                  ( (uint64_t)buf[12] << 7 ) |
776                  ( (uint64_t)buf[13] >> 1 );
777     }
778     else
779     {
780         // round address down to nearest dvd sector start
781         fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
782         fseeko( stream->file_handle, fpos, SEEK_SET );
783         if ( stream->hb_stream_type == program )
784         {
785             skip_to_next_pack( stream );
786         }
787         pp.pts = hb_ps_stream_getVideoPTS( stream );
788     }
789     pp.pos = ftello(stream->file_handle);
790     return pp;
791 }
792
793 static int dur_compare( const void *a, const void *b )
794 {
795     const double *aval = a, *bval = b;
796     return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
797 }
798
799 // given an array of (position, time) samples, compute a max-likelihood
800 // estimate of the average rate by computing the rate between all pairs
801 // of samples then taking the median of those rates.
802 static double compute_stream_rate( struct pts_pos *pp, int n )
803 {
804     int i, j;
805     double rates[NDURSAMPLES * NDURSAMPLES / 2];
806     double *rp = rates;
807
808     // the following nested loops compute the rates between all pairs.
809     *rp = 0;
810     for ( i = 0; i < n-1; ++i )
811     {
812         // Bias the median filter by not including pairs that are "far"
813         // from one another. This is to handle cases where the file is
814         // made of roughly equal size pieces where a symmetric choice of
815         // pairs results in having the same number of intra-piece &
816         // inter-piece rate estimates. This would mean that the median
817         // could easily fall in the inter-piece part of the data which
818         // would give a bogus estimate. The 'ns' index creates an
819         // asymmetry that favors locality.
820         int ns = i + ( n >> 1 );
821         if ( ns > n )
822             ns = n;
823         for ( j = i+1; j < ns; ++j )
824         {
825             if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
826             {
827                 *rp = ((double)( pp[j].pts - pp[i].pts )) /
828                       ((double)( pp[j].pos - pp[i].pos ));
829                                 ++rp;
830             }
831         }
832     }
833     // now compute and return the median of all the (n*n/2) rates we computed
834     // above.
835     int nrates = rp - rates;
836     qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
837     return rates[nrates >> 1];
838 }
839
840 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
841 {
842     struct pts_pos ptspos[NDURSAMPLES];
843     struct pts_pos *pp = ptspos;
844     int i;
845
846     fseeko(stream->file_handle, 0, SEEK_END);
847     uint64_t fsize = ftello(stream->file_handle);
848     uint64_t fincr = fsize / NDURSAMPLES;
849     uint64_t fpos = fincr / 2;
850     for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
851     {
852         *pp++ = hb_sample_pts(stream, fpos);
853     }
854     uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
855     inTitle->duration = dur;
856     dur /= 90000;
857     inTitle->hours    = dur / 3600;
858     inTitle->minutes  = ( dur % 3600 ) / 60;
859     inTitle->seconds  = dur % 60;
860
861     rewind(stream->file_handle);
862 }
863
864 /***********************************************************************
865  * hb_stream_read
866  ***********************************************************************
867  *
868  **********************************************************************/
869 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
870 {
871     if ( src_stream->hb_stream_type == dvd_program )
872     {
873         size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
874                                 src_stream->file_handle);
875         return (amt_read > 0);
876     }
877     if ( src_stream->hb_stream_type == program )
878     {
879         // a general program stream has arbitrary sized pack's. we're
880         // currently positioned at the start of a pack so read up to but
881         // not including the start of the next, expanding the buffer
882         // as necessary.
883         uint8_t *cp = b->data;
884         uint8_t *ep = cp + b->alloc;
885         uint32_t strt_code = -1;
886         int c;
887
888         // consume the first byte of the initial pack so we don't match on
889         // it in the loop below.
890         if ( ( c = getc( src_stream->file_handle ) ) == EOF )
891             return 0;
892
893         *cp++ = c;
894
895         flockfile( src_stream->file_handle );
896         while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
897         {
898             strt_code = ( strt_code << 8 ) | c;
899             if ( strt_code == 0x000001ba )
900                 // we found the start of the next pack
901                 break;
902             if ( cp >= ep )
903             {
904                 // need to expand the buffer
905                 int curSize = cp - b->data;
906                 hb_buffer_realloc( b, curSize * 2 );
907                 cp = b->data + curSize;
908                 ep = b->data + b->alloc;
909             }
910             *cp++ = c;
911         }
912         funlockfile( src_stream->file_handle );
913
914         // if we didn't terminate on an eof back up so the next read
915         // starts on the pack boundary.
916         b->size = cp - b->data;
917         if ( c != EOF )
918         {
919             fseeko( src_stream->file_handle, -4, SEEK_CUR );
920             b->size -= 4;
921         }
922         return 1;
923     }
924     return hb_ts_stream_decode( src_stream, b->data );
925 }
926
927 /***********************************************************************
928  * hb_stream_seek
929  ***********************************************************************
930  *
931  **********************************************************************/
932 int hb_stream_seek( hb_stream_t * src_stream, float f )
933 {
934     off_t stream_size, cur_pos, new_pos;
935     double pos_ratio = f;
936     cur_pos = ftello( src_stream->file_handle );
937     fseeko( src_stream->file_handle, 0, SEEK_END );
938     stream_size = ftello( src_stream->file_handle );
939     new_pos = (off_t) ((double) (stream_size) * pos_ratio);
940     new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
941
942     int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
943     if (r == -1)
944     {
945         fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
946         return 0;
947     }
948
949     if ( src_stream->hb_stream_type == transport )
950     {
951         // We need to drop the current decoder output and move
952         // forwards to the next transport stream packet.
953         hb_ts_stream_reset(src_stream);
954     }
955     else if ( src_stream->hb_stream_type == program )
956     {
957         skip_to_next_pack( src_stream );
958     }
959
960     return 1;
961 }
962
963 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
964 {
965     /* XXX
966      * This is a duplicate of code in dvd.c - it should get factored out
967      * into a common routine. We probably should only be putting the lang
968      * code or a lang pointer into the audio config & let the common description
969      * formatting routine in scan.c do all the stuff below.
970      */
971     snprintf( audio->config.lang.description,
972               sizeof( audio->config.lang.description ), "%s (%s)",
973               strlen(lang->native_name) ? lang->native_name : lang->eng_name,
974               audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
975                   audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
976                       audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : "LPCM" );
977     snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
978               strlen(lang->native_name) ? lang->native_name : lang->eng_name );
979     snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
980               "%s", lang->iso639_2);
981 }
982
983 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
984                                                        int aud_pid_index)
985 {
986     off_t cur_pos = ftello(stream->file_handle);
987     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
988     const uint8_t *buf;
989
990     fseeko(stream->file_handle, 0, SEEK_SET);
991     align_to_next_packet(stream);
992     buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
993
994     /* check that we found a PES header */
995     if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
996     {
997         if (buf[3] == 0xbd)
998         {
999             audio->id = 0x80bd | (aud_pid_index << 8);
1000             audio->config.in.codec = HB_ACODEC_AC3;
1001             hb_log("transport stream pid 0x%x (type 0x%x) is AC-3 audio id 0x%x",
1002                    stream->ts_audio_pids[aud_pid_index],
1003                    stream->ts_stream_type[1 + aud_pid_index],
1004                    audio->id);
1005             stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1006             stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1007         }
1008         else if (buf[3] == 0xfd)
1009         {
1010             /* XXX Extended stream id (ISO 13818-1(2000) Amd 2) - we have to look
1011              * inside the PES extension to find out the real stream id then
1012              * figure out what the heck it means. For now we just use the stream
1013              * type if one was specified. */
1014             const char *atype = 0;
1015             switch (stream->ts_stream_type[1 + aud_pid_index])
1016             {
1017                 case 0x81: // AC-3
1018                     atype = "AC-3";
1019                     audio->config.in.codec = HB_ACODEC_AC3;
1020                     break;
1021                 case 0x82: // HDMV DTS
1022                 case 0x8a: // DTS
1023                     atype = "DTS";
1024                     audio->config.in.codec = HB_ACODEC_DCA;
1025                     break;
1026                 case 0x83: // LPCM
1027                     atype = "PCM";
1028                     audio->config.in.codec = HB_ACODEC_LPCM;
1029                     break;
1030             }
1031             audio->id = 0x80bd | (aud_pid_index << 8);
1032             stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1033             hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1034                    stream->ts_audio_pids[aud_pid_index],
1035                    stream->ts_stream_type[1 + aud_pid_index], atype, audio->id);
1036         }
1037         else if ((buf[3] & 0xe0) == 0xc0)
1038         {
1039             audio->id = buf[3] | aud_pid_index;
1040             audio->config.in.codec = HB_ACODEC_MPGA;
1041             hb_log("transport stream pid 0x%x (type 0x%x) is MPEG audio id 0x%x",
1042                    stream->ts_audio_pids[aud_pid_index],
1043                    stream->ts_stream_type[1 + aud_pid_index],
1044                    audio->id);
1045             stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1046             stream->ts_streamid[1 + aud_pid_index] = buf[3];
1047         }
1048     }
1049     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1050     if ( audio->config.in.codec )
1051     {
1052                 set_audio_description( audio,
1053                   lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1054     }
1055     else
1056     {
1057         hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1058                 stream->ts_audio_pids[aud_pid_index],
1059                 stream->ts_stream_type[1 + aud_pid_index]);
1060         }
1061     return audio;
1062 }
1063
1064 static void add_audio_to_title(hb_title_t *title, int id)
1065 {
1066     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1067
1068     audio->id = id;
1069     switch ( id >> 12 )
1070     {
1071         case 0x0:
1072             audio->config.in.codec = HB_ACODEC_MPGA;
1073             hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1074             break;
1075         case 0x2:
1076             // type 2 is a DVD subtitle stream - just ignore it */
1077             free( audio );
1078             return;
1079         case 0x8:
1080             audio->config.in.codec = HB_ACODEC_AC3;
1081             hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1082             break;
1083         case 0xa:
1084             audio->config.in.codec = HB_ACODEC_LPCM;
1085             hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1086             break;
1087         default:
1088             hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1089             free( audio );
1090             return;
1091
1092     }
1093     set_audio_description( audio, lang_for_code( 0 ) );
1094     hb_list_add( title->list_audio, audio );
1095 }
1096
1097 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1098 {
1099     off_t cur_pos = ftello(stream->file_handle);
1100     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1101     hb_list_t *list = hb_list_init();
1102     // how many blocks we read while searching for audio streams
1103     int blksleft = 4096;
1104     // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1105     // so we use a bitmap to keep track of the ones we've already seen.
1106     // Bit 'i' of smap is set if we've already added the audio for
1107     // audio substream id 'i' to the title's audio list.
1108     uint32_t smap = 0;
1109
1110     // start looking 20% into the file since there's occasionally no
1111     // audio at the beginning (particularly for vobs).
1112     hb_stream_seek(stream, 0.2f);
1113
1114     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1115     {
1116         hb_buffer_t *es;
1117
1118         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1119         hb_demux_ps( buf, list, 0 );
1120
1121         while ( ( es = hb_list_item( list, 0 ) ) )
1122         {
1123             hb_list_rem( list, es );
1124             if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1125             {
1126                 // this PES contains some kind of audio - get the substream id
1127                 // and check if we've seen it already.
1128                 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1129                 if ( (smap & (1 << ssid)) == 0 )
1130                 {
1131                     // we haven't seen this stream before - add it to the
1132                     // title's list of audio streams.
1133                     smap |= (1 << ssid);
1134                     add_audio_to_title(title, es->id);
1135                 }
1136             }
1137             hb_buffer_close( &es );
1138         }
1139     }
1140     hb_list_empty( &list );
1141     hb_buffer_close(&buf);
1142     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1143 }
1144
1145 /***********************************************************************
1146  * hb_ts_stream_init
1147  ***********************************************************************
1148  *
1149  **********************************************************************/
1150
1151 static void hb_ts_stream_init(hb_stream_t *stream)
1152 {
1153         int i;
1154
1155         for (i=0; i < kMaxNumberDecodeStreams; i++)
1156         {
1157                 stream->ts_streamcont[i] = -1;
1158         }
1159         stream->ts_video_pids[0] = -1;
1160     for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1161     {
1162         stream-> ts_audio_pids[i] = -1;
1163     }
1164
1165     stream->ts_packet = malloc( stream->packetsize );
1166
1167         // Find the audio and video pids in the stream
1168         hb_ts_stream_find_pids(stream);
1169
1170         for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1171         {
1172         // demuxing buffer for TS to PS conversion
1173                 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1174         }
1175
1176     stream->ts_streamid[0] = 0xE0;              // stream 0 must be video
1177 }
1178
1179 #define MAX_HOLE 208*80
1180
1181 static off_t align_to_next_packet(hb_stream_t *stream)
1182 {
1183     uint8_t buf[MAX_HOLE];
1184         off_t pos = 0;
1185     off_t start = ftello(stream->file_handle);
1186
1187     if ( start >= stream->packetsize ) {
1188         start -= stream->packetsize;
1189         fseeko(stream->file_handle, start, SEEK_SET);
1190     }
1191
1192     if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1193         {
1194         const uint8_t *bp = buf;
1195         int i;
1196
1197         for ( i = sizeof(buf); --i >= 0; ++bp )
1198         {
1199             if ( have_ts_sync( bp, stream->packetsize ) )
1200             {
1201                 break;
1202             }
1203         }
1204         if ( i >= 0 )
1205         {
1206             pos = ( bp - buf ) - stream->packetsize + 188;
1207             if ( pos < 0 )
1208                 pos = 0;
1209         }
1210         }
1211     fseeko(stream->file_handle, start+pos, SEEK_SET);
1212         return pos;
1213 }
1214
1215
1216 typedef struct {
1217     uint8_t *buf;
1218     uint32_t val;
1219     int pos;
1220 } bitbuf_t;
1221
1222 static const unsigned int bitmask[] = {
1223         0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1224         0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1225         0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1226         0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1227
1228 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1229 {
1230         bb->pos = 0;
1231         bb->buf = buf;
1232         bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1233               (bb->buf[2] << 8) | bb->buf[3];
1234         if (clear)
1235                 memset(bb->buf, 0, bufsize);
1236 }
1237
1238 static inline int buf_size(bitbuf_t *bb)
1239 {
1240         return bb->pos >> 3;
1241 }
1242
1243 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1244 {
1245         unsigned int val;
1246         int left = 32 - (bb->pos & 31);
1247
1248         if (bits < left)
1249         {
1250                 val = (bb->val >> (left - bits)) & bitmask[bits];
1251                 bb->pos += bits;
1252         }
1253         else
1254         {
1255                 val = (bb->val & bitmask[left]) << (bits - left);
1256                 bb->pos += left;
1257                 bits -= left;
1258
1259                 int pos = bb->pos >> 3;
1260                 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1261
1262                 if (bits > 0)
1263                 {
1264                         val |= (bb->val >> (32 - bits)) & bitmask[bits];
1265                         bb->pos += bits;
1266                 }
1267         }
1268
1269         return val;
1270 }
1271
1272 // extract what useful information we can from the elementary stream
1273 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1274 // Descriptors with info we don't currently use are ignored.
1275 // The descriptor list & descriptor item formats are defined in
1276 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1277 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1278                                        const uint8_t *dp, uint8_t dlen)
1279 {
1280     const uint8_t *ep = dp + dlen;
1281
1282     while (dp < ep)
1283     {
1284         switch (dp[0])
1285         {
1286             case 10:    // ISO_639_language descriptor
1287                 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1288                 break;
1289
1290             default:
1291                 break;
1292         }
1293         dp += dp[1] + 2;
1294     }
1295 }
1296
1297 static const char * stream_type_name (uint8_t stream_type)
1298 {
1299     switch( stream_type )
1300     {
1301     case 0x01: return("ISO 11172 (MPEG1) Video");
1302     case 0x02: return("ISO 13818-2 (MPEG2) Video");
1303     case 0x03: return("ISO 11172 (MPEG1) Audio");
1304     case 0x04: return("ISO 13818-3 (MPEG2) Audio");
1305     case 0x05: return("ISO 13818-1 private section");
1306     case 0x06: return("ISO 13818-1 PES private data");
1307     case 0x07: return("ISO 13522 MHEG");
1308     case 0x08: return("ISO 13818-1 DSM-CC");
1309     case 0x09: return("ISO 13818-1 auxiliary");
1310     case 0x0a: return("ISO 13818-6 multi-protocol encap");
1311     case 0x0b: return("ISO 13818-6 DSM-CC U-N msgs");
1312     case 0x0c: return("ISO 13818-6 Stream descriptors");
1313     case 0x0d: return("ISO 13818-6 Sections");
1314     case 0x0e: return("ISO 13818-1 auxiliary");
1315     case 0x0f: return("ISO 13818-7 AAC Audio");
1316     case 0x10: return("MPEG4 Video");
1317     case 0x11: return("MPEG4 Audio");
1318     case 0x12: return("MPEG4 generic");
1319
1320     case 0x14: return("ISO 13818-6 DSM-CC download");
1321
1322     case 0x1b: return("H.264 Video");
1323
1324     case 0x80: return("DigiCipher II Video");
1325     case 0x81: return("A52/AC-3 Audio");
1326     case 0x82: return("HDMV DTS Audio");
1327     case 0x83: return("LPCM Audio");
1328     case 0x84: return("SDDS Audio");
1329     case 0x85: return("ATSC Program ID");
1330     case 0x86: return("SCTE 35 splice info");
1331     case 0x87: return("ATSC E-AC-3");
1332
1333     case 0x8a: return("DTS Audio");
1334
1335     case 0x91: return("A52b/AC-3 Audio");
1336     case 0x92: return("Subtitle");
1337
1338     case 0x94: return("SDDS Audio");
1339     case 0xa0: return("MSCODEC Video");
1340         
1341     case 0xea: return("VC-1 Video");
1342
1343     default:   return("Unknown");
1344     }
1345 }
1346
1347 int decode_program_map(hb_stream_t* stream)
1348 {
1349     bitbuf_t bb;
1350         set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1351
1352     get_bits(&bb, 8);  // table_id
1353     get_bits(&bb, 4);
1354     unsigned int section_length = get_bits(&bb, 12);
1355     stream->pmt_info.section_length = section_length;
1356
1357     unsigned int program_number = get_bits(&bb, 16);
1358     stream->pmt_info.program_number = program_number;
1359     get_bits(&bb, 2);
1360     get_bits(&bb, 5);  // version_number
1361     get_bits(&bb, 1);
1362     get_bits(&bb, 8);  // section_number
1363     get_bits(&bb, 8);  // last_section_number
1364     get_bits(&bb, 3);
1365     unsigned int PCR_PID = get_bits(&bb, 13);
1366     stream->pmt_info.PCR_PID = PCR_PID;
1367     get_bits(&bb, 4);
1368     unsigned int program_info_length = get_bits(&bb, 12);
1369     stream->pmt_info.program_info_length = program_info_length;
1370
1371         int i=0;
1372         unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1373         for (i = 0; i < program_info_length; i++)
1374         {
1375           descriptor_buf[i] = get_bits(&bb, 8);
1376         }
1377
1378         int cur_pos =  9 /* data after the section length field*/ + program_info_length;
1379         int done_reading_stream_types = 0;
1380         while (!done_reading_stream_types)
1381     {
1382         unsigned char stream_type = get_bits(&bb, 8);
1383         get_bits(&bb, 3);
1384         unsigned int elementary_PID = get_bits(&bb, 13);
1385         get_bits(&bb, 4);
1386         unsigned int ES_info_length = get_bits(&bb, 12);
1387
1388         int i=0;
1389         unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1390         for (i=0; i < ES_info_length; i++)
1391         {
1392             ES_info_buf[i] = get_bits(&bb, 8);
1393         }
1394
1395
1396         if (stream->ts_number_video_pids == 0 &&
1397             ( stream_type == 0x02 || stream_type == 0x10 || stream_type == 0x1B ) )
1398         {
1399             stream->ts_video_pids[0] = elementary_PID;
1400             stream->ts_stream_type[0] = stream_type;
1401             stream->ts_number_video_pids = 1;
1402         }
1403         else
1404         {
1405             // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1406             // for mpeg audio. But content producers seem to use other
1407             // values (0x04 and 0x06 have both been observed) so at this point
1408             // we say everything that isn't a video pid is audio then at the end
1409             // of hb_stream_title_scan we'll figure out which are really audio
1410             // by looking at the PES headers.
1411             i = stream->ts_number_audio_pids;
1412             if (i < kMaxNumberAudioPIDS)
1413             {
1414                 stream->ts_audio_pids[i] = elementary_PID;
1415                 stream->ts_stream_type[1 + i] = stream_type;
1416                 if (ES_info_length > 0)
1417                 {
1418                     decode_element_descriptors(stream, i, ES_info_buf,
1419                                                ES_info_length);
1420                 }
1421                 ++stream->ts_number_audio_pids;
1422             }
1423         }
1424
1425         cur_pos += 5 /* stream header */ + ES_info_length;
1426
1427         free(ES_info_buf);
1428
1429         if (cur_pos >= section_length - 4 /* stop before the CRC */)
1430         done_reading_stream_types = 1;
1431     }
1432
1433         free(descriptor_buf);
1434         return 1;
1435 }
1436
1437 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1438 {
1439     // Get adaption header info
1440     int adapt_len = 0;
1441     int adaption = (buf[3] & 0x30) >> 4;
1442     if (adaption == 0)
1443             return 0;
1444     else if (adaption == 0x2)
1445             adapt_len = 184;
1446     else if (adaption == 0x3)
1447             adapt_len = buf[4] + 1;
1448     if (adapt_len > 184)
1449             return 0;
1450
1451     // Get payload start indicator
1452     int start;
1453     start = (buf[1] & 0x40) != 0;
1454
1455     // Get pointer length - only valid in packets with a start flag
1456     int pointer_len = 0;
1457         if (start && stream->pmt_info.reading)
1458         {
1459                 // We just finished a bunch of packets - parse the program map details
1460                 int decode_ok = 0;
1461                 if (stream->pmt_info.tablebuf[0] == 0x02)
1462                         decode_ok = decode_program_map(stream);
1463                 free(stream->pmt_info.tablebuf);
1464                 stream->pmt_info.tablebuf = NULL;
1465                 stream->pmt_info.tablepos = 0;
1466         stream->pmt_info.reading = 0;
1467         if (decode_ok)
1468                         return decode_ok;
1469         }
1470
1471         if (start)
1472         {
1473                 pointer_len = buf[4 + adapt_len] + 1;
1474                 stream->pmt_info.tablepos = 0;
1475         }
1476         // Get Continuity Counter
1477         int continuity_counter = buf[3] & 0x0f;
1478         if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1479         {
1480                 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1481                 return 0;
1482         }
1483         stream->pmt_info.current_continuity_counter = continuity_counter;
1484         stream->pmt_info.reading |= start;
1485
1486     // Add the payload for this packet to the current buffer
1487         int amount_to_copy = 184 - adapt_len - pointer_len;
1488     if (stream->pmt_info.reading && (amount_to_copy > 0))
1489     {
1490                         stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1491
1492             memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1493             stream->pmt_info.tablepos += amount_to_copy;
1494     }
1495
1496     return 0;
1497 }
1498
1499 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1500 {
1501     unsigned char tablebuf[1024];
1502     unsigned int tablepos = 0;
1503
1504     int reading = 0;
1505
1506
1507     // Get adaption header info
1508     int adapt_len = 0;
1509     int adaption = (buf[3] & 0x30) >> 4;
1510     if (adaption == 0)
1511             return 0;
1512     else if (adaption == 0x2)
1513             adapt_len = 184;
1514     else if (adaption == 0x3)
1515             adapt_len = buf[4] + 1;
1516     if (adapt_len > 184)
1517             return 0;
1518
1519     // Get pointer length
1520     int pointer_len = buf[4 + adapt_len] + 1;
1521
1522     // Get payload start indicator
1523     int start;
1524     start = (buf[1] & 0x40) != 0;
1525
1526     if (start)
1527             reading = 1;
1528
1529     // Add the payload for this packet to the current buffer
1530     if (reading && (184 - adapt_len) > 0)
1531     {
1532             if (tablepos + 184 - adapt_len - pointer_len > 1024)
1533             {
1534                     hb_log("decode_PAT - Bad program section length (> 1024)");
1535                     return 0;
1536             }
1537             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1538             tablepos += 184 - adapt_len - pointer_len;
1539     }
1540
1541     if (start && reading)
1542     {
1543             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1544
1545
1546             unsigned int pos = 0;
1547             //while (pos < tablepos)
1548             {
1549                     bitbuf_t bb;
1550                     set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1551
1552                     unsigned char section_id    = get_bits(&bb, 8);
1553                     get_bits(&bb, 4);
1554                     unsigned int section_len    = get_bits(&bb, 12);
1555                     get_bits(&bb, 16); // transport_id
1556                     get_bits(&bb, 2);
1557                     get_bits(&bb, 5);  // version_num
1558                     get_bits(&bb, 1);  // current_next
1559                     get_bits(&bb, 8);  // section_num
1560                     get_bits(&bb, 8);  // last_section
1561
1562                     switch (section_id)
1563                     {
1564                       case 0x00:
1565                         {
1566                           // Program Association Section
1567                           section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
1568                           section_len -= 4;   // Ignore the CRC
1569                           int curr_pos = 0;
1570                                                   stream->ts_number_pat_entries = 0;
1571                           while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1572                           {
1573                             unsigned int pkt_program_num = get_bits(&bb, 16);
1574                                                         stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1575
1576                             get_bits(&bb, 3);  // Reserved
1577                             if (pkt_program_num == 0)
1578                             {
1579                               get_bits(&bb, 13); // pkt_network_id
1580                             }
1581                             else
1582                             {
1583                               unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1584                                 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1585                             }
1586                             curr_pos += 4;
1587                                                         stream->ts_number_pat_entries++;
1588                           }
1589                         }
1590                         break;
1591                       case 0xC7:
1592                             {
1593                                     break;
1594                             }
1595                       case 0xC8:
1596                             {
1597                                     break;
1598                             }
1599                     }
1600
1601                     pos += 3 + section_len;
1602             }
1603
1604             tablepos = 0;
1605     }
1606     return 1;
1607 }
1608
1609 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1610 {
1611         // align to first packet
1612     align_to_next_packet(stream);
1613
1614         // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1615         // to find the program map PID and then decode that to get the list of audio and video PIDs
1616
1617         for (;;)
1618         {
1619         const uint8_t *buf = next_packet( stream );
1620         if ( buf == NULL )
1621         {
1622                         hb_log("hb_ts_stream_find_pids - end of file");
1623                         break;
1624                 }
1625
1626                 // Get pid
1627                 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1628
1629         if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1630                 {
1631                   decode_PAT(buf, stream);
1632                   continue;
1633                 }
1634
1635                 int pat_index = 0;
1636                 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1637                 {
1638                         // There are some streams where the PAT table has multiple entries as if their are
1639                         // multiple programs in the same transport stream, and yet there's actually only one
1640                         // program really in the stream. This seems to be true for transport streams that
1641                         // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1642                         // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1643                         // but the EyeTV is only recording a single (selected) program number and not rewriting the
1644                         // PAT info on export to match what's actually on the stream.
1645                         // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1646                         // on the first pat entry for which we find a matching program map PID.  The ideal solution would
1647                         // be to build a title choice popup from the PAT program number details and then select from
1648                         // their - but right now the API's not capable of that.
1649                         if (pid == stream->pat_info[pat_index].program_map_PID)
1650                         {
1651                           if (build_program_map(buf, stream) > 0)
1652                                 break;
1653                         }
1654                 }
1655                 // Keep going  until we have a complete set of PIDs
1656                 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1657                   break;
1658         }
1659
1660         hb_log("hb_ts_stream_find_pids - found the following PIDS");
1661         hb_log("    Video PIDS : ");
1662     int i;
1663         for (i=0; i < stream->ts_number_video_pids; i++)
1664         {
1665         hb_log( "      0x%x type %s (0x%x)", 
1666                 stream->ts_video_pids[i],
1667                 stream_type_name(stream->ts_stream_type[i]),
1668                 stream->ts_stream_type[i]);
1669         }
1670         hb_log("    Audio PIDS : ");
1671         for (i = 0; i < stream->ts_number_audio_pids; i++)
1672         {
1673         hb_log( "      0x%x type %s (0x%x)", 
1674                 stream->ts_audio_pids[i],
1675                 stream_type_name(stream->ts_stream_type[i+1]),
1676                 stream->ts_stream_type[i+1] );
1677         }
1678  }
1679
1680
1681 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1682 {
1683     if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1684     {
1685         hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1686                 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1687         return;
1688     }
1689     memcpy( stream->fwrite_buf, buf, size );
1690     stream->fwrite_buf += size;
1691 }
1692
1693 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1694 {
1695         uint8_t buf[24];
1696
1697     buf[0] = 0x00;      // pack id
1698     buf[1] = 0x00;
1699     buf[2] = 0x01;
1700     buf[3] = 0xba;
1701
1702     buf[4] = 0x44 |     // SCR
1703              ( ( ( time >> 30 ) & 7 ) << 3 ) |
1704              ( ( time >> 28 ) & 3 );
1705     buf[5] = time >> 20;
1706     buf[6] = 0x04 |
1707              ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1708              ( ( time >> 13 ) & 3 );
1709     buf[7] = time >> 5;
1710     buf[8] = 0x04 | ( time << 3 );
1711
1712     buf[9] = 0x01;      // SCR extension
1713
1714     buf[10] = 384000 >> (22 - 8);     // program mux rate
1715     buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1716     buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1717
1718     buf[13] = 0xf8 | stuffing;
1719
1720     int i;
1721     for (i = 0; i < stuffing; ++i )
1722         buf[14+i] = 0xff;
1723
1724         fwrite64(stream, buf, 14 + stuffing );
1725 }
1726
1727 static void pad_buffer(hb_stream_t* stream, int pad)
1728 {
1729         pad -= 6;
1730
1731         uint8_t buf[6];
1732         buf[0] = 0;
1733     buf[1] = 0;
1734     buf[2] = 0;
1735     buf[3] = 0xbe;
1736         buf[4] = pad >> 8;
1737     buf[5] = pad;
1738
1739         fwrite64(stream, buf, 6);
1740
1741         buf[0] = 0xff;
1742     while ( --pad >= 0 )
1743     {
1744                 fwrite64(stream, buf, 1);
1745         }
1746 }
1747
1748 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1749 {
1750         uint8_t buf[9];
1751
1752     memset(buf, 0, sizeof(buf) );
1753     buf[2] = 1;
1754     buf[3] = streamid;
1755     buf[4] = ( len + 3 ) >> 8;
1756     buf[5] = len + 3;
1757     buf[6] = 0x88;
1758
1759     fwrite64(stream, buf, 9);
1760 }
1761
1762 static void generate_output_data(hb_stream_t *stream, int curstream)
1763 {
1764     uint8_t *tdat = stream->ts_buf[curstream];
1765     int len;
1766
1767     // we always ship a PACK header plus all the data in our demux buf.
1768     // AC3 audio also always needs it substream header.
1769     len = 14 + stream->ts_pos[curstream];
1770     if ( stream->ts_stream_type[curstream] == 0x81)
1771     {
1772         len += 4;
1773     }
1774
1775     if ( ! stream->ts_start[curstream] )
1776     {
1777         // we're in the middle of a chunk of PES data - we need to add
1778         // a 'continuation' PES header after the PACK header.
1779         len += 9;
1780     }
1781
1782     // Write out pack header
1783     // If we don't have 2048 bytes we need to pad to 2048. We can
1784     // add a padding frame after our data but we need at least 7
1785     // bytes of space to do it (6 bytes of header & 1 of pad). If
1786     // we have fewer than 7 bytes left we need to fill the excess
1787     // space with stuffing bytes added to the pack header.
1788     int stuffing = 0;
1789     if ( len > HB_DVD_READ_BUFFER_SIZE )
1790     {
1791         hb_log( "stream ts length botch %d", len );
1792     }
1793     if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1794     {
1795         stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1796     }
1797     write_pack(stream, stream->ts_nextpcr, stuffing );
1798     stream->ts_nextpcr += 10;
1799
1800     if ( stream->ts_start[curstream] )
1801     {
1802         // Start frames already have a PES header but we have modify it
1803         // to map from TS PID to PS stream id. Also, if the stream is AC3
1804         // audio we have to insert an AC3 stream header between the end of
1805         // the PES header and the start of the stream data.
1806
1807         stream->ts_start[curstream] = 0;
1808         tdat[3] = stream->ts_streamid[curstream];
1809
1810         uint16_t plen = stream->ts_pos[curstream] - 6;
1811         if ( stream->ts_stream_type[curstream] == 0x81)
1812         {
1813             // We have to add an AC3 header in front of the data. Add its
1814             // size to the PES packet length.
1815             plen += 4;
1816             tdat[4] = plen >> 8;
1817             tdat[5] = plen;
1818
1819             // Write out the PES header
1820             int hdrsize = 9 + tdat[8];
1821             fwrite64(stream, tdat, hdrsize);
1822
1823             // add a four byte DVD ac3 stream header
1824             uint8_t ac3_substream_id[4];
1825             int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1826             ac3_substream_id[0] = 0x80 | ssid;  // substream id
1827             ac3_substream_id[1] = 0x01;         // number of sync words
1828             ac3_substream_id[2] = 0x00;         // first offset (16 bits)
1829             ac3_substream_id[3] = 0x02;
1830             fwrite64(stream, ac3_substream_id, 4);
1831
1832             // add the rest of the data
1833             fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1834         }
1835         else
1836         {
1837             // not audio - don't need to modify the stream so write what we've got
1838             tdat[4] = plen >> 8;
1839             tdat[5] = plen;
1840             fwrite64( stream,  tdat, stream->ts_pos[curstream] );
1841         }
1842     }
1843     else
1844     {
1845         // data without a PES start header needs a simple 'continuation'
1846         // PES header. AC3 audio also needs its substream header.
1847         if ( stream->ts_stream_type[curstream] != 0x81)
1848         {
1849             make_pes_header(stream, stream->ts_pos[curstream],
1850                             stream->ts_streamid[curstream]);
1851         }
1852         else
1853         {
1854             make_pes_header(stream, stream->ts_pos[curstream] + 4,
1855                             stream->ts_streamid[curstream]);
1856
1857             // add a four byte DVD ac3 stream header
1858             uint8_t ac3_substream_id[4];
1859             int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1860             ac3_substream_id[0] = 0x80 | ssid;  // substream id
1861             ac3_substream_id[1] = 0x01;         // number of sync words
1862             ac3_substream_id[2] = 0x00;         // first offset (16 bits)
1863             ac3_substream_id[3] = 0x02;
1864             fwrite64(stream, ac3_substream_id, 4);
1865         }
1866         fwrite64( stream, tdat, stream->ts_pos[curstream] );
1867     }
1868
1869     // Write padding
1870     int left = HB_DVD_READ_BUFFER_SIZE - len;
1871     if ( left >= 8 )
1872     {
1873         pad_buffer(stream, left);
1874     }
1875
1876     stream->ts_pos[curstream] = 0;
1877 }
1878
1879 static int isIframe( const uint8_t *buf, int adapt_len )
1880 {
1881     // Look for the Group of Pictures packet
1882     int i;
1883     uint32_t strid = 0;
1884
1885     for (i = 4 + adapt_len; i < 188; i++)
1886     {
1887         strid = (strid << 8) | buf[i];
1888         switch ( strid )
1889         {
1890             case 0x000001B8: // group_start_code (GOP header)
1891             case 0x000001B3: // sequence_header code
1892                 return 1;
1893
1894             case 0x00000100: // picture_start_code
1895                 // picture_header, let's see if it's an I-frame
1896                 if (i<185)
1897                 {
1898                     // check if picture_coding_type == 1
1899                     if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1900                     {
1901                         // found an I-frame picture
1902                         return 1;
1903                     }
1904                 }
1905                 break;
1906         }
1907     }
1908     // didn't find an I frame
1909     return 0;
1910 }
1911
1912 /***********************************************************************
1913  * hb_ts_stream_decode
1914  ***********************************************************************
1915  *
1916  **********************************************************************/
1917 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
1918 {
1919     /*
1920      * stash the output buffer pointer in our stream so we don't have to
1921      * pass it & its original value to everything we call.
1922      */
1923     stream->fwrite_buf = obuf;
1924     stream->fwrite_buf_orig = obuf;
1925
1926         // spin until we get a packet of data from some stream or hit eof
1927         while ( 1 )
1928         {
1929         int64_t pcr = stream->ts_lastpcr;
1930         int curstream;
1931
1932         const uint8_t *buf = next_packet(stream);
1933         if ( buf == NULL )
1934         {
1935             // end of file - we didn't finish filling our ps write buffer
1936             // so just discard the remainder (the partial buffer is useless)
1937             hb_log("hb_ts_stream_decode - eof");
1938             return 0;
1939                 }
1940
1941         /* This next section validates the packet */
1942
1943                 // Get pid and use it to find stream state.
1944                 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
1945         if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
1946             continue;
1947
1948                 // Get error
1949                 int errorbit = (buf[1] & 0x80) != 0;
1950                 if (errorbit)
1951                 {
1952                         ts_err( stream, curstream,  "packet error bit set");
1953                         continue;
1954                 }
1955
1956                 // Get adaption header info
1957                 int adaption = (buf[3] & 0x30) >> 4;
1958                 int adapt_len = 0;
1959                 if (adaption == 0)
1960                 {
1961                         ts_err( stream, curstream,  "adaptation code 0");
1962                         continue;
1963                 }
1964                 else if (adaption == 0x2)
1965                         adapt_len = 184;
1966                 else if (adaption == 0x3)
1967                 {
1968                         adapt_len = buf[4] + 1;
1969                         if (adapt_len > 184)
1970                         {
1971                                 ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
1972                 continue;
1973                         }
1974                 }
1975
1976         // if there's an adaptation header & PCR_flag is set
1977         // get the PCR (Program Clock Reference)
1978         if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
1979         {
1980             pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
1981                   ( (uint64_t)buf[7] << (33 - 16) ) |
1982                   ( (uint64_t)buf[8] << (33 - 24) ) |
1983                   ( (uint64_t)buf[9] << (33 - 32) ) |
1984                   ( buf[10] >> 7 );
1985             stream->ts_nextpcr = pcr;
1986
1987             // remember the pcr across calls to this routine
1988             stream->ts_lastpcr = pcr;
1989         }
1990
1991                 if ( pcr == -1 )
1992                 {
1993             // don't accumulate data until we get a pcr
1994                     continue;
1995                 }
1996
1997                 // Get continuity
1998         // Continuity only increments for adaption values of 0x3 or 0x01
1999         // and is not checked for start packets.
2000
2001                 int start = (buf[1] & 0x40) != 0;
2002
2003         if ( (adaption & 0x01) != 0 )
2004                 {
2005             int continuity = (buf[3] & 0xF);
2006             if ( continuity == stream->ts_streamcont[curstream] )
2007             {
2008                 // we got a duplicate packet (usually used to introduce
2009                 // a PCR when one is needed). The only thing that can
2010                 // change in the dup is the PCR which we grabbed above
2011                 // so ignore the rest.
2012                 continue;
2013             }
2014             if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2015                  (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2016                         {
2017                                 ts_err( stream, curstream,  "continuity error: got %d expected %d",
2018                         (int)continuity,
2019                         (stream->ts_streamcont[curstream] + 1) & 0xf );
2020                 stream->ts_streamcont[curstream] = continuity;
2021                                 continue;
2022                         }
2023                         stream->ts_streamcont[curstream] = continuity;
2024                 }
2025
2026         /* If we get here the packet is valid - process its data */
2027
2028         if ( start )
2029         {
2030             // Found a random access point (now we can start a frame/audio packet..)
2031
2032                         // If we were skipping a bad packet, start fresh on this new PES packet..
2033                         if (stream->ts_skipbad[curstream] == 1)
2034                         {
2035                 // video skips to an iframe after a bad packet to minimize
2036                 // screen corruption
2037                 if ( curstream == 0 && !isIframe( buf, adapt_len ) )
2038                 {
2039                     continue;
2040                 }
2041                                 stream->ts_skipbad[curstream] = 0;
2042                         }
2043
2044                         // If we don't have video yet, check to see if this is an
2045             // i_frame (group of picture start)
2046                         if ( curstream == 0 )
2047             {
2048                 if ( !stream->ts_foundfirst[0] )
2049                 {
2050                     if ( stream->ts_stream_type[0] == 2 &&
2051                          !isIframe( buf, adapt_len ) )
2052                     {
2053                         // didn't find an I frame
2054                         continue;
2055                     }
2056                     stream->ts_foundfirst[0] = 1;
2057                 }
2058                 ++stream->frames;
2059             }
2060                         else if ( ! stream->ts_foundfirst[curstream] )
2061             {
2062                 // start other streams only after first video frame found.
2063                 if ( ! stream->ts_foundfirst[0] )
2064                 {
2065                     continue;
2066                 }
2067                 stream->ts_foundfirst[curstream] = 1;
2068                         }
2069
2070             // If we have some data already on this stream, turn it into
2071             // a program stream packet. Then add the payload for this
2072             // packet to the current pid's buffer.
2073             if ( stream->ts_pos[curstream] )
2074             {
2075                 generate_output_data(stream, curstream);
2076                 stream->ts_start[curstream] = 1;
2077                 memcpy(stream->ts_buf[curstream],
2078                        buf + 4 + adapt_len, 184 - adapt_len);
2079                 stream->ts_pos[curstream] = 184 - adapt_len;
2080                 return 1;
2081             }
2082             stream->ts_start[curstream] = 1;
2083         }
2084
2085                 // Add the payload for this packet to the current buffer
2086                 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2087             (184 - adapt_len) > 0)
2088                 {
2089                         memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2090                    buf + 4 + adapt_len, 184 - adapt_len);
2091                         stream->ts_pos[curstream] += 184 - adapt_len;
2092
2093             // if the next TS packet could possibly overflow our 2K output buffer
2094             // we need to generate a packet now. Overflow would be 184 bytes of
2095             // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2096             if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2097             {
2098                 // we have enough data to make a PS packet
2099                 generate_output_data(stream, curstream);
2100                 return 1;
2101             }
2102                 }
2103         }
2104 }
2105
2106 /***********************************************************************
2107  * hb_ts_stream_reset
2108  ***********************************************************************
2109  *
2110  **********************************************************************/
2111 static void hb_ts_stream_reset(hb_stream_t *stream)
2112 {
2113         int i;
2114
2115         for (i=0; i < kMaxNumberDecodeStreams; i++)
2116         {
2117                 stream->ts_pos[i] = 0;
2118                 stream->ts_foundfirst[i] = 0;
2119                 stream->ts_skipbad[i] = 0;
2120                 stream->ts_streamcont[i] = -1;
2121                 stream->ts_start[i] = 0;
2122         }
2123
2124     stream->ts_lastpcr = -1;
2125     stream->ts_nextpcr = -1;
2126
2127     stream->frames = 0;
2128     stream->errors = 0;
2129     stream->last_error_frame = -10000;
2130     stream->last_error_count = 0;
2131
2132     align_to_next_packet(stream);
2133 }
2134