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, ".VOB") != NULL) ||
87 (strstr(path, ".mpeg") != NULL) ||
88 (strstr(path,".ts") != NULL) ||
89 (strstr(path, ".m2t") != NULL) ||
90 (strstr(path, ".TS") != NULL))
98 /***********************************************************************
100 ***********************************************************************
102 **********************************************************************/
103 hb_stream_t * hb_stream_open( char * path )
107 d = calloc( sizeof( hb_stream_t ), 1 );
110 if( !( d->file_handle = fopen( path, "rb" ) ) )
112 hb_log( "hb_stream_open: fopen failed (%s)", path );
116 d->path = strdup( path );
118 if ( ( strstr(d->path,".ts") != NULL) || ( strstr(d->path,".m2t") != NULL) || ( strstr(d->path,".TS") != NULL) )
120 d->stream_type = hb_stream_type_transport;
121 hb_ts_stream_init(d);
123 else if (( strstr(d->path,".mpg") != NULL) || ( strstr(d->path,".vob") != NULL) || ( strstr(d->path,".mpeg") != NULL) || ( strstr(d->path,".VOB") != NULL))
125 d->stream_type = hb_stream_type_program;
135 /***********************************************************************
137 ***********************************************************************
138 * Closes and frees everything
139 **********************************************************************/
140 void hb_stream_close( hb_stream_t ** _d )
142 hb_stream_t * d = *_d;
146 fclose( d->file_handle );
147 d->file_handle = NULL;
152 fclose(d->debug_output);
153 d->debug_output = NULL;
157 for (i = 0; i < kNumDecodeBuffers; i++)
159 if (d->ps_decode_buffer[i].data)
161 free(d->ps_decode_buffer[i].data);
162 d->ps_decode_buffer[i].data = NULL;
166 for (i = 0; i < kMaxNumberDecodeStreams; i++)
168 if (d->ts_packetbuf[i])
170 free(d->ts_packetbuf[i]);
171 d->ts_packetbuf[i] = NULL;
179 /***********************************************************************
180 * hb_ps_stream_title_scan
181 ***********************************************************************
183 **********************************************************************/
184 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
187 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
189 // Copy part of the stream path to the title name
190 char *sep = strrchr(stream->path, '/');
192 strcpy(aTitle->name, sep+1);
193 char *dot_term = strrchr(aTitle->name, '.');
197 // Height, width, rate and aspect ratio information is filled in when the previews are built
199 hb_stream_duration(stream, aTitle);
202 hb_chapter_t * chapter;
203 chapter = calloc( sizeof( hb_chapter_t ), 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 );
211 int i=0, num_audio_tracks = 1;
213 if (stream->stream_type == hb_stream_type_transport)
215 num_audio_tracks = stream->ts_number_audio_pids;
218 for (i=0; i < num_audio_tracks ; i++)
220 // Basic AC-3 Audio track
222 audio = calloc( sizeof( hb_audio_t ), 1 );
224 audio->source_pid = stream->ts_audio_pids[i];
226 hb_stream_set_audio_id_and_codec(stream, audio);
228 hb_list_add( aTitle->list_audio, audio );
234 /***********************************************************************
236 ***********************************************************************
238 **********************************************************************/
239 void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
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)
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;
254 unsigned char *buf = (unsigned char *) malloc(4096);
257 int64_t first_pts = 0, last_pts = 0;
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
263 cur_pos = ftello(stream->file_handle);
264 if (fread(buf, 4096, 1, stream->file_handle) == 1)
267 for (i=0; (i <= 4092) && !done; i++)
269 if ((buf[i] == 0x00) && (buf[i+1] == 0x00) && (buf[i+2] == 0x01) && (buf[i+3] == 0xe0)) // Found a Video Stream
271 // Now look for a PTS field - we need to make sure we have enough space so we back up a little and read
273 fseeko(stream->file_handle, cur_pos + i, SEEK_SET);
274 if (fread(buf, 4096, 1, stream->file_handle) == 1)
276 int has_pts = ( ( buf[7] >> 6 ) & 0x2 ) ? 1 : 0;
279 first_pts = ( ( ( (uint64_t) buf[9] >> 1 ) & 0x7 ) << 30 ) +
281 ( ( buf[11] >> 1 ) << 15 ) +
288 fseeko(stream->file_handle, cur_pos, SEEK_SET);
289 fread(buf, 4096, 1, stream->file_handle);
296 done = 1; // End of data;
299 // Now work back from the end of the stream
300 fseeko(stream->file_handle,0 ,SEEK_END);
306 if (fseeko(stream->file_handle, -4096, SEEK_CUR) < 0)
312 cur_pos = ftello(stream->file_handle);
313 if (fread(buf, 4096, 1, stream->file_handle) == 1)
316 for (i=4092; (i >= 0) && !done; i--)
318 if ((buf[i] == 0x00) && (buf[i+1] == 0x00) && (buf[i+2] == 0x01) && (buf[i+3] == 0xe0)) // Found a Video Stream
320 // Now look for a PTS field - we need to make sure we have enough space so we back up a little and read
322 fseeko(stream->file_handle, cur_pos + i, SEEK_SET);
323 fread(buf, 1, 4096, stream->file_handle);
325 unsigned char pts_dts_flag = buf[7];
327 int has_pts = ( ( buf[7] >> 6 ) & 0x2 ) ? 1 : 0;
330 last_pts = ( ( ( (uint64_t) buf[9] >> 1 ) & 0x7 ) << 30 ) +
332 ( ( buf[11] >> 1 ) << 15 ) +
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);
346 fseeko(stream->file_handle, -4096, SEEK_CUR); // 'Undo' the last read
349 done = 1; // End of data;
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;
361 /***********************************************************************
363 ***********************************************************************
365 **********************************************************************/
366 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
368 if (src_stream->stream_type == hb_stream_type_program)
371 amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1, src_stream->file_handle);
377 else if (src_stream->stream_type == hb_stream_type_transport)
379 int read_buffer_index = src_stream->ps_current_read_buffer_index;
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)
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;
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;
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;
405 hb_ts_stream_decode(src_stream);
407 // Decoding will almost certainly have changed the current read buffer index
408 read_buffer_index = src_stream->ps_current_read_buffer_index;
410 if (src_stream->ps_decode_buffer[read_buffer_index].len == 0)
412 hb_log("hb_stream_read - buffer after decode has zero length data");
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;
427 /***********************************************************************
429 ***********************************************************************
431 **********************************************************************/
432 int hb_stream_seek( hb_stream_t * src_stream, float f )
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);
444 fseeko(src_stream->file_handle, cur_pos, SEEK_SET);
448 if (src_stream->stream_type == hb_stream_type_transport)
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);
455 // Now we must scan forwards for a valid start code (0x000001BA)
457 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
460 if (hb_stream_read(src_stream,buf) == 1)
463 for (i=0; (i <= HB_DVD_READ_BUFFER_SIZE-4) && (!done); i++)
465 if ((buf->data[i] == 0x00) && (buf->data[i+1] == 0x00) && (buf->data[i+2] == 0x01) && (buf->data[i+3] == 0xba))
468 // 'Put Back' the data we've just read (up to this point)
469 hb_stream_put_back(src_stream, i);
474 done = 1; // End of data;
476 hb_buffer_close(&buf);
480 /***********************************************************************
481 * hb_stream_set_audio_id_and_codec
482 ***********************************************************************
484 **********************************************************************/
485 void hb_stream_set_audio_id_and_codec(hb_stream_t *stream, hb_audio_t *audio)
488 cur_pos = ftello(stream->file_handle);
490 hb_buffer_t *buf = NULL;
492 int cur_audio_pid_index = stream->ts_selected_audio_pid_index;
494 if (stream->stream_type == hb_stream_type_transport)
497 for (i=0; i < stream->ts_number_audio_pids; i++)
499 if (stream->ts_audio_pids[i] == audio->source_pid)
501 stream->ts_selected_audio_pid_index = i;
507 //Start at the beginning of the stream
508 hb_stream_seek(stream, 0.0f);
509 // fseeko(stream->file_handle,0 ,SEEK_SET);
511 // Now we must scan forwards for a valid audio start code (0x000001xx)
512 buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
515 // if (fread(buf->data,4096,1,stream->file_handle) == 1)
516 if (hb_stream_read(stream, buf) == 1)
519 for (i=0; (i <= HB_DVD_READ_BUFFER_SIZE-4) && (!done); i++)
521 if ((buf->data[i] == 0x00) && (buf->data[i+1] == 0x00) && (buf->data[i+2] == 0x01))
523 if (buf->data[i+3] == 0xbd)
526 audio->codec = HB_ACODEC_AC3;
529 else if ((buf->data[i+3] & 0xe0) == 0xc0)
531 audio->id = buf->data[i+3];
532 audio->codec = HB_ACODEC_MPGA;
539 done = 1; // End of data;
541 hb_buffer_close(&buf);
543 fseeko(stream->file_handle, cur_pos, SEEK_SET);
545 stream->ts_selected_audio_pid_index = cur_audio_pid_index;
548 /***********************************************************************
549 * hb_stream_update_audio
550 ***********************************************************************
552 **********************************************************************/
553 void hb_stream_update_audio(hb_stream_t *stream, hb_audio_t *audio)
557 if (stream->stream_type == hb_stream_type_program)
559 lang = lang_for_code(0x0000);
561 else if (stream->stream_type == hb_stream_type_transport)
563 // Find the audio stream info for this PID
565 for (i=0; i < stream->ts_number_audio_pids; i++)
567 if (stream->ts_audio_pids[i] == audio->source_pid)
570 if (i == stream->ts_number_audio_pids)
572 hb_log("hb_stream_update_audio - cannot find PID 0x%x (%d) in ts_audio_pids list !", audio->source_pid, audio->source_pid);
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;
583 switch( audio->ac3flags & A52_CHANNEL_MASK )
589 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_MONO;
594 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
596 /* dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input */
598 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_DOLBY;
602 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F2R;
606 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F1R;
610 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F;
613 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F1R;
616 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F2R;
620 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
623 /* add in our own LFE flag if the source has LFE */
624 if (audio->ac3flags & A52_LFE)
626 audio->input_channel_layout = audio->input_channel_layout | HB_INPUT_CH_LAYOUT_HAS_LFE;
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);
634 if ( (audio->ac3flags & A52_CHANNEL_MASK) == A52_DOLBY ) {
635 sprintf( audio->lang + strlen( audio->lang ),
636 " (Dolby Surround)" );
638 sprintf( audio->lang + strlen( audio->lang ),
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));
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 );
649 void hb_stream_set_selected_audio_pid_index(hb_stream_t *stream, int i)
651 stream->ts_selected_audio_pid_index = i;
654 /***********************************************************************
656 ***********************************************************************
658 **********************************************************************/
659 static void hb_stream_put_back(hb_stream_t *stream, int i)
661 if (stream->stream_type == hb_stream_type_program)
663 // Program streams are pretty easy - we just reposition the source file
665 fseeko(stream->file_handle, -(HB_DVD_READ_BUFFER_SIZE-i), SEEK_CUR);
667 else if (stream->stream_type == hb_stream_type_transport)
669 int read_buffer_index = stream->ps_current_read_buffer_index;
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)
676 stream->ps_decode_buffer[read_buffer_index].read_pos -= i;
679 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);
684 /***********************************************************************
686 ***********************************************************************
688 **********************************************************************/
689 #define PS_DECODE_BUFFER_SIZE ( 1024 * 1024 * 4)
691 static void hb_ts_stream_init(hb_stream_t *stream)
693 // Output Program Stream
695 for (i=0; i < kNumDecodeBuffers; i++)
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;
704 for (i=0; i < kMaxNumberDecodeStreams; i++)
706 stream->ts_streamcont[i] = -1;
709 stream->ps_current_write_buffer_index = 0;
710 stream->ps_current_read_buffer_index = 1;
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;
717 stream->debug_output = fopen("/Users/awk/Desktop/hb_debug.mpg", "wb");
719 // Find the audio and video pids in the stream
720 hb_ts_stream_find_pids(stream);
722 for (i=0; i < stream->ts_number_video_pids; i++)
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
729 for (i = stream->ts_number_video_pids; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
731 stream->ts_packetbuf[i] = (unsigned char *) malloc(1024 * 1024);
732 stream->ts_streamid[i] = 0xBD; // Stream 1 is AC-3 Audio
736 // ------------------------------------------------------------------------------------
738 off_t align_to_next_packet(FILE* f)
740 unsigned char buf[188*20];
742 off_t start = ftello(f);
745 if (fread(buf, 188*20, 1, f) == 1)
748 while (!found && (pos < 188))
752 for (i = 0; i < 188*20; i += 188)
754 unsigned char c = buf[pos+i];
756 if ((c != 0x47) && (c != 0x72) && (c != 0x29))
758 // this offset failed, try next
768 pos = 0; // failed to find anything!!!!!?
770 fseek(f, start+pos, SEEK_SET);
775 // ------------------------------------------------------------------------------------
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};
786 static inline void set_buf(unsigned char* buf, int bufsize, int clear)
790 bitval = (bitbuf[0] << 24) | (bitbuf[1] << 16) | (bitbuf[2] << 8) | bitbuf[3];
792 memset(bitbuf, 0, bufsize);
795 static inline int buf_size()
800 static inline void set_bits(unsigned int val, int bits)
802 val &= bitmask[bits];
806 int bitsleft = (8 - (bitpos & 7));
807 if (bits >= bitsleft)
809 bitbuf[bitpos >> 3] |= val >> (bits - bitsleft);
812 val &= bitmask[bits];
816 bitbuf[bitpos >> 3] |= val << (bitsleft - bits);
823 static inline unsigned int get_bits(int bits)
826 int left = 32 - (bitpos & 31);
830 val = (bitval >> (left - bits)) & bitmask[bits];
835 val = (bitval & bitmask[left]) << (bits - left);
839 int pos = bitpos >> 3;
840 bitval = (bitbuf[pos] << 24) | (bitbuf[pos + 1] << 16) | (bitbuf[pos + 2] << 8) | bitbuf[pos + 3];
844 val |= (bitval >> (32 - bits)) & bitmask[bits];
852 // ------------------------------------------------------------------------------------
854 int decode_program_map(unsigned char *buf, hb_stream_t *stream)
856 unsigned char tablebuf[1024];
857 unsigned int tablepos = 0;
862 // Get adaption header info
864 int adaption = (buf[3] & 0x30) >> 4;
867 else if (adaption == 0x2)
869 else if (adaption == 0x3)
870 adapt_len = buf[4] + 1;
874 // Get pointer length
875 int pointer_len = buf[4 + adapt_len] + 1;
877 // Get payload start indicator
879 start = (buf[1] & 0x40) != 0;
884 // Add the payload for this packet to the current buffer
885 if (reading && (184 - adapt_len) > 0)
887 if (tablepos + 184 - adapt_len - pointer_len > 1024)
889 hb_log("decode_program_map - Bad program section length (> 1024)");
892 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
893 tablepos += 184 - adapt_len - pointer_len;
896 if (start && reading)
898 int done_reading_stream_types = 0;
900 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
902 unsigned int pos = 0;
903 set_buf(tablebuf + pos, tablepos - pos, 0);
905 unsigned char section_id = get_bits(8);
907 unsigned int section_length = get_bits(12);
908 unsigned int program_number = get_bits(16);
910 unsigned char version_number = get_bits(5);
912 unsigned char section_number = get_bits(8);
913 unsigned char last_section_number = get_bits(8);
915 unsigned int PCR_PID = get_bits(13);
917 unsigned int program_info_length = get_bits(12);
919 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
920 for (i = 0; i < program_info_length; i++)
922 descriptor_buf[i] = get_bits(8);
925 int cur_pos = 9 /* data so far */ + program_info_length;
926 done_reading_stream_types = 0;
927 while (!done_reading_stream_types)
929 unsigned char stream_type = get_bits(8);
931 unsigned int elementary_PID = get_bits(13);
933 unsigned int ES_info_length = get_bits(12);
936 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
937 for (i=0; i < ES_info_length; i++)
939 ES_info_buf[i] = get_bits(8);
942 if (stream_type == 0x02)
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;
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
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;
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;
957 if (ES_info_length > 0)
959 hb_log("decode_program_map - Elementary Stream Info Present, decode language codes ?");
964 cur_pos += 5 /* stream header */ + ES_info_length;
968 if (cur_pos >= section_length - 4 /* stop before the CRC */)
969 done_reading_stream_types = 1;
972 free(descriptor_buf);
978 int decode_PAT(unsigned char *buf, unsigned int *program_num, unsigned int *network_PID, unsigned int *program_map_PID)
980 // int maxchannels = 8;
981 // static ATSC_CHANNEL_INFO* channels;
983 // if (channels == NULL)
984 // channels = (ATSC_CHANNEL_INFO*) malloc(maxchannels * sizeof(ATSC_CHANNEL_INFO));
988 unsigned char tablebuf[1024];
989 unsigned int tablepos = 0;
994 // Get adaption header info
996 int adaption = (buf[3] & 0x30) >> 4;
999 else if (adaption == 0x2)
1001 else if (adaption == 0x3)
1002 adapt_len = buf[4] + 1;
1003 if (adapt_len > 184)
1006 // Get pointer length
1007 int pointer_len = buf[4 + adapt_len] + 1;
1009 // Get payload start indicator
1011 start = (buf[1] & 0x40) != 0;
1016 // Add the payload for this packet to the current buffer
1017 if (reading && (184 - adapt_len) > 0)
1019 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1021 hb_log("decode_PAT - Bad program section length (> 1024)");
1024 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1025 tablepos += 184 - adapt_len - pointer_len;
1028 if (start && reading)
1030 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1032 unsigned int pos = 0;
1033 //while (pos < tablepos)
1035 set_buf(tablebuf + pos, tablepos - pos, 0);
1037 unsigned char section_id = get_bits(8);
1039 unsigned int section_len = get_bits(12);
1040 unsigned int transport_id = get_bits(16);
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);
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
1056 while (curr_pos < section_len)
1058 unsigned int pkt_program_num = get_bits(16);
1060 *program_num = pkt_program_num;
1062 get_bits(3); // Reserved
1063 if (pkt_program_num == 0)
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);
1068 *network_PID = pkt_network_PID;
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;
1092 pos += 3 + section_len;
1100 static int flushbuf(hb_stream_t *stream)
1102 int old_write_index = stream->ps_current_write_buffer_index;
1104 if (stream->debug_output)
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);
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;
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) )
1116 hb_log("flushbuf - new buffer (index %d) has non zero length and write position !", stream->ps_current_write_buffer_index);
1120 stream->ps_current_read_buffer_index = old_write_index;
1121 stream->ps_decode_buffer[stream->ps_current_read_buffer_index].read_pos = 0;
1126 static int fwrite64(void* buf, int elsize, int elnum, hb_stream_t* stream)
1133 int current_write_index = stream->ps_current_write_buffer_index;
1135 if (size <= stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos)
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;
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;
1149 if (flushbuf(stream))
1151 // FLushing the buffer will have change the current write buffer
1152 current_write_index = stream->ps_current_write_buffer_index;
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;
1162 if (elnum == 1 && written == size)
1165 return written / elsize;
1168 static int write_pack(hb_stream_t* stream, int64_t time)
1170 unsigned char buf[64];
1171 set_buf(buf, 64, 1); // clear buffer
1173 int64_t ext_time = time % 300;
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
1192 return fwrite64(buf, buf_size(), 1, stream) == 1;
1195 static int pad_buffer(hb_stream_t *stream, int pad)
1200 buf[0] = '\x0'; buf[1] = '\x0'; buf[2] = '\x1'; buf[3] = '\xbe';
1201 buf[4] = pad >> 8; buf[5] = pad & 0xff;
1203 if (fwrite64(buf, 6, 1, stream) != 1)
1206 unsigned char padbyte = 0xff;
1208 for (i = 0; i < pad; i++)
1210 if (fwrite64(&padbyte, 1, 1, stream) != 1)
1217 int make_pes_header(unsigned char* buf, int streamid, int len, int64_t PTS, int64_t DTS)
1220 int PTS_DTS_flags = 0;
1235 set_buf(buf, 9 + hdrlen, 1); // clear the buffer
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
1255 if (PTS_DTS_flags == 2)
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
1265 else if (PTS_DTS_flags == 3)
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
1286 int generate_output_data(hb_stream_t *stream, int write_ac3, int curstream, int pid)
1288 unsigned char ac3_substream_id[4];
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;
1301 int written = 0; // Bytes we've written to output file
1302 int pos = 0; // Position in PES packet buffer
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)
1309 hb_log("write_output_stream - Packet's not falling on read buffer size boundries!");
1313 // Get total length of this pack
1314 int len = min(14 + ac3len + stream->ts_packetpos[curstream] - pos, HB_DVD_READ_BUFFER_SIZE);
1316 // Figure out stuffing (if we have less than 16 bytes left)
1318 if (len < HB_DVD_READ_BUFFER_SIZE && HB_DVD_READ_BUFFER_SIZE - len < 16)
1320 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
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))
1329 hb_log("write_output_stream - Couldn't write pack header!");
1333 // if (pid == stream->ts_audio_pids[0])
1334 // stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[kAudioStream];
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)
1340 if ((index_of_selected_pid = index_of_audio_pid(pid,stream)) < 0)
1342 hb_log("generate_output_data - cannot find pid 0x%x (%d) in selected audio or video pids", pid, pid);
1347 stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[stream->ts_number_video_pids + index_of_selected_pid];
1351 stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[index_of_selected_pid];
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;
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
1361 // Write out id, streamid, len
1362 if (fwrite64(stream->ts_packetbuf[curstream] + pos, hdrsize, 1, stream) != 1) // Write pes id, streamid, and len
1364 hb_log("write_output_stream - Failed to write output file!");
1370 for (i = 0; i < stuffing; i++) // Write any stuffing bytes
1372 unsigned char stuff = 0xff;
1373 if (fwrite64(&stuff, 1, 1, stream) != 1)
1375 hb_log("write_output_stream - Failed to write output file!");
1380 // Write ac3 streamid
1383 if (fwrite64(ac3_substream_id, ac3len, 1, stream) != 1)
1385 hb_log("write_output_stream - Failed to write output file!");
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
1393 hb_log("write_output_stream - Failed to write output file!");
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])
1403 // Add pes header for next packet
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);
1410 if ((written % HB_DVD_READ_BUFFER_SIZE) != 0)
1412 int left = HB_DVD_READ_BUFFER_SIZE - (written % HB_DVD_READ_BUFFER_SIZE);
1414 // Pad out to HB_DVD_READ_BUFFER_SIZE bytes
1415 if (!pad_buffer(stream, left))
1417 hb_log("write_output_stream - Couldn't write pad buffer!");
1422 stream->ts_packetpos[curstream] = 0;
1423 stream->ts_streamcont[curstream] = -1;
1428 static void hb_ts_handle_mpeg_audio(hb_stream_t *stream, int curstream, unsigned char* buf, int adapt_len )
1430 // Although we don't have AC3/A52 audio here we can still use the same structure to record this useful information.
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*/;
1437 static int hb_ts_handle_ac3_audio(hb_stream_t *stream, int curstream, unsigned char* buf, int adapt_len )
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)
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))
1449 if (!(stream->ts_packetbuf[curstream][spos] == 0x0b && stream->ts_packetbuf[curstream][spos + 1] == 0x77))
1451 hb_log("hb_ts_stream_decode - Couldn't sync AC3 packet!");
1452 stream->ts_skipbad[curstream] = 1;
1456 while (spos < stream->ts_packetpos[curstream])
1458 stream->ts_packetbuf[curstream][dpos] = stream->ts_packetbuf[curstream][spos];
1462 stream->ts_packetpos[curstream] = dpos;
1465 // Check the next packet to make sure IT starts with a 0x0b77
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)
1474 while (spos < 188 - 2 && !(buf[spos] == 0x0b && buf[spos + 1] == 0x77))
1476 stream->ts_packetbuf[curstream][stream->ts_packetpos[curstream]] = buf[spos];
1477 stream->ts_packetpos[curstream]++;
1481 if (!(buf[spos] == 0x0b && buf[spos + 1] == 0x77))
1483 hb_log("hb_ts_stream_decode - Couldn't sync AC3 packet!");
1484 stream->ts_skipbad[curstream] = 1;
1488 adapt_len = spos - 4 - plen;
1492 while (spos >= pstart - plen)
1494 buf[dpos] = buf[spos];
1500 int flags, rate, bitrate;
1501 if( a52_syncinfo( &buf[pstart], &flags, &rate, &bitrate ) )
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;
1510 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1512 unsigned char buf[188];
1516 unsigned int program_num = 0;
1517 unsigned int network_PID = 0;
1518 unsigned int program_map_PID = 0;
1520 // align to first packet
1521 align_to_next_packet(stream->file_handle);
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
1526 int bytesReadInPacket = 0;
1529 // Try to read packet..
1531 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1535 bytesReadInPacket += bytesRead;
1537 hb_log("hb_ts_stream_find_pids - end of file");
1542 // curfilepos += bytesRead;
1543 bytesReadInPacket = 0;
1547 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1549 // __int64 pos = ftell64(fin);
1550 hb_log("hb_ts_stream_find_pids - Bad transport packet (no sync byte 0x47)!");
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;
1559 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1561 if ((pid == 0x0000) && (program_num == 0))
1563 decode_PAT(buf, &program_num, &network_PID, &program_map_PID);
1569 printf("Need to decode PSIP data !\n");
1573 if ((network_PID > 0) && (pid == network_PID))
1575 printf("Need to Decode network PID section !\n");
1579 if ((program_map_PID > 0) && (pid == program_map_PID))
1581 decode_program_map(buf, stream);
1585 // Skip until we have a complete set of PIDs
1586 if ((stream->ts_number_video_pids == 0) || (stream->ts_number_audio_pids == 0))
1590 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1591 hb_log(" Video PIDS : ");
1593 for (i=0; i < stream->ts_number_video_pids; i++)
1595 hb_log(" 0x%x (%d)", stream->ts_video_pids[i], stream->ts_video_pids[i]);
1597 hb_log(" Audio PIDS : ");
1598 for (i = 0; i < stream->ts_number_audio_pids; i++)
1600 hb_log(" 0x%x (%d)", stream->ts_audio_pids[i], stream->ts_audio_pids[i]);
1604 int index_of_video_pid(int pid, hb_stream_t *stream)
1606 int found_pid = -1, i = 0;
1608 for (i = 0; (i < stream->ts_number_video_pids) && (found_pid < 0); i++)
1610 if (pid == stream->ts_video_pids[i])
1616 int index_of_audio_pid(int pid, hb_stream_t *stream)
1618 int i = 0, found_pid = -1;
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
1624 if (stream->ts_selected_audio_pid_index >= 0)
1626 if (pid == stream->ts_audio_pids[stream->ts_selected_audio_pid_index])
1627 return stream->ts_selected_audio_pid_index;
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++)
1637 if (pid == stream->ts_audio_pids[i])
1643 int index_of_pid(int pid, hb_stream_t *stream)
1647 if ((found_pid = index_of_video_pid(pid, stream)) >= 0)
1650 if ((found_pid = index_of_audio_pid(pid, stream)) >= 0)
1656 /***********************************************************************
1657 * hb_ts_stream_decode
1658 ***********************************************************************
1660 **********************************************************************/
1661 static void hb_ts_stream_decode(hb_stream_t *stream)
1663 unsigned char buf[188];
1668 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1670 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 0;
1671 stream->ts_skipbad[i] = 0;
1676 if ((stream->ts_number_video_pids == 0) || (stream->ts_number_audio_pids == 0))
1678 hb_log("hb_ts_stream_decode - no Video or Audio PID selected, cannot decode transport stream");
1682 int bytesReadInPacket = 0;
1683 int curr_write_buffer_index = stream->ps_current_write_buffer_index;
1685 // Write output data until a buffer switch occurs.
1686 while (curr_write_buffer_index == stream->ps_current_write_buffer_index)
1688 // Try to read packet..
1690 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1694 bytesReadInPacket += bytesRead;
1696 // Flush any outstanding output data - we're done here.
1702 // curfilepos += bytesRead;
1703 bytesReadInPacket = 0;
1707 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
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++)
1713 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1714 stream->ts_skipbad[i] = 1;
1720 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1723 if (index_of_pid(pid, stream) < 0)
1725 // if (pid != stream->ts_audio_pids[0] && pid != stream->ts_video_pids[0])
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)
1732 // Not a video PID perhaps audio ?
1733 if ((index_of_selected_pid = index_of_audio_pid(pid,stream)) < 0)
1735 hb_log("hb_ts_stream_decode - Unknown pid 0x%x (%d)", pid, pid);
1740 curstream = stream->ts_number_video_pids + index_of_selected_pid;
1741 if (curstream > kMaxNumberDecodeStreams)
1743 hb_log("hb_ts_stream_decode - Too many streams %d", curstream);
1749 curstream = index_of_selected_pid;
1751 // if (pid == stream->ts_video_pids[0])
1758 start = (buf[1] & 0x40) != 0;
1760 if (!start && stream->ts_skipbad[curstream])
1764 int errorbit = (buf[1] & 0x80) != 0;
1767 hb_log("hb_ts_stream_decode - Error bit set in packet");
1768 stream->ts_skipbad[curstream] = 1;
1772 // Get adaption header info
1773 int adaption = (buf[3] & 0x30) >> 4;
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
1780 if (continuity != ((stream->ts_streamcont[curstream] + 1) & 0xF))
1782 hb_log("hb_ts_stream_decode - Bad continuity code in packet");
1783 stream->ts_skipbad[curstream] = 1;
1786 stream->ts_streamcont[curstream] = continuity;
1789 // Get adaption header size
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++)
1795 stream->ts_skipbad[i] = 1;
1797 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1800 else if (adaption == 0x2)
1802 else if (adaption == 0x3)
1804 adapt_len = buf[4] + 1;
1805 if (adapt_len > 184)
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++)
1810 stream->ts_skipbad[i] = 1;
1812 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
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)
1821 // Is there an AC3 packet start 0b77 code in this packet??
1823 unsigned char *p = buf + 4 + adapt_len;
1824 while (p <= buf + 186)
1826 if (p[0] == 0x0b && p[1] == 0x77)
1834 // Couldn't find an AC3 sync start in this packet.. don't make a PES packet!
1837 // int pos = ftell(fin);
1838 // error("AC3 packet sync not found in start frame");
1840 adapt_len += 9 + buf[4 + adapt_len + 8];
1846 if (start && (adaption & 0x2) && (buf[5] & 0x10))
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;
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)
1859 // Found a random access point (now we can start a frame/audio packet..)
1862 // Check to see if this is an i_frame (group of picture start)
1863 if (pid == stream->ts_video_pids[0])
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..
1868 unsigned int strid = 0;
1870 for (i = 4 + adapt_len; i < 188; i++)
1872 strid = (strid << 8) | buf[i];
1873 if (strid == 0x000001B8) // group_start_code
1875 // found a Group of Pictures header, subsequent picture must be an I-frame
1878 else if (strid == 0x000001B3) // sequence_header code
1882 else if (strid == 0x00000100) // picture_start_code
1884 // picture_header, let's see if it's an I-frame
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))
1892 // found an I-frame picture
1900 if (!stream->ts_foundfirst[curstream])
1902 stream->ts_foundfirst[curstream] = 1;
1903 // first_video_PCR = PCR;
1909 else if (index_of_audio_pid(pid, stream) >= 0)
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
1913 stream->ts_foundfirst[curstream] |= 1;
1917 // If we were skipping a bad packet, start fresh on this new PES packet..
1918 if (stream->ts_skipbad[curstream] == 1)
1920 stream->ts_skipbad[curstream] = 0;
1921 stream->ts_packetpos[curstream] = 0;
1924 // Get the continuity code of this packet
1925 stream->ts_streamcont[curstream] = continuity;
1928 // Write a 2048 byte program stream packet..
1929 if (start && stream->ts_packetpos[curstream] > 0 && stream->ts_foundfirst[curstream] && !stream->ts_skipbad[curstream])
1931 // Save the substream id block so we can added it to subsequent blocks
1933 // if (pid == stream->ts_audio_pids[0] /*&& audstreamid == 0xBD*/)
1934 if (index_of_audio_pid(pid, stream) >= 0)
1936 if ((stream->ts_audio_stream_type[curstream] == 0x04) || (stream->ts_audio_stream_type[curstream] == 0x81))
1938 write_ac3 = hb_ts_handle_ac3_audio(stream, curstream, buf, adapt_len);
1940 else if (stream->ts_audio_stream_type[curstream] == 0x03)
1942 hb_ts_handle_mpeg_audio(stream, curstream, buf, adapt_len);
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]);
1950 if (generate_output_data(stream, write_ac3, curstream, pid) != 0)
1954 // Add the payload for this packet to the current buffer
1955 if (stream->ts_foundfirst[curstream] && (184 - adapt_len) > 0)
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;
1963 /***********************************************************************
1964 * hb_ts_stream_reset
1965 ***********************************************************************
1967 **********************************************************************/
1968 static void hb_ts_stream_reset(hb_stream_t *stream)
1971 for (i=0; i < kNumDecodeBuffers; i++)
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;
1978 for (i=0; i < kMaxNumberDecodeStreams; i++)
1980 stream->ts_streamcont[i] = -1;
1983 stream->ps_current_write_buffer_index = 0;
1984 stream->ps_current_read_buffer_index = 1;
1986 align_to_next_packet(stream->file_handle);