OSDN Git Service

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