3 This file is part of the HandBrake source code.
4 Homepage: <http://handbrake.fr/>.
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
16 hb_stream_type_unknown = 0,
22 #define kMaxNumberVideoPIDS 1
23 #define kMaxNumberAudioPIDS 15
24 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
25 #define kMaxNumberPMTStreams 32
30 int frames; /* video frames so far */
31 int errors; /* total errors so far */
32 int last_error_frame; /* frame # at last error message */
33 int last_error_count; /* # errors at last error message */
34 int packetsize; /* Transport Stream packet size */
36 int64_t ts_lastpcr; /* the last pcr we found in the TS stream */
37 int64_t ts_nextpcr; /* the next pcr to put in a PS packet */
39 uint8_t *ts_packet; /* buffer for one TS packet */
40 uint8_t *ts_buf[kMaxNumberDecodeStreams];
41 int ts_pos[kMaxNumberDecodeStreams];
42 int8_t ts_foundfirst[kMaxNumberDecodeStreams];
43 int8_t ts_skipbad[kMaxNumberDecodeStreams];
44 int8_t ts_streamcont[kMaxNumberDecodeStreams];
45 int8_t ts_start[kMaxNumberDecodeStreams];
47 uint8_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
48 uint8_t *fwrite_buf_orig; /* PS buffer start (set by hb_ts_stream_decode) */
51 * Stuff before this point is dynamic state updated as we read the
52 * stream. Stuff after this point is stream description state that
53 * we learn during the initial scan but cache so it can be
54 * reused during the conversion read.
56 uint8_t ts_number_video_pids;
57 uint8_t ts_number_audio_pids;
59 int16_t ts_video_pids[kMaxNumberVideoPIDS];
60 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
62 uint8_t ts_streamid[kMaxNumberDecodeStreams];
63 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
67 hb_stream_type_t hb_stream_type;
75 } a52_info[kMaxNumberAudioPIDS];
79 unsigned short program_number;
80 unsigned short program_map_PID;
81 } pat_info[kMaxNumberPMTStreams];
82 int ts_number_pat_entries;
87 unsigned char *tablebuf;
88 unsigned int tablepos;
89 unsigned char current_continuity_counter;
94 int program_info_length;
95 unsigned char *progam_info_descriptor_data;
98 unsigned char stream_type;
99 unsigned short elementary_PID;
100 unsigned short ES_info_length;
101 unsigned char *es_info_descriptor_data;
102 } pmt_stream_info[kMaxNumberPMTStreams];
106 /***********************************************************************
108 **********************************************************************/
109 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
110 static void hb_ts_stream_init(hb_stream_t *stream);
111 static void hb_ts_stream_find_pids(hb_stream_t *stream);
112 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
113 static void hb_ts_stream_reset(hb_stream_t *stream);
114 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
116 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
117 static off_t align_to_next_packet(hb_stream_t *stream);
120 * streams have a bunch of state that's learned during the scan. We don't
121 * want to throw away the state when scan does a close then relearn
122 * everything when reader does an open. So we save the stream state on
123 * the close following a scan and reuse it when 'reader' does an open.
125 static hb_list_t *stream_state_list;
127 static hb_stream_t *hb_stream_lookup( const char *path )
129 if ( stream_state_list == NULL )
135 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
137 if ( strcmp( path, ss->path ) == 0 )
145 static void hb_stream_state_delete( hb_stream_t *ss )
147 hb_list_rem( stream_state_list, ss );
154 * these frontend hb_log because transport streams can have a lot of errors
155 * so we want to rate limit messages. this routine limits the number of
156 * messages to at most one per minute of video. other errors that occur
157 * during the minute are counted & the count is output with the next
158 * error msg we print.
160 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
162 // limit error printing to at most one per minute of video (at 30fps)
164 if ( stream->frames - stream->last_error_frame >= 30*60 )
168 vsnprintf( msg, sizeof(msg), log, args );
170 if ( stream->errors - stream->last_error_count < 10 )
172 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
176 int Edelta = stream->errors - stream->last_error_count;
177 double Epcnt = (double)Edelta * 100. /
178 (stream->frames - stream->last_error_frame);
179 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
180 Edelta, Epcnt, stream->frames, msg );
182 stream->last_error_frame = stream->frames;
183 stream->last_error_count = stream->errors;
187 static void ts_warn( hb_stream_t *stream, char *log, ... )
190 va_start( args, log );
191 ts_warn_helper( stream, log, args );
195 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
198 va_start( args, log );
199 ts_warn_helper( stream, log, args );
202 stream->ts_skipbad[curstream] = 1;
203 stream->ts_pos[curstream] = 0;
204 stream->ts_streamcont[curstream] = -1;
207 static int check_ps_sync(const uint8_t *buf)
209 // a legal MPEG program stream must start with a Pack header in the
211 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
212 (buf[2] == 0x01) && (buf[3] == 0xba);
215 static int check_ps_sys(const uint8_t *buf)
217 // a legal MPEG program stream must start with a Pack followed by a
218 // SYS. If we've already verified the pack, this skips over it and checks
219 // for the sys header.
220 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
221 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
222 (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
225 static int check_ts_sync(const uint8_t *buf)
227 // must have initial sync byte, no scrambling & a legal adaptation ctrl
228 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
231 static int have_ts_sync(const uint8_t *buf, int psize)
233 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
234 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
235 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
236 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
239 static int hb_stream_check_for_ts(const uint8_t *buf)
241 // transport streams should have a sync byte every 188 bytes.
242 // search the first 8KB of buf looking for at least 8 consecutive
243 // correctly located sync patterns.
246 for ( offset = 0; offset < 8*1024-8*188; ++offset )
248 if ( have_ts_sync( &buf[offset], 188) )
249 return 188 | (offset << 8);
250 if ( have_ts_sync( &buf[offset], 192) )
251 return 192 | (offset << 8);
252 if ( have_ts_sync( &buf[offset], 204) )
253 return 204 | (offset << 8);
254 if ( have_ts_sync( &buf[offset], 208) )
255 return 208 | (offset << 8);
260 static int hb_stream_check_for_ps(const uint8_t *buf)
262 // program streams should start with a PACK then a SYS header.
263 return check_ps_sync(buf) && check_ps_sys(buf);
266 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
268 // DVD program streams should have a Pack header every 2048 bytes.
269 // check that we have 4 of these in a row.
270 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
271 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
274 static int hb_stream_get_type(hb_stream_t *stream)
278 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
281 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
283 int offset = psize >> 8;
285 hb_log("file is MPEG Transport Stream with %d byte packets"
286 " offset %d bytes", psize, offset);
287 stream->packetsize = psize;
288 stream->hb_stream_type = transport;
289 hb_ts_stream_init(stream);
292 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
294 hb_log("file is MPEG DVD Program Stream");
295 stream->hb_stream_type = dvd_program;
298 if ( hb_stream_check_for_ps(buf) != 0 )
300 hb_log("file is MPEG Program Stream");
301 stream->hb_stream_type = program;
308 static void hb_stream_delete_dynamic( hb_stream_t *d )
312 fclose( d->file_handle );
313 d->file_handle = NULL;
320 free( d->ts_packet );
323 for (i = 0; i < kMaxNumberDecodeStreams; i++)
333 static void hb_stream_delete( hb_stream_t *d )
335 hb_stream_delete_dynamic( d );
340 /***********************************************************************
342 ***********************************************************************
344 **********************************************************************/
345 hb_stream_t * hb_stream_open( char *path, int opentype )
348 FILE *f = fopen( path, "r" );
351 hb_log( "hb_stream_open: open %s failed", path );
355 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
359 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
364 * if we're opening the stream to read & convert, we need
365 * the state we saved when we scanned the stream. if we're
366 * opening the stream to scan it we want to rebuild the state
367 * (even if we have saved state, the stream may have changed).
369 hb_stream_t *ss = hb_stream_lookup( path );
372 /* opening to read - we must have saved state */
375 hb_log( "hb_stream_open: error: re-opening %s but no scan state", path );
381 * copy the saved state since we might be encoding the same stream
384 memcpy( d, ss, sizeof(*d) );
386 d->opentype = opentype;
387 d->path = strdup( path );
389 if ( d->hb_stream_type == transport )
391 d->ts_packet = malloc( d->packetsize );
394 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
396 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
398 hb_stream_seek( d, 0. );
404 * opening for scan - delete any saved state then (re)scan the stream.
405 * If it's something we can deal with (MPEG2 PS or TS) return a stream
406 * reference structure & null otherwise.
410 hb_stream_state_delete( ss );
413 d->opentype = opentype;
414 d->path = strdup( path );
415 if (d->path != NULL && hb_stream_get_type( d ) != 0 )
419 fclose( d->file_handle );
424 hb_log( "hb_stream_open: open %s failed", path );
429 /***********************************************************************
431 ***********************************************************************
432 * Closes and frees everything
433 **********************************************************************/
434 void hb_stream_close( hb_stream_t ** _d )
436 hb_stream_t *stream = * _d;
437 if ( stream->frames )
439 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
440 stream->errors, (double)stream->errors * 100. /
441 (double)stream->frames );
444 * if the stream was opened for a scan, cache the result, otherwise delete
447 if ( stream->opentype == 0 )
449 hb_stream_delete_dynamic( stream );
450 if ( stream_state_list == NULL )
452 stream_state_list = hb_list_init();
454 hb_list_add( stream_state_list, stream );
458 hb_stream_delete( stream );
463 /* when the file was first opened we made entries for all the audio elementary
464 * streams we found in it. Streams that were later found during the preview scan
465 * now have an audio codec, type, rate, etc., associated with them. At the end
466 * of the scan we delete all the audio entries that weren't found by the scan
467 * or don't have a format we support. This routine deletes audio entry 'indx'
468 * by copying all later entries down one slot. */
469 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
473 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
475 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
476 stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
477 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
480 --stream->ts_number_audio_pids;
483 static int index_of_pid(int pid, hb_stream_t *stream)
487 if ( pid == stream->ts_video_pids[0] )
490 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
491 if ( pid == stream->ts_audio_pids[i] )
497 /***********************************************************************
498 * hb_ps_stream_title_scan
499 ***********************************************************************
501 **********************************************************************/
502 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
505 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
508 // Copy part of the stream path to the title name
509 char *sep = strrchr(stream->path, '/');
511 strcpy(aTitle->name, sep+1);
512 char *dot_term = strrchr(aTitle->name, '.');
516 // Height, width, rate and aspect ratio information is filled in when the previews are built
518 hb_stream_duration(stream, aTitle);
521 hb_chapter_t * chapter;
522 chapter = calloc( sizeof( hb_chapter_t ), 1 );
524 chapter->duration = aTitle->duration;
525 chapter->hours = aTitle->hours;
526 chapter->minutes = aTitle->minutes;
527 chapter->seconds = aTitle->seconds;
528 hb_list_add( aTitle->list_chapter, chapter );
530 // Figure out how many audio streams we really have:
531 // - For transport streams, for each PID listed in the PMT (whether
532 // or not it was an audio stream type) read the bitstream until we
533 // find an packet from that PID containing a PES header and see if
534 // the elementary stream is an audio type.
535 // - For program streams read the first 4MB and take every unique
536 // audio stream we find.
537 if (stream->hb_stream_type == transport)
541 for (i=0; i < stream->ts_number_audio_pids; i++)
543 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
544 if (audio->config.in.codec)
545 hb_list_add( aTitle->list_audio, audio );
549 hb_stream_delete_audio_entry(stream, i);
554 // add the PCR PID if we don't already have it
555 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
557 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
558 stream->pmt_info.PCR_PID;
563 hb_ps_stream_find_audio_ids(stream, aTitle);
570 * read the next transport stream packet from 'stream'. Return NULL if
571 * we hit eof & a pointer to the sync byte otherwise.
573 static const uint8_t *next_packet( hb_stream_t *stream )
575 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
579 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
588 // lost sync - back up to where we started then try to re-establish.
589 off_t pos = ftello(stream->file_handle) - stream->packetsize;
590 off_t pos2 = align_to_next_packet(stream);
593 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
596 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
602 * skip to the start of the next PACK header in program stream src_stream.
604 static void skip_to_next_pack( hb_stream_t *src_stream )
606 // scan forward until we find the start of the next pack
607 uint32_t strt_code = -1;
610 flockfile( src_stream->file_handle );
611 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
613 strt_code = ( strt_code << 8 ) | c;
614 if ( strt_code == 0x000001ba )
615 // we found the start of the next pack
618 funlockfile( src_stream->file_handle );
620 // if we didn't terminate on an eof back up so the next read
621 // starts on the pack boundary.
624 fseeko( src_stream->file_handle, -4, SEEK_CUR );
629 * scan the next MB of 'stream' to find the next start packet for
630 * the Packetized Elementary Stream associated with TS PID 'pid'.
632 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
634 int npack = 100000; // max packets to read
638 const uint8_t *buf = next_packet( stream );
641 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
646 * The PES header is only in TS packets with 'start' set so we check
647 * that first then check for the right PID.
649 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
650 buf[2] != (pid & 0xff))
652 // not a start packet or not the pid we want
656 /* skip over the TS hdr to return a pointer to the PES hdr */
658 switch (buf[3] & 0x30)
660 case 0x00: // illegal
661 case 0x20: // fill packet
664 case 0x30: // adaptation
667 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
680 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
682 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
683 hb_list_t *list = hb_list_init();
684 // how many blocks we read while searching for a video PES header
688 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
692 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
693 hb_demux_ps( buf, list, 0 );
695 while ( ( es = hb_list_item( list, 0 ) ) )
697 hb_list_rem( list, es );
698 if ( es->id == 0xe0 )
700 // this PES contains video - if there's a PTS we're done
701 // hb_demux_ps left the PTS in buf_es->start.
702 if ( es->start != ~0 )
709 hb_buffer_close( &es );
712 hb_list_empty( &list );
713 hb_buffer_close(&buf);
717 /***********************************************************************
719 ***********************************************************************
721 * Finding stream duration is difficult. One issue is that the video file
722 * may have chunks from several different program fragments (main feature,
723 * commercials, station id, trailers, etc.) all with their own base pts
724 * value. We can't find the piece boundaries without reading the entire
725 * file but if we compute a rate based on time stamps from two different
726 * pieces the result will be meaningless. The second issue is that the
727 * data rate of compressed video normally varies by 5-10x over the length
728 * of the video. This says that we want to compute the rate over relatively
729 * long segments to get a representative average but long segments increase
730 * the likelihood that we'll cross a piece boundary.
732 * What we do is take time stamp samples at several places in the file
733 * (currently 16) then compute the average rate (i.e., ticks of video per
734 * byte of the file) for all pairs of samples (N^2 rates computed for N
735 * samples). Some of those rates will be absurd because the samples came
736 * from different segments. Some will be way low or high because the
737 * samples came from a low or high motion part of the segment. But given
738 * that we're comparing *all* pairs the majority of the computed rates
739 * should be near the overall average. So we median filter the computed
740 * rates to pick the most representative value.
742 **********************************************************************/
744 uint64_t pos; /* file position of this PTS sample */
745 uint64_t pts; /* PTS from video stream */
748 #define NDURSAMPLES 16
750 // get one (position, timestamp) sampple from a transport or program
752 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
754 struct pts_pos pp = { 0, 0 };
756 if ( stream->hb_stream_type == transport )
759 fseeko( stream->file_handle, fpos, SEEK_SET );
760 align_to_next_packet( stream );
761 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
764 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
767 if ( ( buf[7] >> 7 ) != 1 )
769 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
772 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
773 ( (uint64_t)buf[10] << 22 ) |
774 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
775 ( (uint64_t)buf[12] << 7 ) |
776 ( (uint64_t)buf[13] >> 1 );
780 // round address down to nearest dvd sector start
781 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
782 fseeko( stream->file_handle, fpos, SEEK_SET );
783 if ( stream->hb_stream_type == program )
785 skip_to_next_pack( stream );
787 pp.pts = hb_ps_stream_getVideoPTS( stream );
789 pp.pos = ftello(stream->file_handle);
793 static int dur_compare( const void *a, const void *b )
795 const double *aval = a, *bval = b;
796 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
799 // given an array of (position, time) samples, compute a max-likelihood
800 // estimate of the average rate by computing the rate between all pairs
801 // of samples then taking the median of those rates.
802 static double compute_stream_rate( struct pts_pos *pp, int n )
805 double rates[NDURSAMPLES * NDURSAMPLES / 2];
808 // the following nested loops compute the rates between all pairs.
810 for ( i = 0; i < n-1; ++i )
812 // Bias the median filter by not including pairs that are "far"
813 // from one another. This is to handle cases where the file is
814 // made of roughly equal size pieces where a symmetric choice of
815 // pairs results in having the same number of intra-piece &
816 // inter-piece rate estimates. This would mean that the median
817 // could easily fall in the inter-piece part of the data which
818 // would give a bogus estimate. The 'ns' index creates an
819 // asymmetry that favors locality.
820 int ns = i + ( n >> 1 );
823 for ( j = i+1; j < ns; ++j )
825 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
827 *rp = ((double)( pp[j].pts - pp[i].pts )) /
828 ((double)( pp[j].pos - pp[i].pos ));
833 // now compute and return the median of all the (n*n/2) rates we computed
835 int nrates = rp - rates;
836 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
837 return rates[nrates >> 1];
840 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
842 struct pts_pos ptspos[NDURSAMPLES];
843 struct pts_pos *pp = ptspos;
846 fseeko(stream->file_handle, 0, SEEK_END);
847 uint64_t fsize = ftello(stream->file_handle);
848 uint64_t fincr = fsize / NDURSAMPLES;
849 uint64_t fpos = fincr / 2;
850 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
852 *pp++ = hb_sample_pts(stream, fpos);
854 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
855 inTitle->duration = dur;
857 inTitle->hours = dur / 3600;
858 inTitle->minutes = ( dur % 3600 ) / 60;
859 inTitle->seconds = dur % 60;
861 rewind(stream->file_handle);
864 /***********************************************************************
866 ***********************************************************************
868 **********************************************************************/
869 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
871 if ( src_stream->hb_stream_type == dvd_program )
873 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
874 src_stream->file_handle);
875 return (amt_read > 0);
877 if ( src_stream->hb_stream_type == program )
879 // a general program stream has arbitrary sized pack's. we're
880 // currently positioned at the start of a pack so read up to but
881 // not including the start of the next, expanding the buffer
883 uint8_t *cp = b->data;
884 uint8_t *ep = cp + b->alloc;
885 uint32_t strt_code = -1;
888 // consume the first byte of the initial pack so we don't match on
889 // it in the loop below.
890 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
895 flockfile( src_stream->file_handle );
896 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
898 strt_code = ( strt_code << 8 ) | c;
899 if ( strt_code == 0x000001ba )
900 // we found the start of the next pack
904 // need to expand the buffer
905 int curSize = cp - b->data;
906 hb_buffer_realloc( b, curSize * 2 );
907 cp = b->data + curSize;
908 ep = b->data + b->alloc;
912 funlockfile( src_stream->file_handle );
914 // if we didn't terminate on an eof back up so the next read
915 // starts on the pack boundary.
916 b->size = cp - b->data;
919 fseeko( src_stream->file_handle, -4, SEEK_CUR );
924 return hb_ts_stream_decode( src_stream, b->data );
927 /***********************************************************************
929 ***********************************************************************
931 **********************************************************************/
932 int hb_stream_seek( hb_stream_t * src_stream, float f )
934 off_t stream_size, cur_pos, new_pos;
935 double pos_ratio = f;
936 cur_pos = ftello( src_stream->file_handle );
937 fseeko( src_stream->file_handle, 0, SEEK_END );
938 stream_size = ftello( src_stream->file_handle );
939 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
940 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
942 int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
945 fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
949 if ( src_stream->hb_stream_type == transport )
951 // We need to drop the current decoder output and move
952 // forwards to the next transport stream packet.
953 hb_ts_stream_reset(src_stream);
955 else if ( src_stream->hb_stream_type == program )
957 skip_to_next_pack( src_stream );
963 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
966 * This is a duplicate of code in dvd.c - it should get factored out
967 * into a common routine. We probably should only be putting the lang
968 * code or a lang pointer into the audio config & let the common description
969 * formatting routine in scan.c do all the stuff below.
971 snprintf( audio->config.lang.description,
972 sizeof( audio->config.lang.description ), "%s (%s)",
973 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
974 audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
975 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
976 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : "LPCM" );
977 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
978 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
979 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
980 "%s", lang->iso639_2);
983 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
986 off_t cur_pos = ftello(stream->file_handle);
987 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
990 fseeko(stream->file_handle, 0, SEEK_SET);
991 align_to_next_packet(stream);
992 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
994 /* check that we found a PES header */
995 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
999 audio->id = 0x80bd | (aud_pid_index << 8);
1000 audio->config.in.codec = HB_ACODEC_AC3;
1001 hb_log("transport stream pid 0x%x (type 0x%x) is AC-3 audio id 0x%x",
1002 stream->ts_audio_pids[aud_pid_index],
1003 stream->ts_stream_type[1 + aud_pid_index],
1005 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1006 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1008 else if (buf[3] == 0xfd)
1010 /* XXX Extended stream id (ISO 13818-1(2000) Amd 2) - we have to look
1011 * inside the PES extension to find out the real stream id then
1012 * figure out what the heck it means. For now we just use the stream
1013 * type if one was specified. */
1014 const char *atype = 0;
1015 switch (stream->ts_stream_type[1 + aud_pid_index])
1019 audio->config.in.codec = HB_ACODEC_AC3;
1021 case 0x82: // HDMV DTS
1024 audio->config.in.codec = HB_ACODEC_DCA;
1028 audio->config.in.codec = HB_ACODEC_LPCM;
1031 audio->id = 0x80bd | (aud_pid_index << 8);
1032 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1033 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1034 stream->ts_audio_pids[aud_pid_index],
1035 stream->ts_stream_type[1 + aud_pid_index], atype, audio->id);
1037 else if ((buf[3] & 0xe0) == 0xc0)
1039 audio->id = buf[3] | aud_pid_index;
1040 audio->config.in.codec = HB_ACODEC_MPGA;
1041 hb_log("transport stream pid 0x%x (type 0x%x) is MPEG audio id 0x%x",
1042 stream->ts_audio_pids[aud_pid_index],
1043 stream->ts_stream_type[1 + aud_pid_index],
1045 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1046 stream->ts_streamid[1 + aud_pid_index] = buf[3];
1049 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1050 if ( audio->config.in.codec )
1052 set_audio_description( audio,
1053 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1057 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1058 stream->ts_audio_pids[aud_pid_index],
1059 stream->ts_stream_type[1 + aud_pid_index]);
1064 static void add_audio_to_title(hb_title_t *title, int id)
1066 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1072 audio->config.in.codec = HB_ACODEC_MPGA;
1073 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1076 // type 2 is a DVD subtitle stream - just ignore it */
1080 audio->config.in.codec = HB_ACODEC_AC3;
1081 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1084 audio->config.in.codec = HB_ACODEC_LPCM;
1085 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1088 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1093 set_audio_description( audio, lang_for_code( 0 ) );
1094 hb_list_add( title->list_audio, audio );
1097 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1099 off_t cur_pos = ftello(stream->file_handle);
1100 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1101 hb_list_t *list = hb_list_init();
1102 // how many blocks we read while searching for audio streams
1103 int blksleft = 4096;
1104 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1105 // so we use a bitmap to keep track of the ones we've already seen.
1106 // Bit 'i' of smap is set if we've already added the audio for
1107 // audio substream id 'i' to the title's audio list.
1110 // start looking 20% into the file since there's occasionally no
1111 // audio at the beginning (particularly for vobs).
1112 hb_stream_seek(stream, 0.2f);
1114 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1118 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1119 hb_demux_ps( buf, list, 0 );
1121 while ( ( es = hb_list_item( list, 0 ) ) )
1123 hb_list_rem( list, es );
1124 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1126 // this PES contains some kind of audio - get the substream id
1127 // and check if we've seen it already.
1128 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1129 if ( (smap & (1 << ssid)) == 0 )
1131 // we haven't seen this stream before - add it to the
1132 // title's list of audio streams.
1133 smap |= (1 << ssid);
1134 add_audio_to_title(title, es->id);
1137 hb_buffer_close( &es );
1140 hb_list_empty( &list );
1141 hb_buffer_close(&buf);
1142 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1145 /***********************************************************************
1147 ***********************************************************************
1149 **********************************************************************/
1151 static void hb_ts_stream_init(hb_stream_t *stream)
1155 for (i=0; i < kMaxNumberDecodeStreams; i++)
1157 stream->ts_streamcont[i] = -1;
1159 stream->ts_video_pids[0] = -1;
1160 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1162 stream-> ts_audio_pids[i] = -1;
1165 stream->ts_packet = malloc( stream->packetsize );
1167 // Find the audio and video pids in the stream
1168 hb_ts_stream_find_pids(stream);
1170 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1172 // demuxing buffer for TS to PS conversion
1173 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1176 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
1179 #define MAX_HOLE 208*80
1181 static off_t align_to_next_packet(hb_stream_t *stream)
1183 uint8_t buf[MAX_HOLE];
1185 off_t start = ftello(stream->file_handle);
1187 if ( start >= stream->packetsize ) {
1188 start -= stream->packetsize;
1189 fseeko(stream->file_handle, start, SEEK_SET);
1192 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1194 const uint8_t *bp = buf;
1197 for ( i = sizeof(buf); --i >= 0; ++bp )
1199 if ( have_ts_sync( bp, stream->packetsize ) )
1206 pos = ( bp - buf ) - stream->packetsize + 188;
1211 fseeko(stream->file_handle, start+pos, SEEK_SET);
1222 static const unsigned int bitmask[] = {
1223 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1224 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1225 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1226 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1228 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1232 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1233 (bb->buf[2] << 8) | bb->buf[3];
1235 memset(bb->buf, 0, bufsize);
1238 static inline int buf_size(bitbuf_t *bb)
1240 return bb->pos >> 3;
1243 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1246 int left = 32 - (bb->pos & 31);
1250 val = (bb->val >> (left - bits)) & bitmask[bits];
1255 val = (bb->val & bitmask[left]) << (bits - left);
1259 int pos = bb->pos >> 3;
1260 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1264 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1272 // extract what useful information we can from the elementary stream
1273 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1274 // Descriptors with info we don't currently use are ignored.
1275 // The descriptor list & descriptor item formats are defined in
1276 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1277 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1278 const uint8_t *dp, uint8_t dlen)
1280 const uint8_t *ep = dp + dlen;
1286 case 10: // ISO_639_language descriptor
1287 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1297 static const char * stream_type_name (uint8_t stream_type)
1299 switch( stream_type )
1301 case 0x01: return("ISO 11172 (MPEG1) Video");
1302 case 0x02: return("ISO 13818-2 (MPEG2) Video");
1303 case 0x03: return("ISO 11172 (MPEG1) Audio");
1304 case 0x04: return("ISO 13818-3 (MPEG2) Audio");
1305 case 0x05: return("ISO 13818-1 private section");
1306 case 0x06: return("ISO 13818-1 PES private data");
1307 case 0x07: return("ISO 13522 MHEG");
1308 case 0x08: return("ISO 13818-1 DSM-CC");
1309 case 0x09: return("ISO 13818-1 auxiliary");
1310 case 0x0a: return("ISO 13818-6 multi-protocol encap");
1311 case 0x0b: return("ISO 13818-6 DSM-CC U-N msgs");
1312 case 0x0c: return("ISO 13818-6 Stream descriptors");
1313 case 0x0d: return("ISO 13818-6 Sections");
1314 case 0x0e: return("ISO 13818-1 auxiliary");
1315 case 0x0f: return("ISO 13818-7 AAC Audio");
1316 case 0x10: return("MPEG4 Video");
1317 case 0x11: return("MPEG4 Audio");
1318 case 0x12: return("MPEG4 generic");
1320 case 0x14: return("ISO 13818-6 DSM-CC download");
1322 case 0x1b: return("H.264 Video");
1324 case 0x80: return("DigiCipher II Video");
1325 case 0x81: return("A52/AC-3 Audio");
1326 case 0x82: return("HDMV DTS Audio");
1327 case 0x83: return("LPCM Audio");
1328 case 0x84: return("SDDS Audio");
1329 case 0x85: return("ATSC Program ID");
1330 case 0x86: return("SCTE 35 splice info");
1331 case 0x87: return("ATSC E-AC-3");
1333 case 0x8a: return("DTS Audio");
1335 case 0x91: return("A52b/AC-3 Audio");
1336 case 0x92: return("Subtitle");
1338 case 0x94: return("SDDS Audio");
1339 case 0xa0: return("MSCODEC Video");
1341 case 0xea: return("VC-1 Video");
1343 default: return("Unknown");
1347 int decode_program_map(hb_stream_t* stream)
1350 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1352 get_bits(&bb, 8); // table_id
1354 unsigned int section_length = get_bits(&bb, 12);
1355 stream->pmt_info.section_length = section_length;
1357 unsigned int program_number = get_bits(&bb, 16);
1358 stream->pmt_info.program_number = program_number;
1360 get_bits(&bb, 5); // version_number
1362 get_bits(&bb, 8); // section_number
1363 get_bits(&bb, 8); // last_section_number
1365 unsigned int PCR_PID = get_bits(&bb, 13);
1366 stream->pmt_info.PCR_PID = PCR_PID;
1368 unsigned int program_info_length = get_bits(&bb, 12);
1369 stream->pmt_info.program_info_length = program_info_length;
1372 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1373 for (i = 0; i < program_info_length; i++)
1375 descriptor_buf[i] = get_bits(&bb, 8);
1378 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1379 int done_reading_stream_types = 0;
1380 while (!done_reading_stream_types)
1382 unsigned char stream_type = get_bits(&bb, 8);
1384 unsigned int elementary_PID = get_bits(&bb, 13);
1386 unsigned int ES_info_length = get_bits(&bb, 12);
1389 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1390 for (i=0; i < ES_info_length; i++)
1392 ES_info_buf[i] = get_bits(&bb, 8);
1396 if (stream->ts_number_video_pids == 0 &&
1397 ( stream_type == 0x02 || stream_type == 0x10 || stream_type == 0x1B ) )
1399 stream->ts_video_pids[0] = elementary_PID;
1400 stream->ts_stream_type[0] = stream_type;
1401 stream->ts_number_video_pids = 1;
1405 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1406 // for mpeg audio. But content producers seem to use other
1407 // values (0x04 and 0x06 have both been observed) so at this point
1408 // we say everything that isn't a video pid is audio then at the end
1409 // of hb_stream_title_scan we'll figure out which are really audio
1410 // by looking at the PES headers.
1411 i = stream->ts_number_audio_pids;
1412 if (i < kMaxNumberAudioPIDS)
1414 stream->ts_audio_pids[i] = elementary_PID;
1415 stream->ts_stream_type[1 + i] = stream_type;
1416 if (ES_info_length > 0)
1418 decode_element_descriptors(stream, i, ES_info_buf,
1421 ++stream->ts_number_audio_pids;
1425 cur_pos += 5 /* stream header */ + ES_info_length;
1429 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1430 done_reading_stream_types = 1;
1433 free(descriptor_buf);
1437 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1439 // Get adaption header info
1441 int adaption = (buf[3] & 0x30) >> 4;
1444 else if (adaption == 0x2)
1446 else if (adaption == 0x3)
1447 adapt_len = buf[4] + 1;
1448 if (adapt_len > 184)
1451 // Get payload start indicator
1453 start = (buf[1] & 0x40) != 0;
1455 // Get pointer length - only valid in packets with a start flag
1456 int pointer_len = 0;
1457 if (start && stream->pmt_info.reading)
1459 // We just finished a bunch of packets - parse the program map details
1461 if (stream->pmt_info.tablebuf[0] == 0x02)
1462 decode_ok = decode_program_map(stream);
1463 free(stream->pmt_info.tablebuf);
1464 stream->pmt_info.tablebuf = NULL;
1465 stream->pmt_info.tablepos = 0;
1466 stream->pmt_info.reading = 0;
1473 pointer_len = buf[4 + adapt_len] + 1;
1474 stream->pmt_info.tablepos = 0;
1476 // Get Continuity Counter
1477 int continuity_counter = buf[3] & 0x0f;
1478 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1480 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1483 stream->pmt_info.current_continuity_counter = continuity_counter;
1484 stream->pmt_info.reading |= start;
1486 // Add the payload for this packet to the current buffer
1487 int amount_to_copy = 184 - adapt_len - pointer_len;
1488 if (stream->pmt_info.reading && (amount_to_copy > 0))
1490 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1492 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1493 stream->pmt_info.tablepos += amount_to_copy;
1499 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1501 unsigned char tablebuf[1024];
1502 unsigned int tablepos = 0;
1507 // Get adaption header info
1509 int adaption = (buf[3] & 0x30) >> 4;
1512 else if (adaption == 0x2)
1514 else if (adaption == 0x3)
1515 adapt_len = buf[4] + 1;
1516 if (adapt_len > 184)
1519 // Get pointer length
1520 int pointer_len = buf[4 + adapt_len] + 1;
1522 // Get payload start indicator
1524 start = (buf[1] & 0x40) != 0;
1529 // Add the payload for this packet to the current buffer
1530 if (reading && (184 - adapt_len) > 0)
1532 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1534 hb_log("decode_PAT - Bad program section length (> 1024)");
1537 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1538 tablepos += 184 - adapt_len - pointer_len;
1541 if (start && reading)
1543 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1546 unsigned int pos = 0;
1547 //while (pos < tablepos)
1550 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1552 unsigned char section_id = get_bits(&bb, 8);
1554 unsigned int section_len = get_bits(&bb, 12);
1555 get_bits(&bb, 16); // transport_id
1557 get_bits(&bb, 5); // version_num
1558 get_bits(&bb, 1); // current_next
1559 get_bits(&bb, 8); // section_num
1560 get_bits(&bb, 8); // last_section
1566 // Program Association Section
1567 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1568 section_len -= 4; // Ignore the CRC
1570 stream->ts_number_pat_entries = 0;
1571 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1573 unsigned int pkt_program_num = get_bits(&bb, 16);
1574 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1576 get_bits(&bb, 3); // Reserved
1577 if (pkt_program_num == 0)
1579 get_bits(&bb, 13); // pkt_network_id
1583 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1584 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1587 stream->ts_number_pat_entries++;
1601 pos += 3 + section_len;
1609 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1611 // align to first packet
1612 align_to_next_packet(stream);
1614 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1615 // to find the program map PID and then decode that to get the list of audio and video PIDs
1619 const uint8_t *buf = next_packet( stream );
1622 hb_log("hb_ts_stream_find_pids - end of file");
1627 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1629 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1631 decode_PAT(buf, stream);
1636 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1638 // There are some streams where the PAT table has multiple entries as if their are
1639 // multiple programs in the same transport stream, and yet there's actually only one
1640 // program really in the stream. This seems to be true for transport streams that
1641 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1642 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1643 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1644 // PAT info on export to match what's actually on the stream.
1645 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1646 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1647 // be to build a title choice popup from the PAT program number details and then select from
1648 // their - but right now the API's not capable of that.
1649 if (pid == stream->pat_info[pat_index].program_map_PID)
1651 if (build_program_map(buf, stream) > 0)
1655 // Keep going until we have a complete set of PIDs
1656 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1660 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1661 hb_log(" Video PIDS : ");
1663 for (i=0; i < stream->ts_number_video_pids; i++)
1665 hb_log( " 0x%x type %s (0x%x)",
1666 stream->ts_video_pids[i],
1667 stream_type_name(stream->ts_stream_type[i]),
1668 stream->ts_stream_type[i]);
1670 hb_log(" Audio PIDS : ");
1671 for (i = 0; i < stream->ts_number_audio_pids; i++)
1673 hb_log( " 0x%x type %s (0x%x)",
1674 stream->ts_audio_pids[i],
1675 stream_type_name(stream->ts_stream_type[i+1]),
1676 stream->ts_stream_type[i+1] );
1681 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1683 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1685 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1686 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1689 memcpy( stream->fwrite_buf, buf, size );
1690 stream->fwrite_buf += size;
1693 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1697 buf[0] = 0x00; // pack id
1702 buf[4] = 0x44 | // SCR
1703 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1704 ( ( time >> 28 ) & 3 );
1705 buf[5] = time >> 20;
1707 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1708 ( ( time >> 13 ) & 3 );
1710 buf[8] = 0x04 | ( time << 3 );
1712 buf[9] = 0x01; // SCR extension
1714 buf[10] = 384000 >> (22 - 8); // program mux rate
1715 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1716 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1718 buf[13] = 0xf8 | stuffing;
1721 for (i = 0; i < stuffing; ++i )
1724 fwrite64(stream, buf, 14 + stuffing );
1727 static void pad_buffer(hb_stream_t* stream, int pad)
1739 fwrite64(stream, buf, 6);
1742 while ( --pad >= 0 )
1744 fwrite64(stream, buf, 1);
1748 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1752 memset(buf, 0, sizeof(buf) );
1755 buf[4] = ( len + 3 ) >> 8;
1759 fwrite64(stream, buf, 9);
1762 static void generate_output_data(hb_stream_t *stream, int curstream)
1764 uint8_t *tdat = stream->ts_buf[curstream];
1767 // we always ship a PACK header plus all the data in our demux buf.
1768 // AC3 audio also always needs it substream header.
1769 len = 14 + stream->ts_pos[curstream];
1770 if ( stream->ts_stream_type[curstream] == 0x81)
1775 if ( ! stream->ts_start[curstream] )
1777 // we're in the middle of a chunk of PES data - we need to add
1778 // a 'continuation' PES header after the PACK header.
1782 // Write out pack header
1783 // If we don't have 2048 bytes we need to pad to 2048. We can
1784 // add a padding frame after our data but we need at least 7
1785 // bytes of space to do it (6 bytes of header & 1 of pad). If
1786 // we have fewer than 7 bytes left we need to fill the excess
1787 // space with stuffing bytes added to the pack header.
1789 if ( len > HB_DVD_READ_BUFFER_SIZE )
1791 hb_log( "stream ts length botch %d", len );
1793 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1795 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1797 write_pack(stream, stream->ts_nextpcr, stuffing );
1798 stream->ts_nextpcr += 10;
1800 if ( stream->ts_start[curstream] )
1802 // Start frames already have a PES header but we have modify it
1803 // to map from TS PID to PS stream id. Also, if the stream is AC3
1804 // audio we have to insert an AC3 stream header between the end of
1805 // the PES header and the start of the stream data.
1807 stream->ts_start[curstream] = 0;
1808 tdat[3] = stream->ts_streamid[curstream];
1810 uint16_t plen = stream->ts_pos[curstream] - 6;
1811 if ( stream->ts_stream_type[curstream] == 0x81)
1813 // We have to add an AC3 header in front of the data. Add its
1814 // size to the PES packet length.
1816 tdat[4] = plen >> 8;
1819 // Write out the PES header
1820 int hdrsize = 9 + tdat[8];
1821 fwrite64(stream, tdat, hdrsize);
1823 // add a four byte DVD ac3 stream header
1824 uint8_t ac3_substream_id[4];
1825 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1826 ac3_substream_id[0] = 0x80 | ssid; // substream id
1827 ac3_substream_id[1] = 0x01; // number of sync words
1828 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1829 ac3_substream_id[3] = 0x02;
1830 fwrite64(stream, ac3_substream_id, 4);
1832 // add the rest of the data
1833 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1837 // not audio - don't need to modify the stream so write what we've got
1838 tdat[4] = plen >> 8;
1840 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1845 // data without a PES start header needs a simple 'continuation'
1846 // PES header. AC3 audio also needs its substream header.
1847 if ( stream->ts_stream_type[curstream] != 0x81)
1849 make_pes_header(stream, stream->ts_pos[curstream],
1850 stream->ts_streamid[curstream]);
1854 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1855 stream->ts_streamid[curstream]);
1857 // add a four byte DVD ac3 stream header
1858 uint8_t ac3_substream_id[4];
1859 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1860 ac3_substream_id[0] = 0x80 | ssid; // substream id
1861 ac3_substream_id[1] = 0x01; // number of sync words
1862 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1863 ac3_substream_id[3] = 0x02;
1864 fwrite64(stream, ac3_substream_id, 4);
1866 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1870 int left = HB_DVD_READ_BUFFER_SIZE - len;
1873 pad_buffer(stream, left);
1876 stream->ts_pos[curstream] = 0;
1879 static int isIframe( const uint8_t *buf, int adapt_len )
1881 // Look for the Group of Pictures packet
1885 for (i = 4 + adapt_len; i < 188; i++)
1887 strid = (strid << 8) | buf[i];
1890 case 0x000001B8: // group_start_code (GOP header)
1891 case 0x000001B3: // sequence_header code
1894 case 0x00000100: // picture_start_code
1895 // picture_header, let's see if it's an I-frame
1898 // check if picture_coding_type == 1
1899 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1901 // found an I-frame picture
1908 // didn't find an I frame
1912 /***********************************************************************
1913 * hb_ts_stream_decode
1914 ***********************************************************************
1916 **********************************************************************/
1917 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
1920 * stash the output buffer pointer in our stream so we don't have to
1921 * pass it & its original value to everything we call.
1923 stream->fwrite_buf = obuf;
1924 stream->fwrite_buf_orig = obuf;
1926 // spin until we get a packet of data from some stream or hit eof
1929 int64_t pcr = stream->ts_lastpcr;
1932 const uint8_t *buf = next_packet(stream);
1935 // end of file - we didn't finish filling our ps write buffer
1936 // so just discard the remainder (the partial buffer is useless)
1937 hb_log("hb_ts_stream_decode - eof");
1941 /* This next section validates the packet */
1943 // Get pid and use it to find stream state.
1944 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
1945 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
1949 int errorbit = (buf[1] & 0x80) != 0;
1952 ts_err( stream, curstream, "packet error bit set");
1956 // Get adaption header info
1957 int adaption = (buf[3] & 0x30) >> 4;
1961 ts_err( stream, curstream, "adaptation code 0");
1964 else if (adaption == 0x2)
1966 else if (adaption == 0x3)
1968 adapt_len = buf[4] + 1;
1969 if (adapt_len > 184)
1971 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
1976 // if there's an adaptation header & PCR_flag is set
1977 // get the PCR (Program Clock Reference)
1978 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
1980 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
1981 ( (uint64_t)buf[7] << (33 - 16) ) |
1982 ( (uint64_t)buf[8] << (33 - 24) ) |
1983 ( (uint64_t)buf[9] << (33 - 32) ) |
1985 stream->ts_nextpcr = pcr;
1987 // remember the pcr across calls to this routine
1988 stream->ts_lastpcr = pcr;
1993 // don't accumulate data until we get a pcr
1998 // Continuity only increments for adaption values of 0x3 or 0x01
1999 // and is not checked for start packets.
2001 int start = (buf[1] & 0x40) != 0;
2003 if ( (adaption & 0x01) != 0 )
2005 int continuity = (buf[3] & 0xF);
2006 if ( continuity == stream->ts_streamcont[curstream] )
2008 // we got a duplicate packet (usually used to introduce
2009 // a PCR when one is needed). The only thing that can
2010 // change in the dup is the PCR which we grabbed above
2011 // so ignore the rest.
2014 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2015 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2017 ts_err( stream, curstream, "continuity error: got %d expected %d",
2019 (stream->ts_streamcont[curstream] + 1) & 0xf );
2020 stream->ts_streamcont[curstream] = continuity;
2023 stream->ts_streamcont[curstream] = continuity;
2026 /* If we get here the packet is valid - process its data */
2030 // Found a random access point (now we can start a frame/audio packet..)
2032 // If we were skipping a bad packet, start fresh on this new PES packet..
2033 if (stream->ts_skipbad[curstream] == 1)
2035 // video skips to an iframe after a bad packet to minimize
2036 // screen corruption
2037 if ( curstream == 0 && !isIframe( buf, adapt_len ) )
2041 stream->ts_skipbad[curstream] = 0;
2044 // If we don't have video yet, check to see if this is an
2045 // i_frame (group of picture start)
2046 if ( curstream == 0 )
2048 if ( !stream->ts_foundfirst[0] )
2050 if ( stream->ts_stream_type[0] == 2 &&
2051 !isIframe( buf, adapt_len ) )
2053 // didn't find an I frame
2056 stream->ts_foundfirst[0] = 1;
2060 else if ( ! stream->ts_foundfirst[curstream] )
2062 // start other streams only after first video frame found.
2063 if ( ! stream->ts_foundfirst[0] )
2067 stream->ts_foundfirst[curstream] = 1;
2070 // If we have some data already on this stream, turn it into
2071 // a program stream packet. Then add the payload for this
2072 // packet to the current pid's buffer.
2073 if ( stream->ts_pos[curstream] )
2075 generate_output_data(stream, curstream);
2076 stream->ts_start[curstream] = 1;
2077 memcpy(stream->ts_buf[curstream],
2078 buf + 4 + adapt_len, 184 - adapt_len);
2079 stream->ts_pos[curstream] = 184 - adapt_len;
2082 stream->ts_start[curstream] = 1;
2085 // Add the payload for this packet to the current buffer
2086 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2087 (184 - adapt_len) > 0)
2089 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2090 buf + 4 + adapt_len, 184 - adapt_len);
2091 stream->ts_pos[curstream] += 184 - adapt_len;
2093 // if the next TS packet could possibly overflow our 2K output buffer
2094 // we need to generate a packet now. Overflow would be 184 bytes of
2095 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2096 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2098 // we have enough data to make a PS packet
2099 generate_output_data(stream, curstream);
2106 /***********************************************************************
2107 * hb_ts_stream_reset
2108 ***********************************************************************
2110 **********************************************************************/
2111 static void hb_ts_stream_reset(hb_stream_t *stream)
2115 for (i=0; i < kMaxNumberDecodeStreams; i++)
2117 stream->ts_pos[i] = 0;
2118 stream->ts_foundfirst[i] = 0;
2119 stream->ts_skipbad[i] = 0;
2120 stream->ts_streamcont[i] = -1;
2121 stream->ts_start[i] = 0;
2124 stream->ts_lastpcr = -1;
2125 stream->ts_nextpcr = -1;
2129 stream->last_error_frame = -10000;
2130 stream->last_error_count = 0;
2132 align_to_next_packet(stream);