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. */
9 #include "a52dec/a52.h"
13 #define min(a, b) a < b ? a : b
15 typedef enum { hb_stream_type_unknown = 0, hb_stream_type_transport, hb_stream_type_program } hb_stream_type_t;
17 #define kMaxNumberDecodeStreams 8
18 #define kMaxNumberVideoPIDS 16
19 #define kMaxNumberAudioPIDS 32
20 //#define kVideoStream 0
21 //#define kAudioStream 1
22 #define kNumDecodeBuffers 2
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
32 hb_stream_type_t stream_type;
34 int ps_current_write_buffer_index;
35 int ps_current_read_buffer_index;
43 } ps_decode_buffer[kNumDecodeBuffers];
50 } a52_info[kMaxNumberAudioPIDS];
52 int ts_video_pids[kMaxNumberVideoPIDS];
53 int ts_audio_pids[kMaxNumberAudioPIDS];
55 int ts_number_video_pids;
56 int ts_number_audio_pids;
57 int ts_selected_audio_pid_index;
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];
71 /***********************************************************************
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);
82 int hb_stream_is_stream_type( char * path )
84 if ((strstr(path,".mpg") != NULL) ||
85 (strstr(path,".vob") != NULL) ||
86 (strstr(path,".ts") != NULL) ||
87 (strstr(path, ".m2t") != NULL))
95 /***********************************************************************
97 ***********************************************************************
99 **********************************************************************/
100 hb_stream_t * hb_stream_open( char * path )
104 d = calloc( sizeof( hb_stream_t ), 1 );
107 if( !( d->file_handle = fopen( path, "rb" ) ) )
109 hb_log( "hb_stream_open: fopen failed (%s)", path );
113 d->path = strdup( path );
115 if ( ( strstr(d->path,".ts") != NULL) || ( strstr(d->path,".m2t") != NULL))
117 d->stream_type = hb_stream_type_transport;
118 hb_ts_stream_init(d);
120 else if (( strstr(d->path,".mpg") != NULL) || ( strstr(d->path,".vob") != NULL))
122 d->stream_type = hb_stream_type_program;
132 /***********************************************************************
134 ***********************************************************************
135 * Closes and frees everything
136 **********************************************************************/
137 void hb_stream_close( hb_stream_t ** _d )
139 hb_stream_t * d = *_d;
143 fclose( d->file_handle );
144 d->file_handle = NULL;
149 fclose(d->debug_output);
150 d->debug_output = NULL;
154 for (i = 0; i < kNumDecodeBuffers; i++)
156 if (d->ps_decode_buffer[i].data)
158 free(d->ps_decode_buffer[i].data);
159 d->ps_decode_buffer[i].data = NULL;
163 for (i = 0; i < kMaxNumberDecodeStreams; i++)
165 if (d->ts_packetbuf[i])
167 free(d->ts_packetbuf[i]);
168 d->ts_packetbuf[i] = NULL;
176 /***********************************************************************
177 * hb_ps_stream_title_scan
178 ***********************************************************************
180 **********************************************************************/
181 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
184 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
186 // Copy part of the stream path to the title name
187 char *sep = strrchr(stream->path, '/');
189 strcpy(aTitle->name, sep+1);
190 char *dot_term = strrchr(aTitle->name, '.');
194 // Height, width, rate and aspect ratio information is filled in when the previews are built
196 hb_stream_duration(stream, aTitle);
199 hb_chapter_t * chapter;
200 chapter = calloc( sizeof( hb_chapter_t ), 1 );
202 chapter->duration = aTitle->duration;
203 chapter->hours = aTitle->hours;
204 chapter->minutes = aTitle->minutes;
205 chapter->seconds = aTitle->seconds;
206 hb_list_add( aTitle->list_chapter, chapter );
208 int i=0, num_audio_tracks = 1;
210 if (stream->stream_type == hb_stream_type_transport)
212 num_audio_tracks = stream->ts_number_audio_pids;
215 for (i=0; i < num_audio_tracks ; i++)
217 // Basic AC-3 Audio track
219 audio = calloc( sizeof( hb_audio_t ), 1 );
221 audio->source_pid = stream->ts_audio_pids[i];
223 hb_stream_set_audio_id_and_codec(stream, audio);
225 hb_list_add( aTitle->list_audio, audio );
231 /***********************************************************************
233 ***********************************************************************
235 **********************************************************************/
236 void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
238 // VOB Files often have exceedingly unusual PTS values in them - they will progress for a while
239 // and then reset without warning !
240 if (strstr(stream->path,".vob") != NULL)
242 // So we'll use a 'fake duration' that should give enough time !
243 int64_t duration = 4 * 3600 * 90000;
244 inTitle->duration = duration; //90LL * dvdtime2msec( &d->pgc->playback_time );
245 inTitle->hours = inTitle->duration / 90000 / 3600;
246 inTitle->minutes = ( ( inTitle->duration / 90000 ) % 3600 ) / 60;
247 inTitle->seconds = ( inTitle->duration / 90000 ) % 60;
251 unsigned char *buf = (unsigned char *) malloc(4096);
254 int64_t first_pts = 0, last_pts = 0;
256 // To calculate the duration we look for the first and last presentation time stamps in the stream for video data
257 // and then use the delta
260 cur_pos = ftello(stream->file_handle);
261 if (fread(buf, 4096, 1, stream->file_handle) == 1)
264 for (i=0; (i <= 4092) && !done; i++)
266 if ((buf[i] == 0x00) && (buf[i+1] == 0x00) && (buf[i+2] == 0x01) && (buf[i+3] == 0xe0)) // Found a Video Stream
268 // Now look for a PTS field - we need to make sure we have enough space so we back up a little and read
270 fseeko(stream->file_handle, cur_pos + i, SEEK_SET);
271 if (fread(buf, 4096, 1, stream->file_handle) == 1)
273 int has_pts = ( ( buf[7] >> 6 ) & 0x2 ) ? 1 : 0;
276 first_pts = ( ( ( (uint64_t) buf[9] >> 1 ) & 0x7 ) << 30 ) +
278 ( ( buf[11] >> 1 ) << 15 ) +
285 fseeko(stream->file_handle, cur_pos, SEEK_SET);
286 fread(buf, 4096, 1, stream->file_handle);
293 done = 1; // End of data;
296 // Now work back from the end of the stream
297 fseeko(stream->file_handle,0 ,SEEK_END);
303 if (fseeko(stream->file_handle, -4096, SEEK_CUR) < 0)
309 cur_pos = ftello(stream->file_handle);
310 if (fread(buf, 4096, 1, stream->file_handle) == 1)
313 for (i=4092; (i >= 0) && !done; i--)
315 if ((buf[i] == 0x00) && (buf[i+1] == 0x00) && (buf[i+2] == 0x01) && (buf[i+3] == 0xe0)) // Found a Video Stream
317 // Now look for a PTS field - we need to make sure we have enough space so we back up a little and read
319 fseeko(stream->file_handle, cur_pos + i, SEEK_SET);
320 fread(buf, 1, 4096, stream->file_handle);
322 unsigned char pts_dts_flag = buf[7];
324 int has_pts = ( ( buf[7] >> 6 ) & 0x2 ) ? 1 : 0;
327 last_pts = ( ( ( (uint64_t) buf[9] >> 1 ) & 0x7 ) << 30 ) +
329 ( ( buf[11] >> 1 ) << 15 ) +
337 // Re Read the original data and carry on (i is still valid in the old buffer)
338 fseeko(stream->file_handle, cur_pos, SEEK_SET);
339 fread(buf, 4096, 1, stream->file_handle);
343 fseeko(stream->file_handle, -4096, SEEK_CUR); // 'Undo' the last read
346 done = 1; // End of data;
350 int64_t duration = last_pts - first_pts;
351 inTitle->duration = duration; //90LL * dvdtime2msec( &d->pgc->playback_time );
352 inTitle->hours = inTitle->duration / 90000 / 3600;
353 inTitle->minutes = ( ( inTitle->duration / 90000 ) % 3600 ) / 60;
354 inTitle->seconds = ( inTitle->duration / 90000 ) % 60;
358 /***********************************************************************
360 ***********************************************************************
362 **********************************************************************/
363 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
365 if (src_stream->stream_type == hb_stream_type_program)
368 amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1, src_stream->file_handle);
374 else if (src_stream->stream_type == hb_stream_type_transport)
376 int read_buffer_index = src_stream->ps_current_read_buffer_index;
378 // Transport streams are a little more complex - we might be able to just
379 // read from the transport stream conversion buffer (if there's enough data)
380 // or we may need to transfer what's left and fill it again.
381 if (src_stream->ps_decode_buffer[read_buffer_index].len - src_stream->ps_decode_buffer[read_buffer_index].read_pos > HB_DVD_READ_BUFFER_SIZE)
383 memcpy(b->data, src_stream->ps_decode_buffer[read_buffer_index].data + src_stream->ps_decode_buffer[read_buffer_index].read_pos,HB_DVD_READ_BUFFER_SIZE);
384 src_stream->ps_decode_buffer[read_buffer_index].read_pos += HB_DVD_READ_BUFFER_SIZE;
389 // Not quite enough data in the buffer - transfer what is present, fill the buffer and then
390 // transfer what's still needed.
391 int transfer_size = HB_DVD_READ_BUFFER_SIZE;
392 int amt_avail_to_transfer = src_stream->ps_decode_buffer[read_buffer_index].len - src_stream->ps_decode_buffer[read_buffer_index].read_pos;
393 memcpy(b->data, src_stream->ps_decode_buffer[read_buffer_index].data + src_stream->ps_decode_buffer[read_buffer_index].read_pos, amt_avail_to_transfer);
394 transfer_size -= amt_avail_to_transfer;
395 src_stream->ps_decode_buffer[read_buffer_index].read_pos += amt_avail_to_transfer;
397 // Give up this buffer - decoding may well need it, and we're done
398 src_stream->ps_decode_buffer[read_buffer_index].write_pos = 0;
399 src_stream->ps_decode_buffer[read_buffer_index].len = 0;
402 hb_ts_stream_decode(src_stream);
404 // Decoding will almost certainly have changed the current read buffer index
405 read_buffer_index = src_stream->ps_current_read_buffer_index;
407 if (src_stream->ps_decode_buffer[read_buffer_index].len == 0)
409 hb_log("hb_stream_read - buffer after decode has zero length data");
413 // Read the bit we still need
414 memcpy(b->data+amt_avail_to_transfer, src_stream->ps_decode_buffer[read_buffer_index].data + src_stream->ps_decode_buffer[read_buffer_index].read_pos,transfer_size);
415 src_stream->ps_decode_buffer[read_buffer_index].read_pos += transfer_size;
424 /***********************************************************************
426 ***********************************************************************
428 **********************************************************************/
429 int hb_stream_seek( hb_stream_t * src_stream, float f )
431 off_t stream_size, cur_pos, new_pos;
432 double pos_ratio = f;
433 cur_pos = ftello(src_stream->file_handle);
434 fseeko(src_stream->file_handle,0 ,SEEK_END);
435 stream_size = ftello(src_stream->file_handle);
436 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
437 int r = fseeko(src_stream->file_handle, new_pos, SEEK_SET);
441 fseeko(src_stream->file_handle, cur_pos, SEEK_SET);
445 if (src_stream->stream_type == hb_stream_type_transport)
447 // We need to drop the current decoder output and move
448 // forwards to the next transport stream packet.
449 hb_ts_stream_reset(src_stream);
452 // Now we must scan forwards for a valid start code (0x000001BA)
454 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
457 if (hb_stream_read(src_stream,buf) == 1)
460 for (i=0; (i <= HB_DVD_READ_BUFFER_SIZE-4) && (!done); i++)
462 if ((buf->data[i] == 0x00) && (buf->data[i+1] == 0x00) && (buf->data[i+2] == 0x01) && (buf->data[i+3] == 0xba))
465 // 'Put Back' the data we've just read (up to this point)
466 hb_stream_put_back(src_stream, i);
471 done = 1; // End of data;
473 hb_buffer_close(&buf);
477 /***********************************************************************
478 * hb_stream_set_audio_id_and_codec
479 ***********************************************************************
481 **********************************************************************/
482 void hb_stream_set_audio_id_and_codec(hb_stream_t *stream, hb_audio_t *audio)
485 cur_pos = ftello(stream->file_handle);
487 hb_buffer_t *buf = NULL;
489 int cur_audio_pid_index = stream->ts_selected_audio_pid_index;
491 if (stream->stream_type == hb_stream_type_transport)
494 for (i=0; i < stream->ts_number_audio_pids; i++)
496 if (stream->ts_audio_pids[i] == audio->source_pid)
498 stream->ts_selected_audio_pid_index = i;
504 //Start at the beginning of the stream
505 hb_stream_seek(stream, 0.0f);
506 // fseeko(stream->file_handle,0 ,SEEK_SET);
508 // Now we must scan forwards for a valid audio start code (0x000001xx)
509 buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
512 // if (fread(buf->data,4096,1,stream->file_handle) == 1)
513 if (hb_stream_read(stream, buf) == 1)
516 for (i=0; (i <= HB_DVD_READ_BUFFER_SIZE-4) && (!done); i++)
518 if ((buf->data[i] == 0x00) && (buf->data[i+1] == 0x00) && (buf->data[i+2] == 0x01))
520 if (buf->data[i+3] == 0xbd)
523 audio->codec = HB_ACODEC_AC3;
526 else if ((buf->data[i+3] & 0xe0) == 0xc0)
528 audio->id = buf->data[i+3];
529 audio->codec = HB_ACODEC_MPGA;
536 done = 1; // End of data;
538 hb_buffer_close(&buf);
540 fseeko(stream->file_handle, cur_pos, SEEK_SET);
542 stream->ts_selected_audio_pid_index = cur_audio_pid_index;
545 /***********************************************************************
546 * hb_stream_update_audio
547 ***********************************************************************
549 **********************************************************************/
550 void hb_stream_update_audio(hb_stream_t *stream, hb_audio_t *audio)
554 if (stream->stream_type == hb_stream_type_program)
556 lang = lang_for_code('');
558 else if (stream->stream_type == hb_stream_type_transport)
560 // Find the audio stream info for this PID
562 for (i=0; i < stream->ts_number_audio_pids; i++)
564 if (stream->ts_audio_pids[i] == audio->source_pid)
567 if (i == stream->ts_number_audio_pids)
569 hb_log("hb_stream_update_audio - cannot find PID 0x%x (%d) in ts_audio_pids list !", audio->source_pid, audio->source_pid);
573 lang = lang_for_code(stream->a52_info[i].lang_code);
574 audio->rate = stream->a52_info[i].rate;
575 audio->bitrate = stream->a52_info[i].bitrate;
576 audio->config.a52.ac3flags = audio->ac3flags = stream->a52_info[i].flags;
580 switch( audio->ac3flags & A52_CHANNEL_MASK )
586 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_MONO;
591 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
593 /* dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input */
595 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_DOLBY;
599 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F2R;
603 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F1R;
607 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F;
610 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F1R;
613 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F2R;
617 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
620 /* add in our own LFE flag if the source has LFE */
621 if (audio->ac3flags & A52_LFE)
623 audio->input_channel_layout = audio->input_channel_layout | HB_INPUT_CH_LAYOUT_HAS_LFE;
626 snprintf( audio->lang, sizeof( audio->lang ), "%s (%s)", strlen(lang->native_name) ? lang->native_name : lang->eng_name,
627 audio->codec == HB_ACODEC_AC3 ? "AC3" : ( audio->codec == HB_ACODEC_MPGA ? "MPEG" : "LPCM" ) );
628 snprintf( audio->lang_simple, sizeof( audio->lang_simple ), "%s", strlen(lang->native_name) ? lang->native_name : lang->eng_name );
629 snprintf( audio->iso639_2, sizeof( audio->iso639_2 ), "%s", lang->iso639_2);
631 if ( (audio->ac3flags & A52_CHANNEL_MASK) == A52_DOLBY ) {
632 sprintf( audio->lang + strlen( audio->lang ),
633 " (Dolby Surround)" );
635 sprintf( audio->lang + strlen( audio->lang ),
637 HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(audio->input_channel_layout) +
638 HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(audio->input_channel_layout),
639 HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(audio->input_channel_layout));
642 hb_log( "hb_stream_update_audio: id=%x, lang=%s, 3cc=%s, rate = %d, bitrate = %d, flags = 0x%x (%d)", audio->id, audio->lang, audio->iso639_2, audio->rate, audio->bitrate, audio->ac3flags, audio->ac3flags );
646 void hb_stream_set_selected_audio_pid_index(hb_stream_t *stream, int i)
648 stream->ts_selected_audio_pid_index = i;
651 /***********************************************************************
653 ***********************************************************************
655 **********************************************************************/
656 static void hb_stream_put_back(hb_stream_t *stream, int i)
658 if (stream->stream_type == hb_stream_type_program)
660 // Program streams are pretty easy - we just reposition the source file
662 fseeko(stream->file_handle, -(HB_DVD_READ_BUFFER_SIZE-i), SEEK_CUR);
664 else if (stream->stream_type == hb_stream_type_transport)
666 int read_buffer_index = stream->ps_current_read_buffer_index;
668 // Transport streams are a little more tricky - so long as the
669 // amount to back up is still within the current decode buffer
670 // we can just adjust the read pos.
671 if (stream->ps_decode_buffer[read_buffer_index].read_pos - i > 0)
673 stream->ps_decode_buffer[read_buffer_index].read_pos -= i;
676 fprintf(stderr, "hb_stream_put_back - trying to step beyond the start of the buffer, read_pos = %d amt to put back = %d\n", stream->ps_decode_buffer[read_buffer_index].read_pos, i);
681 /***********************************************************************
683 ***********************************************************************
685 **********************************************************************/
686 #define PS_DECODE_BUFFER_SIZE ( 1024 * 1024 * 4)
688 static void hb_ts_stream_init(hb_stream_t *stream)
690 // Output Program Stream
692 for (i=0; i < kNumDecodeBuffers; i++)
694 stream->ps_decode_buffer[i].data = (unsigned char *) malloc(PS_DECODE_BUFFER_SIZE);
695 stream->ps_decode_buffer[i].read_pos = 0;
696 stream->ps_decode_buffer[i].size = PS_DECODE_BUFFER_SIZE;
697 stream->ps_decode_buffer[i].len = 0;
698 stream->ps_decode_buffer[i].write_pos = 0;
701 for (i=0; i < kMaxNumberDecodeStreams; i++)
703 stream->ts_streamcont[i] = -1;
706 stream->ps_current_write_buffer_index = 0;
707 stream->ps_current_read_buffer_index = 1;
709 // This is the index (in ts_audio_pids) of the selected
710 // output stream. It should not be set until after all the
711 // pids in the stream have been discovered.
712 stream->ts_selected_audio_pid_index = -1;
714 stream->debug_output = fopen("/Users/awk/Desktop/hb_debug.mpg", "wb");
716 // Find the audio and video pids in the stream
717 hb_ts_stream_find_pids(stream);
719 for (i=0; i < stream->ts_number_video_pids; i++)
721 // In progress audio/video data during the transport stream -> program stream processing
722 stream->ts_packetbuf[i] = (unsigned char *) malloc(1024 * 1024);
723 stream->ts_streamid[i] = 0xE0; // Stream is Video
726 for (i = stream->ts_number_video_pids; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
728 stream->ts_packetbuf[i] = (unsigned char *) malloc(1024 * 1024);
729 stream->ts_streamid[i] = 0xBD; // Stream 1 is AC-3 Audio
733 // ------------------------------------------------------------------------------------
735 off_t align_to_next_packet(FILE* f)
737 unsigned char buf[188*20];
739 off_t start = ftello(f);
742 if (fread(buf, 188*20, 1, f) == 1)
745 while (!found && (pos < 188))
749 for (i = 0; i < 188*20; i += 188)
751 unsigned char c = buf[pos+i];
753 if ((c != 0x47) && (c != 0x72) && (c != 0x29))
755 // this offset failed, try next
765 pos = 0; // failed to find anything!!!!!?
767 fseek(f, start+pos, SEEK_SET);
772 // ------------------------------------------------------------------------------------
775 unsigned int bitval = 0;
776 unsigned char* bitbuf = NULL;
777 unsigned int bitmask[] = {
778 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
779 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
780 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
781 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
783 static inline void set_buf(unsigned char* buf, int bufsize, int clear)
787 bitval = (bitbuf[0] << 24) | (bitbuf[1] << 16) | (bitbuf[2] << 8) | bitbuf[3];
789 memset(bitbuf, 0, bufsize);
792 static inline int buf_size()
797 static inline void set_bits(unsigned int val, int bits)
799 val &= bitmask[bits];
803 int bitsleft = (8 - (bitpos & 7));
804 if (bits >= bitsleft)
806 bitbuf[bitpos >> 3] |= val >> (bits - bitsleft);
809 val &= bitmask[bits];
813 bitbuf[bitpos >> 3] |= val << (bitsleft - bits);
820 static inline unsigned int get_bits(int bits)
823 int left = 32 - (bitpos & 31);
827 val = (bitval >> (left - bits)) & bitmask[bits];
832 val = (bitval & bitmask[left]) << (bits - left);
836 int pos = bitpos >> 3;
837 bitval = (bitbuf[pos] << 24) | (bitbuf[pos + 1] << 16) | (bitbuf[pos + 2] << 8) | bitbuf[pos + 3];
841 val |= (bitval >> (32 - bits)) & bitmask[bits];
849 // ------------------------------------------------------------------------------------
851 int decode_program_map(unsigned char *buf, hb_stream_t *stream)
853 unsigned char tablebuf[1024];
854 unsigned int tablepos = 0;
859 // Get adaption header info
861 int adaption = (buf[3] & 0x30) >> 4;
864 else if (adaption == 0x2)
866 else if (adaption == 0x3)
867 adapt_len = buf[4] + 1;
871 // Get pointer length
872 int pointer_len = buf[4 + adapt_len] + 1;
874 // Get payload start indicator
876 start = (buf[1] & 0x40) != 0;
881 // Add the payload for this packet to the current buffer
882 if (reading && (184 - adapt_len) > 0)
884 if (tablepos + 184 - adapt_len - pointer_len > 1024)
886 hb_log("decode_program_map - Bad program section length (> 1024)");
889 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
890 tablepos += 184 - adapt_len - pointer_len;
893 if (start && reading)
895 int done_reading_stream_types = 0;
897 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
899 unsigned int pos = 0;
900 set_buf(tablebuf + pos, tablepos - pos, 0);
902 unsigned char section_id = get_bits(8);
904 unsigned int section_length = get_bits(12);
905 unsigned int program_number = get_bits(16);
907 unsigned char version_number = get_bits(5);
909 unsigned char section_number = get_bits(8);
910 unsigned char last_section_number = get_bits(8);
912 unsigned int PCR_PID = get_bits(13);
914 unsigned int program_info_length = get_bits(12);
916 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
917 for (i = 0; i < program_info_length; i++)
919 descriptor_buf[i] = get_bits(8);
922 int cur_pos = 9 /* data so far */ + program_info_length;
923 done_reading_stream_types = 0;
924 while (!done_reading_stream_types)
926 unsigned char stream_type = get_bits(8);
928 unsigned int elementary_PID = get_bits(13);
930 unsigned int ES_info_length = get_bits(12);
933 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
934 for (i=0; i < ES_info_length; i++)
936 ES_info_buf[i] = get_bits(8);
939 if (stream_type == 0x02)
941 if (stream->ts_number_video_pids <= kMaxNumberVideoPIDS)
942 stream->ts_number_video_pids++;
943 stream->ts_video_pids[stream->ts_number_video_pids-1] = elementary_PID;
945 if ((stream_type == 0x04) || (stream_type == 0x81) || (stream_type == 0x03) || (stream_type == 0x06)) // ATSC Defines stream type 0x81 for AC-3/A52 audio, there's also some evidence of streams using type 6 for AC-3 audio too
947 if (stream->ts_number_audio_pids <= kMaxNumberAudioPIDS)
948 stream->ts_number_audio_pids++;
949 stream->ts_audio_pids[stream->ts_number_audio_pids-1] = elementary_PID;
951 stream->a52_info[stream->ts_number_audio_pids-1].lang_code = 'e' << 8 | 'n';
952 stream->ts_audio_stream_type[stream->ts_number_audio_pids-1] = stream_type;
954 if (ES_info_length > 0)
956 hb_log("decode_program_map - Elementary Stream Info Present, decode language codes ?");
961 cur_pos += 5 /* stream header */ + ES_info_length;
965 if (cur_pos >= section_length - 4 /* stop before the CRC */)
966 done_reading_stream_types = 1;
969 free(descriptor_buf);
975 int decode_PAT(unsigned char *buf, unsigned int *program_num, unsigned int *network_PID, unsigned int *program_map_PID)
977 // int maxchannels = 8;
978 // static ATSC_CHANNEL_INFO* channels;
980 // if (channels == NULL)
981 // channels = (ATSC_CHANNEL_INFO*) malloc(maxchannels * sizeof(ATSC_CHANNEL_INFO));
985 unsigned char tablebuf[1024];
986 unsigned int tablepos = 0;
991 // Get adaption header info
993 int adaption = (buf[3] & 0x30) >> 4;
996 else if (adaption == 0x2)
998 else if (adaption == 0x3)
999 adapt_len = buf[4] + 1;
1000 if (adapt_len > 184)
1003 // Get pointer length
1004 int pointer_len = buf[4 + adapt_len] + 1;
1006 // Get payload start indicator
1008 start = (buf[1] & 0x40) != 0;
1013 // Add the payload for this packet to the current buffer
1014 if (reading && (184 - adapt_len) > 0)
1016 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1018 hb_log("decode_PAT - Bad program section length (> 1024)");
1021 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1022 tablepos += 184 - adapt_len - pointer_len;
1025 if (start && reading)
1027 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1029 unsigned int pos = 0;
1030 //while (pos < tablepos)
1032 set_buf(tablebuf + pos, tablepos - pos, 0);
1034 unsigned char section_id = get_bits(8);
1036 unsigned int section_len = get_bits(12);
1037 unsigned int transport_id = get_bits(16);
1039 unsigned int version_num = get_bits(5);
1040 unsigned int current_next = get_bits(1);
1041 unsigned int section_num = get_bits(8);
1042 unsigned int last_section = get_bits(8);
1043 // unsigned int protocol_ver = get_bits(8);
1049 // Program Association Section
1050 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1051 section_len -= 4; // Ignore the CRC
1053 while (curr_pos < section_len)
1055 unsigned int pkt_program_num = get_bits(16);
1057 *program_num = pkt_program_num;
1059 get_bits(3); // Reserved
1060 if (pkt_program_num == 0)
1062 unsigned int pkt_network_PID = get_bits(13);
1063 // printf("PAT - Transport ID = 0x%x (%d) program_num 0x%x (%d) network_PID = 0x%x (%d)\n", transport_id, transport_id, pkt_program_num, pkt_program_num, pkt_network_PID, pkt_network_PID);
1065 *network_PID = pkt_network_PID;
1070 unsigned int pkt_program_map_PID = get_bits(13);
1071 // printf("PAT - Transport ID = 0x%x (%d) program_num 0x%x (%d) program_map_PID = 0x%x (%d)\n", transport_id, transport_id, pkt_program_num, pkt_program_num, pkt_program_map_PID, pkt_program_map_PID);
1072 if (program_map_PID)
1073 *program_map_PID = pkt_program_map_PID;
1089 pos += 3 + section_len;
1097 static int flushbuf(hb_stream_t *stream)
1099 int old_write_index = stream->ps_current_write_buffer_index;
1101 if (stream->debug_output)
1103 fwrite(stream->ps_decode_buffer[stream->ps_current_write_buffer_index].data, stream->ps_decode_buffer[stream->ps_current_write_buffer_index].len, 1, stream->debug_output);
1106 // Flip the buffers and start moving on to the next
1107 stream->ps_current_write_buffer_index++;
1108 if (stream->ps_current_write_buffer_index > kNumDecodeBuffers-1)
1109 stream->ps_current_write_buffer_index = 0;
1111 if ( (stream->ps_decode_buffer[stream->ps_current_write_buffer_index].len != 0) || (stream->ps_decode_buffer[stream->ps_current_write_buffer_index].write_pos != 0) )
1113 hb_log("flushbuf - new buffer (index %d) has non zero length and write position !", stream->ps_current_write_buffer_index);
1117 stream->ps_current_read_buffer_index = old_write_index;
1118 stream->ps_decode_buffer[stream->ps_current_read_buffer_index].read_pos = 0;
1123 static int fwrite64(void* buf, int elsize, int elnum, hb_stream_t* stream)
1130 int current_write_index = stream->ps_current_write_buffer_index;
1132 if (size <= stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos)
1134 memcpy(stream->ps_decode_buffer[current_write_index].data + stream->ps_decode_buffer[current_write_index].write_pos, buf, size);
1135 stream->ps_decode_buffer[current_write_index].write_pos += size;
1136 stream->ps_decode_buffer[current_write_index].len = stream->ps_decode_buffer[current_write_index].write_pos;
1141 memcpy(stream->ps_decode_buffer[current_write_index].data + stream->ps_decode_buffer[current_write_index].write_pos, buf, stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos);
1142 written += stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos;
1143 stream->ps_decode_buffer[current_write_index].write_pos += stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos;
1144 stream->ps_decode_buffer[current_write_index].len = stream->ps_decode_buffer[current_write_index].write_pos;
1146 if (flushbuf(stream))
1148 // FLushing the buffer will have change the current write buffer
1149 current_write_index = stream->ps_current_write_buffer_index;
1151 memcpy(stream->ps_decode_buffer[current_write_index].data, (unsigned char*)buf + written, size - written);
1152 stream->ps_decode_buffer[current_write_index].write_pos += size - written;
1153 stream->ps_decode_buffer[current_write_index].len = stream->ps_decode_buffer[current_write_index].write_pos;
1154 written += size - written;
1159 if (elnum == 1 && written == size)
1162 return written / elsize;
1165 static int write_pack(hb_stream_t* stream, int64_t time)
1167 unsigned char buf[64];
1168 set_buf(buf, 64, 1); // clear buffer
1170 int64_t ext_time = time % 300;
1173 set_bits(0x000001ba, 32); // pack id 32
1174 set_bits(1, 2); // 0x01 2
1175 set_bits((unsigned int)(time >> 30), 3); // system_clock_reference_base 3
1176 set_bits(1, 1); // marker_bit 1
1177 set_bits((unsigned int)(time >> 15), 15); // system_clock_reference_base 15
1178 set_bits(1, 1); // marker_bit 1
1179 set_bits((unsigned int)time, 15); // system_clock_reference_base1 15
1180 set_bits(1, 1); // marker_bit 1
1181 set_bits((unsigned int)ext_time, 9); // system_clock_reference_extension 9
1182 set_bits(1, 1); // marker_bit 1
1183 set_bits(DEMUX, 22); // program_mux_rate 22
1184 set_bits(1, 1); // marker_bit 1
1185 set_bits(1, 1); // marker_bit 1
1186 set_bits(31, 5); // reserved 5
1187 set_bits(0, 3); // pack_stuffing_length 3
1189 return fwrite64(buf, buf_size(), 1, stream) == 1;
1192 static int pad_buffer(hb_stream_t *stream, int pad)
1197 buf[0] = '\x0'; buf[1] = '\x0'; buf[2] = '\x1'; buf[3] = '\xbe';
1198 buf[4] = pad >> 8; buf[5] = pad & 0xff;
1200 if (fwrite64(buf, 6, 1, stream) != 1)
1203 unsigned char padbyte = 0xff;
1205 for (i = 0; i < pad; i++)
1207 if (fwrite64(&padbyte, 1, 1, stream) != 1)
1214 int make_pes_header(unsigned char* buf, int streamid, int len, int64_t PTS, int64_t DTS)
1217 int PTS_DTS_flags = 0;
1232 set_buf(buf, 9 + hdrlen, 1); // clear the buffer
1234 set_bits(0x000001, 24); // packet_start_code_prefix 24
1235 set_bits((unsigned int)streamid, 8); // directory_stream_id 8
1236 set_bits(len, 16); // PES_packet_length 16
1237 set_bits(0x2, 2); // '10' 2
1238 set_bits(0, 2); // PES_scrambling_control 2
1239 set_bits(1, 1); // PES_priority 1
1240 set_bits(0, 1); // data_alignment_indicator 1
1241 set_bits(0, 1); // copyright 1
1242 set_bits(0, 1); // original_or_copy 1
1243 set_bits(PTS_DTS_flags, 2); // PTS_DTS_flags 2
1244 set_bits(0, 1); // ESCR_flag 1
1245 set_bits(0, 1); // ES_rate_flag 1
1246 set_bits(0, 1); // DSM_trick_mode_flag 1
1247 set_bits(0, 1); // additional_copy_info_flag 1
1248 set_bits(0, 1); // PES_CRC_flag 1
1249 set_bits(0, 1); // PES_extension_flag 1
1250 set_bits(hdrlen, 8); // PES_header_data_length 8
1252 if (PTS_DTS_flags == 2)
1254 set_bits(2, 4); // '0010' 4
1255 set_bits((unsigned int)(PTS >> 30), 3); // PTS [32..30] 3
1256 set_bits(1, 1); // marker bit 1
1257 set_bits((unsigned int)(PTS >> 15), 15); // PTS [29..15] 15
1258 set_bits(1, 1); // marker bit 1
1259 set_bits((unsigned int)PTS, 15); // PTS [14..0] 15
1260 set_bits(1, 1); // marker bit 1
1262 else if (PTS_DTS_flags == 3)
1264 set_bits(3, 4); // '0011' 4
1265 set_bits((unsigned int)(PTS >> 30), 3); // PTS [32..30] 3
1266 set_bits(1, 1); // marker bit 1
1267 set_bits((unsigned int)(PTS >> 15), 15); // PTS [29..15] 15
1268 set_bits(1, 1); // marker bit 1
1269 set_bits((unsigned int)PTS, 15); // PTS [14..0] 15
1270 set_bits(1, 1); // marker bit 1
1271 set_bits(1, 4); // '0001' 4
1272 set_bits((unsigned int)(DTS >> 30), 3); // DTS [32..30] 3
1273 set_bits(1, 1); // marker bit 1
1274 set_bits((unsigned int)(DTS >> 15), 15); // DTS [29..15] 15
1275 set_bits(1, 1); // marker bit 1
1276 set_bits((unsigned int)DTS, 15); // DTS [14..0] 15
1277 set_bits(1, 1); // marker bit 1
1283 int generate_output_data(hb_stream_t *stream, int write_ac3, int curstream, int pid)
1285 unsigned char ac3_substream_id[4];
1290 // Make a four byte ac3 streamid
1291 ac3_substream_id[0] = 0x80; // Four byte AC3 CODE??
1292 ac3_substream_id[1] = 0x01;
1293 ac3_substream_id[2] = 0x00; // WHY??? OH WHY??
1294 ac3_substream_id[3] = 0x02;
1298 int written = 0; // Bytes we've written to output file
1299 int pos = 0; // Position in PES packet buffer
1303 // int64_t fpos = ftell64(fout);
1304 if ((stream->ps_decode_buffer[stream->ps_current_write_buffer_index].len % HB_DVD_READ_BUFFER_SIZE) != 0)
1306 hb_log("write_output_stream - Packet's not falling on read buffer size boundries!");
1310 // Get total length of this pack
1311 int len = min(14 + ac3len + stream->ts_packetpos[curstream] - pos, HB_DVD_READ_BUFFER_SIZE);
1313 // Figure out stuffing (if we have less than 16 bytes left)
1315 if (len < HB_DVD_READ_BUFFER_SIZE && HB_DVD_READ_BUFFER_SIZE - len < 16)
1317 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1321 // Write out pack header
1322 off_t file_offset = ftello(stream->file_handle);
1323 int64_t packet_time = (file_offset * CLOCKRATE / STREAMRATE) + 0 /*file_time*/;
1324 if (!write_pack(stream, packet_time))
1326 hb_log("write_output_stream - Couldn't write pack header!");
1330 // if (pid == stream->ts_audio_pids[0])
1331 // stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[kAudioStream];
1333 // stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[kVideoStream];
1334 int index_of_selected_pid = -1;
1335 if ((index_of_selected_pid = index_of_video_pid(pid,stream)) < 0)
1337 if ((index_of_selected_pid = index_of_audio_pid(pid,stream)) < 0)
1339 hb_log("generate_output_data - cannot find pid 0x%x (%d) in selected audio or video pids", pid, pid);
1344 stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[stream->ts_number_video_pids + index_of_selected_pid];
1348 stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[index_of_selected_pid];
1351 // Subtract pack size (14) and pes id and len (6) from lenth
1352 stream->ts_packetbuf[curstream][pos + 4] = (len - 6 - 14) >> 8; stream->ts_packetbuf[curstream][pos + 5] = (len - 6 - 14) & 0xFF;
1354 // Add any stuffing bytes to header extra len
1355 int hdrsize = 9 + stream->ts_packetbuf[curstream][pos + 8];
1356 stream->ts_packetbuf[curstream][pos + 8] += stuffing; // Add stuffing to header bytes
1358 // Write out id, streamid, len
1359 if (fwrite64(stream->ts_packetbuf[curstream] + pos, hdrsize, 1, stream) != 1) // Write pes id, streamid, and len
1361 hb_log("write_output_stream - Failed to write output file!");
1367 for (i = 0; i < stuffing; i++) // Write any stuffing bytes
1369 unsigned char stuff = 0xff;
1370 if (fwrite64(&stuff, 1, 1, stream) != 1)
1372 hb_log("write_output_stream - Failed to write output file!");
1377 // Write ac3 streamid
1380 if (fwrite64(ac3_substream_id, ac3len, 1, stream) != 1)
1382 hb_log("write_output_stream - Failed to write output file!");
1387 // Write rest of data len minus headersize (9) stuffing, and pack size (14)
1388 if (fwrite64(stream->ts_packetbuf[curstream] + pos + hdrsize, len - hdrsize - 14 - stuffing - ac3len, 1, stream) != 1) // Write data bytes
1390 hb_log("write_output_stream - Failed to write output file!");
1395 // Add len minus stuff we added like the pack (14) and the stuffing.
1396 pos += len - 14 - stuffing - ac3len;
1397 if (pos == stream->ts_packetpos[curstream])
1400 // Add pes header for next packet
1402 // make_pes_header(stream->ts_packetbuf[curstream] + pos, (pid == stream->ts_video_pids[0] ? stream->ts_streamid[kVideoStream] : stream->ts_streamid[kAudioStream]), 0, -1, -1);
1403 make_pes_header(stream->ts_packetbuf[curstream] + pos, stream->ts_streamid[curstream], 0, -1, -1);
1407 if ((written % HB_DVD_READ_BUFFER_SIZE) != 0)
1409 int left = HB_DVD_READ_BUFFER_SIZE - (written % HB_DVD_READ_BUFFER_SIZE);
1411 // Pad out to HB_DVD_READ_BUFFER_SIZE bytes
1412 if (!pad_buffer(stream, left))
1414 hb_log("write_output_stream - Couldn't write pad buffer!");
1419 stream->ts_packetpos[curstream] = 0;
1420 stream->ts_streamcont[curstream] = -1;
1425 static void hb_ts_handle_mpeg_audio(hb_stream_t *stream, int curstream, unsigned char* buf, int adapt_len )
1427 // Although we don't have AC3/A52 audio here we can still use the same structure to record this useful information.
1429 stream->a52_info[curstream - stream->ts_number_video_pids].flags = A52_STEREO;
1430 stream->a52_info[curstream - stream->ts_number_video_pids].rate = 48000 /*Hz*/;
1431 stream->a52_info[curstream - stream->ts_number_video_pids].bitrate = 384000 /*Bps*/;
1434 static int hb_ts_handle_ac3_audio(hb_stream_t *stream, int curstream, unsigned char* buf, int adapt_len )
1438 // Make sure we start with 0x0b77
1439 if (stream->ts_packetbuf[curstream][9 + stream->ts_packetbuf[curstream][8]] != 0x0b || stream->ts_packetbuf[curstream][9 + stream->ts_packetbuf[curstream][8] + 1] != 0x77)
1441 spos = 9 + stream->ts_packetbuf[curstream][8];
1442 dpos = 9 + stream->ts_packetbuf[curstream][8];
1443 while (spos <= stream->ts_packetpos[curstream] - 2 && !(stream->ts_packetbuf[curstream][spos] == 0x0b && stream->ts_packetbuf[curstream][spos + 1] == 0x77))
1446 if (!(stream->ts_packetbuf[curstream][spos] == 0x0b && stream->ts_packetbuf[curstream][spos + 1] == 0x77))
1448 hb_log("hb_ts_stream_decode - Couldn't sync AC3 packet!");
1449 stream->ts_skipbad[curstream] = 1;
1453 while (spos < stream->ts_packetpos[curstream])
1455 stream->ts_packetbuf[curstream][dpos] = stream->ts_packetbuf[curstream][spos];
1459 stream->ts_packetpos[curstream] = dpos;
1462 // Check the next packet to make sure IT starts with a 0x0b77
1464 // if (buf[4 + adapt_len] == 0 && buf[4 + adapt_len + 1] == 0 && // Starting with an mpeg header?
1465 // buf[4 + adapt_len + 2] == 1 && buf[4 + adapt_len + 3] == 0xBD)
1466 plen = 9 + buf[4 + adapt_len + 8];
1467 int pstart = 4 + adapt_len + plen;
1468 if (buf[pstart] != 0x0b || buf[pstart + 1] != 0x77)
1471 while (spos < 188 - 2 && !(buf[spos] == 0x0b && buf[spos + 1] == 0x77))
1473 stream->ts_packetbuf[curstream][stream->ts_packetpos[curstream]] = buf[spos];
1474 stream->ts_packetpos[curstream]++;
1478 if (!(buf[spos] == 0x0b && buf[spos + 1] == 0x77))
1480 hb_log("hb_ts_stream_decode - Couldn't sync AC3 packet!");
1481 stream->ts_skipbad[curstream] = 1;
1485 adapt_len = spos - 4 - plen;
1489 while (spos >= pstart - plen)
1491 buf[dpos] = buf[spos];
1497 int flags, rate, bitrate;
1498 if( a52_syncinfo( &buf[pstart], &flags, &rate, &bitrate ) )
1500 stream->a52_info[curstream - stream->ts_number_video_pids].flags = flags;
1501 stream->a52_info[curstream - stream->ts_number_video_pids].rate = rate;
1502 stream->a52_info[curstream - stream->ts_number_video_pids].bitrate = bitrate;
1507 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1509 unsigned char buf[188];
1513 unsigned int program_num = 0;
1514 unsigned int network_PID = 0;
1515 unsigned int program_map_PID = 0;
1517 // align to first packet
1518 align_to_next_packet(stream->file_handle);
1520 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1521 // to find the program map PID and then decode that to get the list of audio and video PIDs
1523 int bytesReadInPacket = 0;
1526 // Try to read packet..
1528 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1532 bytesReadInPacket += bytesRead;
1534 hb_log("hb_ts_stream_find_pids - end of file");
1539 // curfilepos += bytesRead;
1540 bytesReadInPacket = 0;
1544 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1546 // __int64 pos = ftell64(fin);
1547 hb_log("hb_ts_stream_find_pids - Bad transport packet (no sync byte 0x47)!");
1549 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1550 stream->ts_skipbad[i] = 1;
1551 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1556 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1558 if ((pid == 0x0000) && (program_num == 0))
1560 decode_PAT(buf, &program_num, &network_PID, &program_map_PID);
1566 printf("Need to decode PSIP data !\n");
1570 if ((network_PID > 0) && (pid == network_PID))
1572 printf("Need to Decode network PID section !\n");
1576 if ((program_map_PID > 0) && (pid == program_map_PID))
1578 decode_program_map(buf, stream);
1582 // Skip until we have a complete set of PIDs
1583 if ((stream->ts_number_video_pids == 0) || (stream->ts_number_audio_pids == 0))
1587 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1588 hb_log(" Video PIDS : ");
1590 for (i=0; i < stream->ts_number_video_pids; i++)
1592 hb_log(" 0x%x (%d)", stream->ts_video_pids[i], stream->ts_video_pids[i]);
1594 hb_log(" Audio PIDS : ");
1595 for (i = 0; i < stream->ts_number_audio_pids; i++)
1597 hb_log(" 0x%x (%d)", stream->ts_audio_pids[i], stream->ts_audio_pids[i]);
1601 int index_of_video_pid(int pid, hb_stream_t *stream)
1603 int found_pid = -1, i = 0;
1605 for (i = 0; (i < stream->ts_number_video_pids) && (found_pid < 0); i++)
1607 if (pid == stream->ts_video_pids[i])
1613 int index_of_audio_pid(int pid, hb_stream_t *stream)
1615 int i = 0, found_pid = -1;
1617 // If a selected audio pid index has been set it indicates
1618 // which of the potential pids we need to output so only return
1619 // that index for the appropriate pid. Other pids should just
1621 if (stream->ts_selected_audio_pid_index >= 0)
1623 if (pid == stream->ts_audio_pids[stream->ts_selected_audio_pid_index])
1624 return stream->ts_selected_audio_pid_index;
1629 // If no specific pid index is set then we're probably just gathering
1630 // pid and/or stream information (during DecodePreviews for example)
1631 // so return the appropriate index
1632 for (i = 0; (i < stream->ts_number_audio_pids) && (found_pid < 0); i++)
1634 if (pid == stream->ts_audio_pids[i])
1640 int index_of_pid(int pid, hb_stream_t *stream)
1644 if ((found_pid = index_of_video_pid(pid, stream)) >= 0)
1647 if ((found_pid = index_of_audio_pid(pid, stream)) >= 0)
1653 /***********************************************************************
1654 * hb_ts_stream_decode
1655 ***********************************************************************
1657 **********************************************************************/
1658 static void hb_ts_stream_decode(hb_stream_t *stream)
1660 unsigned char buf[188];
1665 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1667 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 0;
1668 stream->ts_skipbad[i] = 0;
1673 if ((stream->ts_number_video_pids == 0) || (stream->ts_number_audio_pids == 0))
1675 hb_log("hb_ts_stream_decode - no Video or Audio PID selected, cannot decode transport stream");
1679 int bytesReadInPacket = 0;
1680 int curr_write_buffer_index = stream->ps_current_write_buffer_index;
1682 // Write output data until a buffer switch occurs.
1683 while (curr_write_buffer_index == stream->ps_current_write_buffer_index)
1685 // Try to read packet..
1687 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1691 bytesReadInPacket += bytesRead;
1693 // Flush any outstanding output data - we're done here.
1699 // curfilepos += bytesRead;
1700 bytesReadInPacket = 0;
1704 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1706 // __int64 pos = ftell64(fin);
1707 hb_log("hb_ts_stream_decode - Bad transport packet (no sync byte 0x47)!");
1708 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1710 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1711 stream->ts_skipbad[i] = 1;
1717 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1720 if (index_of_pid(pid, stream) < 0)
1722 // if (pid != stream->ts_audio_pids[0] && pid != stream->ts_video_pids[0])
1725 // Get the pos and buf - we organize our streams as 'n' video streams then 'm' audio streams
1726 int index_of_selected_pid = -1;
1727 if ((index_of_selected_pid = index_of_video_pid(pid,stream)) < 0)
1729 // Not a video PID perhaps audio ?
1730 if ((index_of_selected_pid = index_of_audio_pid(pid,stream)) < 0)
1732 hb_log("hb_ts_stream_decode - Unknown pid 0x%x (%d)", pid, pid);
1737 curstream = stream->ts_number_video_pids + index_of_selected_pid;
1738 if (curstream > kMaxNumberDecodeStreams)
1740 hb_log("hb_ts_stream_decode - Too many streams %d", curstream);
1746 curstream = index_of_selected_pid;
1748 // if (pid == stream->ts_video_pids[0])
1755 start = (buf[1] & 0x40) != 0;
1757 if (!start && stream->ts_skipbad[curstream])
1761 int errorbit = (buf[1] & 0x80) != 0;
1764 hb_log("hb_ts_stream_decode - Error bit set in packet");
1765 stream->ts_skipbad[curstream] = 1;
1769 // Get adaption header info
1770 int adaption = (buf[3] & 0x30) >> 4;
1774 int continuity = (buf[3] & 0xF);
1775 if ((stream->ts_streamcont[curstream] != -1) && (adaption & 0x01 == 0x01)) // Continuity only increments for adaption values of 0x3 or 0x01
1777 if (continuity != ((stream->ts_streamcont[curstream] + 1) & 0xF))
1779 hb_log("hb_ts_stream_decode - Bad continuity code in packet");
1780 stream->ts_skipbad[curstream] = 1;
1783 stream->ts_streamcont[curstream] = continuity;
1786 // Get adaption header size
1789 hb_log("hb_ts_stream_decode - Bad adaption code (code was 0)!");
1790 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1792 stream->ts_skipbad[i] = 1;
1794 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1797 else if (adaption == 0x2)
1799 else if (adaption == 0x3)
1801 adapt_len = buf[4] + 1;
1802 if (adapt_len > 184)
1804 hb_log("hb_ts_stream_decode - Invalid adapt len (was > 183)!");
1805 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1807 stream->ts_skipbad[i] = 1;
1809 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1813 // HBO is slick, it doesn't bother to sync AC3 packets with PES elementary stream packets.. so
1814 // we have to swizzle them together! (ARGHH!)
1815 // if (pid == stream->ts_audio_pids[0] && start)
1816 if ((index_of_audio_pid(pid, stream) >= 0) && start)
1818 // Is there an AC3 packet start 0b77 code in this packet??
1820 unsigned char *p = buf + 4 + adapt_len;
1821 while (p <= buf + 186)
1823 if (p[0] == 0x0b && p[1] == 0x77)
1831 // Couldn't find an AC3 sync start in this packet.. don't make a PES packet!
1834 // int pos = ftell(fin);
1835 // error("AC3 packet sync not found in start frame");
1837 adapt_len += 9 + buf[4 + adapt_len + 8];
1843 if (start && (adaption & 0x2) && (buf[5] & 0x10))
1845 int64_t PCR_base = ((int64_t)buf[6] << 25) | ((int64_t)buf[7] << 17) |
1846 ((int64_t)buf[8] << 9) | ((int64_t)buf[9] << 1) | ((int64_t)buf[10] >> 7);
1847 int64_t PCR_ext = ((int64_t)(buf[10] & 0x1) << 8) | ((int64_t)buf[11]);
1848 int64_t PCR = PCR_base * 300 + PCR_ext;
1852 // bool random = false;
1853 // if (start && (adaption & 0x2))
1854 // random = (buf[5] & 0x40) != 0; // BUG: SOME TS STREAMS DON'T HAVE THE RANDOM BIT (ABC!! ALIAS)
1856 // Found a random access point (now we can start a frame/audio packet..)
1859 // Check to see if this is an i_frame (group of picture start)
1860 if (pid == stream->ts_video_pids[0])
1862 // printf("Found Video Start for pid 0x%x\n", pid);
1863 // Look for the Group of Pictures packet.. indicates this is an I-Frame packet..
1865 unsigned int strid = 0;
1867 for (i = 4 + adapt_len; i < 188; i++)
1869 strid = (strid << 8) | buf[i];
1870 if (strid == 0x000001B8) // group_start_code
1872 // found a Group of Pictures header, subsequent picture must be an I-frame
1875 else if (strid == 0x000001B3) // sequence_header code
1879 else if (strid == 0x00000100) // picture_start_code
1881 // picture_header, let's see if it's an I-frame
1884 // int pic_start_code = (buf[i+2] >> 3) & 0x07;
1885 // hb_log("hb_ts_stream_decode - picture_start_code header value = 0x%x (%d)", pic_start_code, pic_start_code);
1886 // check if picture_coding_type == 1
1887 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1889 // found an I-frame picture
1897 if (!stream->ts_foundfirst[curstream])
1899 stream->ts_foundfirst[curstream] = 1;
1900 // first_video_PCR = PCR;
1906 else if (index_of_audio_pid(pid, stream) >= 0)
1908 if (stream->ts_foundfirst[0]) // Set audio found first ONLY after first video frame found. There's an assumption here that stream '0' is a video stream
1910 stream->ts_foundfirst[curstream] |= 1;
1914 // If we were skipping a bad packet, start fresh on this new PES packet..
1915 if (stream->ts_skipbad[curstream] == 1)
1917 stream->ts_skipbad[curstream] = 0;
1918 stream->ts_packetpos[curstream] = 0;
1921 // Get the continuity code of this packet
1922 stream->ts_streamcont[curstream] = continuity;
1925 // Write a 2048 byte program stream packet..
1926 if (start && stream->ts_packetpos[curstream] > 0 && stream->ts_foundfirst[curstream] && !stream->ts_skipbad[curstream])
1928 // Save the substream id block so we can added it to subsequent blocks
1930 // if (pid == stream->ts_audio_pids[0] /*&& audstreamid == 0xBD*/)
1931 if (index_of_audio_pid(pid, stream) >= 0)
1933 if ((stream->ts_audio_stream_type[curstream] == 0x04) || (stream->ts_audio_stream_type[curstream] == 0x81))
1935 write_ac3 = hb_ts_handle_ac3_audio(stream, curstream, buf, adapt_len);
1937 else if (stream->ts_audio_stream_type[curstream] == 0x03)
1939 hb_ts_handle_mpeg_audio(stream, curstream, buf, adapt_len);
1943 hb_log("hb_ts_stream_decode - Unknown Audio Stream type ! 0x%x (%d)", stream->ts_audio_stream_type[curstream], stream->ts_audio_stream_type[curstream]);
1947 if (generate_output_data(stream, write_ac3, curstream, pid) != 0)
1951 // Add the payload for this packet to the current buffer
1952 if (stream->ts_foundfirst[curstream] && (184 - adapt_len) > 0)
1954 memcpy(stream->ts_packetbuf[curstream] + stream->ts_packetpos[curstream], buf + 4 + adapt_len, 184 - adapt_len);
1955 stream->ts_packetpos[curstream] += 184 - adapt_len;
1960 /***********************************************************************
1961 * hb_ts_stream_reset
1962 ***********************************************************************
1964 **********************************************************************/
1965 static void hb_ts_stream_reset(hb_stream_t *stream)
1968 for (i=0; i < kNumDecodeBuffers; i++)
1970 stream->ps_decode_buffer[i].read_pos = 0;
1971 stream->ps_decode_buffer[i].write_pos = 0;
1972 stream->ps_decode_buffer[i].len = 0;
1975 for (i=0; i < kMaxNumberDecodeStreams; i++)
1977 stream->ts_streamcont[i] = -1;
1980 stream->ps_current_write_buffer_index = 0;
1981 stream->ps_current_read_buffer_index = 1;
1983 align_to_next_packet(stream->file_handle);