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 kMaxNumberVideoPIDS 1
18 #define kMaxNumberAudioPIDS 16
19 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
20 #define kMaxNumberPMTStreams 32
27 hb_stream_type_t stream_type;
29 int frames; /* video frames so far */
30 int errors; /* total errors so far */
31 int last_error_frame; /* frame # at last error message */
32 int last_error_count; /* # errors at last error message */
34 int64_t ts_lastpcr; /* the last pcr we found in the TS stream */
35 int64_t ts_nextpcr; /* the next pcr to put in a PS packet */
37 int ts_video_pids[kMaxNumberVideoPIDS];
38 int ts_audio_pids[kMaxNumberAudioPIDS];
40 int ts_number_video_pids;
41 int ts_number_audio_pids;
43 uint8_t *ts_buf[kMaxNumberDecodeStreams];
44 int ts_pos[kMaxNumberDecodeStreams];
45 int ts_streamid[kMaxNumberDecodeStreams];
46 int ts_audio_stream_type[kMaxNumberDecodeStreams];
47 int8_t ts_foundfirst[kMaxNumberDecodeStreams];
48 int8_t ts_skipbad[kMaxNumberDecodeStreams];
49 int8_t ts_streamcont[kMaxNumberDecodeStreams];
50 int8_t ts_start[kMaxNumberDecodeStreams];
57 } a52_info[kMaxNumberAudioPIDS];
61 unsigned short program_number;
62 unsigned short program_map_PID;
63 } pat_info[kMaxNumberPMTStreams];
64 int ts_number_pat_entries;
69 unsigned char *tablebuf;
70 unsigned int tablepos;
71 unsigned char current_continuity_counter;
76 int program_info_length;
77 unsigned char *progam_info_descriptor_data;
80 unsigned char stream_type;
81 unsigned short elementary_PID;
82 unsigned short ES_info_length;
83 unsigned char *es_info_descriptor_data;
84 } pmt_stream_info[kMaxNumberPMTStreams];
88 /***********************************************************************
90 **********************************************************************/
91 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
92 static void hb_ts_stream_init(hb_stream_t *stream);
93 static void hb_ts_stream_find_pids(hb_stream_t *stream);
94 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
95 static void hb_ts_stream_reset(hb_stream_t *stream);
96 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
98 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
99 static off_t align_to_next_packet(FILE* f);
102 * streams have a bunch of state that's learned during the scan. We don't
103 * want to throw away the state when scan does a close then relearn
104 * everything when reader does an open. So we basically ignore
105 * a stream close, remember the most recent stream we've opened and only
106 * delete it when a stream of a different name is opened.
108 static hb_stream_t *current_stream;
111 static inline int check_ps_sync(const uint8_t *buf)
113 // a legal MPEG program stream must start with a Pack header in the
115 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
116 (buf[2] == 0x01) && (buf[3] == 0xba);
119 static inline int check_ts_sync(const uint8_t *buf)
121 // must have initial sync byte, no scrambling & a legal adaptation ctrl
122 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
125 static inline int have_ts_sync(const uint8_t *buf)
127 return check_ts_sync(&buf[0*188]) && check_ts_sync(&buf[1*188]) &&
128 check_ts_sync(&buf[2*188]) && check_ts_sync(&buf[3*188]) &&
129 check_ts_sync(&buf[4*188]) && check_ts_sync(&buf[5*188]) &&
130 check_ts_sync(&buf[6*188]) && check_ts_sync(&buf[7*188]);
133 static int hb_stream_check_for_ts(const uint8_t *buf)
135 // transport streams should have a sync byte every 188 bytes.
136 // search the first KB of buf looking for at least 8 consecutive
137 // correctly located sync patterns.
140 for ( offset = 0; offset < 1024; ++offset )
142 if ( have_ts_sync( &buf[offset]) )
148 static int hb_stream_check_for_ps(const uint8_t *buf)
150 // program streams should have a Pack header every 2048 bytes.
151 // check that we have 4 of these.
152 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
153 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
156 static int hb_stream_get_type(hb_stream_t *stream)
160 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
162 if ( hb_stream_check_for_ts(buf) != 0 )
164 hb_log("file is MPEG Transport Stream");
165 stream->stream_type = hb_stream_type_transport;
166 hb_ts_stream_init(stream);
169 if ( hb_stream_check_for_ps(buf) != 0 )
171 hb_log("file is MPEG Program Stream");
172 stream->stream_type = hb_stream_type_program;
179 static void hb_stream_delete( hb_stream_t ** _d )
181 hb_stream_t * d = *_d;
185 fclose( d->file_handle );
186 d->file_handle = NULL;
191 for (i = 0; i < kMaxNumberDecodeStreams; i++)
204 /***********************************************************************
206 ***********************************************************************
208 **********************************************************************/
209 hb_stream_t * hb_stream_open( char * path )
213 if (strcmp( path, current_stream->path ) == 0 )
215 hb_stream_seek( current_stream, 0. );
216 return current_stream;
218 hb_stream_delete( ¤t_stream );
220 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
222 /* open the file and see if it's a type we know about. return a stream
223 * reference structure if we can deal with it & NULL otherwise. */
224 if( ( d->file_handle = fopen( path, "rb" ) ) )
226 d->path = strdup( path );
227 if (d->path != NULL && hb_stream_get_type( d ) != 0 )
232 fclose( d->file_handle );
236 hb_log( "hb_stream_open: open %s failed", path );
241 /***********************************************************************
243 ***********************************************************************
244 * Closes and frees everything
245 **********************************************************************/
246 void hb_stream_close( hb_stream_t ** _d )
248 hb_stream_t *stream = * _d;
249 if ( stream->frames )
251 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
252 stream->errors, (double)stream->errors * 100. /
253 (double)stream->frames );
257 /* when the file was first opened we made entries for all the audio elementary
258 * streams we found in it. Streams that were later found during the preview scan
259 * now have an audio codec, type, rate, etc., associated with them. At the end
260 * of the scan we delete all the audio entries that weren't found by the scan
261 * or don't have a format we support. This routine deletes audio entry 'indx'
262 * by copying all later entries down one slot. */
263 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
267 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
269 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
270 stream->ts_audio_stream_type[1 + indx] = stream->ts_audio_stream_type[1+i];
271 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
274 --stream->ts_number_audio_pids;
277 static int index_of_pid(int pid, hb_stream_t *stream)
281 if ( pid == stream->ts_video_pids[0] )
284 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
285 if ( pid == stream->ts_audio_pids[i] )
291 /***********************************************************************
292 * hb_ps_stream_title_scan
293 ***********************************************************************
295 **********************************************************************/
296 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
299 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
302 // Copy part of the stream path to the title name
303 char *sep = strrchr(stream->path, '/');
305 strcpy(aTitle->name, sep+1);
306 char *dot_term = strrchr(aTitle->name, '.');
310 // Height, width, rate and aspect ratio information is filled in when the previews are built
312 hb_stream_duration(stream, aTitle);
315 hb_chapter_t * chapter;
316 chapter = calloc( sizeof( hb_chapter_t ), 1 );
318 chapter->duration = aTitle->duration;
319 chapter->hours = aTitle->hours;
320 chapter->minutes = aTitle->minutes;
321 chapter->seconds = aTitle->seconds;
322 hb_list_add( aTitle->list_chapter, chapter );
324 // Figure out how many audio streams we really have:
325 // - For transport streams, for each PID listed in the PMT (whether
326 // or not it was an audio stream type) read the bitstream until we
327 // find an packet from that PID containing a PES header and see if
328 // the elementary stream is an audio type.
329 // - For program streams read the first 4MB and take every unique
330 // audio stream we find.
331 if (stream->stream_type == hb_stream_type_transport)
335 for (i=0; i < stream->ts_number_audio_pids; i++)
337 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
339 hb_list_add( aTitle->list_audio, audio );
343 hb_stream_delete_audio_entry(stream, i);
348 // add the PCR PID if we don't already have it
349 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
351 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
352 stream->pmt_info.PCR_PID;
357 hb_ps_stream_find_audio_ids(stream, aTitle);
364 * scan the next MB of 'stream' to find the next start packet for
365 * the Packetized Elementary Stream associated with TS PID 'pid'.
367 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
369 static uint8_t buf[188];
370 int npack = 100000; // max packets to read
374 if (fread(buf, 1, 188, stream->file_handle) != 188)
376 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
381 hb_log("hb_ts_stream_getPEStype: lost sync while searching for PID 0x%x", pid);
382 align_to_next_packet(stream->file_handle);
387 * The PES header is only in TS packets with 'start' set so we check
388 * that first then check for the right PID.
390 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
391 buf[2] != (pid & 0xff))
393 // not a start packet or not the pid we want
397 /* skip over the TS hdr to return a pointer to the PES hdr */
399 switch (buf[3] & 0x30)
401 case 0x00: // illegal
402 case 0x20: // fill packet
405 case 0x30: // adaptation
408 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
421 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
423 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
424 hb_list_t *list = hb_list_init();
425 // how many blocks we read while searching for a video PES header
429 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
433 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
434 hb_demux_ps(buf, list);
436 while ( ( es = hb_list_item( list, 0 ) ) )
438 hb_list_rem( list, es );
439 if ( es->id == 0xe0 )
441 // this PES contains video - if there's a PTS we're done
442 // hb_demux_ps left the PTS in buf_es->start.
443 if ( es->start != ~0 )
450 hb_buffer_close( &es );
453 hb_list_empty( &list );
454 hb_buffer_close(&buf);
458 /***********************************************************************
460 ***********************************************************************
462 * Finding stream duration is difficult. One issue is that the video file
463 * may have chunks from several different program fragments (main feature,
464 * commercials, station id, trailers, etc.) all with their own base pts
465 * value. We can't find the piece boundaries without reading the entire
466 * file but if we compute a rate based on time stamps from two different
467 * pieces the result will be meaningless. The second issue is that the
468 * data rate of compressed video normally varies by 5-10x over the length
469 * of the video. This says that we want to compute the rate over relatively
470 * long segments to get a representative average but long segments increase
471 * the likelihood that we'll cross a piece boundary.
473 * What we do is take time stamp samples at several places in the file
474 * (currently 16) then compute the average rate (i.e., ticks of video per
475 * byte of the file) for all pairs of samples (N^2 rates computed for N
476 * samples). Some of those rates will be absurd because the samples came
477 * from different segments. Some will be way low or high because the
478 * samples came from a low or high motion part of the segment. But given
479 * that we're comparing *all* pairs the majority of the computed rates
480 * should be near the overall average. So we median filter the computed
481 * rates to pick the most representative value.
483 **********************************************************************/
485 uint64_t pos; /* file position of this PTS sample */
486 uint64_t pts; /* PTS from video stream */
489 #define NDURSAMPLES 16
491 // get one (position, timestamp) sampple from a transport or program
493 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
495 struct pts_pos pp = { 0, 0 };
497 if ( stream->stream_type == hb_stream_type_program )
499 // round address down to nearest dvd sector start
500 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
501 fseeko( stream->file_handle, fpos, SEEK_SET );
502 pp.pts = hb_ps_stream_getVideoPTS( stream );
507 fseeko( stream->file_handle, fpos, SEEK_SET );
508 align_to_next_packet( stream->file_handle );
509 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
512 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
515 if ( ( buf[7] >> 7 ) != 1 )
517 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
520 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
521 ( (uint64_t)buf[10] << 22 ) |
522 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
523 ( (uint64_t)buf[12] << 7 ) |
524 ( (uint64_t)buf[13] >> 1 );
526 pp.pos = ftello(stream->file_handle);
527 hb_log("hb_sample_pts: pts %lld at %llu", pp.pts, pp.pos );
531 static int dur_compare( const void *a, const void *b )
533 const double *aval = a, *bval = b;
534 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
537 // given an array of (position, time) samples, compute a max-likelihood
538 // estimate of the average rate by computing the rate between all pairs
539 // of samples then taking the median of those rates.
540 static double compute_stream_rate( struct pts_pos *pp, int n )
543 double rates[NDURSAMPLES * NDURSAMPLES / 2];
546 // the following nested loops compute the rates between all pairs.
548 for ( i = 0; i < n-1; ++i )
550 // Bias the median filter by not including pairs that are "far"
551 // from one another. This is to handle cases where the file is
552 // made of roughly equal size pieces where a symmetric choice of
553 // pairs results in having the same number of intra-piece &
554 // inter-piece rate estimates. This would mean that the median
555 // could easily fall in the inter-piece part of the data which
556 // would give a bogus estimate. The 'ns' index creates an
557 // asymmetry that favors locality.
558 int ns = i + ( n >> 1 );
561 for ( j = i+1; j < ns; ++j )
563 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
565 *rp = ((double)( pp[j].pts - pp[i].pts )) /
566 ((double)( pp[j].pos - pp[i].pos ));
571 // now compute and return the median of all the (n*n/2) rates we computed
573 int nrates = rp - rates;
574 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
575 return rates[nrates >> 1];
578 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
580 struct pts_pos ptspos[NDURSAMPLES];
581 struct pts_pos *pp = ptspos;
584 fseeko(stream->file_handle, 0, SEEK_END);
585 uint64_t fsize = ftello(stream->file_handle);
586 uint64_t fincr = fsize / NDURSAMPLES;
587 uint64_t fpos = fincr / 2;
588 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
590 *pp++ = hb_sample_pts(stream, fpos);
592 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
593 inTitle->duration = dur;
595 inTitle->hours = dur / 3600;
596 inTitle->minutes = ( dur % 3600 ) / 60;
597 inTitle->seconds = dur % 60;
599 rewind(stream->file_handle);
602 /***********************************************************************
604 ***********************************************************************
606 **********************************************************************/
607 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
609 if ( src_stream->stream_type == hb_stream_type_program )
611 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
612 src_stream->file_handle);
613 return (amt_read > 0);
615 return hb_ts_stream_decode( src_stream, b->data );
618 /***********************************************************************
620 ***********************************************************************
622 **********************************************************************/
623 int hb_stream_seek( hb_stream_t * src_stream, float f )
625 off_t stream_size, cur_pos, new_pos;
626 double pos_ratio = f;
627 cur_pos = ftello(src_stream->file_handle);
628 fseeko(src_stream->file_handle,0 ,SEEK_END);
629 stream_size = ftello(src_stream->file_handle);
630 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
631 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
632 int r = fseeko(src_stream->file_handle, new_pos, SEEK_SET);
636 fseeko(src_stream->file_handle, cur_pos, SEEK_SET);
640 if (src_stream->stream_type == hb_stream_type_transport)
642 // We need to drop the current decoder output and move
643 // forwards to the next transport stream packet.
644 hb_ts_stream_reset(src_stream);
650 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
653 off_t cur_pos = ftello(stream->file_handle);
654 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
657 fseeko(stream->file_handle, 0, SEEK_SET);
658 align_to_next_packet(stream->file_handle);
659 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
661 /* check that we found a PES header */
662 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
666 audio->id = 0x80bd | (aud_pid_index << 8);
667 audio->codec = HB_ACODEC_AC3;
668 hb_log("transport stream pid 0x%x (type 0x%x) is AC-3 audio id 0x%x",
669 stream->ts_audio_pids[aud_pid_index],
670 stream->ts_audio_stream_type[1 + aud_pid_index],
672 stream->ts_audio_stream_type[1 + aud_pid_index] = 0x81;
673 stream->ts_streamid[1 + aud_pid_index] = buf[3];
675 else if ((buf[3] & 0xe0) == 0xc0)
677 audio->id = buf[3] | aud_pid_index;
678 audio->codec = HB_ACODEC_MPGA;
679 hb_log("transport stream pid 0x%x (type 0x%x) is MPEG audio id 0x%x",
680 stream->ts_audio_pids[aud_pid_index],
681 stream->ts_audio_stream_type[1 + aud_pid_index],
683 stream->ts_audio_stream_type[1 + aud_pid_index] = 0x03;
684 stream->ts_streamid[1 + aud_pid_index] = buf[3];
687 fseeko(stream->file_handle, cur_pos, SEEK_SET);
690 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
691 stream->ts_audio_pids[aud_pid_index],
692 stream->ts_audio_stream_type[1 + aud_pid_index]);
697 static void add_audio_to_title(hb_title_t *title, int id)
699 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
705 audio->codec = HB_ACODEC_MPGA;
706 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
709 // type 2 is a DVD subtitle stream - just ignore it */
713 audio->codec = HB_ACODEC_AC3;
714 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
717 audio->codec = HB_ACODEC_LPCM;
718 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
721 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
726 hb_list_add( title->list_audio, audio );
729 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
731 off_t cur_pos = ftello(stream->file_handle);
732 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
733 hb_list_t *list = hb_list_init();
734 // how many blocks we read while searching for audio streams
736 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
737 // so we use a bitmap to keep track of the ones we've already seen.
738 // Bit 'i' of smap is set if we've already added the audio for
739 // audio substream id 'i' to the title's audio list.
742 // start looking 20% into the file since there's occasionally no
743 // audio at the beginning (particularly for vobs).
744 hb_stream_seek(stream, 0.2f);
746 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
750 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
751 hb_demux_ps(buf, list);
753 while ( ( es = hb_list_item( list, 0 ) ) )
755 hb_list_rem( list, es );
756 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
758 // this PES contains some kind of audio - get the substream id
759 // and check if we've seen it already.
760 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
761 if ( (smap & (1 << ssid)) == 0 )
763 // we haven't seen this stream before - add it to the
764 // title's list of audio streams.
766 add_audio_to_title(title, es->id);
769 hb_buffer_close( &es );
772 hb_list_empty( &list );
773 hb_buffer_close(&buf);
774 fseeko(stream->file_handle, cur_pos, SEEK_SET);
777 /***********************************************************************
778 * hb_stream_update_audio
779 ***********************************************************************
781 **********************************************************************/
782 void hb_stream_update_audio(hb_stream_t *stream, hb_audio_t *audio)
786 if (stream->stream_type == hb_stream_type_transport)
788 // Find the audio stream info for this PID. The stream index is
789 // the subchannel id which is in the bottom four bits for MPEG audio
790 // and the bottom four bits of the upper byte for everything else.
791 int i = ( audio->id >= 0xd0 ? audio->id >> 8 : audio->id ) & 0xf;
792 if (i >= stream->ts_number_audio_pids)
794 hb_log("hb_stream_update_audio: no PID for audio stream 0x%x",
798 if (audio->id < 0xd0)
800 /* XXX fake mpeg audio sample rate & bps */
801 stream->a52_info[i].flags = A52_STEREO;
802 stream->a52_info[i].rate = 48000 /*Hz*/;
803 stream->a52_info[i].bitrate = 384000 /*Bps*/;
806 lang = lang_for_code(stream->a52_info[i].lang_code);
808 audio->rate = stream->a52_info[i].rate;
810 audio->bitrate = stream->a52_info[i].bitrate;
811 if (!audio->config.a52.ac3flags)
812 audio->config.a52.ac3flags = audio->ac3flags = stream->a52_info[i].flags;
817 // XXX should try to get language code from the AC3 bitstream
818 lang = lang_for_code(0x0000);
821 if (!audio->input_channel_layout)
823 switch( audio->ac3flags & A52_CHANNEL_MASK )
829 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_MONO;
834 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
836 /* dolby (DPL1 aka Dolby Surround = 4.0 matrix-encoded) input */
838 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_DOLBY;
842 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F2R;
846 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F1R;
850 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_3F;
853 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F1R;
856 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_2F2R;
860 audio->input_channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
863 /* add in our own LFE flag if the source has LFE */
864 if (audio->ac3flags & A52_LFE)
866 audio->input_channel_layout = audio->input_channel_layout | HB_INPUT_CH_LAYOUT_HAS_LFE;
870 snprintf( audio->lang, sizeof( audio->lang ), "%s (%s)", strlen(lang->native_name) ? lang->native_name : lang->eng_name,
871 audio->codec == HB_ACODEC_AC3 ? "AC3" : ( audio->codec == HB_ACODEC_MPGA ? "MPEG" : ( audio->codec == HB_ACODEC_DCA ? "DTS" : "LPCM" ) ) );
872 snprintf( audio->lang_simple, sizeof( audio->lang_simple ), "%s", strlen(lang->native_name) ? lang->native_name : lang->eng_name );
873 snprintf( audio->iso639_2, sizeof( audio->iso639_2 ), "%s", lang->iso639_2);
875 if ( (audio->ac3flags & A52_CHANNEL_MASK) == A52_DOLBY ) {
876 sprintf( audio->lang + strlen( audio->lang ),
877 " (Dolby Surround)" );
879 sprintf( audio->lang + strlen( audio->lang ),
881 HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(audio->input_channel_layout) +
882 HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(audio->input_channel_layout),
883 HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(audio->input_channel_layout));
886 hb_log( "stream: audio %x: lang %s, rate %d, bitrate %d, "
887 "flags = 0x%x", audio->id, audio->lang, audio->rate,
888 audio->bitrate, audio->ac3flags );
892 /***********************************************************************
894 ***********************************************************************
896 **********************************************************************/
898 static void hb_ts_stream_init(hb_stream_t *stream)
902 for (i=0; i < kMaxNumberDecodeStreams; i++)
904 stream->ts_streamcont[i] = -1;
906 stream->ts_video_pids[0] = -1;
907 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
909 stream-> ts_audio_pids[i] = -1;
912 // Find the audio and video pids in the stream
913 hb_ts_stream_find_pids(stream);
915 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
917 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
919 // demuxing buffer for TS to PS conversion
920 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
924 // ------------------------------------------------------------------------------------
926 static off_t align_to_next_packet(FILE* f)
928 unsigned char buf[188*20];
930 off_t start = ftello(f);
933 if (fread(buf, 188*20, 1, f) == 1)
936 while (!found && (pos < 188))
940 for (i = 0; i < 188*20; i += 188)
942 unsigned char c = buf[pos+i];
944 if ((c != 0x47) && (c != 0x72) && (c != 0x29))
946 // this offset failed, try next
956 pos = 0; // failed to find anything!!!!!?
958 fseeko(f, start+pos, SEEK_SET);
963 // ------------------------------------------------------------------------------------
966 unsigned int bitval = 0;
967 unsigned char* bitbuf = NULL;
968 unsigned int bitmask[] = {
969 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
970 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
971 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
972 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
974 static inline void set_buf(unsigned char* buf, int bufsize, int clear)
978 bitval = (bitbuf[0] << 24) | (bitbuf[1] << 16) | (bitbuf[2] << 8) | bitbuf[3];
980 memset(bitbuf, 0, bufsize);
983 static inline int buf_size()
988 static inline void set_bits(unsigned int val, int bits)
990 val &= bitmask[bits];
994 int bitsleft = (8 - (bitpos & 7));
995 if (bits >= bitsleft)
997 bitbuf[bitpos >> 3] |= val >> (bits - bitsleft);
1000 val &= bitmask[bits];
1004 bitbuf[bitpos >> 3] |= val << (bitsleft - bits);
1011 static inline unsigned int get_bits(int bits)
1014 int left = 32 - (bitpos & 31);
1018 val = (bitval >> (left - bits)) & bitmask[bits];
1023 val = (bitval & bitmask[left]) << (bits - left);
1027 int pos = bitpos >> 3;
1028 bitval = (bitbuf[pos] << 24) | (bitbuf[pos + 1] << 16) | (bitbuf[pos + 2] << 8) | bitbuf[pos + 3];
1032 val |= (bitval >> (32 - bits)) & bitmask[bits];
1040 // extract what useful information we can from the elementary stream
1041 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1042 // Descriptors with info we don't currently use are ignored.
1043 // The descriptor list & descriptor item formats are defined in
1044 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1045 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1046 const uint8_t *dp, uint8_t dlen)
1048 const uint8_t *ep = dp + dlen;
1054 case 10: // ISO_639_language descriptor
1055 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1065 int decode_program_map(hb_stream_t* stream)
1067 set_buf(stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1069 get_bits(8); // table_id
1071 unsigned int section_length = get_bits(12);
1072 stream->pmt_info.section_length = section_length;
1074 unsigned int program_number = get_bits(16);
1075 stream->pmt_info.program_number = program_number;
1077 get_bits(5); // version_number
1079 get_bits(8); // section_number
1080 get_bits(8); // last_section_number
1082 unsigned int PCR_PID = get_bits(13);
1083 stream->pmt_info.PCR_PID = PCR_PID;
1085 unsigned int program_info_length = get_bits(12);
1086 stream->pmt_info.program_info_length = program_info_length;
1089 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1090 for (i = 0; i < program_info_length; i++)
1092 descriptor_buf[i] = get_bits(8);
1095 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1096 int done_reading_stream_types = 0;
1097 while (!done_reading_stream_types)
1099 unsigned char stream_type = get_bits(8);
1101 unsigned int elementary_PID = get_bits(13);
1103 unsigned int ES_info_length = get_bits(12);
1106 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1107 for (i=0; i < ES_info_length; i++)
1109 ES_info_buf[i] = get_bits(8);
1112 if (stream_type == 0x02)
1114 if (stream->ts_number_video_pids <= kMaxNumberVideoPIDS)
1115 stream->ts_number_video_pids++;
1116 stream->ts_video_pids[stream->ts_number_video_pids-1] = elementary_PID;
1120 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1121 // for mpeg audio. But content producers seem to use other
1122 // values (0x04 and 0x06 have both been observed) so at this point
1123 // we say everything that isn't a video pid is audio then at the end
1124 // of hb_stream_title_scan we'll figure out which are really audio
1125 // by looking at the PES headers.
1126 i = stream->ts_number_audio_pids;
1127 if (i < kMaxNumberAudioPIDS)
1128 stream->ts_number_audio_pids++;
1129 stream->ts_audio_pids[i] = elementary_PID;
1130 stream->ts_audio_stream_type[1 + i] = stream_type;
1132 if (ES_info_length > 0)
1134 decode_element_descriptors(stream, i, ES_info_buf, ES_info_length);
1138 cur_pos += 5 /* stream header */ + ES_info_length;
1142 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1143 done_reading_stream_types = 1;
1146 free(descriptor_buf);
1150 // ------------------------------------------------------------------------------------
1152 int build_program_map(unsigned char *buf, hb_stream_t *stream)
1154 // Get adaption header info
1156 int adaption = (buf[3] & 0x30) >> 4;
1159 else if (adaption == 0x2)
1161 else if (adaption == 0x3)
1162 adapt_len = buf[4] + 1;
1163 if (adapt_len > 184)
1166 // Get payload start indicator
1168 start = (buf[1] & 0x40) != 0;
1170 // Get pointer length - only valid in packets with a start flag
1171 int pointer_len = 0;
1172 if (start && stream->pmt_info.reading)
1174 // We just finished a bunch of packets - parse the program map details
1176 if (stream->pmt_info.tablebuf[0] == 0x02)
1177 decode_ok = decode_program_map(stream);
1178 free(stream->pmt_info.tablebuf);
1179 stream->pmt_info.tablebuf = NULL;
1180 stream->pmt_info.tablepos = 0;
1181 stream->pmt_info.reading = 0;
1188 pointer_len = buf[4 + adapt_len] + 1;
1189 stream->pmt_info.tablepos = 0;
1191 // Get Continuity Counter
1192 int continuity_counter = buf[3] & 0x0f;
1193 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1195 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1198 stream->pmt_info.current_continuity_counter = continuity_counter;
1199 stream->pmt_info.reading |= start;
1201 // Add the payload for this packet to the current buffer
1202 int amount_to_copy = 184 - adapt_len - pointer_len;
1203 if (stream->pmt_info.reading && (amount_to_copy > 0))
1205 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1207 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1208 stream->pmt_info.tablepos += amount_to_copy;
1214 int decode_PAT(unsigned char *buf, hb_stream_t *stream)
1216 unsigned char tablebuf[1024];
1217 unsigned int tablepos = 0;
1222 // Get adaption header info
1224 int adaption = (buf[3] & 0x30) >> 4;
1227 else if (adaption == 0x2)
1229 else if (adaption == 0x3)
1230 adapt_len = buf[4] + 1;
1231 if (adapt_len > 184)
1234 // Get pointer length
1235 int pointer_len = buf[4 + adapt_len] + 1;
1237 // Get payload start indicator
1239 start = (buf[1] & 0x40) != 0;
1244 // Add the payload for this packet to the current buffer
1245 if (reading && (184 - adapt_len) > 0)
1247 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1249 hb_log("decode_PAT - Bad program section length (> 1024)");
1252 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1253 tablepos += 184 - adapt_len - pointer_len;
1256 if (start && reading)
1258 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1261 unsigned int pos = 0;
1262 //while (pos < tablepos)
1264 set_buf(tablebuf + pos, tablepos - pos, 0);
1266 unsigned char section_id = get_bits(8);
1268 unsigned int section_len = get_bits(12);
1269 get_bits(16); // transport_id
1271 get_bits(5); // version_num
1272 get_bits(1); // current_next
1273 get_bits(8); // section_num
1274 get_bits(8); // last_section
1280 // Program Association Section
1281 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1282 section_len -= 4; // Ignore the CRC
1284 stream->ts_number_pat_entries = 0;
1285 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1287 unsigned int pkt_program_num = get_bits(16);
1288 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1290 get_bits(3); // Reserved
1291 if (pkt_program_num == 0)
1293 get_bits(13); // pkt_network_id
1297 unsigned int pkt_program_map_PID = get_bits(13);
1298 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1301 stream->ts_number_pat_entries++;
1315 pos += 3 + section_len;
1323 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1325 unsigned char buf[188];
1327 // align to first packet
1328 align_to_next_packet(stream->file_handle);
1330 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1331 // to find the program map PID and then decode that to get the list of audio and video PIDs
1333 int bytesReadInPacket = 0;
1336 // Try to read packet..
1338 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1342 bytesReadInPacket += bytesRead;
1344 hb_log("hb_ts_stream_find_pids - end of file");
1349 bytesReadInPacket = 0;
1353 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1355 off_t pos = ftello(stream->file_handle) - 188;
1356 off_t pos2 = align_to_next_packet(stream->file_handle);
1359 hb_log( "hb_ts_stream_find_pids: eof while re-establishing sync @ %lld",
1363 hb_log("hb_ts_stream_decode: sync lost @%lld, regained after %lld bytes",
1369 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1371 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1373 decode_PAT(buf, stream);
1378 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1380 // There are some streams where the PAT table has multiple entries as if their are
1381 // multiple programs in the same transport stream, and yet there's actually only one
1382 // program really in the stream. This seems to be true for transport streams that
1383 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1384 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1385 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1386 // PAT info on export to match what's actually on the stream.
1387 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1388 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1389 // be to build a title choice popup from the PAT program number details and then select from
1390 // their - but right now the API's not capable of that.
1391 if (pid == stream->pat_info[pat_index].program_map_PID)
1393 if (build_program_map(buf, stream) > 0)
1397 // Keep going until we have a complete set of PIDs
1398 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1402 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1403 hb_log(" Video PIDS : ");
1405 for (i=0; i < stream->ts_number_video_pids; i++)
1407 hb_log(" 0x%x (%d)", stream->ts_video_pids[i], stream->ts_video_pids[i]);
1409 hb_log(" Audio PIDS : ");
1410 for (i = 0; i < stream->ts_number_audio_pids; i++)
1412 hb_log(" 0x%x (%d)", stream->ts_audio_pids[i], stream->ts_audio_pids[i]);
1417 static uint8_t *fwrite_buf;
1418 static uint8_t *fwrite_buf_orig;
1420 static void set_fwrite_buf( uint8_t *obuf )
1423 fwrite_buf_orig = obuf;
1426 static void fwrite64( void* buf, int size )
1428 if ( (fwrite_buf - fwrite_buf_orig) + size > 2048 )
1430 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1431 size, fwrite_buf - fwrite_buf_orig );
1434 memcpy( fwrite_buf, buf, size );
1438 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1441 set_buf(buf, 64, 1); // clear buffer
1443 set_bits(0x000001ba, 32); // pack id 32
1444 set_bits(1, 2); // 0x01 2
1445 set_bits(time >> 30, 3); // system_clock_reference_base 3
1446 set_bits(1, 1); // marker_bit 1
1447 set_bits(time >> 15, 15); // system_clock_reference_base 15
1448 set_bits(1, 1); // marker_bit 1
1449 set_bits(time, 15); // system_clock_reference_base1 15
1450 set_bits(1, 1); // marker_bit 1
1451 set_bits(0, 9); // system_clock_reference_extension 9
1452 set_bits(1, 1); // marker_bit 1
1453 set_bits(384000, 22); // program_mux_rate 22
1454 set_bits(1, 1); // marker_bit 1
1455 set_bits(1, 1); // marker_bit 1
1456 set_bits(31, 5); // reserved 5
1457 set_bits(stuffing, 3); // pack_stuffing_length 3
1458 while ( --stuffing >= 0 )
1462 fwrite64(buf, buf_size());
1465 static void pad_buffer(int pad)
1480 while ( --pad >= 0 )
1486 static void make_pes_header(int len, uint8_t streamid)
1489 set_buf(buf, 9, 1); // clear the buffer
1491 set_bits(0x000001, 24); // packet_start_code_prefix 24
1492 set_bits(streamid, 8); // directory_stream_id 8
1493 set_bits(len + 3, 16); // PES_packet_length 16
1494 set_bits(0x2, 2); // '10' 2
1495 set_bits(0, 2); // PES_scrambling_control 2
1496 set_bits(1, 1); // PES_priority 1
1497 set_bits(0, 1); // data_alignment_indicator 1
1498 set_bits(0, 1); // copyright 1
1499 set_bits(0, 1); // original_or_copy 1
1500 set_bits(0, 2); // PTS_DTS_flags 2
1501 set_bits(0, 1); // ESCR_flag 1
1502 set_bits(0, 1); // ES_rate_flag 1
1503 set_bits(0, 1); // DSM_trick_mode_flag 1
1504 set_bits(0, 1); // additional_copy_info_flag 1
1505 set_bits(0, 1); // PES_CRC_flag 1
1506 set_bits(0, 1); // PES_extension_flag 1
1507 set_bits(0, 8); // PES_header_data_length 8
1512 static void generate_output_data(hb_stream_t *stream, int curstream)
1514 uint8_t *tdat = stream->ts_buf[curstream];
1517 // we always ship a PACK header plus all the data in our demux buf.
1518 // AC3 audio also always needs it substream header.
1519 len = 14 + stream->ts_pos[curstream];
1520 if ( stream->ts_audio_stream_type[curstream] == 0x81)
1525 if ( ! stream->ts_start[curstream] )
1527 // we're in the middle of a chunk of PES data - we need to add
1528 // a 'continuation' PES header after the PACK header.
1532 // Write out pack header
1533 // If we don't have 2048 bytes we need to pad to 2048. We can
1534 // add a padding frame after our data but we need at least 7
1535 // bytes of space to do it (6 bytes of header & 1 of pad). If
1536 // we have fewer than 7 bytes left we need to fill the excess
1537 // space with stuffing bytes added to the pack header.
1539 if ( len > HB_DVD_READ_BUFFER_SIZE )
1541 hb_log( "stream ts length botch %d", len );
1543 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1545 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1547 write_pack(stream, stream->ts_nextpcr, stuffing );
1548 stream->ts_nextpcr += 10;
1550 if ( stream->ts_start[curstream] )
1552 // Start frames already have a PES header but we have modify it
1553 // to map from TS PID to PS stream id. Also, if the stream is AC3
1554 // audio we have to insert an AC3 stream header between the end of
1555 // the PES header and the start of the stream data.
1557 stream->ts_start[curstream] = 0;
1558 tdat[3] = stream->ts_streamid[curstream];
1560 uint16_t plen = stream->ts_pos[curstream] - 6;
1561 if ( stream->ts_audio_stream_type[curstream] == 0x81)
1563 // We have to add an AC3 header in front of the data. Add its
1564 // size to the PES packet length.
1566 tdat[4] = plen >> 8;
1569 // Write out the PES header
1570 int hdrsize = 9 + tdat[8];
1571 fwrite64(tdat, hdrsize);
1573 // add a four byte DVD ac3 stream header
1574 uint8_t ac3_substream_id[4];
1575 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1576 ac3_substream_id[0] = 0x80 | ssid; // substream id
1577 ac3_substream_id[1] = 0x01; // number of sync words
1578 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1579 ac3_substream_id[3] = 0x02;
1580 fwrite64(ac3_substream_id, 4);
1582 // add the rest of the data
1583 fwrite64(tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1587 // not audio - don't need to modify the stream so write what we've got
1588 tdat[4] = plen >> 8;
1590 fwrite64( tdat, stream->ts_pos[curstream] );
1595 // data without a PES start header needs a simple 'continuation'
1596 // PES header. AC3 audio also needs its substream header.
1597 if ( stream->ts_audio_stream_type[curstream] != 0x81)
1599 make_pes_header(stream->ts_pos[curstream],
1600 stream->ts_streamid[curstream]);
1604 make_pes_header(stream->ts_pos[curstream] + 4,
1605 stream->ts_streamid[curstream]);
1607 // add a four byte DVD ac3 stream header
1608 uint8_t ac3_substream_id[4];
1609 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1610 ac3_substream_id[0] = 0x80 | ssid; // substream id
1611 ac3_substream_id[1] = 0x01; // number of sync words
1612 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1613 ac3_substream_id[3] = 0x02;
1614 fwrite64(ac3_substream_id, 4);
1616 fwrite64( tdat, stream->ts_pos[curstream] );
1620 int left = HB_DVD_READ_BUFFER_SIZE - len;
1626 stream->ts_pos[curstream] = 0;
1629 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
1631 // limit error printing to at most one per minute of video (at 30fps)
1633 if ( stream->frames - stream->last_error_frame >= 30*60 )
1637 vsnprintf( msg, sizeof(msg), log, args );
1639 if ( stream->errors - stream->last_error_count < 10 )
1641 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
1645 int Edelta = stream->errors - stream->last_error_count;
1646 double Epcnt = (double)Edelta * 100. /
1647 (stream->frames - stream->last_error_frame);
1648 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
1649 Edelta, Epcnt, stream->frames, msg );
1651 stream->last_error_frame = stream->frames;
1652 stream->last_error_count = stream->errors;
1656 static void ts_warn( hb_stream_t *stream, char *log, ... )
1659 va_start( args, log );
1660 ts_warn_helper( stream, log, args );
1664 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
1667 va_start( args, log );
1668 ts_warn_helper( stream, log, args );
1671 stream->ts_skipbad[curstream] = 1;
1672 stream->ts_pos[curstream] = 0;
1673 stream->ts_streamcont[curstream] = -1;
1676 static int isIframe( const uint8_t *buf, int adapt_len )
1678 // Look for the Group of Pictures packet
1682 for (i = 4 + adapt_len; i < 188; i++)
1684 strid = (strid << 8) | buf[i];
1687 case 0x000001B8: // group_start_code (GOP header)
1688 case 0x000001B3: // sequence_header code
1691 case 0x00000100: // picture_start_code
1692 // picture_header, let's see if it's an I-frame
1695 // check if picture_coding_type == 1
1696 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1698 // found an I-frame picture
1705 // didn't find an I frame
1709 /***********************************************************************
1710 * hb_ts_stream_decode
1711 ***********************************************************************
1713 **********************************************************************/
1714 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
1716 int64_t pcr = stream->ts_lastpcr;
1720 set_fwrite_buf( obuf );
1722 // spin until we get a packet of data from some stream or hit eof
1725 if ((fread(buf, 188, 1, stream->file_handle)) != 1)
1727 // end of file - we didn't finish filling our ps write buffer
1728 // so just discard the remainder (the partial buffer is useless)
1729 hb_log("hb_ts_stream_decode - eof");
1733 /* This next section validates the packet */
1736 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1738 // lost sync - back up to where we started then try to
1739 // re-establish sync.
1740 off_t pos = ftello(stream->file_handle) - 188;
1741 off_t pos2 = align_to_next_packet(stream->file_handle);
1744 hb_log( "hb_ts_stream_decode: eof while re-establishing sync @ %lld",
1748 ts_warn( stream, "hb_ts_stream_decode: sync lost @%lld, "
1749 "regained after %lld bytes", pos, pos2 );
1753 // Get pid and use it to find stream state.
1754 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
1755 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
1759 int errorbit = (buf[1] & 0x80) != 0;
1762 ts_err( stream, curstream, "packet error bit set");
1766 // Get adaption header info
1767 int adaption = (buf[3] & 0x30) >> 4;
1771 ts_err( stream, curstream, "adaptation code 0");
1774 else if (adaption == 0x2)
1776 else if (adaption == 0x3)
1778 adapt_len = buf[4] + 1;
1779 if (adapt_len > 184)
1781 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
1786 // if there's an adaptation header & PCR_flag is set
1787 // get the PCR (Program Clock Reference)
1788 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
1790 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
1791 ( (uint64_t)buf[7] << (33 - 16) ) |
1792 ( (uint64_t)buf[8] << (33 - 24) ) |
1793 ( (uint64_t)buf[9] << (33 - 32) ) |
1795 stream->ts_nextpcr = pcr;
1797 // remember the pcr across calls to this routine
1798 stream->ts_lastpcr = pcr;
1803 // don't accumulate data until we get a pcr
1808 // Continuity only increments for adaption values of 0x3 or 0x01
1809 // and is not checked for start packets.
1811 int start = (buf[1] & 0x40) != 0;
1813 if ( (adaption & 0x01) != 0 )
1815 int continuity = (buf[3] & 0xF);
1816 if ( continuity == stream->ts_streamcont[curstream] )
1818 // we got a duplicate packet (usually used to introduce
1819 // a PCR when one is needed). The only thing that can
1820 // change in the dup is the PCR which we grabbed above
1821 // so ignore the rest.
1824 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
1825 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
1827 ts_err( stream, curstream, "continuity error: got %d expected %d",
1829 (stream->ts_streamcont[curstream] + 1) & 0xf );
1830 stream->ts_streamcont[curstream] = continuity;
1833 stream->ts_streamcont[curstream] = continuity;
1836 /* If we get here the packet is valid - process its data */
1840 // Found a random access point (now we can start a frame/audio packet..)
1842 // If we were skipping a bad packet, start fresh on this new PES packet..
1843 if (stream->ts_skipbad[curstream] == 1)
1845 // video skips to an iframe after a bad packet to minimize
1846 // screen corruption
1847 if ( curstream == 0 && !isIframe( buf, adapt_len ) )
1851 stream->ts_skipbad[curstream] = 0;
1854 // If we don't have video yet, check to see if this is an
1855 // i_frame (group of picture start)
1856 if ( curstream == 0 )
1858 if ( !stream->ts_foundfirst[0] )
1860 if ( !isIframe( buf, adapt_len ) )
1862 // didn't find an I frame
1865 stream->ts_foundfirst[0] = 1;
1869 else if ( ! stream->ts_foundfirst[curstream] )
1871 // start other streams only after first video frame found.
1872 if ( ! stream->ts_foundfirst[0] )
1876 stream->ts_foundfirst[curstream] = 1;
1879 // If we have some data already on this stream, turn it into
1880 // a program stream packet. Then add the payload for this
1881 // packet to the current pid's buffer.
1882 if ( stream->ts_pos[curstream] )
1884 generate_output_data(stream, curstream);
1885 stream->ts_start[curstream] = 1;
1886 memcpy(stream->ts_buf[curstream],
1887 buf + 4 + adapt_len, 184 - adapt_len);
1888 stream->ts_pos[curstream] = 184 - adapt_len;
1891 stream->ts_start[curstream] = 1;
1894 // Add the payload for this packet to the current buffer
1895 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
1896 (184 - adapt_len) > 0)
1898 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
1899 buf + 4 + adapt_len, 184 - adapt_len);
1900 stream->ts_pos[curstream] += 184 - adapt_len;
1902 // if the next TS packet could possibly overflow our 2K output buffer
1903 // we need to generate a packet now. Overflow would be 184 bytes of
1904 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
1905 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
1907 // we have enough data to make a PS packet
1908 generate_output_data(stream, curstream);
1915 /***********************************************************************
1916 * hb_ts_stream_reset
1917 ***********************************************************************
1919 **********************************************************************/
1920 static void hb_ts_stream_reset(hb_stream_t *stream)
1924 for (i=0; i < kMaxNumberDecodeStreams; i++)
1926 stream->ts_pos[i] = 0;
1927 stream->ts_foundfirst[i] = 0;
1928 stream->ts_skipbad[i] = 0;
1929 stream->ts_streamcont[i] = -1;
1930 stream->ts_start[i] = 0;
1933 stream->ts_lastpcr = -1;
1934 stream->ts_nextpcr = -1;
1938 stream->last_error_frame = -10000;
1939 stream->last_error_count = 0;
1941 align_to_next_packet(stream->file_handle);