OSDN Git Service

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