OSDN Git Service

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