OSDN Git Service

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