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
23 #define kMaxNumberPMTStreams 32
25 #define CLOCKRATE ((int64_t)27000000) // MPEG System clock rate
26 #define STREAMRATE ((int64_t)2401587) // Original HD stream rate 19.2 Mbps
27 #define DEMUX (((int)STREAMRATE * 8) / 50)// Demux value for HD content STREAMRATE / 50
33 hb_stream_type_t stream_type;
35 int ps_current_write_buffer_index;
36 int ps_current_read_buffer_index;
44 } ps_decode_buffer[kNumDecodeBuffers];
51 } a52_info[kMaxNumberAudioPIDS];
53 int ts_video_pids[kMaxNumberVideoPIDS];
54 int ts_audio_pids[kMaxNumberAudioPIDS];
56 int ts_number_video_pids;
57 int ts_number_audio_pids;
58 int ts_selected_audio_pid_index;
60 unsigned char* ts_packetbuf[kMaxNumberDecodeStreams];
61 int ts_packetpos[kMaxNumberDecodeStreams];
62 // int ts_bufpackets[kMaxNumberDecodeStreams];
63 int ts_foundfirst[kMaxNumberDecodeStreams];
64 int ts_skipbad[kMaxNumberDecodeStreams];
65 int ts_streamcont[kMaxNumberDecodeStreams];
66 int ts_streamid[kMaxNumberDecodeStreams];
67 int ts_audio_stream_type[kMaxNumberAudioPIDS];
71 unsigned short program_number;
72 unsigned short program_map_PID;
73 } pat_info[kMaxNumberPMTStreams];
74 int ts_number_pat_entries;
79 unsigned char *tablebuf;
80 unsigned int tablepos;
81 unsigned char current_continuity_counter;
86 int program_info_length;
87 unsigned char *progam_info_descriptor_data;
90 unsigned char stream_type;
91 unsigned short elementary_PID;
92 unsigned short ES_info_length;
93 unsigned char *es_info_descriptor_data;
94 } pmt_stream_info[kMaxNumberPMTStreams];
98 /***********************************************************************
100 **********************************************************************/
101 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
102 static void hb_ts_stream_init(hb_stream_t *stream);
103 static void hb_ts_stream_find_pids(hb_stream_t *stream);
104 static void hb_ts_stream_decode(hb_stream_t *stream);
105 static void hb_ts_stream_reset(hb_stream_t *stream);
106 static void hb_stream_put_back(hb_stream_t *stream, int i);
107 static void hb_stream_set_audio_id_and_codec(hb_stream_t *stream, hb_audio_t *audio);
109 int hb_stream_is_stream_type( char * path )
111 if ((strstr(path,".mpg") != NULL) ||
112 (strstr(path,".vob") != NULL) ||
113 (strstr(path, ".VOB") != NULL) ||
114 (strstr(path, ".mpeg") != NULL) ||
115 (strstr(path,".ts") != NULL) ||
116 (strstr(path, ".m2t") != NULL) ||
117 (strstr(path, ".TS") != NULL))
125 /***********************************************************************
127 ***********************************************************************
129 **********************************************************************/
130 hb_stream_t * hb_stream_open( char * path )
134 d = calloc( sizeof( hb_stream_t ), 1 );
137 if( !( d->file_handle = fopen( path, "rb" ) ) )
139 hb_log( "hb_stream_open: fopen failed (%s)", path );
143 d->path = strdup( path );
145 if ( ( strstr(d->path,".ts") != NULL) || ( strstr(d->path,".m2t") != NULL) || ( strstr(d->path,".TS") != NULL) )
147 d->stream_type = hb_stream_type_transport;
148 hb_ts_stream_init(d);
150 else if (( strstr(d->path,".mpg") != NULL) || ( strstr(d->path,".vob") != NULL) || ( strstr(d->path,".mpeg") != NULL) || ( strstr(d->path,".VOB") != NULL))
152 d->stream_type = hb_stream_type_program;
162 /***********************************************************************
164 ***********************************************************************
165 * Closes and frees everything
166 **********************************************************************/
167 void hb_stream_close( hb_stream_t ** _d )
169 hb_stream_t * d = *_d;
173 fclose( d->file_handle );
174 d->file_handle = NULL;
178 for (i = 0; i < kNumDecodeBuffers; i++)
180 if (d->ps_decode_buffer[i].data)
182 free(d->ps_decode_buffer[i].data);
183 d->ps_decode_buffer[i].data = NULL;
187 for (i = 0; i < kMaxNumberDecodeStreams; i++)
189 if (d->ts_packetbuf[i])
191 free(d->ts_packetbuf[i]);
192 d->ts_packetbuf[i] = NULL;
200 /***********************************************************************
201 * hb_ps_stream_title_scan
202 ***********************************************************************
204 **********************************************************************/
205 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
208 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
210 // Copy part of the stream path to the title name
211 char *sep = strrchr(stream->path, '/');
213 strcpy(aTitle->name, sep+1);
214 char *dot_term = strrchr(aTitle->name, '.');
218 // Height, width, rate and aspect ratio information is filled in when the previews are built
220 hb_stream_duration(stream, aTitle);
223 hb_chapter_t * chapter;
224 chapter = calloc( sizeof( hb_chapter_t ), 1 );
226 chapter->duration = aTitle->duration;
227 chapter->hours = aTitle->hours;
228 chapter->minutes = aTitle->minutes;
229 chapter->seconds = aTitle->seconds;
230 hb_list_add( aTitle->list_chapter, chapter );
232 int i=0, num_audio_tracks = 1;
234 if (stream->stream_type == hb_stream_type_transport)
236 num_audio_tracks = stream->ts_number_audio_pids;
239 for (i=0; i < num_audio_tracks ; i++)
241 // Basic AC-3 Audio track
243 audio = calloc( sizeof( hb_audio_t ), 1 );
245 audio->source_pid = stream->ts_audio_pids[i];
247 hb_stream_set_audio_id_and_codec(stream, audio);
249 hb_list_add( aTitle->list_audio, audio );
255 /***********************************************************************
257 ***********************************************************************
259 **********************************************************************/
260 void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
262 // VOB Files often have exceedingly unusual PTS values in them - they will progress for a while
263 // and then reset without warning !
264 if (strstr(stream->path,".vob") != NULL)
266 // So we'll use a 'fake duration' that should give enough time !
267 int64_t duration = 4 * 3600 * 90000;
268 inTitle->duration = duration; //90LL * dvdtime2msec( &d->pgc->playback_time );
269 inTitle->hours = inTitle->duration / 90000 / 3600;
270 inTitle->minutes = ( ( inTitle->duration / 90000 ) % 3600 ) / 60;
271 inTitle->seconds = ( inTitle->duration / 90000 ) % 60;
275 unsigned char *buf = (unsigned char *) malloc(4096);
278 int64_t first_pts = 0, last_pts = 0;
280 // To calculate the duration we look for the first and last presentation time stamps in the stream for video data
281 // and then use the delta
284 cur_pos = ftello(stream->file_handle);
285 if (fread(buf, 4096, 1, stream->file_handle) == 1)
288 for (i=0; (i <= 4092) && !done; i++)
290 if ((buf[i] == 0x00) && (buf[i+1] == 0x00) && (buf[i+2] == 0x01) && (buf[i+3] == 0xe0)) // Found a Video Stream
292 // Now look for a PTS field - we need to make sure we have enough space so we back up a little and read
294 fseeko(stream->file_handle, cur_pos + i, SEEK_SET);
295 if (fread(buf, 4096, 1, stream->file_handle) == 1)
297 int has_pts = ( ( buf[7] >> 6 ) & 0x2 ) ? 1 : 0;
300 first_pts = ( ( ( (uint64_t) buf[9] >> 1 ) & 0x7 ) << 30 ) +
302 ( ( buf[11] >> 1 ) << 15 ) +
309 fseeko(stream->file_handle, cur_pos, SEEK_SET);
310 fread(buf, 4096, 1, stream->file_handle);
317 done = 1; // End of data;
320 // Now work back from the end of the stream
321 fseeko(stream->file_handle,0 ,SEEK_END);
327 if (fseeko(stream->file_handle, -4096, SEEK_CUR) < 0)
333 cur_pos = ftello(stream->file_handle);
334 if (fread(buf, 4096, 1, stream->file_handle) == 1)
337 for (i=4092; (i >= 0) && !done; i--)
339 if ((buf[i] == 0x00) && (buf[i+1] == 0x00) && (buf[i+2] == 0x01) && (buf[i+3] == 0xe0)) // Found a Video Stream
341 // Now look for a PTS field - we need to make sure we have enough space so we back up a little and read
343 fseeko(stream->file_handle, cur_pos + i, SEEK_SET);
344 fread(buf, 1, 4096, stream->file_handle);
346 unsigned char pts_dts_flag = buf[7];
348 int has_pts = ( ( buf[7] >> 6 ) & 0x2 ) ? 1 : 0;
351 last_pts = ( ( ( (uint64_t) buf[9] >> 1 ) & 0x7 ) << 30 ) +
353 ( ( buf[11] >> 1 ) << 15 ) +
361 // Re Read the original data and carry on (i is still valid in the old buffer)
362 fseeko(stream->file_handle, cur_pos, SEEK_SET);
363 fread(buf, 4096, 1, stream->file_handle);
367 fseeko(stream->file_handle, -4096, SEEK_CUR); // 'Undo' the last read
370 done = 1; // End of data;
374 int64_t duration = last_pts - first_pts;
375 inTitle->duration = duration; //90LL * dvdtime2msec( &d->pgc->playback_time );
376 inTitle->hours = inTitle->duration / 90000 / 3600;
377 inTitle->minutes = ( ( inTitle->duration / 90000 ) % 3600 ) / 60;
378 inTitle->seconds = ( inTitle->duration / 90000 ) % 60;
382 /***********************************************************************
384 ***********************************************************************
386 **********************************************************************/
387 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
389 if (src_stream->stream_type == hb_stream_type_program)
392 amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1, src_stream->file_handle);
398 else if (src_stream->stream_type == hb_stream_type_transport)
400 int read_buffer_index = src_stream->ps_current_read_buffer_index;
402 // Transport streams are a little more complex - we might be able to just
403 // read from the transport stream conversion buffer (if there's enough data)
404 // or we may need to transfer what's left and fill it again.
405 if (src_stream->ps_decode_buffer[read_buffer_index].len - src_stream->ps_decode_buffer[read_buffer_index].read_pos > HB_DVD_READ_BUFFER_SIZE)
407 memcpy(b->data, src_stream->ps_decode_buffer[read_buffer_index].data + src_stream->ps_decode_buffer[read_buffer_index].read_pos,HB_DVD_READ_BUFFER_SIZE);
408 src_stream->ps_decode_buffer[read_buffer_index].read_pos += HB_DVD_READ_BUFFER_SIZE;
413 // Not quite enough data in the buffer - transfer what is present, fill the buffer and then
414 // transfer what's still needed.
415 int transfer_size = HB_DVD_READ_BUFFER_SIZE;
416 int amt_avail_to_transfer = src_stream->ps_decode_buffer[read_buffer_index].len - src_stream->ps_decode_buffer[read_buffer_index].read_pos;
417 memcpy(b->data, src_stream->ps_decode_buffer[read_buffer_index].data + src_stream->ps_decode_buffer[read_buffer_index].read_pos, amt_avail_to_transfer);
418 transfer_size -= amt_avail_to_transfer;
419 src_stream->ps_decode_buffer[read_buffer_index].read_pos += amt_avail_to_transfer;
421 // Give up this buffer - decoding may well need it, and we're done
422 src_stream->ps_decode_buffer[read_buffer_index].write_pos = 0;
423 src_stream->ps_decode_buffer[read_buffer_index].len = 0;
426 hb_ts_stream_decode(src_stream);
428 // Decoding will almost certainly have changed the current read buffer index
429 read_buffer_index = src_stream->ps_current_read_buffer_index;
431 if (src_stream->ps_decode_buffer[read_buffer_index].len == 0)
433 hb_log("hb_stream_read - buffer after decode has zero length data");
437 // Read the bit we still need
438 memcpy(b->data+amt_avail_to_transfer, src_stream->ps_decode_buffer[read_buffer_index].data + src_stream->ps_decode_buffer[read_buffer_index].read_pos,transfer_size);
439 src_stream->ps_decode_buffer[read_buffer_index].read_pos += transfer_size;
448 /***********************************************************************
450 ***********************************************************************
452 **********************************************************************/
453 int hb_stream_seek( hb_stream_t * src_stream, float f )
455 off_t stream_size, cur_pos, new_pos;
456 double pos_ratio = f;
457 cur_pos = ftello(src_stream->file_handle);
458 fseeko(src_stream->file_handle,0 ,SEEK_END);
459 stream_size = ftello(src_stream->file_handle);
460 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
461 int r = fseeko(src_stream->file_handle, new_pos, SEEK_SET);
465 fseeko(src_stream->file_handle, cur_pos, SEEK_SET);
469 if (src_stream->stream_type == hb_stream_type_transport)
471 // We need to drop the current decoder output and move
472 // forwards to the next transport stream packet.
473 hb_ts_stream_reset(src_stream);
476 // Now we must scan forwards for a valid start code (0x000001BA)
478 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
481 if (hb_stream_read(src_stream,buf) == 1)
484 for (i=0; (i <= HB_DVD_READ_BUFFER_SIZE-4) && (!done); i++)
486 if ((buf->data[i] == 0x00) && (buf->data[i+1] == 0x00) && (buf->data[i+2] == 0x01) && (buf->data[i+3] == 0xba))
489 // 'Put Back' the data we've just read (up to this point)
490 hb_stream_put_back(src_stream, i);
495 done = 1; // End of data;
497 hb_buffer_close(&buf);
501 /***********************************************************************
502 * hb_stream_set_audio_id_and_codec
503 ***********************************************************************
505 **********************************************************************/
506 void hb_stream_set_audio_id_and_codec(hb_stream_t *stream, hb_audio_t *audio)
509 cur_pos = ftello(stream->file_handle);
511 hb_buffer_t *buf = NULL;
513 int cur_audio_pid_index = stream->ts_selected_audio_pid_index;
515 if (stream->stream_type == hb_stream_type_transport)
518 for (i=0; i < stream->ts_number_audio_pids; i++)
520 if (stream->ts_audio_pids[i] == audio->source_pid)
522 stream->ts_selected_audio_pid_index = i;
528 //Start at the beginning of the stream
529 hb_stream_seek(stream, 0.0f);
531 // Now we must scan forwards for a valid audio start code (0x000001xx)
532 buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
535 if (hb_stream_read(stream, buf) == 1)
538 for (i=0; (i <= HB_DVD_READ_BUFFER_SIZE-4) && (!done); i++)
540 if ((buf->data[i] == 0x00) && (buf->data[i+1] == 0x00) && (buf->data[i+2] == 0x01))
542 if (buf->data[i+3] == 0xbd)
545 audio->codec = HB_ACODEC_AC3;
548 else if ((buf->data[i+3] & 0xe0) == 0xc0)
550 audio->id = buf->data[i+3];
551 audio->codec = HB_ACODEC_MPGA;
558 done = 1; // End of data;
560 hb_buffer_close(&buf);
562 fseeko(stream->file_handle, cur_pos, SEEK_SET);
564 stream->ts_selected_audio_pid_index = cur_audio_pid_index;
567 /***********************************************************************
568 * hb_stream_update_audio
569 ***********************************************************************
571 **********************************************************************/
572 void hb_stream_update_audio(hb_stream_t *stream, hb_audio_t *audio)
576 if (stream->stream_type == hb_stream_type_program)
578 lang = lang_for_code(0x0000);
580 else if (stream->stream_type == hb_stream_type_transport)
582 // Find the audio stream info for this PID
584 for (i=0; i < stream->ts_number_audio_pids; i++)
586 if (stream->ts_audio_pids[i] == audio->source_pid)
589 if (i == stream->ts_number_audio_pids)
591 hb_log("hb_stream_update_audio - cannot find PID 0x%x (%d) in ts_audio_pids list !", audio->source_pid, audio->source_pid);
595 lang = lang_for_code(stream->a52_info[i].lang_code);
597 audio->rate = stream->a52_info[i].rate;
599 audio->bitrate = stream->a52_info[i].bitrate;
600 if (!audio->config.a52.ac3flags)
601 audio->config.a52.ac3flags = audio->ac3flags = stream->a52_info[i].flags;
605 if (!audio->input_channel_layout)
607 switch( audio->ac3flags & A52_CHANNEL_MASK )
613 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_MONO;
618 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
620 /* dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input */
622 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_DOLBY;
626 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F2R;
630 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F1R;
634 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F;
637 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F1R;
640 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F2R;
644 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
647 /* add in our own LFE flag if the source has LFE */
648 if (audio->ac3flags & A52_LFE)
650 audio->input_channel_layout = audio->input_channel_layout | HB_INPUT_CH_LAYOUT_HAS_LFE;
654 snprintf( audio->lang, sizeof( audio->lang ), "%s (%s)", strlen(lang->native_name) ? lang->native_name : lang->eng_name,
655 audio->codec == HB_ACODEC_AC3 ? "AC3" : ( audio->codec == HB_ACODEC_MPGA ? "MPEG" : "LPCM" ) );
656 snprintf( audio->lang_simple, sizeof( audio->lang_simple ), "%s", strlen(lang->native_name) ? lang->native_name : lang->eng_name );
657 snprintf( audio->iso639_2, sizeof( audio->iso639_2 ), "%s", lang->iso639_2);
659 if ( (audio->ac3flags & A52_CHANNEL_MASK) == A52_DOLBY ) {
660 sprintf( audio->lang + strlen( audio->lang ),
661 " (Dolby Surround)" );
663 sprintf( audio->lang + strlen( audio->lang ),
665 HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(audio->input_channel_layout) +
666 HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(audio->input_channel_layout),
667 HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(audio->input_channel_layout));
670 hb_log( "hb_stream_update_audio: id=%x, lang=%s, 3cc=%s, rate = %d, bitrate = %d, flags = 0x%x (%d)", audio->id, audio->lang, audio->iso639_2, audio->rate, audio->bitrate, audio->ac3flags, audio->ac3flags );
674 void hb_stream_set_selected_audio_pid_index(hb_stream_t *stream, int i)
676 stream->ts_selected_audio_pid_index = i;
679 /***********************************************************************
681 ***********************************************************************
683 **********************************************************************/
684 static void hb_stream_put_back(hb_stream_t *stream, int i)
686 if (stream->stream_type == hb_stream_type_program)
688 // Program streams are pretty easy - we just reposition the source file
690 fseeko(stream->file_handle, -(HB_DVD_READ_BUFFER_SIZE-i), SEEK_CUR);
692 else if (stream->stream_type == hb_stream_type_transport)
694 int read_buffer_index = stream->ps_current_read_buffer_index;
696 // Transport streams are a little more tricky - so long as the
697 // amount to back up is still within the current decode buffer
698 // we can just adjust the read pos.
699 if (stream->ps_decode_buffer[read_buffer_index].read_pos - i > 0)
701 stream->ps_decode_buffer[read_buffer_index].read_pos -= i;
704 hb_error("hb_stream_put_back - trying to step beyond the start of the buffer, read_pos = %d amt to put back = %d\n", stream->ps_decode_buffer[read_buffer_index].read_pos, i);
709 /***********************************************************************
711 ***********************************************************************
713 **********************************************************************/
714 #define PS_DECODE_BUFFER_SIZE ( 1024 * 1024 * 4)
716 static void hb_ts_stream_init(hb_stream_t *stream)
718 // Output Program Stream
720 for (i=0; i < kNumDecodeBuffers; i++)
722 stream->ps_decode_buffer[i].data = (unsigned char *) malloc(PS_DECODE_BUFFER_SIZE);
723 stream->ps_decode_buffer[i].read_pos = 0;
724 stream->ps_decode_buffer[i].size = PS_DECODE_BUFFER_SIZE;
725 stream->ps_decode_buffer[i].len = 0;
726 stream->ps_decode_buffer[i].write_pos = 0;
729 for (i=0; i < kMaxNumberDecodeStreams; i++)
731 stream->ts_streamcont[i] = -1;
734 stream->ps_current_write_buffer_index = 0;
735 stream->ps_current_read_buffer_index = 1;
737 // This is the index (in ts_audio_pids) of the selected
738 // output stream. It should not be set until after all the
739 // pids in the stream have been discovered.
740 stream->ts_selected_audio_pid_index = -1;
742 // Find the audio and video pids in the stream
743 hb_ts_stream_find_pids(stream);
745 for (i=0; i < stream->ts_number_video_pids; i++)
747 // In progress audio/video data during the transport stream -> program stream processing
748 stream->ts_packetbuf[i] = (unsigned char *) malloc(1024 * 1024);
749 stream->ts_streamid[i] = 0xE0; // Stream is Video
752 for (i = stream->ts_number_video_pids; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
754 stream->ts_packetbuf[i] = (unsigned char *) malloc(1024 * 1024);
755 stream->ts_streamid[i] = 0xBD; // Stream 1 is AC-3 Audio
759 // ------------------------------------------------------------------------------------
761 off_t align_to_next_packet(FILE* f)
763 unsigned char buf[188*20];
765 off_t start = ftello(f);
768 if (fread(buf, 188*20, 1, f) == 1)
771 while (!found && (pos < 188))
775 for (i = 0; i < 188*20; i += 188)
777 unsigned char c = buf[pos+i];
779 if ((c != 0x47) && (c != 0x72) && (c != 0x29))
781 // this offset failed, try next
791 pos = 0; // failed to find anything!!!!!?
793 fseek(f, start+pos, SEEK_SET);
798 // ------------------------------------------------------------------------------------
801 unsigned int bitval = 0;
802 unsigned char* bitbuf = NULL;
803 unsigned int bitmask[] = {
804 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
805 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
806 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
807 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
809 static inline void set_buf(unsigned char* buf, int bufsize, int clear)
813 bitval = (bitbuf[0] << 24) | (bitbuf[1] << 16) | (bitbuf[2] << 8) | bitbuf[3];
815 memset(bitbuf, 0, bufsize);
818 static inline int buf_size()
823 static inline void set_bits(unsigned int val, int bits)
825 val &= bitmask[bits];
829 int bitsleft = (8 - (bitpos & 7));
830 if (bits >= bitsleft)
832 bitbuf[bitpos >> 3] |= val >> (bits - bitsleft);
835 val &= bitmask[bits];
839 bitbuf[bitpos >> 3] |= val << (bitsleft - bits);
846 static inline unsigned int get_bits(int bits)
849 int left = 32 - (bitpos & 31);
853 val = (bitval >> (left - bits)) & bitmask[bits];
858 val = (bitval & bitmask[left]) << (bits - left);
862 int pos = bitpos >> 3;
863 bitval = (bitbuf[pos] << 24) | (bitbuf[pos + 1] << 16) | (bitbuf[pos + 2] << 8) | bitbuf[pos + 3];
867 val |= (bitval >> (32 - bits)) & bitmask[bits];
875 int decode_program_map(hb_stream_t* stream)
877 unsigned int pos = 0;
878 set_buf(stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
880 unsigned char table_id = get_bits(8);
882 unsigned int section_length = get_bits(12);
883 stream->pmt_info.section_length = section_length;
885 unsigned int program_number = get_bits(16);
886 stream->pmt_info.program_number = program_number;
888 unsigned char version_number = get_bits(5);
890 unsigned char section_number = get_bits(8);
891 unsigned char last_section_number = get_bits(8);
893 unsigned int PCR_PID = get_bits(13);
894 stream->pmt_info.PCR_PID = PCR_PID;
896 unsigned int program_info_length = get_bits(12);
897 stream->pmt_info.program_info_length = program_info_length;
900 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
901 for (i = 0; i < program_info_length; i++)
903 descriptor_buf[i] = get_bits(8);
906 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
907 int done_reading_stream_types = 0;
908 while (!done_reading_stream_types)
910 unsigned char stream_type = get_bits(8);
912 unsigned int elementary_PID = get_bits(13);
914 unsigned int ES_info_length = get_bits(12);
917 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
918 for (i=0; i < ES_info_length; i++)
920 ES_info_buf[i] = get_bits(8);
923 if (stream_type == 0x02)
925 if (stream->ts_number_video_pids <= kMaxNumberVideoPIDS)
926 stream->ts_number_video_pids++;
927 stream->ts_video_pids[stream->ts_number_video_pids-1] = elementary_PID;
929 if ((stream_type == 0x04) || (stream_type == 0x81) || (stream_type == 0x03) || (stream_type == 0x06)) // ATSC Defines stream type 0x81 for AC-3/A52 audio, there's also some evidence of streams using type 6 for AC-3 audio too
931 if (stream->ts_number_audio_pids <= kMaxNumberAudioPIDS)
932 stream->ts_number_audio_pids++;
933 stream->ts_audio_pids[stream->ts_number_audio_pids-1] = elementary_PID;
935 stream->a52_info[stream->ts_number_audio_pids-1].lang_code = 'e' << 8 | 'n';
936 stream->ts_audio_stream_type[stream->ts_number_audio_pids-1] = stream_type;
938 if (ES_info_length > 0)
940 hb_log("decode_program_map - Elementary Stream Info Present, decode language codes ?");
945 cur_pos += 5 /* stream header */ + ES_info_length;
949 if (cur_pos >= section_length - 4 /* stop before the CRC */)
950 done_reading_stream_types = 1;
953 free(descriptor_buf);
957 // ------------------------------------------------------------------------------------
959 int build_program_map(unsigned char *buf, hb_stream_t *stream)
961 // Get adaption header info
963 int adaption = (buf[3] & 0x30) >> 4;
966 else if (adaption == 0x2)
968 else if (adaption == 0x3)
969 adapt_len = buf[4] + 1;
973 // Get payload start indicator
975 start = (buf[1] & 0x40) != 0;
977 // Get pointer length - only valid in packets with a start flag
979 if (start && stream->pmt_info.reading)
981 // We just finished a bunch of packets - parse the program map details
983 if (stream->pmt_info.tablebuf[0] == 0x02)
984 decode_ok = decode_program_map(stream);
985 free(stream->pmt_info.tablebuf);
986 stream->pmt_info.tablebuf = NULL;
987 stream->pmt_info.tablepos = 0;
988 stream->pmt_info.reading = 0;
995 pointer_len = buf[4 + adapt_len] + 1;
996 stream->pmt_info.tablepos = 0;
998 // Get Continuity Counter
999 int continuity_counter = buf[3] & 0x0f;
1000 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1002 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1005 stream->pmt_info.current_continuity_counter = continuity_counter;
1006 stream->pmt_info.reading |= start;
1008 // Add the payload for this packet to the current buffer
1009 int amount_to_copy = 184 - adapt_len - pointer_len;
1010 if (stream->pmt_info.reading && (amount_to_copy > 0))
1012 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1014 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1015 stream->pmt_info.tablepos += amount_to_copy;
1021 int decode_PAT(unsigned char *buf, hb_stream_t *stream)
1023 unsigned char tablebuf[1024];
1024 unsigned int tablepos = 0;
1029 // Get adaption header info
1031 int adaption = (buf[3] & 0x30) >> 4;
1034 else if (adaption == 0x2)
1036 else if (adaption == 0x3)
1037 adapt_len = buf[4] + 1;
1038 if (adapt_len > 184)
1041 // Get pointer length
1042 int pointer_len = buf[4 + adapt_len] + 1;
1044 // Get payload start indicator
1046 start = (buf[1] & 0x40) != 0;
1051 // Add the payload for this packet to the current buffer
1052 if (reading && (184 - adapt_len) > 0)
1054 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1056 hb_log("decode_PAT - Bad program section length (> 1024)");
1059 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1060 tablepos += 184 - adapt_len - pointer_len;
1063 if (start && reading)
1065 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1068 unsigned int pos = 0;
1069 //while (pos < tablepos)
1071 set_buf(tablebuf + pos, tablepos - pos, 0);
1073 unsigned char section_id = get_bits(8);
1075 unsigned int section_len = get_bits(12);
1076 unsigned int transport_id = get_bits(16);
1078 unsigned int version_num = get_bits(5);
1079 unsigned int current_next = get_bits(1);
1080 unsigned int section_num = get_bits(8);
1081 unsigned int last_section = get_bits(8);
1087 // Program Association Section
1088 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1089 section_len -= 4; // Ignore the CRC
1091 stream->ts_number_pat_entries = 0;
1092 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1094 unsigned int pkt_program_num = get_bits(16);
1095 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1097 get_bits(3); // Reserved
1098 if (pkt_program_num == 0)
1100 unsigned int pkt_network_PID = get_bits(13);
1104 unsigned int pkt_program_map_PID = get_bits(13);
1105 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1108 stream->ts_number_pat_entries++;
1122 pos += 3 + section_len;
1130 static int flushbuf(hb_stream_t *stream)
1132 int old_write_index = stream->ps_current_write_buffer_index;
1134 // Flip the buffers and start moving on to the next
1135 stream->ps_current_write_buffer_index++;
1136 if (stream->ps_current_write_buffer_index > kNumDecodeBuffers-1)
1137 stream->ps_current_write_buffer_index = 0;
1139 if ( (stream->ps_decode_buffer[stream->ps_current_write_buffer_index].len != 0) || (stream->ps_decode_buffer[stream->ps_current_write_buffer_index].write_pos != 0) )
1141 hb_log("flushbuf - new buffer (index %d) has non zero length and write position !", stream->ps_current_write_buffer_index);
1145 stream->ps_current_read_buffer_index = old_write_index;
1146 stream->ps_decode_buffer[stream->ps_current_read_buffer_index].read_pos = 0;
1151 static int fwrite64(void* buf, int elsize, int elnum, hb_stream_t* stream)
1158 int current_write_index = stream->ps_current_write_buffer_index;
1160 if (size <= stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos)
1162 memcpy(stream->ps_decode_buffer[current_write_index].data + stream->ps_decode_buffer[current_write_index].write_pos, buf, size);
1163 stream->ps_decode_buffer[current_write_index].write_pos += size;
1164 stream->ps_decode_buffer[current_write_index].len = stream->ps_decode_buffer[current_write_index].write_pos;
1169 memcpy(stream->ps_decode_buffer[current_write_index].data + stream->ps_decode_buffer[current_write_index].write_pos, buf, stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos);
1170 written += stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos;
1171 stream->ps_decode_buffer[current_write_index].write_pos += stream->ps_decode_buffer[current_write_index].size - stream->ps_decode_buffer[current_write_index].write_pos;
1172 stream->ps_decode_buffer[current_write_index].len = stream->ps_decode_buffer[current_write_index].write_pos;
1174 if (flushbuf(stream))
1176 // FLushing the buffer will have change the current write buffer
1177 current_write_index = stream->ps_current_write_buffer_index;
1179 memcpy(stream->ps_decode_buffer[current_write_index].data, (unsigned char*)buf + written, size - written);
1180 stream->ps_decode_buffer[current_write_index].write_pos += size - written;
1181 stream->ps_decode_buffer[current_write_index].len = stream->ps_decode_buffer[current_write_index].write_pos;
1182 written += size - written;
1187 if (elnum == 1 && written == size)
1190 return written / elsize;
1193 static int write_pack(hb_stream_t* stream, int64_t time)
1195 unsigned char buf[64];
1196 set_buf(buf, 64, 1); // clear buffer
1198 int64_t ext_time = time % 300;
1201 set_bits(0x000001ba, 32); // pack id 32
1202 set_bits(1, 2); // 0x01 2
1203 set_bits((unsigned int)(time >> 30), 3); // system_clock_reference_base 3
1204 set_bits(1, 1); // marker_bit 1
1205 set_bits((unsigned int)(time >> 15), 15); // system_clock_reference_base 15
1206 set_bits(1, 1); // marker_bit 1
1207 set_bits((unsigned int)time, 15); // system_clock_reference_base1 15
1208 set_bits(1, 1); // marker_bit 1
1209 set_bits((unsigned int)ext_time, 9); // system_clock_reference_extension 9
1210 set_bits(1, 1); // marker_bit 1
1211 set_bits(DEMUX, 22); // program_mux_rate 22
1212 set_bits(1, 1); // marker_bit 1
1213 set_bits(1, 1); // marker_bit 1
1214 set_bits(31, 5); // reserved 5
1215 set_bits(0, 3); // pack_stuffing_length 3
1217 return fwrite64(buf, buf_size(), 1, stream) == 1;
1220 static int pad_buffer(hb_stream_t *stream, int pad)
1225 buf[0] = '\x0'; buf[1] = '\x0'; buf[2] = '\x1'; buf[3] = '\xbe';
1226 buf[4] = pad >> 8; buf[5] = pad & 0xff;
1228 if (fwrite64(buf, 6, 1, stream) != 1)
1231 unsigned char padbyte = 0xff;
1233 for (i = 0; i < pad; i++)
1235 if (fwrite64(&padbyte, 1, 1, stream) != 1)
1242 int make_pes_header(unsigned char* buf, int streamid, int len, int64_t PTS, int64_t DTS)
1245 int PTS_DTS_flags = 0;
1260 set_buf(buf, 9 + hdrlen, 1); // clear the buffer
1262 set_bits(0x000001, 24); // packet_start_code_prefix 24
1263 set_bits((unsigned int)streamid, 8); // directory_stream_id 8
1264 set_bits(len, 16); // PES_packet_length 16
1265 set_bits(0x2, 2); // '10' 2
1266 set_bits(0, 2); // PES_scrambling_control 2
1267 set_bits(1, 1); // PES_priority 1
1268 set_bits(0, 1); // data_alignment_indicator 1
1269 set_bits(0, 1); // copyright 1
1270 set_bits(0, 1); // original_or_copy 1
1271 set_bits(PTS_DTS_flags, 2); // PTS_DTS_flags 2
1272 set_bits(0, 1); // ESCR_flag 1
1273 set_bits(0, 1); // ES_rate_flag 1
1274 set_bits(0, 1); // DSM_trick_mode_flag 1
1275 set_bits(0, 1); // additional_copy_info_flag 1
1276 set_bits(0, 1); // PES_CRC_flag 1
1277 set_bits(0, 1); // PES_extension_flag 1
1278 set_bits(hdrlen, 8); // PES_header_data_length 8
1280 if (PTS_DTS_flags == 2)
1282 set_bits(2, 4); // '0010' 4
1283 set_bits((unsigned int)(PTS >> 30), 3); // PTS [32..30] 3
1284 set_bits(1, 1); // marker bit 1
1285 set_bits((unsigned int)(PTS >> 15), 15); // PTS [29..15] 15
1286 set_bits(1, 1); // marker bit 1
1287 set_bits((unsigned int)PTS, 15); // PTS [14..0] 15
1288 set_bits(1, 1); // marker bit 1
1290 else if (PTS_DTS_flags == 3)
1292 set_bits(3, 4); // '0011' 4
1293 set_bits((unsigned int)(PTS >> 30), 3); // PTS [32..30] 3
1294 set_bits(1, 1); // marker bit 1
1295 set_bits((unsigned int)(PTS >> 15), 15); // PTS [29..15] 15
1296 set_bits(1, 1); // marker bit 1
1297 set_bits((unsigned int)PTS, 15); // PTS [14..0] 15
1298 set_bits(1, 1); // marker bit 1
1299 set_bits(1, 4); // '0001' 4
1300 set_bits((unsigned int)(DTS >> 30), 3); // DTS [32..30] 3
1301 set_bits(1, 1); // marker bit 1
1302 set_bits((unsigned int)(DTS >> 15), 15); // DTS [29..15] 15
1303 set_bits(1, 1); // marker bit 1
1304 set_bits((unsigned int)DTS, 15); // DTS [14..0] 15
1305 set_bits(1, 1); // marker bit 1
1311 int generate_output_data(hb_stream_t *stream, int write_ac3, int curstream, int pid)
1313 unsigned char ac3_substream_id[4];
1318 // Make a four byte ac3 streamid
1319 ac3_substream_id[0] = 0x80; // Four byte AC3 CODE??
1320 ac3_substream_id[1] = 0x01;
1321 ac3_substream_id[2] = 0x00; // WHY??? OH WHY??
1322 ac3_substream_id[3] = 0x02;
1326 int written = 0; // Bytes we've written to output file
1327 int pos = 0; // Position in PES packet buffer
1331 if ((stream->ps_decode_buffer[stream->ps_current_write_buffer_index].len % HB_DVD_READ_BUFFER_SIZE) != 0)
1333 hb_log("write_output_stream - Packet's not falling on read buffer size boundries!");
1337 // Get total length of this pack
1338 int len = min(14 + ac3len + stream->ts_packetpos[curstream] - pos, HB_DVD_READ_BUFFER_SIZE);
1340 // Figure out stuffing (if we have less than 16 bytes left)
1342 if (len < HB_DVD_READ_BUFFER_SIZE && HB_DVD_READ_BUFFER_SIZE - len < 16)
1344 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1348 // Write out pack header
1349 off_t file_offset = ftello(stream->file_handle);
1350 int64_t packet_time = (file_offset * CLOCKRATE / STREAMRATE) + 0 /*file_time*/;
1351 if (!write_pack(stream, packet_time))
1353 hb_log("write_output_stream - Couldn't write pack header!");
1357 int index_of_selected_pid = -1;
1358 if ((index_of_selected_pid = index_of_video_pid(pid,stream)) < 0)
1360 if ((index_of_selected_pid = index_of_audio_pid(pid,stream)) < 0)
1362 hb_log("generate_output_data - cannot find pid 0x%x (%d) in selected audio or video pids", pid, pid);
1367 stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[stream->ts_number_video_pids + index_of_selected_pid];
1371 stream->ts_packetbuf[curstream][pos + 3] = stream->ts_streamid[index_of_selected_pid];
1374 // Subtract pack size (14) and pes id and len (6) from lenth
1375 stream->ts_packetbuf[curstream][pos + 4] = (len - 6 - 14) >> 8; stream->ts_packetbuf[curstream][pos + 5] = (len - 6 - 14) & 0xFF;
1377 // Add any stuffing bytes to header extra len
1378 int hdrsize = 9 + stream->ts_packetbuf[curstream][pos + 8];
1379 stream->ts_packetbuf[curstream][pos + 8] += stuffing; // Add stuffing to header bytes
1381 // Write out id, streamid, len
1382 if (fwrite64(stream->ts_packetbuf[curstream] + pos, hdrsize, 1, stream) != 1) // Write pes id, streamid, and len
1384 hb_log("write_output_stream - Failed to write output file!");
1390 for (i = 0; i < stuffing; i++) // Write any stuffing bytes
1392 unsigned char stuff = 0xff;
1393 if (fwrite64(&stuff, 1, 1, stream) != 1)
1395 hb_log("write_output_stream - Failed to write output file!");
1400 // Write ac3 streamid
1403 if (fwrite64(ac3_substream_id, ac3len, 1, stream) != 1)
1405 hb_log("write_output_stream - Failed to write output file!");
1410 // Write rest of data len minus headersize (9) stuffing, and pack size (14)
1411 if (fwrite64(stream->ts_packetbuf[curstream] + pos + hdrsize, len - hdrsize - 14 - stuffing - ac3len, 1, stream) != 1) // Write data bytes
1413 hb_log("write_output_stream - Failed to write output file!");
1418 // Add len minus stuff we added like the pack (14) and the stuffing.
1419 pos += len - 14 - stuffing - ac3len;
1420 if (pos == stream->ts_packetpos[curstream])
1423 // Add pes header for next packet
1425 // make_pes_header(stream->ts_packetbuf[curstream] + pos, (pid == stream->ts_video_pids[0] ? stream->ts_streamid[kVideoStream] : stream->ts_streamid[kAudioStream]), 0, -1, -1);
1426 make_pes_header(stream->ts_packetbuf[curstream] + pos, stream->ts_streamid[curstream], 0, -1, -1);
1430 if ((written % HB_DVD_READ_BUFFER_SIZE) != 0)
1432 int left = HB_DVD_READ_BUFFER_SIZE - (written % HB_DVD_READ_BUFFER_SIZE);
1434 // Pad out to HB_DVD_READ_BUFFER_SIZE bytes
1435 if (!pad_buffer(stream, left))
1437 hb_log("write_output_stream - Couldn't write pad buffer!");
1442 stream->ts_packetpos[curstream] = 0;
1443 stream->ts_streamcont[curstream] = -1;
1448 static void hb_ts_handle_mpeg_audio(hb_stream_t *stream, int curstream, unsigned char* buf, int adapt_len )
1450 // Although we don't have AC3/A52 audio here we can still use the same structure to record this useful information.
1452 stream->a52_info[curstream - stream->ts_number_video_pids].flags = A52_STEREO;
1453 stream->a52_info[curstream - stream->ts_number_video_pids].rate = 48000 /*Hz*/;
1454 stream->a52_info[curstream - stream->ts_number_video_pids].bitrate = 384000 /*Bps*/;
1457 static int hb_ts_handle_ac3_audio(hb_stream_t *stream, int curstream, unsigned char* buf, int adapt_len )
1461 // Make sure we start with 0x0b77
1462 if (stream->ts_packetbuf[curstream][9 + stream->ts_packetbuf[curstream][8]] != 0x0b || stream->ts_packetbuf[curstream][9 + stream->ts_packetbuf[curstream][8] + 1] != 0x77)
1464 spos = 9 + stream->ts_packetbuf[curstream][8];
1465 dpos = 9 + stream->ts_packetbuf[curstream][8];
1466 while (spos <= stream->ts_packetpos[curstream] - 2 && !(stream->ts_packetbuf[curstream][spos] == 0x0b && stream->ts_packetbuf[curstream][spos + 1] == 0x77))
1469 if (!(stream->ts_packetbuf[curstream][spos] == 0x0b && stream->ts_packetbuf[curstream][spos + 1] == 0x77))
1471 hb_log("hb_ts_stream_decode - Couldn't sync AC3 packet!");
1472 stream->ts_skipbad[curstream] = 1;
1476 while (spos < stream->ts_packetpos[curstream])
1478 stream->ts_packetbuf[curstream][dpos] = stream->ts_packetbuf[curstream][spos];
1482 stream->ts_packetpos[curstream] = dpos;
1485 // Check the next packet to make sure IT starts with a 0x0b77
1487 // if (buf[4 + adapt_len] == 0 && buf[4 + adapt_len + 1] == 0 && // Starting with an mpeg header?
1488 // buf[4 + adapt_len + 2] == 1 && buf[4 + adapt_len + 3] == 0xBD)
1489 plen = 9 + buf[4 + adapt_len + 8];
1490 int pstart = 4 + adapt_len + plen;
1491 if (buf[pstart] != 0x0b || buf[pstart + 1] != 0x77)
1494 while (spos < 188 - 2 && !(buf[spos] == 0x0b && buf[spos + 1] == 0x77))
1496 stream->ts_packetbuf[curstream][stream->ts_packetpos[curstream]] = buf[spos];
1497 stream->ts_packetpos[curstream]++;
1501 if (!(buf[spos] == 0x0b && buf[spos + 1] == 0x77))
1503 hb_log("hb_ts_stream_decode - Couldn't sync AC3 packet!");
1504 stream->ts_skipbad[curstream] = 1;
1508 adapt_len = spos - 4 - plen;
1512 while (spos >= pstart - plen)
1514 buf[dpos] = buf[spos];
1520 int flags, rate, bitrate;
1521 if( a52_syncinfo( &buf[pstart], &flags, &rate, &bitrate ) )
1523 stream->a52_info[curstream - stream->ts_number_video_pids].flags = flags;
1524 stream->a52_info[curstream - stream->ts_number_video_pids].rate = rate;
1525 stream->a52_info[curstream - stream->ts_number_video_pids].bitrate = bitrate;
1530 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1532 unsigned char buf[188];
1536 unsigned int program_num = 0;
1537 unsigned int network_PID = 0;
1538 unsigned int program_map_PID = 0;
1540 // align to first packet
1541 align_to_next_packet(stream->file_handle);
1543 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1544 // to find the program map PID and then decode that to get the list of audio and video PIDs
1546 int bytesReadInPacket = 0;
1549 // Try to read packet..
1551 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1555 bytesReadInPacket += bytesRead;
1557 hb_log("hb_ts_stream_find_pids - end of file");
1562 bytesReadInPacket = 0;
1566 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1568 // __int64 pos = ftell64(fin);
1569 hb_log("hb_ts_stream_find_pids - Bad transport packet (no sync byte 0x47)!");
1571 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1572 stream->ts_skipbad[i] = 1;
1573 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1578 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1580 if ((pid == 0x0000) && (program_num == 0))
1582 decode_PAT(buf, stream);
1588 printf("Need to decode PSIP data !\n");
1592 if ((network_PID > 0) && (pid == network_PID))
1594 printf("Need to Decode network PID section !\n");
1599 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1601 // There are some streams where the PAT table has multiple entries as if their are
1602 // multiple programs in the same transport stream, and yet there's actually only one
1603 // program really in the stream. This seems to be true for transport streams that
1604 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1605 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1606 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1607 // PAT info on export to match what's actually on the stream.
1608 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1609 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1610 // be to build a title choice popup from the PAT program number details and then select from
1611 // their - but right now the API's not capable of that.
1612 if (pid == stream->pat_info[pat_index].program_map_PID)
1614 if (build_program_map(buf, stream) > 0)
1618 // Keep going until we have a complete set of PIDs
1619 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1623 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1624 hb_log(" Video PIDS : ");
1626 for (i=0; i < stream->ts_number_video_pids; i++)
1628 hb_log(" 0x%x (%d)", stream->ts_video_pids[i], stream->ts_video_pids[i]);
1630 hb_log(" Audio PIDS : ");
1631 for (i = 0; i < stream->ts_number_audio_pids; i++)
1633 hb_log(" 0x%x (%d)", stream->ts_audio_pids[i], stream->ts_audio_pids[i]);
1637 int index_of_video_pid(int pid, hb_stream_t *stream)
1639 int found_pid = -1, i = 0;
1641 for (i = 0; (i < stream->ts_number_video_pids) && (found_pid < 0); i++)
1643 if (pid == stream->ts_video_pids[i])
1649 int index_of_audio_pid(int pid, hb_stream_t *stream)
1651 int i = 0, found_pid = -1;
1653 // If a selected audio pid index has been set it indicates
1654 // which of the potential pids we need to output so only return
1655 // that index for the appropriate pid. Other pids should just
1657 if (stream->ts_selected_audio_pid_index >= 0)
1659 if (pid == stream->ts_audio_pids[stream->ts_selected_audio_pid_index])
1660 return stream->ts_selected_audio_pid_index;
1665 // If no specific pid index is set then we're probably just gathering
1666 // pid and/or stream information (during DecodePreviews for example)
1667 // so return the appropriate index
1668 for (i = 0; (i < stream->ts_number_audio_pids) && (found_pid < 0); i++)
1670 if (pid == stream->ts_audio_pids[i])
1676 int index_of_pid(int pid, hb_stream_t *stream)
1680 if ((found_pid = index_of_video_pid(pid, stream)) >= 0)
1683 if ((found_pid = index_of_audio_pid(pid, stream)) >= 0)
1689 /***********************************************************************
1690 * hb_ts_stream_decode
1691 ***********************************************************************
1693 **********************************************************************/
1694 static void hb_ts_stream_decode(hb_stream_t *stream)
1696 unsigned char buf[188];
1701 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1703 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 0;
1704 stream->ts_skipbad[i] = 0;
1709 if ((stream->ts_number_video_pids == 0) || (stream->ts_number_audio_pids == 0))
1711 hb_log("hb_ts_stream_decode - no Video or Audio PID selected, cannot decode transport stream");
1715 int bytesReadInPacket = 0;
1716 int curr_write_buffer_index = stream->ps_current_write_buffer_index;
1718 // Write output data until a buffer switch occurs.
1719 while (curr_write_buffer_index == stream->ps_current_write_buffer_index)
1721 // Try to read packet..
1723 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1727 bytesReadInPacket += bytesRead;
1729 // Flush any outstanding output data - we're done here.
1735 // curfilepos += bytesRead;
1736 bytesReadInPacket = 0;
1740 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1742 // __int64 pos = ftell64(fin);
1743 hb_log("hb_ts_stream_decode - Bad transport packet (no sync byte 0x47)!");
1744 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1746 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1747 stream->ts_skipbad[i] = 1;
1753 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1756 if (index_of_pid(pid, stream) < 0)
1758 // if (pid != stream->ts_audio_pids[0] && pid != stream->ts_video_pids[0])
1761 // Get the pos and buf - we organize our streams as 'n' video streams then 'm' audio streams
1762 int index_of_selected_pid = -1;
1763 if ((index_of_selected_pid = index_of_video_pid(pid,stream)) < 0)
1765 // Not a video PID perhaps audio ?
1766 if ((index_of_selected_pid = index_of_audio_pid(pid,stream)) < 0)
1768 hb_log("hb_ts_stream_decode - Unknown pid 0x%x (%d)", pid, pid);
1773 curstream = stream->ts_number_video_pids + index_of_selected_pid;
1774 if (curstream > kMaxNumberDecodeStreams)
1776 hb_log("hb_ts_stream_decode - Too many streams %d", curstream);
1782 curstream = index_of_selected_pid;
1784 // if (pid == stream->ts_video_pids[0])
1791 start = (buf[1] & 0x40) != 0;
1793 if (!start && stream->ts_skipbad[curstream])
1797 int errorbit = (buf[1] & 0x80) != 0;
1800 hb_log("hb_ts_stream_decode - Error bit set in packet");
1801 stream->ts_skipbad[curstream] = 1;
1805 // Get adaption header info
1806 int adaption = (buf[3] & 0x30) >> 4;
1810 int continuity = (buf[3] & 0xF);
1811 if ((stream->ts_streamcont[curstream] != -1) && (adaption & 0x01 == 0x01)) // Continuity only increments for adaption values of 0x3 or 0x01
1813 if (continuity != ((stream->ts_streamcont[curstream] + 1) & 0xF))
1815 hb_log("hb_ts_stream_decode - Bad continuity code in packet");
1816 stream->ts_skipbad[curstream] = 1;
1819 stream->ts_streamcont[curstream] = continuity;
1822 // Get adaption header size
1825 hb_log("hb_ts_stream_decode - Bad adaption code (code was 0)!");
1826 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1828 stream->ts_skipbad[i] = 1;
1830 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1833 else if (adaption == 0x2)
1835 else if (adaption == 0x3)
1837 adapt_len = buf[4] + 1;
1838 if (adapt_len > 184)
1840 hb_log("hb_ts_stream_decode - Invalid adapt len (was > 183)!");
1841 for (i=0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1843 stream->ts_skipbad[i] = 1;
1845 // stream->ts_skipbad[kAudioStream] = stream->ts_skipbad[kVideoStream] = 1;
1849 // HBO is slick, it doesn't bother to sync AC3 packets with PES elementary stream packets.. so
1850 // we have to swizzle them together! (ARGHH!)
1851 // if (pid == stream->ts_audio_pids[0] && start)
1852 if ((index_of_audio_pid(pid, stream) >= 0) && start)
1854 // Is there an AC3 packet start 0b77 code in this packet??
1856 unsigned char *p = buf + 4 + adapt_len;
1857 while (p <= buf + 186)
1859 if (p[0] == 0x0b && p[1] == 0x77)
1867 // Couldn't find an AC3 sync start in this packet.. don't make a PES packet!
1870 // int pos = ftell(fin);
1871 // error("AC3 packet sync not found in start frame");
1873 adapt_len += 9 + buf[4 + adapt_len + 8];
1879 if (start && (adaption & 0x2) && (buf[5] & 0x10))
1881 int64_t PCR_base = ((int64_t)buf[6] << 25) | ((int64_t)buf[7] << 17) |
1882 ((int64_t)buf[8] << 9) | ((int64_t)buf[9] << 1) | ((int64_t)buf[10] >> 7);
1883 int64_t PCR_ext = ((int64_t)(buf[10] & 0x1) << 8) | ((int64_t)buf[11]);
1884 int64_t PCR = PCR_base * 300 + PCR_ext;
1888 // bool random = false;
1889 // if (start && (adaption & 0x2))
1890 // random = (buf[5] & 0x40) != 0; // BUG: SOME TS STREAMS DON'T HAVE THE RANDOM BIT (ABC!! ALIAS)
1892 // Found a random access point (now we can start a frame/audio packet..)
1895 // Check to see if this is an i_frame (group of picture start)
1896 if (pid == stream->ts_video_pids[0])
1898 // printf("Found Video Start for pid 0x%x\n", pid);
1899 // Look for the Group of Pictures packet.. indicates this is an I-Frame packet..
1901 unsigned int strid = 0;
1903 for (i = 4 + adapt_len; i < 188; i++)
1905 strid = (strid << 8) | buf[i];
1906 if (strid == 0x000001B8) // group_start_code
1908 // found a Group of Pictures header, subsequent picture must be an I-frame
1911 else if (strid == 0x000001B3) // sequence_header code
1915 else if (strid == 0x00000100) // picture_start_code
1917 // picture_header, let's see if it's an I-frame
1920 // int pic_start_code = (buf[i+2] >> 3) & 0x07;
1921 // hb_log("hb_ts_stream_decode - picture_start_code header value = 0x%x (%d)", pic_start_code, pic_start_code);
1922 // check if picture_coding_type == 1
1923 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1925 // found an I-frame picture
1933 if (!stream->ts_foundfirst[curstream])
1935 stream->ts_foundfirst[curstream] = 1;
1936 // first_video_PCR = PCR;
1942 else if (index_of_audio_pid(pid, stream) >= 0)
1944 if (stream->ts_foundfirst[0]) // Set audio found first ONLY after first video frame found. There's an assumption here that stream '0' is a video stream
1946 stream->ts_foundfirst[curstream] |= 1;
1950 // If we were skipping a bad packet, start fresh on this new PES packet..
1951 if (stream->ts_skipbad[curstream] == 1)
1953 stream->ts_skipbad[curstream] = 0;
1954 stream->ts_packetpos[curstream] = 0;
1957 // Get the continuity code of this packet
1958 stream->ts_streamcont[curstream] = continuity;
1961 // Write a 2048 byte program stream packet..
1962 if (start && stream->ts_packetpos[curstream] > 0 && stream->ts_foundfirst[curstream] && !stream->ts_skipbad[curstream])
1964 // Save the substream id block so we can added it to subsequent blocks
1966 // if (pid == stream->ts_audio_pids[0] /*&& audstreamid == 0xBD*/)
1967 if (index_of_audio_pid(pid, stream) >= 0)
1969 // Curstream is a zero based index of streams and includes both video and audio streams, so we must subtract the numver of video streams
1970 // from the indes value used here since ts_audio_stream_type is indexed only by audio streams.
1971 if ((stream->ts_audio_stream_type[curstream - stream->ts_number_video_pids] == 0x04) || (stream->ts_audio_stream_type[curstream - stream->ts_number_video_pids] == 0x81))
1973 write_ac3 = hb_ts_handle_ac3_audio(stream, curstream, buf, adapt_len);
1975 else if (stream->ts_audio_stream_type[curstream - stream->ts_number_video_pids] == 0x03)
1977 hb_ts_handle_mpeg_audio(stream, curstream, buf, adapt_len);
1981 hb_log("hb_ts_stream_decode - Unknown Audio Stream type ! 0x%x (%d)", stream->ts_audio_stream_type[curstream - stream->ts_number_video_pids], stream->ts_audio_stream_type[curstream - stream->ts_number_video_pids]);
1985 if (generate_output_data(stream, write_ac3, curstream, pid) != 0)
1989 // Add the payload for this packet to the current buffer
1990 if (stream->ts_foundfirst[curstream] && (184 - adapt_len) > 0)
1992 memcpy(stream->ts_packetbuf[curstream] + stream->ts_packetpos[curstream], buf + 4 + adapt_len, 184 - adapt_len);
1993 stream->ts_packetpos[curstream] += 184 - adapt_len;
1998 /***********************************************************************
1999 * hb_ts_stream_reset
2000 ***********************************************************************
2002 **********************************************************************/
2003 static void hb_ts_stream_reset(hb_stream_t *stream)
2006 for (i=0; i < kNumDecodeBuffers; i++)
2008 stream->ps_decode_buffer[i].read_pos = 0;
2009 stream->ps_decode_buffer[i].write_pos = 0;
2010 stream->ps_decode_buffer[i].len = 0;
2013 for (i=0; i < kMaxNumberDecodeStreams; i++)
2015 stream->ts_streamcont[i] = -1;
2018 stream->ps_current_write_buffer_index = 0;
2019 stream->ps_current_read_buffer_index = 1;
2021 align_to_next_packet(stream->file_handle);