OSDN Git Service

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