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
16 hb_stream_type_unknown = 0,
17 hb_stream_type_transport,
18 hb_stream_type_program
21 #define kMaxNumberVideoPIDS 1
22 #define kMaxNumberAudioPIDS 15
23 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
24 #define kMaxNumberPMTStreams 32
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 uint8_t *ts_buf[kMaxNumberDecodeStreams];
38 int ts_pos[kMaxNumberDecodeStreams];
39 int8_t ts_foundfirst[kMaxNumberDecodeStreams];
40 int8_t ts_skipbad[kMaxNumberDecodeStreams];
41 int8_t ts_streamcont[kMaxNumberDecodeStreams];
42 int8_t ts_start[kMaxNumberDecodeStreams];
44 uint8_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
45 uint8_t *fwrite_buf_orig; /* PS buffer start (set by hb_ts_stream_decode) */
48 * Stuff before this point is dynamic state updated as we read the
49 * stream. Stuff after this point is stream description state that
50 * we learn during the initial scan but cache so it can be
51 * reused during the conversion read.
53 int16_t ts_video_pids[kMaxNumberVideoPIDS];
54 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
56 uint8_t ts_number_video_pids;
57 uint8_t ts_number_audio_pids;
59 uint8_t ts_streamid[kMaxNumberDecodeStreams];
60 uint8_t ts_audio_stream_type[kMaxNumberDecodeStreams];
64 hb_stream_type_t stream_type;
72 } a52_info[kMaxNumberAudioPIDS];
76 unsigned short program_number;
77 unsigned short program_map_PID;
78 } pat_info[kMaxNumberPMTStreams];
79 int ts_number_pat_entries;
84 unsigned char *tablebuf;
85 unsigned int tablepos;
86 unsigned char current_continuity_counter;
91 int program_info_length;
92 unsigned char *progam_info_descriptor_data;
95 unsigned char stream_type;
96 unsigned short elementary_PID;
97 unsigned short ES_info_length;
98 unsigned char *es_info_descriptor_data;
99 } pmt_stream_info[kMaxNumberPMTStreams];
103 /***********************************************************************
105 **********************************************************************/
106 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
107 static void hb_ts_stream_init(hb_stream_t *stream);
108 static void hb_ts_stream_find_pids(hb_stream_t *stream);
109 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
110 static void hb_ts_stream_reset(hb_stream_t *stream);
111 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
113 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
114 static off_t align_to_next_packet(FILE* f);
117 * streams have a bunch of state that's learned during the scan. We don't
118 * want to throw away the state when scan does a close then relearn
119 * everything when reader does an open. So we save the stream state on
120 * the close following a scan and reuse it when 'reader' does an open.
122 static hb_list_t *stream_state_list;
124 static hb_stream_t *hb_stream_lookup( const char *path )
126 if ( stream_state_list == NULL )
132 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
134 if ( strcmp( path, ss->path ) == 0 )
142 static void hb_stream_state_delete( hb_stream_t *ss )
144 hb_list_rem( stream_state_list, ss );
149 static inline int check_ps_sync(const uint8_t *buf)
151 // a legal MPEG program stream must start with a Pack header in the
153 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
154 (buf[2] == 0x01) && (buf[3] == 0xba);
157 static inline int check_ts_sync(const uint8_t *buf)
159 // must have initial sync byte, no scrambling & a legal adaptation ctrl
160 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
163 static inline int have_ts_sync(const uint8_t *buf)
165 return check_ts_sync(&buf[0*188]) && check_ts_sync(&buf[1*188]) &&
166 check_ts_sync(&buf[2*188]) && check_ts_sync(&buf[3*188]) &&
167 check_ts_sync(&buf[4*188]) && check_ts_sync(&buf[5*188]) &&
168 check_ts_sync(&buf[6*188]) && check_ts_sync(&buf[7*188]);
171 static int hb_stream_check_for_ts(const uint8_t *buf)
173 // transport streams should have a sync byte every 188 bytes.
174 // search the first KB of buf looking for at least 8 consecutive
175 // correctly located sync patterns.
178 for ( offset = 0; offset < 1024; ++offset )
180 if ( have_ts_sync( &buf[offset]) )
186 static int hb_stream_check_for_ps(const uint8_t *buf)
188 // program streams should have a Pack header every 2048 bytes.
189 // check that we have 4 of these.
190 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
191 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
194 static int hb_stream_get_type(hb_stream_t *stream)
198 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
200 if ( hb_stream_check_for_ts(buf) != 0 )
202 hb_log("file is MPEG Transport Stream");
203 stream->stream_type = hb_stream_type_transport;
204 hb_ts_stream_init(stream);
207 if ( hb_stream_check_for_ps(buf) != 0 )
209 hb_log("file is MPEG Program Stream");
210 stream->stream_type = hb_stream_type_program;
217 static void hb_stream_delete_dynamic( hb_stream_t *d )
221 fclose( d->file_handle );
222 d->file_handle = NULL;
227 for (i = 0; i < kMaxNumberDecodeStreams; i++)
237 static void hb_stream_delete( hb_stream_t *d )
239 hb_stream_delete_dynamic( d );
244 /***********************************************************************
246 ***********************************************************************
248 **********************************************************************/
249 hb_stream_t * hb_stream_open( char *path, int opentype )
252 FILE *f = fopen( path, "r" );
255 hb_log( "hb_stream_open: open %s failed", path );
259 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
263 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
268 * if we're opening the stream to read & convert, we need
269 * the state we saved when we scanned the stream. if we're
270 * opening the stream to scan it we want to rebuild the state
271 * (even if we have saved state, the stream may have changed).
273 hb_stream_t *ss = hb_stream_lookup( path );
276 /* opening to read - we must have saved state */
279 hb_log( "hb_stream_open: error: re-opening %s but no scan state", path );
285 * copy the saved state since we might be encoding the same stream
288 memcpy( d, ss, sizeof(*d) );
290 d->opentype = opentype;
291 d->path = strdup( path );
293 if ( d->stream_type == hb_stream_type_transport )
296 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
298 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
300 hb_stream_seek( d, 0. );
306 * opening for scan - delete any saved state then (re)scan the stream.
307 * If it's something we can deal with (MPEG2 PS or TS) return a stream
308 * reference structure & null otherwise.
313 hb_stream_state_delete( ss );
316 d->opentype = opentype;
317 d->path = strdup( path );
318 if (d->path != NULL && hb_stream_get_type( d ) != 0 )
322 fclose( d->file_handle );
327 hb_log( "hb_stream_open: open %s failed", path );
332 /***********************************************************************
334 ***********************************************************************
335 * Closes and frees everything
336 **********************************************************************/
337 void hb_stream_close( hb_stream_t ** _d )
339 hb_stream_t *stream = * _d;
340 if ( stream->frames )
342 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
343 stream->errors, (double)stream->errors * 100. /
344 (double)stream->frames );
347 * if the stream was opened for a scan, cache the result, otherwise delete
350 if ( stream->opentype == 0 )
352 hb_stream_delete_dynamic( stream );
353 if ( stream_state_list == NULL )
355 stream_state_list = hb_list_init();
357 hb_list_add( stream_state_list, stream );
361 hb_stream_delete( stream );
366 /* when the file was first opened we made entries for all the audio elementary
367 * streams we found in it. Streams that were later found during the preview scan
368 * now have an audio codec, type, rate, etc., associated with them. At the end
369 * of the scan we delete all the audio entries that weren't found by the scan
370 * or don't have a format we support. This routine deletes audio entry 'indx'
371 * by copying all later entries down one slot. */
372 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
376 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
378 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
379 stream->ts_audio_stream_type[1 + indx] = stream->ts_audio_stream_type[1+i];
380 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
383 --stream->ts_number_audio_pids;
386 static int index_of_pid(int pid, hb_stream_t *stream)
390 if ( pid == stream->ts_video_pids[0] )
393 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
394 if ( pid == stream->ts_audio_pids[i] )
400 /***********************************************************************
401 * hb_ps_stream_title_scan
402 ***********************************************************************
404 **********************************************************************/
405 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
408 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
411 // Copy part of the stream path to the title name
412 char *sep = strrchr(stream->path, '/');
414 strcpy(aTitle->name, sep+1);
415 char *dot_term = strrchr(aTitle->name, '.');
419 // Height, width, rate and aspect ratio information is filled in when the previews are built
421 hb_stream_duration(stream, aTitle);
424 hb_chapter_t * chapter;
425 chapter = calloc( sizeof( hb_chapter_t ), 1 );
427 chapter->duration = aTitle->duration;
428 chapter->hours = aTitle->hours;
429 chapter->minutes = aTitle->minutes;
430 chapter->seconds = aTitle->seconds;
431 hb_list_add( aTitle->list_chapter, chapter );
433 // Figure out how many audio streams we really have:
434 // - For transport streams, for each PID listed in the PMT (whether
435 // or not it was an audio stream type) read the bitstream until we
436 // find an packet from that PID containing a PES header and see if
437 // the elementary stream is an audio type.
438 // - For program streams read the first 4MB and take every unique
439 // audio stream we find.
440 if (stream->stream_type == hb_stream_type_transport)
444 for (i=0; i < stream->ts_number_audio_pids; i++)
446 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
447 if (audio->config.in.codec)
448 hb_list_add( aTitle->list_audio, audio );
452 hb_stream_delete_audio_entry(stream, i);
457 // add the PCR PID if we don't already have it
458 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
460 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
461 stream->pmt_info.PCR_PID;
466 hb_ps_stream_find_audio_ids(stream, aTitle);
473 * scan the next MB of 'stream' to find the next start packet for
474 * the Packetized Elementary Stream associated with TS PID 'pid'.
476 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
478 static uint8_t buf[188];
479 int npack = 100000; // max packets to read
483 if (fread(buf, 1, 188, stream->file_handle) != 188)
485 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
490 hb_log("hb_ts_stream_getPEStype: lost sync while searching for PID 0x%x", pid);
491 align_to_next_packet(stream->file_handle);
496 * The PES header is only in TS packets with 'start' set so we check
497 * that first then check for the right PID.
499 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
500 buf[2] != (pid & 0xff))
502 // not a start packet or not the pid we want
506 /* skip over the TS hdr to return a pointer to the PES hdr */
508 switch (buf[3] & 0x30)
510 case 0x00: // illegal
511 case 0x20: // fill packet
514 case 0x30: // adaptation
517 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
530 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
532 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
533 hb_list_t *list = hb_list_init();
534 // how many blocks we read while searching for a video PES header
538 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
542 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
543 hb_demux_ps(buf, list);
545 while ( ( es = hb_list_item( list, 0 ) ) )
547 hb_list_rem( list, es );
548 if ( es->id == 0xe0 )
550 // this PES contains video - if there's a PTS we're done
551 // hb_demux_ps left the PTS in buf_es->start.
552 if ( es->start != ~0 )
559 hb_buffer_close( &es );
562 hb_list_empty( &list );
563 hb_buffer_close(&buf);
567 /***********************************************************************
569 ***********************************************************************
571 * Finding stream duration is difficult. One issue is that the video file
572 * may have chunks from several different program fragments (main feature,
573 * commercials, station id, trailers, etc.) all with their own base pts
574 * value. We can't find the piece boundaries without reading the entire
575 * file but if we compute a rate based on time stamps from two different
576 * pieces the result will be meaningless. The second issue is that the
577 * data rate of compressed video normally varies by 5-10x over the length
578 * of the video. This says that we want to compute the rate over relatively
579 * long segments to get a representative average but long segments increase
580 * the likelihood that we'll cross a piece boundary.
582 * What we do is take time stamp samples at several places in the file
583 * (currently 16) then compute the average rate (i.e., ticks of video per
584 * byte of the file) for all pairs of samples (N^2 rates computed for N
585 * samples). Some of those rates will be absurd because the samples came
586 * from different segments. Some will be way low or high because the
587 * samples came from a low or high motion part of the segment. But given
588 * that we're comparing *all* pairs the majority of the computed rates
589 * should be near the overall average. So we median filter the computed
590 * rates to pick the most representative value.
592 **********************************************************************/
594 uint64_t pos; /* file position of this PTS sample */
595 uint64_t pts; /* PTS from video stream */
598 #define NDURSAMPLES 16
600 // get one (position, timestamp) sampple from a transport or program
602 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
604 struct pts_pos pp = { 0, 0 };
606 if ( stream->stream_type == hb_stream_type_program )
608 // round address down to nearest dvd sector start
609 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
610 fseeko( stream->file_handle, fpos, SEEK_SET );
611 pp.pts = hb_ps_stream_getVideoPTS( stream );
616 fseeko( stream->file_handle, fpos, SEEK_SET );
617 align_to_next_packet( stream->file_handle );
618 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
621 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
624 if ( ( buf[7] >> 7 ) != 1 )
626 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
629 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
630 ( (uint64_t)buf[10] << 22 ) |
631 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
632 ( (uint64_t)buf[12] << 7 ) |
633 ( (uint64_t)buf[13] >> 1 );
635 pp.pos = ftello(stream->file_handle);
636 hb_log("hb_sample_pts: pts %lld at %llu", pp.pts, pp.pos );
640 static int dur_compare( const void *a, const void *b )
642 const double *aval = a, *bval = b;
643 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
646 // given an array of (position, time) samples, compute a max-likelihood
647 // estimate of the average rate by computing the rate between all pairs
648 // of samples then taking the median of those rates.
649 static double compute_stream_rate( struct pts_pos *pp, int n )
652 double rates[NDURSAMPLES * NDURSAMPLES / 2];
655 // the following nested loops compute the rates between all pairs.
657 for ( i = 0; i < n-1; ++i )
659 // Bias the median filter by not including pairs that are "far"
660 // from one another. This is to handle cases where the file is
661 // made of roughly equal size pieces where a symmetric choice of
662 // pairs results in having the same number of intra-piece &
663 // inter-piece rate estimates. This would mean that the median
664 // could easily fall in the inter-piece part of the data which
665 // would give a bogus estimate. The 'ns' index creates an
666 // asymmetry that favors locality.
667 int ns = i + ( n >> 1 );
670 for ( j = i+1; j < ns; ++j )
672 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
674 *rp = ((double)( pp[j].pts - pp[i].pts )) /
675 ((double)( pp[j].pos - pp[i].pos ));
680 // now compute and return the median of all the (n*n/2) rates we computed
682 int nrates = rp - rates;
683 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
684 return rates[nrates >> 1];
687 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
689 struct pts_pos ptspos[NDURSAMPLES];
690 struct pts_pos *pp = ptspos;
693 fseeko(stream->file_handle, 0, SEEK_END);
694 uint64_t fsize = ftello(stream->file_handle);
695 uint64_t fincr = fsize / NDURSAMPLES;
696 uint64_t fpos = fincr / 2;
697 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
699 *pp++ = hb_sample_pts(stream, fpos);
701 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
702 inTitle->duration = dur;
704 inTitle->hours = dur / 3600;
705 inTitle->minutes = ( dur % 3600 ) / 60;
706 inTitle->seconds = dur % 60;
708 rewind(stream->file_handle);
711 /***********************************************************************
713 ***********************************************************************
715 **********************************************************************/
716 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
718 if ( src_stream->stream_type == hb_stream_type_program )
720 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
721 src_stream->file_handle);
722 return (amt_read > 0);
724 return hb_ts_stream_decode( src_stream, b->data );
727 /***********************************************************************
729 ***********************************************************************
731 **********************************************************************/
732 int hb_stream_seek( hb_stream_t * src_stream, float f )
734 off_t stream_size, cur_pos, new_pos;
735 double pos_ratio = f;
736 cur_pos = ftello(src_stream->file_handle);
737 fseeko(src_stream->file_handle,0 ,SEEK_END);
738 stream_size = ftello(src_stream->file_handle);
739 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
740 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
741 int r = fseeko(src_stream->file_handle, new_pos, SEEK_SET);
745 fseeko(src_stream->file_handle, cur_pos, SEEK_SET);
749 if (src_stream->stream_type == hb_stream_type_transport)
751 // We need to drop the current decoder output and move
752 // forwards to the next transport stream packet.
753 hb_ts_stream_reset(src_stream);
759 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
762 * This is a duplicate of code in dvd.c - it should get factored out
763 * into a common routine. We probably should only be putting the lang
764 * code or a lang pointer into the audio config & let the common description
765 * formatting routine in scan.c do all the stuff below.
767 snprintf( audio->config.lang.description,
768 sizeof( audio->config.lang.description ), "%s (%s)",
769 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
770 audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
771 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
772 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : "LPCM" );
773 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
774 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
775 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
776 "%s", lang->iso639_2);
779 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
782 off_t cur_pos = ftello(stream->file_handle);
783 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
786 fseeko(stream->file_handle, 0, SEEK_SET);
787 align_to_next_packet(stream->file_handle);
788 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
790 /* check that we found a PES header */
791 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
795 audio->id = 0x80bd | (aud_pid_index << 8);
796 audio->config.in.codec = HB_ACODEC_AC3;
797 hb_log("transport stream pid 0x%x (type 0x%x) is AC-3 audio id 0x%x",
798 stream->ts_audio_pids[aud_pid_index],
799 stream->ts_audio_stream_type[1 + aud_pid_index],
801 stream->ts_audio_stream_type[1 + aud_pid_index] = 0x81;
802 stream->ts_streamid[1 + aud_pid_index] = buf[3];
804 else if ((buf[3] & 0xe0) == 0xc0)
806 audio->id = buf[3] | aud_pid_index;
807 audio->config.in.codec = HB_ACODEC_MPGA;
808 hb_log("transport stream pid 0x%x (type 0x%x) is MPEG audio id 0x%x",
809 stream->ts_audio_pids[aud_pid_index],
810 stream->ts_audio_stream_type[1 + aud_pid_index],
812 stream->ts_audio_stream_type[1 + aud_pid_index] = 0x03;
813 stream->ts_streamid[1 + aud_pid_index] = buf[3];
816 fseeko(stream->file_handle, cur_pos, SEEK_SET);
817 if ( audio->config.in.codec )
819 set_audio_description( audio,
820 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
824 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
825 stream->ts_audio_pids[aud_pid_index],
826 stream->ts_audio_stream_type[1 + aud_pid_index]);
831 static void add_audio_to_title(hb_title_t *title, int id)
833 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
839 audio->config.in.codec = HB_ACODEC_MPGA;
840 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
843 // type 2 is a DVD subtitle stream - just ignore it */
847 audio->config.in.codec = HB_ACODEC_AC3;
848 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
851 audio->config.in.codec = HB_ACODEC_LPCM;
852 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
855 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
860 set_audio_description( audio, lang_for_code( 0 ) );
861 hb_list_add( title->list_audio, audio );
864 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
866 off_t cur_pos = ftello(stream->file_handle);
867 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
868 hb_list_t *list = hb_list_init();
869 // how many blocks we read while searching for audio streams
871 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
872 // so we use a bitmap to keep track of the ones we've already seen.
873 // Bit 'i' of smap is set if we've already added the audio for
874 // audio substream id 'i' to the title's audio list.
877 // start looking 20% into the file since there's occasionally no
878 // audio at the beginning (particularly for vobs).
879 hb_stream_seek(stream, 0.2f);
881 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
885 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
886 hb_demux_ps(buf, list);
888 while ( ( es = hb_list_item( list, 0 ) ) )
890 hb_list_rem( list, es );
891 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
893 // this PES contains some kind of audio - get the substream id
894 // and check if we've seen it already.
895 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
896 if ( (smap & (1 << ssid)) == 0 )
898 // we haven't seen this stream before - add it to the
899 // title's list of audio streams.
901 add_audio_to_title(title, es->id);
904 hb_buffer_close( &es );
907 hb_list_empty( &list );
908 hb_buffer_close(&buf);
909 fseeko(stream->file_handle, cur_pos, SEEK_SET);
912 /***********************************************************************
914 ***********************************************************************
916 **********************************************************************/
918 static void hb_ts_stream_init(hb_stream_t *stream)
922 for (i=0; i < kMaxNumberDecodeStreams; i++)
924 stream->ts_streamcont[i] = -1;
926 stream->ts_video_pids[0] = -1;
927 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
929 stream-> ts_audio_pids[i] = -1;
932 // Find the audio and video pids in the stream
933 hb_ts_stream_find_pids(stream);
935 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
937 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
939 // demuxing buffer for TS to PS conversion
940 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
944 // ------------------------------------------------------------------------------------
946 static off_t align_to_next_packet(FILE* f)
948 unsigned char buf[188*20];
950 off_t start = ftello(f);
953 if (fread(buf, 188*20, 1, f) == 1)
956 while (!found && (pos < 188))
960 for (i = 0; i < 188*20; i += 188)
962 unsigned char c = buf[pos+i];
964 if ((c != 0x47) && (c != 0x72) && (c != 0x29))
966 // this offset failed, try next
976 pos = 0; // failed to find anything!!!!!?
978 fseeko(f, start+pos, SEEK_SET);
990 static const unsigned int bitmask[] = {
991 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
992 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
993 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
994 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
996 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1000 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1001 (bb->buf[2] << 8) | bb->buf[3];
1003 memset(bb->buf, 0, bufsize);
1006 static inline int buf_size(bitbuf_t *bb)
1008 return bb->pos >> 3;
1011 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1014 int left = 32 - (bb->pos & 31);
1018 val = (bb->val >> (left - bits)) & bitmask[bits];
1023 val = (bb->val & bitmask[left]) << (bits - left);
1027 int pos = bb->pos >> 3;
1028 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1032 val |= (bb->val >> (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)
1068 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1070 get_bits(&bb, 8); // table_id
1072 unsigned int section_length = get_bits(&bb, 12);
1073 stream->pmt_info.section_length = section_length;
1075 unsigned int program_number = get_bits(&bb, 16);
1076 stream->pmt_info.program_number = program_number;
1078 get_bits(&bb, 5); // version_number
1080 get_bits(&bb, 8); // section_number
1081 get_bits(&bb, 8); // last_section_number
1083 unsigned int PCR_PID = get_bits(&bb, 13);
1084 stream->pmt_info.PCR_PID = PCR_PID;
1086 unsigned int program_info_length = get_bits(&bb, 12);
1087 stream->pmt_info.program_info_length = program_info_length;
1090 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1091 for (i = 0; i < program_info_length; i++)
1093 descriptor_buf[i] = get_bits(&bb, 8);
1096 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1097 int done_reading_stream_types = 0;
1098 while (!done_reading_stream_types)
1100 unsigned char stream_type = get_bits(&bb, 8);
1102 unsigned int elementary_PID = get_bits(&bb, 13);
1104 unsigned int ES_info_length = get_bits(&bb, 12);
1107 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1108 for (i=0; i < ES_info_length; i++)
1110 ES_info_buf[i] = get_bits(&bb, 8);
1113 if (stream_type == 0x02)
1115 if (stream->ts_number_video_pids <= kMaxNumberVideoPIDS)
1116 stream->ts_number_video_pids++;
1117 stream->ts_video_pids[stream->ts_number_video_pids-1] = elementary_PID;
1121 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1122 // for mpeg audio. But content producers seem to use other
1123 // values (0x04 and 0x06 have both been observed) so at this point
1124 // we say everything that isn't a video pid is audio then at the end
1125 // of hb_stream_title_scan we'll figure out which are really audio
1126 // by looking at the PES headers.
1127 i = stream->ts_number_audio_pids;
1128 if (i < kMaxNumberAudioPIDS)
1129 stream->ts_number_audio_pids++;
1130 stream->ts_audio_pids[i] = elementary_PID;
1131 stream->ts_audio_stream_type[1 + i] = stream_type;
1133 if (ES_info_length > 0)
1135 decode_element_descriptors(stream, i, ES_info_buf, ES_info_length);
1139 cur_pos += 5 /* stream header */ + ES_info_length;
1143 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1144 done_reading_stream_types = 1;
1147 free(descriptor_buf);
1151 // ------------------------------------------------------------------------------------
1153 int build_program_map(unsigned char *buf, hb_stream_t *stream)
1155 // Get adaption header info
1157 int adaption = (buf[3] & 0x30) >> 4;
1160 else if (adaption == 0x2)
1162 else if (adaption == 0x3)
1163 adapt_len = buf[4] + 1;
1164 if (adapt_len > 184)
1167 // Get payload start indicator
1169 start = (buf[1] & 0x40) != 0;
1171 // Get pointer length - only valid in packets with a start flag
1172 int pointer_len = 0;
1173 if (start && stream->pmt_info.reading)
1175 // We just finished a bunch of packets - parse the program map details
1177 if (stream->pmt_info.tablebuf[0] == 0x02)
1178 decode_ok = decode_program_map(stream);
1179 free(stream->pmt_info.tablebuf);
1180 stream->pmt_info.tablebuf = NULL;
1181 stream->pmt_info.tablepos = 0;
1182 stream->pmt_info.reading = 0;
1189 pointer_len = buf[4 + adapt_len] + 1;
1190 stream->pmt_info.tablepos = 0;
1192 // Get Continuity Counter
1193 int continuity_counter = buf[3] & 0x0f;
1194 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1196 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1199 stream->pmt_info.current_continuity_counter = continuity_counter;
1200 stream->pmt_info.reading |= start;
1202 // Add the payload for this packet to the current buffer
1203 int amount_to_copy = 184 - adapt_len - pointer_len;
1204 if (stream->pmt_info.reading && (amount_to_copy > 0))
1206 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1208 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1209 stream->pmt_info.tablepos += amount_to_copy;
1215 int decode_PAT(unsigned char *buf, hb_stream_t *stream)
1217 unsigned char tablebuf[1024];
1218 unsigned int tablepos = 0;
1223 // Get adaption header info
1225 int adaption = (buf[3] & 0x30) >> 4;
1228 else if (adaption == 0x2)
1230 else if (adaption == 0x3)
1231 adapt_len = buf[4] + 1;
1232 if (adapt_len > 184)
1235 // Get pointer length
1236 int pointer_len = buf[4 + adapt_len] + 1;
1238 // Get payload start indicator
1240 start = (buf[1] & 0x40) != 0;
1245 // Add the payload for this packet to the current buffer
1246 if (reading && (184 - adapt_len) > 0)
1248 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1250 hb_log("decode_PAT - Bad program section length (> 1024)");
1253 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1254 tablepos += 184 - adapt_len - pointer_len;
1257 if (start && reading)
1259 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1262 unsigned int pos = 0;
1263 //while (pos < tablepos)
1266 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1268 unsigned char section_id = get_bits(&bb, 8);
1270 unsigned int section_len = get_bits(&bb, 12);
1271 get_bits(&bb, 16); // transport_id
1273 get_bits(&bb, 5); // version_num
1274 get_bits(&bb, 1); // current_next
1275 get_bits(&bb, 8); // section_num
1276 get_bits(&bb, 8); // last_section
1282 // Program Association Section
1283 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1284 section_len -= 4; // Ignore the CRC
1286 stream->ts_number_pat_entries = 0;
1287 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1289 unsigned int pkt_program_num = get_bits(&bb, 16);
1290 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1292 get_bits(&bb, 3); // Reserved
1293 if (pkt_program_num == 0)
1295 get_bits(&bb, 13); // pkt_network_id
1299 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1300 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1303 stream->ts_number_pat_entries++;
1317 pos += 3 + section_len;
1325 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1327 unsigned char buf[188];
1329 // align to first packet
1330 align_to_next_packet(stream->file_handle);
1332 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1333 // to find the program map PID and then decode that to get the list of audio and video PIDs
1335 int bytesReadInPacket = 0;
1338 // Try to read packet..
1340 if ((bytesRead = fread(buf+bytesReadInPacket, 1, 188-bytesReadInPacket, stream->file_handle)) != 188-bytesReadInPacket)
1344 bytesReadInPacket += bytesRead;
1346 hb_log("hb_ts_stream_find_pids - end of file");
1351 bytesReadInPacket = 0;
1355 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1357 off_t pos = ftello(stream->file_handle) - 188;
1358 off_t pos2 = align_to_next_packet(stream->file_handle);
1361 hb_log( "hb_ts_stream_find_pids: eof while re-establishing sync @ %lld",
1365 hb_log("hb_ts_stream_decode: sync lost @%lld, regained after %lld bytes",
1371 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1373 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1375 decode_PAT(buf, stream);
1380 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1382 // There are some streams where the PAT table has multiple entries as if their are
1383 // multiple programs in the same transport stream, and yet there's actually only one
1384 // program really in the stream. This seems to be true for transport streams that
1385 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1386 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1387 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1388 // PAT info on export to match what's actually on the stream.
1389 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1390 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1391 // be to build a title choice popup from the PAT program number details and then select from
1392 // their - but right now the API's not capable of that.
1393 if (pid == stream->pat_info[pat_index].program_map_PID)
1395 if (build_program_map(buf, stream) > 0)
1399 // Keep going until we have a complete set of PIDs
1400 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1404 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1405 hb_log(" Video PIDS : ");
1407 for (i=0; i < stream->ts_number_video_pids; i++)
1409 hb_log(" 0x%x (%d)", stream->ts_video_pids[i], stream->ts_video_pids[i]);
1411 hb_log(" Audio PIDS : ");
1412 for (i = 0; i < stream->ts_number_audio_pids; i++)
1414 hb_log(" 0x%x (%d)", stream->ts_audio_pids[i], stream->ts_audio_pids[i]);
1419 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1421 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1423 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1424 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1427 memcpy( stream->fwrite_buf, buf, size );
1428 stream->fwrite_buf += size;
1431 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1435 buf[0] = 0x00; // pack id
1440 buf[4] = 0x44 | // SCR
1441 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1442 ( ( time >> 28 ) & 3 );
1443 buf[5] = time >> 20;
1445 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1446 ( ( time >> 13 ) & 3 );
1448 buf[8] = 0x04 | ( time << 3 );
1450 buf[9] = 0x01; // SCR extension
1452 buf[10] = 384000 >> (22 - 8); // program mux rate
1453 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1454 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1456 buf[13] = 0xf8 | stuffing;
1459 for (i = 0; i < stuffing; ++i )
1462 fwrite64(stream, buf, 14 + stuffing );
1465 static void pad_buffer(hb_stream_t* stream, int pad)
1477 fwrite64(stream, buf, 6);
1480 while ( --pad >= 0 )
1482 fwrite64(stream, buf, 1);
1486 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1490 memset(buf, 0, sizeof(buf) );
1493 buf[4] = ( len + 3 ) >> 8;
1497 fwrite64(stream, buf, 9);
1500 static void generate_output_data(hb_stream_t *stream, int curstream)
1502 uint8_t *tdat = stream->ts_buf[curstream];
1505 // we always ship a PACK header plus all the data in our demux buf.
1506 // AC3 audio also always needs it substream header.
1507 len = 14 + stream->ts_pos[curstream];
1508 if ( stream->ts_audio_stream_type[curstream] == 0x81)
1513 if ( ! stream->ts_start[curstream] )
1515 // we're in the middle of a chunk of PES data - we need to add
1516 // a 'continuation' PES header after the PACK header.
1520 // Write out pack header
1521 // If we don't have 2048 bytes we need to pad to 2048. We can
1522 // add a padding frame after our data but we need at least 7
1523 // bytes of space to do it (6 bytes of header & 1 of pad). If
1524 // we have fewer than 7 bytes left we need to fill the excess
1525 // space with stuffing bytes added to the pack header.
1527 if ( len > HB_DVD_READ_BUFFER_SIZE )
1529 hb_log( "stream ts length botch %d", len );
1531 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1533 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1535 write_pack(stream, stream->ts_nextpcr, stuffing );
1536 stream->ts_nextpcr += 10;
1538 if ( stream->ts_start[curstream] )
1540 // Start frames already have a PES header but we have modify it
1541 // to map from TS PID to PS stream id. Also, if the stream is AC3
1542 // audio we have to insert an AC3 stream header between the end of
1543 // the PES header and the start of the stream data.
1545 stream->ts_start[curstream] = 0;
1546 tdat[3] = stream->ts_streamid[curstream];
1548 uint16_t plen = stream->ts_pos[curstream] - 6;
1549 if ( stream->ts_audio_stream_type[curstream] == 0x81)
1551 // We have to add an AC3 header in front of the data. Add its
1552 // size to the PES packet length.
1554 tdat[4] = plen >> 8;
1557 // Write out the PES header
1558 int hdrsize = 9 + tdat[8];
1559 fwrite64(stream, tdat, hdrsize);
1561 // add a four byte DVD ac3 stream header
1562 uint8_t ac3_substream_id[4];
1563 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1564 ac3_substream_id[0] = 0x80 | ssid; // substream id
1565 ac3_substream_id[1] = 0x01; // number of sync words
1566 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1567 ac3_substream_id[3] = 0x02;
1568 fwrite64(stream, ac3_substream_id, 4);
1570 // add the rest of the data
1571 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1575 // not audio - don't need to modify the stream so write what we've got
1576 tdat[4] = plen >> 8;
1578 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1583 // data without a PES start header needs a simple 'continuation'
1584 // PES header. AC3 audio also needs its substream header.
1585 if ( stream->ts_audio_stream_type[curstream] != 0x81)
1587 make_pes_header(stream, stream->ts_pos[curstream],
1588 stream->ts_streamid[curstream]);
1592 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1593 stream->ts_streamid[curstream]);
1595 // add a four byte DVD ac3 stream header
1596 uint8_t ac3_substream_id[4];
1597 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1598 ac3_substream_id[0] = 0x80 | ssid; // substream id
1599 ac3_substream_id[1] = 0x01; // number of sync words
1600 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1601 ac3_substream_id[3] = 0x02;
1602 fwrite64(stream, ac3_substream_id, 4);
1604 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1608 int left = HB_DVD_READ_BUFFER_SIZE - len;
1611 pad_buffer(stream, left);
1614 stream->ts_pos[curstream] = 0;
1617 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
1619 // limit error printing to at most one per minute of video (at 30fps)
1621 if ( stream->frames - stream->last_error_frame >= 30*60 )
1625 vsnprintf( msg, sizeof(msg), log, args );
1627 if ( stream->errors - stream->last_error_count < 10 )
1629 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
1633 int Edelta = stream->errors - stream->last_error_count;
1634 double Epcnt = (double)Edelta * 100. /
1635 (stream->frames - stream->last_error_frame);
1636 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
1637 Edelta, Epcnt, stream->frames, msg );
1639 stream->last_error_frame = stream->frames;
1640 stream->last_error_count = stream->errors;
1644 static void ts_warn( hb_stream_t *stream, char *log, ... )
1647 va_start( args, log );
1648 ts_warn_helper( stream, log, args );
1652 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
1655 va_start( args, log );
1656 ts_warn_helper( stream, log, args );
1659 stream->ts_skipbad[curstream] = 1;
1660 stream->ts_pos[curstream] = 0;
1661 stream->ts_streamcont[curstream] = -1;
1664 static int isIframe( const uint8_t *buf, int adapt_len )
1666 // Look for the Group of Pictures packet
1670 for (i = 4 + adapt_len; i < 188; i++)
1672 strid = (strid << 8) | buf[i];
1675 case 0x000001B8: // group_start_code (GOP header)
1676 case 0x000001B3: // sequence_header code
1679 case 0x00000100: // picture_start_code
1680 // picture_header, let's see if it's an I-frame
1683 // check if picture_coding_type == 1
1684 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1686 // found an I-frame picture
1693 // didn't find an I frame
1697 /***********************************************************************
1698 * hb_ts_stream_decode
1699 ***********************************************************************
1701 **********************************************************************/
1702 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
1704 int64_t pcr = stream->ts_lastpcr;
1709 * stash the output buffer pointer in our stream so we don't have to
1710 * pass it & its original value to everything we call.
1712 stream->fwrite_buf = obuf;
1713 stream->fwrite_buf_orig = obuf;
1715 // spin until we get a packet of data from some stream or hit eof
1718 if ((fread(buf, 188, 1, stream->file_handle)) != 1)
1720 // end of file - we didn't finish filling our ps write buffer
1721 // so just discard the remainder (the partial buffer is useless)
1722 hb_log("hb_ts_stream_decode - eof");
1726 /* This next section validates the packet */
1729 if ((buf[0] != 0x47) && (buf[0] != 0x72) && (buf[0] != 0x29))
1731 // lost sync - back up to where we started then try to
1732 // re-establish sync.
1733 off_t pos = ftello(stream->file_handle) - 188;
1734 off_t pos2 = align_to_next_packet(stream->file_handle);
1737 hb_log( "hb_ts_stream_decode: eof while re-establishing sync @ %lld",
1741 ts_warn( stream, "hb_ts_stream_decode: sync lost @%lld, "
1742 "regained after %lld bytes", pos, pos2 );
1746 // Get pid and use it to find stream state.
1747 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
1748 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
1752 int errorbit = (buf[1] & 0x80) != 0;
1755 ts_err( stream, curstream, "packet error bit set");
1759 // Get adaption header info
1760 int adaption = (buf[3] & 0x30) >> 4;
1764 ts_err( stream, curstream, "adaptation code 0");
1767 else if (adaption == 0x2)
1769 else if (adaption == 0x3)
1771 adapt_len = buf[4] + 1;
1772 if (adapt_len > 184)
1774 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
1779 // if there's an adaptation header & PCR_flag is set
1780 // get the PCR (Program Clock Reference)
1781 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
1783 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
1784 ( (uint64_t)buf[7] << (33 - 16) ) |
1785 ( (uint64_t)buf[8] << (33 - 24) ) |
1786 ( (uint64_t)buf[9] << (33 - 32) ) |
1788 stream->ts_nextpcr = pcr;
1790 // remember the pcr across calls to this routine
1791 stream->ts_lastpcr = pcr;
1796 // don't accumulate data until we get a pcr
1801 // Continuity only increments for adaption values of 0x3 or 0x01
1802 // and is not checked for start packets.
1804 int start = (buf[1] & 0x40) != 0;
1806 if ( (adaption & 0x01) != 0 )
1808 int continuity = (buf[3] & 0xF);
1809 if ( continuity == stream->ts_streamcont[curstream] )
1811 // we got a duplicate packet (usually used to introduce
1812 // a PCR when one is needed). The only thing that can
1813 // change in the dup is the PCR which we grabbed above
1814 // so ignore the rest.
1817 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
1818 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
1820 ts_err( stream, curstream, "continuity error: got %d expected %d",
1822 (stream->ts_streamcont[curstream] + 1) & 0xf );
1823 stream->ts_streamcont[curstream] = continuity;
1826 stream->ts_streamcont[curstream] = continuity;
1829 /* If we get here the packet is valid - process its data */
1833 // Found a random access point (now we can start a frame/audio packet..)
1835 // If we were skipping a bad packet, start fresh on this new PES packet..
1836 if (stream->ts_skipbad[curstream] == 1)
1838 // video skips to an iframe after a bad packet to minimize
1839 // screen corruption
1840 if ( curstream == 0 && !isIframe( buf, adapt_len ) )
1844 stream->ts_skipbad[curstream] = 0;
1847 // If we don't have video yet, check to see if this is an
1848 // i_frame (group of picture start)
1849 if ( curstream == 0 )
1851 if ( !stream->ts_foundfirst[0] )
1853 if ( !isIframe( buf, adapt_len ) )
1855 // didn't find an I frame
1858 stream->ts_foundfirst[0] = 1;
1862 else if ( ! stream->ts_foundfirst[curstream] )
1864 // start other streams only after first video frame found.
1865 if ( ! stream->ts_foundfirst[0] )
1869 stream->ts_foundfirst[curstream] = 1;
1872 // If we have some data already on this stream, turn it into
1873 // a program stream packet. Then add the payload for this
1874 // packet to the current pid's buffer.
1875 if ( stream->ts_pos[curstream] )
1877 generate_output_data(stream, curstream);
1878 stream->ts_start[curstream] = 1;
1879 memcpy(stream->ts_buf[curstream],
1880 buf + 4 + adapt_len, 184 - adapt_len);
1881 stream->ts_pos[curstream] = 184 - adapt_len;
1884 stream->ts_start[curstream] = 1;
1887 // Add the payload for this packet to the current buffer
1888 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
1889 (184 - adapt_len) > 0)
1891 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
1892 buf + 4 + adapt_len, 184 - adapt_len);
1893 stream->ts_pos[curstream] += 184 - adapt_len;
1895 // if the next TS packet could possibly overflow our 2K output buffer
1896 // we need to generate a packet now. Overflow would be 184 bytes of
1897 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
1898 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
1900 // we have enough data to make a PS packet
1901 generate_output_data(stream, curstream);
1908 /***********************************************************************
1909 * hb_ts_stream_reset
1910 ***********************************************************************
1912 **********************************************************************/
1913 static void hb_ts_stream_reset(hb_stream_t *stream)
1917 for (i=0; i < kMaxNumberDecodeStreams; i++)
1919 stream->ts_pos[i] = 0;
1920 stream->ts_foundfirst[i] = 0;
1921 stream->ts_skipbad[i] = 0;
1922 stream->ts_streamcont[i] = -1;
1923 stream->ts_start[i] = 0;
1926 stream->ts_lastpcr = -1;
1927 stream->ts_nextpcr = -1;
1931 stream->last_error_frame = -10000;
1932 stream->last_error_count = 0;
1934 align_to_next_packet(stream->file_handle);