OSDN Git Service

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