OSDN Git Service

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