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. */
14 #include "a52dec/a52.h"
15 #include "mp4v2/mp4v2.h"
17 #define min(a, b) a < b ? a : b
20 * This table defines how ISO MPEG stream type codes map to HandBrake
21 * codecs. It is indexed by the 8 bit stream type and contains the codec
22 * worker object id and a parameter for that worker proc (ignored except
23 * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
25 * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
26 * doesn't handle the stream type.
29 enum { N, U, A, V } kind; /* not handled / unknown / audio / video */
30 int codec; /* HB worker object id of codec */
31 int codec_param; /* param for codec (usually ffmpeg codec id) */
32 const char* name; /* description of type */
35 #define st(id, kind, codec, codec_param, name) \
36 [id] = { kind, codec, codec_param, name }
38 static const stream2codec_t st2codec[256] = {
39 st(0x01, V, WORK_DECMPEG2, 0, "MPEG1"),
40 st(0x02, V, WORK_DECMPEG2, 0, "MPEG2"),
41 st(0x03, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG1"),
42 st(0x04, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG2"),
43 st(0x05, N, 0, 0, "ISO 13818-1 private section"),
44 st(0x06, U, 0, 0, "ISO 13818-1 PES private data"),
45 st(0x07, N, 0, 0, "ISO 13522 MHEG"),
46 st(0x08, N, 0, 0, "ISO 13818-1 DSM-CC"),
47 st(0x09, N, 0, 0, "ISO 13818-1 auxiliary"),
48 st(0x0a, N, 0, 0, "ISO 13818-6 encap"),
49 st(0x0b, N, 0, 0, "ISO 13818-6 DSM-CC U-N msgs"),
50 st(0x0c, N, 0, 0, "ISO 13818-6 Stream descriptors"),
51 st(0x0d, N, 0, 0, "ISO 13818-6 Sections"),
52 st(0x0e, N, 0, 0, "ISO 13818-1 auxiliary"),
53 st(0x0f, A, HB_ACODEC_MPGA, CODEC_ID_AAC, "ISO 13818-7 AAC Audio"),
54 st(0x10, V, WORK_DECAVCODECV, CODEC_ID_MPEG4, "MPEG4"),
55 st(0x11, A, HB_ACODEC_MPGA, CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
56 st(0x12, U, 0, 0, "MPEG4 generic"),
58 st(0x14, N, 0, 0, "ISO 13818-6 DSM-CC download"),
60 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
62 st(0x80, N, 0, 0, "DigiCipher II Video"),
63 st(0x81, A, HB_ACODEC_AC3, 0, "AC-3"),
64 st(0x82, A, HB_ACODEC_DCA, 0, "HDMV DTS"),
65 st(0x83, A, HB_ACODEC_LPCM, 0, "LPCM"),
66 st(0x84, A, 0, 0, "SDDS"),
67 st(0x85, U, 0, 0, "ATSC Program ID"),
68 st(0x86, A, HB_ACODEC_DCA, 0, "DTS-HD"),
69 st(0x87, A, 0, 0, "E-AC-3"),
71 st(0x8a, A, HB_ACODEC_DCA, 0, "DTS"),
73 st(0x91, A, HB_ACODEC_AC3, 0, "AC-3"),
74 st(0x92, N, 0, 0, "Subtitle"),
76 st(0x94, A, 0, 0, "SDDS"),
77 st(0xa0, V, 0, 0, "MSCODEC"),
79 st(0xea, V, WORK_DECAVCODECV, CODEC_ID_VC1, "VC1"),
84 hb_stream_type_unknown = 0,
91 #define kMaxNumberVideoPIDS 1
92 #define kMaxNumberAudioPIDS 31
93 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
94 #define kMaxNumberPMTStreams 32
99 int frames; /* video frames so far */
100 int errors; /* total errors so far */
101 int last_error_frame; /* frame # at last error message */
102 int last_error_count; /* # errors at last error message */
103 int packetsize; /* Transport Stream packet size */
105 uint8_t need_keyframe; // non-zero if want to start at a keyframe
106 uint8_t ts_found_pcr; // non-zero if we've found at least one input pcr
107 int ts_pcr_out; // sequence number of most recent output pcr
108 int ts_pcr_in; // sequence number of most recent input pcr
109 int64_t ts_pcr; // most recent input pcr
110 int64_t ts_pcrhist[4]; // circular buffer of output pcrs
112 uint8_t *ts_packet; /* buffer for one TS packet */
113 hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
114 int ts_pos[kMaxNumberDecodeStreams];
115 int8_t ts_skipbad[kMaxNumberDecodeStreams];
116 int8_t ts_streamcont[kMaxNumberDecodeStreams];
117 uint8_t ts_pkt_summary[kMaxNumberDecodeStreams][8];
119 hb_buffer_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
121 int chapter; /* Chapter that we are currently in */
122 int64_t chapter_end; /* HB time that the current chapter ends */
125 * Stuff before this point is dynamic state updated as we read the
126 * stream. Stuff after this point is stream description state that
127 * we learn during the initial scan but cache so it can be
128 * reused during the conversion read.
130 uint8_t ts_number_video_pids;
131 uint8_t ts_number_audio_pids;
132 uint8_t ts_flags; // stream characteristics:
133 #define TS_HAS_PCR (1 << 0) // at least one PCR seen
134 #define TS_HAS_RAP (1 << 1) // Random Access Point bit seen
135 #define TS_HAS_RSEI (1 << 2) // "Restart point" SEI seen
136 uint8_t ts_IDRs; // # IDRs found during duration scan
138 int16_t ts_video_pids[kMaxNumberVideoPIDS];
139 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
141 uint32_t ts_format_id[kMaxNumberDecodeStreams];
142 #define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
143 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
144 uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
148 hb_stream_type_t hb_stream_type;
151 AVFormatContext *ffmpeg_ic;
152 AVPacket *ffmpeg_pkt;
153 double ffmpeg_tsconv[MAX_STREAMS];
154 uint8_t ffmpeg_video_id;
161 } a52_info[kMaxNumberAudioPIDS];
165 unsigned short program_number;
166 unsigned short program_map_PID;
167 } pat_info[kMaxNumberPMTStreams];
168 int ts_number_pat_entries;
173 unsigned char *tablebuf;
174 unsigned int tablepos;
175 unsigned char current_continuity_counter;
179 unsigned int PCR_PID;
180 int program_info_length;
181 unsigned char *progam_info_descriptor_data;
184 unsigned char stream_type;
185 unsigned short elementary_PID;
186 unsigned short ES_info_length;
187 unsigned char *es_info_descriptor_data;
188 } pmt_stream_info[kMaxNumberPMTStreams];
192 /***********************************************************************
194 **********************************************************************/
195 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
196 static void hb_ts_stream_init(hb_stream_t *stream);
197 static void hb_ts_stream_find_pids(hb_stream_t *stream);
198 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
199 static void hb_ts_stream_reset(hb_stream_t *stream);
200 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
202 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
203 static off_t align_to_next_packet(hb_stream_t *stream);
205 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
206 static void ffmpeg_close( hb_stream_t *d );
207 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
208 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
209 static int ffmpeg_seek( hb_stream_t *stream, float frac );
210 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts );
213 * streams have a bunch of state that's learned during the scan. We don't
214 * want to throw away the state when scan does a close then relearn
215 * everything when reader does an open. So we save the stream state on
216 * the close following a scan and reuse it when 'reader' does an open.
218 static hb_list_t *stream_state_list;
220 static hb_stream_t *hb_stream_lookup( const char *path )
222 if ( stream_state_list == NULL )
228 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
230 if ( strcmp( path, ss->path ) == 0 )
238 static void hb_stream_state_delete( hb_stream_t *ss )
240 hb_list_rem( stream_state_list, ss );
247 * these frontend hb_log because transport streams can have a lot of errors
248 * so we want to rate limit messages. this routine limits the number of
249 * messages to at most one per minute of video. other errors that occur
250 * during the minute are counted & the count is output with the next
251 * error msg we print.
253 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
255 // limit error printing to at most one per minute of video (at 30fps)
257 if ( stream->frames - stream->last_error_frame >= 30*60 )
261 vsnprintf( msg, sizeof(msg), log, args );
263 if ( stream->errors - stream->last_error_count < 10 )
265 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
269 int Edelta = stream->errors - stream->last_error_count;
270 double Epcnt = (double)Edelta * 100. /
271 (stream->frames - stream->last_error_frame);
272 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
273 Edelta, Epcnt, stream->frames, msg );
275 stream->last_error_frame = stream->frames;
276 stream->last_error_count = stream->errors;
280 static void ts_warn( hb_stream_t*, char*, ... ) HB_WPRINTF(2,3);
281 static void ts_err( hb_stream_t*, int, char*, ... ) HB_WPRINTF(3,4);
283 static void ts_warn( hb_stream_t *stream, char *log, ... )
286 va_start( args, log );
287 ts_warn_helper( stream, log, args );
291 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
294 va_start( args, log );
295 ts_warn_helper( stream, log, args );
298 stream->ts_skipbad[curstream] = 1;
299 stream->ts_pos[curstream] = 0;
300 stream->ts_streamcont[curstream] = -1;
303 static int check_ps_sync(const uint8_t *buf)
305 // a legal MPEG program stream must start with a Pack header in the
307 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
308 (buf[2] == 0x01) && (buf[3] == 0xba);
311 static int check_ps_sc(const uint8_t *buf)
313 // a legal MPEG program stream must start with a Pack followed by a
314 // some other start code. If we've already verified the pack, this skip
315 // it and checks for a start code prefix.
316 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
317 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) && (buf[pos+2] == 0x01);
320 static int check_ts_sync(const uint8_t *buf)
322 // must have initial sync byte, no scrambling & a legal adaptation ctrl
323 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
326 static int have_ts_sync(const uint8_t *buf, int psize)
328 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
329 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
330 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
331 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
334 static int hb_stream_check_for_ts(const uint8_t *buf)
336 // transport streams should have a sync byte every 188 bytes.
337 // search the first 8KB of buf looking for at least 8 consecutive
338 // correctly located sync patterns.
341 for ( offset = 0; offset < 8*1024-8*188; ++offset )
343 if ( have_ts_sync( &buf[offset], 188) )
344 return 188 | (offset << 8);
345 if ( have_ts_sync( &buf[offset], 192) )
346 return 192 | (offset << 8);
347 if ( have_ts_sync( &buf[offset], 204) )
348 return 204 | (offset << 8);
349 if ( have_ts_sync( &buf[offset], 208) )
350 return 208 | (offset << 8);
355 static int hb_stream_check_for_ps(const uint8_t *buf)
357 // program streams should start with a PACK then some other mpeg start
358 // code (usually a SYS but that might be missing if we only have a clip).
361 for ( offset = 0; offset < 8*1024-24; ++offset )
363 if ( check_ps_sync( &buf[offset] ) && check_ps_sc( &buf[offset] ) )
369 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
371 // DVD program streams should have a Pack header every 2048 bytes.
372 // check that we have 4 of these in a row.
373 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
374 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
377 static int hb_stream_get_type(hb_stream_t *stream)
382 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
385 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
387 int offset = psize >> 8;
389 hb_log("file is MPEG Transport Stream with %d byte packets"
390 " offset %d bytes", psize, offset);
391 stream->packetsize = psize;
392 stream->hb_stream_type = transport;
393 hb_ts_stream_init(stream);
394 if ( !stream->ts_number_video_pids || !stream->ts_number_audio_pids )
400 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
402 hb_log("file is MPEG DVD Program Stream");
403 stream->hb_stream_type = dvd_program;
408 if ( hb_stream_check_for_ps(buf) != 0 )
410 hb_log("file is MPEG Program Stream");
411 stream->hb_stream_type = program;
414 // Seek back to handle start codes that run over end of last buffer
415 fseek( stream->file_handle, -28, SEEK_CUR );
416 } while ( --i && fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) );
421 static void hb_stream_delete_dynamic( hb_stream_t *d )
425 fclose( d->file_handle );
426 d->file_handle = NULL;
433 free( d->ts_packet );
436 for (i = 0; i < kMaxNumberDecodeStreams; i++)
440 hb_buffer_close(&(d->ts_buf[i]));
446 static void hb_stream_delete( hb_stream_t *d )
448 hb_stream_delete_dynamic( d );
453 static int audio_inactive( hb_stream_t *stream, int indx )
455 int aud_indx = indx - 1;
457 if ( stream->ts_audio_pids[aud_indx] < 0 )
459 // PID declared inactive by hb_stream_title_scan
462 if ( stream->ts_audio_pids[aud_indx] == stream->pmt_info.PCR_PID )
464 // PCR PID is always active
468 // see if we should make the stream inactive because scan.c didn't
469 // find a valid audio bitstream.
471 for ( i = 0; i < hb_list_count( stream->title->list_audio ); ++i )
473 hb_audio_t *audio = hb_list_item( stream->title->list_audio, i );
474 if ( audio->id == indx )
479 // not in the title's audio list - declare the PID inactive
480 stream->ts_audio_pids[aud_indx] = -stream->ts_audio_pids[aud_indx];
484 /***********************************************************************
486 ***********************************************************************
488 **********************************************************************/
489 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
491 FILE *f = fopen( path, "rb" );
494 hb_log( "hb_stream_open: open %s failed", path );
498 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
502 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
507 * if we're opening the stream to read & convert, we need
508 * the state we saved when we scanned the stream. if we're
509 * opening the stream to scan it we want to rebuild the state
510 * (even if we have saved state, the stream may have changed).
512 hb_stream_t *ss = hb_stream_lookup( path );
513 if ( title && ss && ss->hb_stream_type != ffmpeg )
516 * copy the saved state since we might be encoding the same stream
519 memcpy( d, ss, sizeof(*d) );
522 d->path = strdup( path );
524 if ( d->hb_stream_type == transport )
526 d->ts_packet = malloc( d->packetsize );
529 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
531 if ( i && audio_inactive( d, i ) )
533 // this PID isn't wanted (we don't have a codec for it
534 // or scan didn't find audio parameters)
537 d->ts_buf[i] = hb_buffer_init(d->packetsize);
538 d->ts_buf[i]->size = 0;
540 hb_stream_seek( d, 0. );
546 * opening for scan - delete any saved state then (re)scan the stream.
547 * If it's something we can deal with (MPEG2 PS or TS) return a stream
548 * reference structure & null otherwise.
552 hb_stream_state_delete( ss );
556 d->path = strdup( path );
557 if (d->path != NULL )
559 if ( hb_stream_get_type( d ) != 0 )
563 fclose( d->file_handle );
564 d->file_handle = NULL;
565 if ( ffmpeg_open( d, title ) )
570 if ( d->file_handle )
572 fclose( d->file_handle );
578 hb_log( "hb_stream_open: open %s failed", path );
583 /***********************************************************************
585 ***********************************************************************
586 * Closes and frees everything
587 **********************************************************************/
588 void hb_stream_close( hb_stream_t ** _d )
590 hb_stream_t *stream = * _d;
592 if ( stream->hb_stream_type == ffmpeg )
594 ffmpeg_close( stream );
595 hb_stream_delete( stream );
600 if ( stream->frames )
602 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
603 stream->errors, (double)stream->errors * 100. /
604 (double)stream->frames );
608 * if the stream was opened for a scan, cache the result, otherwise delete
611 if ( stream->title == NULL )
613 hb_stream_delete_dynamic( stream );
614 if ( stream_state_list == NULL )
616 stream_state_list = hb_list_init();
618 hb_list_add( stream_state_list, stream );
622 hb_stream_delete( stream );
627 /* when the file was first opened we made entries for all the audio elementary
628 * streams we found in it. Streams that were later found during the preview scan
629 * now have an audio codec, type, rate, etc., associated with them. At the end
630 * of the scan we delete all the audio entries that weren't found by the scan
631 * or don't have a format we support. This routine deletes audio entry 'indx'
632 * by setting its PID to an invalid value so no packet will match it. (We can't
633 * move any of the entries since the index of the entry is used as the id
634 * of the media stream for HB. */
635 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
637 if ( stream->ts_audio_pids[indx] > 0 )
639 stream->ts_audio_pids[indx] = -stream->ts_audio_pids[indx];
643 static int index_of_pid(int pid, hb_stream_t *stream)
647 if ( pid == stream->ts_video_pids[0] )
650 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
651 if ( pid == stream->ts_audio_pids[i] )
657 /***********************************************************************
658 * hb_ps_stream_title_scan
659 ***********************************************************************
661 **********************************************************************/
662 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
664 if ( stream->hb_stream_type == ffmpeg )
665 return ffmpeg_title_scan( stream );
668 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
669 aTitle->type = HB_STREAM_TYPE;
672 // Copy part of the stream path to the title name
673 char *sep = strrchr(stream->path, '/');
675 strcpy(aTitle->name, sep+1);
676 char *dot_term = strrchr(aTitle->name, '.');
680 // Height, width, rate and aspect ratio information is filled in when the previews are built
682 hb_stream_duration(stream, aTitle);
685 hb_chapter_t * chapter;
686 chapter = calloc( sizeof( hb_chapter_t ), 1 );
688 chapter->duration = aTitle->duration;
689 chapter->hours = aTitle->hours;
690 chapter->minutes = aTitle->minutes;
691 chapter->seconds = aTitle->seconds;
692 hb_list_add( aTitle->list_chapter, chapter );
694 // Figure out how many audio streams we really have:
695 // - For transport streams, for each PID listed in the PMT (whether
696 // or not it was an audio stream type) read the bitstream until we
697 // find an packet from that PID containing a PES header and see if
698 // the elementary stream is an audio type.
699 // - For program streams read the first 4MB and take every unique
700 // audio stream we find.
701 if (stream->hb_stream_type == transport)
705 for (i=0; i < stream->ts_number_audio_pids; i++)
707 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
708 if (audio->config.in.codec)
709 hb_list_add( aTitle->list_audio, audio );
713 hb_stream_delete_audio_entry(stream, i);
717 // make sure we're grabbing the PCR PID
718 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
720 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
721 stream->pmt_info.PCR_PID;
724 // set the video id, codec & muxer
725 aTitle->video_id = 0;
726 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
727 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
728 aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
730 if ( ( stream->ts_flags & TS_HAS_PCR ) == 0 )
732 hb_log( "transport stream missing PCRs - using video DTS instead" );
735 if ( stream->ts_IDRs < 1 )
737 hb_log( "transport stream doesn't seem to have video IDR frames" );
738 aTitle->flags |= HBTF_NO_IDR;
743 hb_ps_stream_find_audio_ids(stream, aTitle);
750 * read the next transport stream packet from 'stream'. Return NULL if
751 * we hit eof & a pointer to the sync byte otherwise.
753 static const uint8_t *next_packet( hb_stream_t *stream )
755 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
759 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
768 // lost sync - back up to where we started then try to re-establish.
769 off_t pos = ftello(stream->file_handle) - stream->packetsize;
770 off_t pos2 = align_to_next_packet(stream);
773 hb_log( "next_packet: eof while re-establishing sync @ %"PRId64, pos );
776 ts_warn( stream, "next_packet: sync lost @ %"PRId64", regained after %"PRId64" bytes",
782 * skip to the start of the next PACK header in program stream src_stream.
784 static void skip_to_next_pack( hb_stream_t *src_stream )
786 // scan forward until we find the start of the next pack
787 uint32_t strt_code = -1;
790 flockfile( src_stream->file_handle );
791 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
793 strt_code = ( strt_code << 8 ) | c;
794 if ( strt_code == 0x000001ba )
795 // we found the start of the next pack
798 funlockfile( src_stream->file_handle );
800 // if we didn't terminate on an eof back up so the next read
801 // starts on the pack boundary.
804 fseeko( src_stream->file_handle, -4, SEEK_CUR );
808 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
810 // For mpeg2: look for a gop start or i-frame picture start
811 // for h.264: look for idr nal type or a slice header for an i-frame
812 // for vc1: look for a Sequence header
817 if ( stream->ts_stream_type[0] <= 2 )
819 // This section of the code handles MPEG-1 and MPEG-2 video streams
820 for (i = 13 + adapt_len; i < 188; i++)
822 strid = (strid << 8) | buf[i];
823 if ( ( strid >> 8 ) == 1 )
825 // we found a start code
829 case 0xB8: // group_start_code (GOP header)
830 case 0xB3: // sequence_header code
833 case 0x00: // picture_start_code
834 // picture_header, let's see if it's an I-frame
837 // check if picture_coding_type == 1
838 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
840 // found an I-frame picture
848 // didn't find an I-frame
851 if ( stream->ts_stream_type[0] == 0x1b )
853 // we have an h.264 stream
854 for (i = 13 + adapt_len; i < 188; i++)
856 strid = (strid << 8) | buf[i];
857 if ( ( strid >> 8 ) == 1 )
859 // we found a start code - remove the ref_idc from the nal type
860 uint8_t nal_type = strid & 0x1f;
861 if ( nal_type == 0x05 )
862 // h.264 IDR picture start
866 // didn't find an I-frame
869 if ( stream->ts_stream_type[0] == 0xea )
871 // we have an vc1 stream
872 for (i = 13 + adapt_len; i < 188; i++)
874 strid = (strid << 8) | buf[i];
875 if ( strid == 0x10f )
877 // the ffmpeg vc1 decoder requires a seq hdr code in the first
882 // didn't find an I-frame
886 // we don't understand the stream type so just say "yes" otherwise
887 // we'll discard all the video.
892 * scan the next MB of 'stream' to find the next start packet for
893 * the Packetized Elementary Stream associated with TS PID 'pid'.
895 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
897 int npack = 300000; // max packets to read
901 const uint8_t *buf = next_packet( stream );
904 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
908 // while we're reading the stream, check if it has valid PCRs
909 // and/or random access points.
910 uint32_t pack_pid = ( (buf[1] & 0x1f) << 8 ) | buf[2];
911 if ( pack_pid == stream->pmt_info.PCR_PID )
913 if ( ( buf[5] & 0x10 ) &&
914 ( ( ( buf[3] & 0x30 ) == 0x20 ) ||
915 ( ( buf[3] & 0x30 ) == 0x30 && buf[4] > 6 ) ) )
917 stream->ts_flags |= TS_HAS_PCR;
922 stream->ts_flags |= TS_HAS_RAP;
926 * The PES header is only in TS packets with 'start' set so we check
927 * that first then check for the right PID.
929 if ((buf[1] & 0x40) == 0 || pack_pid != pid )
931 // not a start packet or not the pid we want
935 /* skip over the TS hdr to return a pointer to the PES hdr */
937 switch (buf[3] & 0x30)
939 case 0x00: // illegal
940 case 0x20: // fill packet
943 case 0x30: // adaptation
946 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
952 /* PES hdr has to begin with an mpeg start code */
953 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
963 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
965 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
966 hb_list_t *list = hb_list_init();
967 // how many blocks we read while searching for a video PES header
971 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
975 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
976 hb_demux_ps( buf, list, 0 );
978 while ( ( es = hb_list_item( list, 0 ) ) )
980 hb_list_rem( list, es );
981 if ( es->id == 0xe0 )
983 // this PES contains video - if there's a PTS we're done
984 // hb_demux_ps left the PTS in buf_es->start.
985 if ( es->start != ~0 )
992 hb_buffer_close( &es );
995 hb_list_empty( &list );
996 hb_buffer_close(&buf);
1000 /***********************************************************************
1001 * hb_stream_duration
1002 ***********************************************************************
1004 * Finding stream duration is difficult. One issue is that the video file
1005 * may have chunks from several different program fragments (main feature,
1006 * commercials, station id, trailers, etc.) all with their own base pts
1007 * value. We can't find the piece boundaries without reading the entire
1008 * file but if we compute a rate based on time stamps from two different
1009 * pieces the result will be meaningless. The second issue is that the
1010 * data rate of compressed video normally varies by 5-10x over the length
1011 * of the video. This says that we want to compute the rate over relatively
1012 * long segments to get a representative average but long segments increase
1013 * the likelihood that we'll cross a piece boundary.
1015 * What we do is take time stamp samples at several places in the file
1016 * (currently 16) then compute the average rate (i.e., ticks of video per
1017 * byte of the file) for all pairs of samples (N^2 rates computed for N
1018 * samples). Some of those rates will be absurd because the samples came
1019 * from different segments. Some will be way low or high because the
1020 * samples came from a low or high motion part of the segment. But given
1021 * that we're comparing *all* pairs the majority of the computed rates
1022 * should be near the overall average. So we median filter the computed
1023 * rates to pick the most representative value.
1025 **********************************************************************/
1027 uint64_t pos; /* file position of this PTS sample */
1028 uint64_t pts; /* PTS from video stream */
1031 #define NDURSAMPLES 128
1033 // get one (position, timestamp) sampple from a transport or program
1035 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
1037 struct pts_pos pp = { 0, 0 };
1039 if ( stream->hb_stream_type == transport )
1042 fseeko( stream->file_handle, fpos, SEEK_SET );
1043 align_to_next_packet( stream );
1044 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
1047 hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
1050 if ( ( buf[7] >> 7 ) != 1 )
1052 hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
1055 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
1056 ( (uint64_t)buf[10] << 22 ) |
1057 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
1058 ( (uint64_t)buf[12] << 7 ) |
1059 ( (uint64_t)buf[13] >> 1 );
1061 if ( isIframe( stream, buf, -4 ) )
1063 if ( stream->ts_IDRs < 255 )
1071 // round address down to nearest dvd sector start
1072 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
1073 fseeko( stream->file_handle, fpos, SEEK_SET );
1074 if ( stream->hb_stream_type == program )
1076 skip_to_next_pack( stream );
1078 pp.pts = hb_ps_stream_getVideoPTS( stream );
1080 pp.pos = ftello(stream->file_handle);
1084 static int dur_compare( const void *a, const void *b )
1086 const double *aval = a, *bval = b;
1087 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
1090 // given an array of (position, time) samples, compute a max-likelihood
1091 // estimate of the average rate by computing the rate between all pairs
1092 // of samples then taking the median of those rates.
1093 static double compute_stream_rate( struct pts_pos *pp, int n )
1096 double rates[NDURSAMPLES * NDURSAMPLES / 8];
1099 // the following nested loops compute the rates between all pairs.
1101 for ( i = 0; i < n-1; ++i )
1103 // Bias the median filter by not including pairs that are "far"
1104 // from one another. This is to handle cases where the file is
1105 // made of roughly equal size pieces where a symmetric choice of
1106 // pairs results in having the same number of intra-piece &
1107 // inter-piece rate estimates. This would mean that the median
1108 // could easily fall in the inter-piece part of the data which
1109 // would give a bogus estimate. The 'ns' index creates an
1110 // asymmetry that favors locality.
1111 int ns = i + ( n >> 3 );
1114 for ( j = i+1; j < ns; ++j )
1116 if ( (uint64_t)(pp[j].pts - pp[i].pts) > 90000LL*3600*6 )
1118 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
1120 *rp = ((double)( pp[j].pts - pp[i].pts )) /
1121 ((double)( pp[j].pos - pp[i].pos ));
1126 // now compute and return the median of all the (n*n/2) rates we computed
1128 int nrates = rp - rates;
1129 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
1130 return rates[nrates >> 1];
1133 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
1135 struct pts_pos ptspos[NDURSAMPLES];
1136 struct pts_pos *pp = ptspos;
1139 fseeko(stream->file_handle, 0, SEEK_END);
1140 uint64_t fsize = ftello(stream->file_handle);
1141 uint64_t fincr = fsize / NDURSAMPLES;
1142 uint64_t fpos = fincr / 2;
1143 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1145 *pp++ = hb_sample_pts(stream, fpos);
1147 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1148 inTitle->duration = dur;
1150 inTitle->hours = dur / 3600;
1151 inTitle->minutes = ( dur % 3600 ) / 60;
1152 inTitle->seconds = dur % 60;
1154 rewind(stream->file_handle);
1157 /***********************************************************************
1159 ***********************************************************************
1161 **********************************************************************/
1162 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1164 if ( src_stream->hb_stream_type == ffmpeg )
1166 return ffmpeg_read( src_stream, b );
1168 if ( src_stream->hb_stream_type == dvd_program )
1170 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1171 src_stream->file_handle);
1172 return (amt_read > 0);
1174 if ( src_stream->hb_stream_type == program )
1176 // a general program stream has arbitrary sized pack's. we're
1177 // currently positioned at the start of a pack so read up to but
1178 // not including the start of the next, expanding the buffer
1180 uint8_t *cp = b->data;
1181 uint8_t *ep = cp + b->alloc;
1182 uint32_t strt_code = -1;
1185 // consume the first byte of the initial pack so we don't match on
1186 // it in the loop below.
1187 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1192 flockfile( src_stream->file_handle );
1193 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1195 strt_code = ( strt_code << 8 ) | c;
1196 if ( strt_code == 0x000001ba )
1197 // we found the start of the next pack
1201 // need to expand the buffer
1202 int curSize = cp - b->data;
1203 hb_buffer_realloc( b, curSize * 2 );
1204 cp = b->data + curSize;
1205 ep = b->data + b->alloc;
1208 // Non-video streams can emulate start codes, so we need
1209 // to inspect PES packets and skip over their data
1210 // sections to avoid mis-detection of the next pack header.
1211 if ( ( strt_code >> 8 ) == 0x000001 &&
1212 ( strt_code & 0xff ) >= 0xbb )
1215 c = getc_unlocked( src_stream->file_handle );
1219 c = getc_unlocked( src_stream->file_handle );
1223 if ( cp+len+2 > ep )
1225 // need to expand the buffer
1226 int curSize = cp - b->data;
1227 if ( curSize * 2 > curSize+len+2 )
1228 hb_buffer_realloc( b, curSize * 2 );
1230 hb_buffer_realloc( b, curSize + len + 2 );
1231 cp = b->data + curSize;
1232 ep = b->data + b->alloc;
1236 fread( cp, 1, len, src_stream->file_handle );
1240 funlockfile( src_stream->file_handle );
1242 // if we didn't terminate on an eof back up so the next read
1243 // starts on the pack boundary.
1244 b->size = cp - b->data;
1247 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1248 // Only 3 of the 4 bytes read were added to the buffer.
1253 return hb_ts_stream_decode( src_stream, b );
1256 int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
1259 if ( stream->hb_stream_type != ffmpeg )
1261 // currently meaningliess for transport and program streams
1264 if ( !stream || !stream->title ||
1265 chapter_num > hb_list_count( stream->title->list_chapter ) )
1270 int64_t sum_dur = 0;
1271 hb_chapter_t *chapter = NULL;
1273 for ( i = 0; i < chapter_num; ++i)
1275 chapter = hb_list_item( stream->title->list_chapter, i );
1276 sum_dur += chapter->duration;
1278 stream->chapter = chapter_num - 1;
1279 stream->chapter_end = sum_dur;
1281 int64_t pos = ( ( ( sum_dur - chapter->duration ) * AV_TIME_BASE ) / 90000 );
1283 hb_deep_log( 2, "Seeking to chapter %d: starts %"PRId64", ends %"PRId64", AV pos %"PRId64,
1284 chapter_num, sum_dur - chapter->duration, sum_dur, pos);
1286 if ( chapter_num > 1 && pos > 0 )
1288 av_seek_frame( stream->ffmpeg_ic, -1, pos, 0);
1292 // ffmpeg has a bug that causes the first PTS after
1293 // av_find_stream_info() is called to be incorrect.
1294 // av_find_stream_info is called whenever opening a file
1295 // with ffmpeg. av_seek_frame clears the condition
1296 // that causes the problem. since hb_stream_seek_chapter
1297 // is called before we start reading, make sure
1298 // we do a seek here.
1299 av_seek_frame( stream->ffmpeg_ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
1304 /***********************************************************************
1306 ***********************************************************************
1307 * Return the number of the chapter that we are currently in. We store
1308 * the chapter number starting from 0, so + 1 for the real chpater num.
1309 **********************************************************************/
1310 int hb_stream_chapter( hb_stream_t * src_stream )
1312 return( src_stream->chapter + 1 );
1315 /***********************************************************************
1317 ***********************************************************************
1319 **********************************************************************/
1320 int hb_stream_seek( hb_stream_t * stream, float f )
1322 if ( stream->hb_stream_type == ffmpeg )
1324 return ffmpeg_seek( stream, f );
1326 off_t stream_size, cur_pos, new_pos;
1327 double pos_ratio = f;
1328 cur_pos = ftello( stream->file_handle );
1329 fseeko( stream->file_handle, 0, SEEK_END );
1330 stream_size = ftello( stream->file_handle );
1331 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1332 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1334 int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1337 fseeko( stream->file_handle, cur_pos, SEEK_SET );
1341 if ( stream->hb_stream_type == transport )
1343 // We need to drop the current decoder output and move
1344 // forwards to the next transport stream packet.
1345 hb_ts_stream_reset(stream);
1348 if ( stream->ts_IDRs )
1350 // the stream has IDRs so look for one.
1351 stream->need_keyframe = 1;
1356 // we're at the beginning - say we have video sync so that we
1357 // won't drop initial SPS & PPS data on an AVC stream.
1358 stream->need_keyframe = 0;
1361 else if ( stream->hb_stream_type == program )
1363 skip_to_next_pack( stream );
1369 int hb_stream_seek_ts( hb_stream_t * stream, int64_t ts )
1371 if ( stream->hb_stream_type == ffmpeg )
1373 return ffmpeg_seek_ts( stream, ts );
1378 static const char* make_upper( const char* s )
1380 static char name[8];
1382 char *ep = cp + sizeof(name)-1;
1384 while ( *s && cp < ep )
1386 *cp++ = islower(*s)? toupper(*s) : *s;
1393 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1396 * This is a duplicate of code in dvd.c - it should get factored out
1397 * into a common routine. We probably should only be putting the lang
1398 * code or a lang pointer into the audio config & let the common description
1399 * formatting routine in scan.c do all the stuff below.
1401 const char *codec_name;
1404 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1405 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1406 avcodec_find_decoder( cc->codec_id ) )
1408 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1409 if ( !strcmp( codec_name, "LIBFAAD" ) )
1414 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1415 avcodec_find_decoder( audio->config.in.codec_param ) )
1417 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1421 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1422 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1423 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1424 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1425 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1428 snprintf( audio->config.lang.description,
1429 sizeof( audio->config.lang.description ), "%s (%s)",
1430 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1432 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1433 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1434 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1435 "%s", lang->iso639_2);
1438 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1441 off_t cur_pos = ftello(stream->file_handle);
1442 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1445 fseeko(stream->file_handle, 0, SEEK_SET);
1446 align_to_next_packet(stream);
1447 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1449 /* check that we found a PES header */
1451 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1453 stype = stream->ts_stream_type[1 + aud_pid_index];
1455 // 0xbd ("private stream 1") is the normal container for non-ISO
1456 // media - AC3/DCA/PCM/etc.
1457 if ( buf[3] == 0xbd )
1459 if ( st2codec[stype].kind == U )
1461 // XXX assume unknown stream types are AC-3 (if they're not
1462 // audio we'll find that out during the scan but if they're
1463 // some other type of audio we'll end up ignoring them).
1465 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1468 else if ( buf[3] == 0xfd )
1470 // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1471 // the blu ray consortium apparently forgot to read the portion
1472 // of the MPEG spec that says one PID should map to one media
1473 // stream and multiplexed multiple types of audio into one PID
1474 // using the extended stream identifier of the PES header to
1475 // distinguish them. So we have to check if that's happening and
1476 // if so tell the runtime what esid we want.
1477 if ( st2codec[stype].kind == A && stype == 0x83 &&
1478 stream->ts_format_id[1 + aud_pid_index] == TS_FORMAT_ID_AC3 )
1480 // This is an interleaved TrueHD/AC-3 stream and the esid of
1482 stream->ts_multiplexed[1 + aud_pid_index] = 0x76;
1484 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1486 if ( st2codec[stype].kind == A && stype == 0x86 )
1488 // This is an interleaved DTS-HD/DTS stream and the esid of
1490 stream->ts_multiplexed[1 + aud_pid_index] = 0x71;
1492 stream->ts_stream_type[1 + aud_pid_index] = 0x82;
1495 else if ((buf[3] & 0xe0) == 0xc0)
1497 // 0xC0 - 0xCF are the normal containers for ISO-standard
1498 // media (mpeg2 audio and mpeg4 AAC).
1499 if ( st2codec[stype].kind == U )
1501 // XXX assume unknown stream types are MPEG audio
1503 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1511 // if we found an audio stream type & HB has a codec that can decode it
1512 // finish configuring the audio so we'll add it to the title's list.
1513 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1515 audio->id = 1 + aud_pid_index;
1516 audio->config.in.codec = st2codec[stype].codec;
1517 audio->config.in.codec_param = st2codec[stype].codec_param;
1518 set_audio_description( audio,
1519 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1520 hb_log("transport stream pid 0x%x (type 0x%x) may be %s audio (id 0x%x)",
1521 stream->ts_audio_pids[aud_pid_index],
1522 stype, st2codec[stype].name, audio->id);
1528 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1529 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1530 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1534 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1535 stream->ts_audio_pids[aud_pid_index],
1536 stream->ts_stream_type[1 + aud_pid_index]);
1539 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1543 static void add_audio_to_title(hb_title_t *title, int id)
1545 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1551 audio->config.in.codec = HB_ACODEC_MPGA;
1552 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1555 // type 2 is a DVD subtitle stream - just ignore it */
1559 audio->config.in.codec = HB_ACODEC_AC3;
1560 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1563 audio->config.in.codec = HB_ACODEC_LPCM;
1564 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1567 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1572 set_audio_description( audio, lang_for_code( 0 ) );
1573 hb_list_add( title->list_audio, audio );
1576 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1578 off_t cur_pos = ftello(stream->file_handle);
1579 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1580 hb_list_t *list = hb_list_init();
1581 // how many blocks we read while searching for audio streams
1582 int blksleft = 4096;
1583 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1584 // so we use a bitmap to keep track of the ones we've already seen.
1585 // Bit 'i' of smap is set if we've already added the audio for
1586 // audio substream id 'i' to the title's audio list.
1589 // start looking 20% into the file since there's occasionally no
1590 // audio at the beginning (particularly for vobs).
1591 hb_stream_seek(stream, 0.2f);
1593 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1597 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1598 hb_demux_ps( buf, list, 0 );
1600 while ( ( es = hb_list_item( list, 0 ) ) )
1602 hb_list_rem( list, es );
1603 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1605 // this PES contains some kind of audio - get the substream id
1606 // and check if we've seen it already.
1607 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1608 if ( (smap & (1 << ssid)) == 0 )
1610 // we haven't seen this stream before - add it to the
1611 // title's list of audio streams.
1612 smap |= (1 << ssid);
1613 add_audio_to_title(title, es->id);
1616 hb_buffer_close( &es );
1619 hb_list_empty( &list );
1620 hb_buffer_close(&buf);
1621 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1624 /***********************************************************************
1626 ***********************************************************************
1628 **********************************************************************/
1630 static void hb_ts_stream_init(hb_stream_t *stream)
1634 for (i=0; i < kMaxNumberDecodeStreams; i++)
1636 stream->ts_streamcont[i] = -1;
1638 stream->ts_video_pids[0] = -1;
1639 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1641 stream-> ts_audio_pids[i] = -1;
1644 stream->ts_packet = malloc( stream->packetsize );
1646 // Find the audio and video pids in the stream
1647 hb_ts_stream_find_pids(stream);
1649 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1651 // demuxing buffer for TS to PS conversion
1652 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1653 stream->ts_buf[i]->size = 0;
1657 #define MAX_HOLE 208*80
1659 static off_t align_to_next_packet(hb_stream_t *stream)
1661 uint8_t buf[MAX_HOLE];
1663 off_t start = ftello(stream->file_handle);
1665 if ( start >= stream->packetsize ) {
1666 start -= stream->packetsize;
1667 fseeko(stream->file_handle, start, SEEK_SET);
1670 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1672 const uint8_t *bp = buf;
1675 for ( i = sizeof(buf); --i >= 0; ++bp )
1677 if ( have_ts_sync( bp, stream->packetsize ) )
1684 pos = ( bp - buf ) - stream->packetsize + 188;
1689 fseeko(stream->file_handle, start+pos, SEEK_SET);
1700 static const unsigned int bitmask[] = {
1701 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1702 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1703 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1704 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1706 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1710 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1711 (bb->buf[2] << 8) | bb->buf[3];
1713 memset(bb->buf, 0, bufsize);
1716 static inline int buf_size(bitbuf_t *bb)
1718 return bb->pos >> 3;
1721 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1724 int left = 32 - (bb->pos & 31);
1728 val = (bb->val >> (left - bits)) & bitmask[bits];
1733 val = (bb->val & bitmask[left]) << (bits - left);
1737 int pos = bb->pos >> 3;
1738 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1742 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1750 // extract what useful information we can from the elementary stream
1751 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1752 // Descriptors with info we don't currently use are ignored.
1753 // The descriptor list & descriptor item formats are defined in
1754 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1755 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1756 const uint8_t *dp, uint8_t dlen)
1758 const uint8_t *ep = dp + dlen;
1764 case 5: // Registration descriptor
1765 stream->ts_format_id[esindx+1] = (dp[2] << 24) | (dp[3] << 16) |
1766 (dp[4] << 8) | dp[5];
1769 case 10: // ISO_639_language descriptor
1770 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1773 case 0x6a: // DVB AC-3 descriptor
1774 stream->ts_stream_type[esindx+1] = 0x81;
1784 static const char *stream_type_name (uint8_t stream_type)
1786 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1789 int decode_program_map(hb_stream_t* stream)
1792 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1794 get_bits(&bb, 8); // table_id
1796 unsigned int section_length = get_bits(&bb, 12);
1797 stream->pmt_info.section_length = section_length;
1799 unsigned int program_number = get_bits(&bb, 16);
1800 stream->pmt_info.program_number = program_number;
1802 get_bits(&bb, 5); // version_number
1804 get_bits(&bb, 8); // section_number
1805 get_bits(&bb, 8); // last_section_number
1807 unsigned int PCR_PID = get_bits(&bb, 13);
1808 stream->pmt_info.PCR_PID = PCR_PID;
1810 unsigned int program_info_length = get_bits(&bb, 12);
1811 stream->pmt_info.program_info_length = program_info_length;
1814 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1815 for (i = 0; i < program_info_length; i++)
1817 descriptor_buf[i] = get_bits(&bb, 8);
1820 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1821 int done_reading_stream_types = 0;
1822 while (!done_reading_stream_types)
1824 unsigned char stream_type = get_bits(&bb, 8);
1826 unsigned int elementary_PID = get_bits(&bb, 13);
1828 unsigned int ES_info_length = get_bits(&bb, 12);
1831 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1832 for (i=0; i < ES_info_length; i++)
1834 ES_info_buf[i] = get_bits(&bb, 8);
1838 if ( index_of_pid( elementary_PID, stream ) < 0 )
1840 // don't have this pid yet
1841 if (stream->ts_number_video_pids == 0 &&
1842 st2codec[stream_type].kind == V )
1844 stream->ts_video_pids[0] = elementary_PID;
1845 stream->ts_stream_type[0] = stream_type;
1846 stream->ts_number_video_pids = 1;
1850 // Defined audio stream types are 0x81 for AC-3/A52 audio
1851 // and 0x03 for mpeg audio. But content producers seem to
1852 // use other values (0x04 and 0x06 have both been observed)
1853 // so at this point we say everything that isn't a video
1854 // pid is audio then at the end of hb_stream_title_scan
1855 // we'll figure out which are really audio by looking at
1857 i = stream->ts_number_audio_pids;
1858 if (i < kMaxNumberAudioPIDS)
1860 stream->ts_audio_pids[i] = elementary_PID;
1861 stream->ts_stream_type[1 + i] = stream_type;
1862 if (ES_info_length > 0)
1864 decode_element_descriptors(stream, i, ES_info_buf,
1867 ++stream->ts_number_audio_pids;
1872 cur_pos += 5 /* stream header */ + ES_info_length;
1876 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1877 done_reading_stream_types = 1;
1880 free(descriptor_buf);
1884 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1886 // Get adaption header info
1888 int adaption = (buf[3] & 0x30) >> 4;
1891 else if (adaption == 0x2)
1893 else if (adaption == 0x3)
1894 adapt_len = buf[4] + 1;
1895 if (adapt_len > 184)
1898 // Get payload start indicator
1900 start = (buf[1] & 0x40) != 0;
1902 // Get pointer length - only valid in packets with a start flag
1903 int pointer_len = 0;
1907 pointer_len = buf[4 + adapt_len] + 1;
1908 stream->pmt_info.tablepos = 0;
1910 // Get Continuity Counter
1911 int continuity_counter = buf[3] & 0x0f;
1912 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1914 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1917 stream->pmt_info.current_continuity_counter = continuity_counter;
1918 stream->pmt_info.reading |= start;
1920 // Add the payload for this packet to the current buffer
1921 int amount_to_copy = 184 - adapt_len - pointer_len;
1922 if (stream->pmt_info.reading && (amount_to_copy > 0))
1924 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1926 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1927 stream->pmt_info.tablepos += amount_to_copy;
1929 if (stream->pmt_info.tablepos > 3)
1931 // We have enough to check the section length
1933 length = ((stream->pmt_info.tablebuf[1] << 8) +
1934 stream->pmt_info.tablebuf[2]) & 0xFFF;
1935 if (stream->pmt_info.tablepos > length + 1)
1937 // We just finished a bunch of packets - parse the program map details
1939 if (stream->pmt_info.tablebuf[0] == 0x02)
1940 decode_ok = decode_program_map(stream);
1941 free(stream->pmt_info.tablebuf);
1942 stream->pmt_info.tablebuf = NULL;
1943 stream->pmt_info.tablepos = 0;
1944 stream->pmt_info.reading = 0;
1954 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1956 unsigned char tablebuf[1024];
1957 unsigned int tablepos = 0;
1962 // Get adaption header info
1964 int adaption = (buf[3] & 0x30) >> 4;
1967 else if (adaption == 0x2)
1969 else if (adaption == 0x3)
1970 adapt_len = buf[4] + 1;
1971 if (adapt_len > 184)
1974 // Get pointer length
1975 int pointer_len = buf[4 + adapt_len] + 1;
1977 // Get payload start indicator
1979 start = (buf[1] & 0x40) != 0;
1984 // Add the payload for this packet to the current buffer
1985 if (reading && (184 - adapt_len) > 0)
1987 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1989 hb_log("decode_PAT - Bad program section length (> 1024)");
1992 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1993 tablepos += 184 - adapt_len - pointer_len;
1996 if (start && reading)
1998 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
2001 unsigned int pos = 0;
2002 //while (pos < tablepos)
2005 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
2007 unsigned char section_id = get_bits(&bb, 8);
2009 unsigned int section_len = get_bits(&bb, 12);
2010 get_bits(&bb, 16); // transport_id
2012 get_bits(&bb, 5); // version_num
2013 get_bits(&bb, 1); // current_next
2014 get_bits(&bb, 8); // section_num
2015 get_bits(&bb, 8); // last_section
2021 // Program Association Section
2022 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
2023 section_len -= 4; // Ignore the CRC
2025 stream->ts_number_pat_entries = 0;
2026 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
2028 unsigned int pkt_program_num = get_bits(&bb, 16);
2029 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
2031 get_bits(&bb, 3); // Reserved
2032 if (pkt_program_num == 0)
2034 get_bits(&bb, 13); // pkt_network_id
2038 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
2039 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
2042 stream->ts_number_pat_entries++;
2056 pos += 3 + section_len;
2064 static void hb_ts_stream_find_pids(hb_stream_t *stream)
2066 // To be different from every other broadcaster in the world, New Zealand TV
2067 // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
2068 // we may have the tail of the previous program at the beginning of this
2069 // file, take our PMT from the middle of the file.
2070 fseeko(stream->file_handle, 0, SEEK_END);
2071 uint64_t fsize = ftello(stream->file_handle);
2072 fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
2073 align_to_next_packet(stream);
2075 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
2076 // to find the program map PID and then decode that to get the list of audio and video PIDs
2080 const uint8_t *buf = next_packet( stream );
2084 hb_log("hb_ts_stream_find_pids - end of file");
2089 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
2091 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
2093 decode_PAT(buf, stream);
2098 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
2100 // There are some streams where the PAT table has multiple entries as if their are
2101 // multiple programs in the same transport stream, and yet there's actually only one
2102 // program really in the stream. This seems to be true for transport streams that
2103 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
2104 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
2105 // but the EyeTV is only recording a single (selected) program number and not rewriting the
2106 // PAT info on export to match what's actually on the stream.
2107 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
2108 // on the first pat entry for which we find a matching program map PID. The ideal solution would
2109 // be to build a title choice popup from the PAT program number details and then select from
2110 // their - but right now the API's not capable of that.
2111 if (stream->pat_info[pat_index].program_number != 0 &&
2112 pid == stream->pat_info[pat_index].program_map_PID)
2114 if (build_program_map(buf, stream) > 0)
2118 // Keep going until we have a complete set of PIDs
2119 if (stream->ts_number_video_pids > 0)
2123 hb_log("hb_ts_stream_find_pids - found the following PIDS");
2124 hb_log(" Video PIDS : ");
2126 for (i=0; i < stream->ts_number_video_pids; i++)
2128 hb_log( " 0x%x type %s (0x%x)",
2129 stream->ts_video_pids[i],
2130 stream_type_name(stream->ts_stream_type[i]),
2131 stream->ts_stream_type[i]);
2133 hb_log(" Audio PIDS : ");
2134 for (i = 0; i < stream->ts_number_audio_pids; i++)
2136 hb_log( " 0x%x type %s (0x%x)",
2137 stream->ts_audio_pids[i],
2138 stream_type_name(stream->ts_stream_type[i+1]),
2139 stream->ts_stream_type[i+1] );
2144 static void fwrite64( hb_stream_t *stream, void *buf, int len )
2148 int pos = stream->fwrite_buf->size;
2149 if ( pos + len > stream->fwrite_buf->alloc )
2151 int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
2152 hb_buffer_realloc(stream->fwrite_buf, size);
2154 memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
2155 stream->fwrite_buf->size += len;
2159 // convert a PES PTS or DTS to an int64
2160 static int64_t pes_timestamp( const uint8_t *pes )
2162 int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2163 ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
2164 ( pes[3] << 7 ) | ( pes[4] >> 1 );
2168 static void generate_output_data(hb_stream_t *stream, int curstream)
2170 hb_buffer_t *buf = stream->fwrite_buf;
2171 uint8_t *tdat = stream->ts_buf[curstream]->data;
2173 buf->id = curstream;
2175 // check if this packet was referenced to an older pcr and if that
2176 // pcr was significantly different than the one we're using now.
2177 // (the reason for the uint cast on the pcr difference is that the
2178 // difference is significant if it advanced by more than 200ms or if
2179 // it went backwards by any amount. The negative numbers look like huge
2180 // unsigned ints so the cast allows both conditions to be checked at once.
2181 int bufpcr = stream->ts_buf[curstream]->cur;
2182 int curpcr = stream->ts_pcr_out;
2183 if ( bufpcr && bufpcr < curpcr &&
2184 (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2186 // we've sent up a new pcr but have a packet referenced to an
2187 // old pcr and the difference was enough to trigger a discontinuity
2188 // correction. smash the timestamps or we'll mess up the correction.
2190 buf->renderOffset = -1;
2194 if ( stream->ts_pcr_out != stream->ts_pcr_in )
2196 // we have a new pcr
2197 stream->ts_pcr_out = stream->ts_pcr_in;
2198 buf->stop = stream->ts_pcr;
2199 stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2206 // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2207 // off the PES header.
2208 if ( tdat[7] & 0xc0 )
2210 buf->start = pes_timestamp( tdat + 9 );
2211 buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2217 buf->renderOffset = -1;
2220 int hlen = tdat[8] + 9;
2222 fwrite64( stream, tdat + hlen, stream->ts_pos[curstream] - hlen );
2224 stream->ts_pos[curstream] = 0;
2225 stream->ts_buf[curstream]->size = 0;
2228 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2230 if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2234 size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2235 hb_buffer_realloc(stream->ts_buf[idx], size);
2237 memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2238 stream->ts_pos[idx] += len;
2239 stream->ts_buf[idx]->size += len;
2242 /***********************************************************************
2243 * hb_ts_stream_decode
2244 ***********************************************************************
2246 **********************************************************************/
2247 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2250 * stash the output buffer pointer in our stream so we don't have to
2251 * pass it & its original value to everything we call.
2254 stream->fwrite_buf = obuf;
2256 // spin until we get a packet of data from some stream or hit eof
2261 const uint8_t *buf = next_packet(stream);
2264 // end of file - we didn't finish filling our ps write buffer
2265 // so just discard the remainder (the partial buffer is useless)
2266 hb_log("hb_ts_stream_decode - eof");
2270 /* This next section validates the packet */
2272 // Get pid and use it to find stream state.
2273 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2274 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2278 int errorbit = (buf[1] & 0x80) != 0;
2281 ts_err( stream, curstream, "packet error bit set");
2285 // Get adaption header info
2286 int adaption = (buf[3] & 0x30) >> 4;
2290 ts_err( stream, curstream, "adaptation code 0");
2293 else if (adaption == 0x2)
2295 else if (adaption == 0x3)
2297 adapt_len = buf[4] + 1;
2298 if (adapt_len > 184)
2300 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2305 if ( adapt_len > 0 )
2307 if ( buf[5] & 0x40 )
2309 // found a random access point
2311 // if there's an adaptation header & PCR_flag is set
2312 // get the PCR (Program Clock Reference)
2313 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2315 stream->ts_pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2316 ( (uint64_t)buf[7] << (33 - 16) ) |
2317 ( (uint64_t)buf[8] << (33 - 24) ) |
2318 ( (uint64_t)buf[9] << (33 - 32) ) |
2320 ++stream->ts_pcr_in;
2321 stream->ts_found_pcr = 1;
2325 // If we don't have a PCR yet but the stream has PCRs just loop
2326 // so we don't process anything until we have a clock reference.
2327 // Unfortunately the HD Home Run appears to null out the PCR so if
2328 // we didn't detect a PCR during scan keep going and we'll use
2329 // the video stream DTS for the PCR.
2331 if ( !stream->ts_found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
2337 // Continuity only increments for adaption values of 0x3 or 0x01
2338 // and is not checked for start packets.
2340 int start = (buf[1] & 0x40) != 0;
2342 if ( (adaption & 0x01) != 0 )
2344 int continuity = (buf[3] & 0xF);
2345 if ( continuity == stream->ts_streamcont[curstream] )
2347 // Spliced transport streams can have duplicate
2348 // continuity counts at the splice boundary.
2349 // Test to see if the packet is really a duplicate
2350 // by comparing packet summaries to see if they
2354 summary[0] = adaption;
2355 summary[1] = adapt_len;
2356 if (adapt_len + 4 + 6 + 9 <= 188)
2358 memcpy(&summary[2], buf+4+adapt_len+9, 6);
2362 memset(&summary[2], 0, 6);
2364 if ( memcmp( summary, stream->ts_pkt_summary[curstream], 8 ) == 0 )
2366 // we got a duplicate packet (usually used to introduce
2367 // a PCR when one is needed). The only thing that can
2368 // change in the dup is the PCR which we grabbed above
2369 // so ignore the rest.
2373 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2374 !stream->ts_skipbad[curstream] &&
2375 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2377 ts_err( stream, curstream, "continuity error: got %d expected %d",
2379 (stream->ts_streamcont[curstream] + 1) & 0xf );
2380 stream->ts_streamcont[curstream] = continuity;
2383 stream->ts_streamcont[curstream] = continuity;
2385 // Save a summary of this packet for later duplicate
2386 // testing. The summary includes some header information
2387 // and payload bytes. Should be enough to detect
2389 stream->ts_pkt_summary[curstream][0] = adaption;
2390 stream->ts_pkt_summary[curstream][1] = adapt_len;
2391 if (adapt_len + 4 + 6 + 9 <= 188)
2393 memcpy(&stream->ts_pkt_summary[curstream][2],
2394 buf+4+adapt_len+9, 6);
2398 memset(&stream->ts_pkt_summary[curstream][2], 0, 6);
2402 /* If we get here the packet is valid - process its data */
2406 // Found a random access point (now we can start a frame/audio packet..)
2408 if ( stream->need_keyframe )
2410 // we're looking for the first video frame because we're
2411 // doing random access during 'scan'
2412 if ( curstream != 0 || !isIframe( stream, buf, adapt_len ) )
2414 // not the video stream or didn't find an I frame
2415 // but we'll only wait 255 video frames for an I frame.
2416 if ( curstream != 0 || ++stream->need_keyframe )
2421 stream->need_keyframe = 0;
2424 // If we were skipping a bad packet, start fresh on this new PES packet..
2425 if (stream->ts_skipbad[curstream] == 1)
2427 stream->ts_skipbad[curstream] = 0;
2430 if ( curstream == 0 )
2434 // if we don't have a pcr yet use the dts from this frame
2435 if ( !stream->ts_found_pcr )
2437 // PES must begin with an mpeg start code & contain
2439 const uint8_t *pes = buf + adapt_len + 4;
2440 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2441 ( pes[7] >> 6 ) == 0 )
2445 // if we have a dts use it otherwise use the pts
2446 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40? 14 : 9 ) );
2447 ++stream->ts_pcr_in;
2451 // if this is a multiplexed stream make sure this is the
2452 // substream we want.
2453 if ( stream->ts_multiplexed[curstream] )
2455 // PES must begin with an mpeg start code & contain
2457 const uint8_t *pes = buf + adapt_len + 4;
2458 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2461 stream->ts_skipbad[curstream] = 1;
2464 // the last byte of the header is the extension id. see if
2465 // it's the one we want.
2466 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2468 stream->ts_skipbad[curstream] = 1;
2473 // If we have some data already on this stream, turn it into
2474 // a program stream packet. Then add the payload for this
2475 // packet to the current pid's buffer.
2476 if ( stream->ts_pos[curstream] )
2478 // we have to ship the old packet before updating the pcr
2479 // since the packet we've been accumulating is referenced
2481 generate_output_data(stream, curstream);
2483 // remember the pcr that was in effect when we started
2485 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2486 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2490 // remember the pcr that was in effect when we started this packet.
2491 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2494 // Add the payload for this packet to the current buffer
2495 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2497 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2499 // see if we've hit the end of this PES packet
2500 const uint8_t *pes = stream->ts_buf[curstream]->data;
2501 int len = ( pes[4] << 8 ) + pes[5] + 6;
2502 if ( len > 6 && stream->ts_pos[curstream] == len &&
2503 pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2505 generate_output_data(stream, curstream);
2512 static void hb_ts_stream_reset(hb_stream_t *stream)
2516 for (i=0; i < kMaxNumberDecodeStreams; i++)
2518 stream->ts_pos[i] = 0;
2519 stream->ts_skipbad[i] = 1;
2520 stream->ts_streamcont[i] = -1;
2523 stream->need_keyframe = 0;
2525 stream->ts_found_pcr = 0;
2526 stream->ts_pcr_out = 0;
2527 stream->ts_pcr_in = 0;
2532 stream->last_error_frame = -10000;
2533 stream->last_error_count = 0;
2535 align_to_next_packet(stream);
2538 // ------------------------------------------------------------------
2539 // Support for reading media files via the ffmpeg libraries.
2541 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2543 // add a codec to the context here so it will be there when we
2544 // read the first packet.
2545 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2546 context->workaround_bugs = FF_BUG_AUTODETECT;
2547 context->error_recognition = 1;
2548 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2549 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2550 hb_avcodec_open( context, codec );
2553 // The ffmpeg stream reader / parser shares a lot of state with the
2554 // decoder via a codec context kept in the AVStream of the reader's
2555 // AVFormatContext. Since decoding is done in a different thread we
2556 // have to somehow pass this codec context to the decoder and we have
2557 // to do it before the first packet is read (so we can't put the info
2558 // in the buf we'll send downstream). Decoders don't have any way to
2559 // get to the stream directly (they're not passed the title or job
2560 // pointers during a scan) so this is a back door for the decoder to
2561 // get the codec context. We just stick the stream pointer in the next
2562 // slot an array of pointers maintained as a circular list then return
2563 // the index into the list combined with the ffmpeg stream index as the
2564 // codec_param that will be passed to the decoder init routine. We make
2565 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2566 // so that we don't have to do a complicated allocator or worry about
2567 // deleting entries on close.
2569 // Entries can only be added to this list during a scan and are never
2570 // deleted so the list access doesn't require locking.
2571 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2572 static int ffmpeg_stream_cur; // where we put the last stream pointer
2573 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2574 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2576 // add a stream to the list & return the appropriate codec_param to access it
2577 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2579 if ( !ffmpeg_streams )
2581 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2584 // the title scan adds all the ffmpeg media streams at once so we
2585 // only add a new entry to our stream list if the stream is different
2587 int slot = ffmpeg_stream_cur;
2588 if ( ffmpeg_streams[slot] != stream )
2590 // new stream - put it in the next slot of the stream list
2591 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2592 ffmpeg_streams[slot] = stream;
2595 ffmpeg_add_codec( stream, stream_index );
2597 return ( stream_index << ffmpeg_sl_bits ) | slot;
2600 // we're about to open 'title' to convert it - remap the stream associated
2601 // with the video & audio codec params of the title to refer to 'stream'
2602 // (the original scan stream was closed and no longer exists).
2603 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2605 // all the video & audio came from the same stream so remapping
2606 // the video's stream slot takes care of everything.
2607 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2608 ffmpeg_streams[slot] = stream;
2610 // add codecs for all the streams used by the title
2611 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2615 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2617 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2619 ffmpeg_add_codec( stream,
2620 audio->config.in.codec_param >> ffmpeg_sl_bits );
2625 void *hb_ffmpeg_context( int codec_param )
2627 int slot = codec_param & (ffmpeg_sl_size - 1);
2628 int stream_index = codec_param >> ffmpeg_sl_bits;
2629 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2632 void *hb_ffmpeg_avstream( int codec_param )
2634 int slot = codec_param & (ffmpeg_sl_size - 1);
2635 int stream_index = codec_param >> ffmpeg_sl_bits;
2636 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2639 static AVFormatContext *ffmpeg_deferred_close;
2641 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2643 if ( ffmpeg_deferred_close )
2645 av_close_input_file( ffmpeg_deferred_close );
2646 ffmpeg_deferred_close = NULL;
2648 AVFormatContext *ic;
2650 av_log_set_level( AV_LOG_ERROR );
2651 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2655 if ( av_find_stream_info( ic ) < 0 )
2658 stream->ffmpeg_ic = ic;
2659 stream->hb_stream_type = ffmpeg;
2660 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2661 av_init_packet( stream->ffmpeg_pkt );
2662 stream->chapter_end = INT64_MAX;
2666 // we're opening for read. scan passed out codec params that
2667 // indexed its stream so we need to remap them so they point
2669 ffmpeg_remap_stream( stream, title );
2670 av_log_set_level( AV_LOG_ERROR );
2674 // we're opening for scan. let ffmpeg put some info into the
2675 // log about what we've got.
2676 av_log_set_level( AV_LOG_INFO );
2677 dump_format( ic, 0, stream->path, 0 );
2678 av_log_set_level( AV_LOG_ERROR );
2680 // accept this file if it has at least one video stream we can decode
2682 for (i = 0; i < ic->nb_streams; ++i )
2684 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2689 if ( i >= ic->nb_streams )
2695 av_close_input_file( ic );
2699 static void ffmpeg_close( hb_stream_t *d )
2701 // XXX since we're sharing the CodecContext with the downstream
2702 // decoder proc we can't close the stream. We need to reference count
2703 // this so we can close it when both are done with their instance but
2704 // for now just defer the close until the next stream open or close.
2705 if ( ffmpeg_deferred_close )
2707 av_close_input_file( ffmpeg_deferred_close );
2709 ffmpeg_deferred_close = d->ffmpeg_ic;
2710 if ( d->ffmpeg_pkt != NULL )
2712 free( d->ffmpeg_pkt );
2713 d->ffmpeg_pkt = NULL;
2717 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2719 AVStream *st = stream->ffmpeg_ic->streams[id];
2720 AVCodecContext *codec = st->codec;
2722 // scan will ignore any audio without a bitrate. Since we've already
2723 // typed the audio in order to determine its codec we set up the audio
2725 if ( codec->bit_rate || codec->sample_rate )
2727 static const int chan2layout[] = {
2728 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2729 HB_INPUT_CH_LAYOUT_MONO,
2730 HB_INPUT_CH_LAYOUT_STEREO,
2731 HB_INPUT_CH_LAYOUT_2F1R,
2732 HB_INPUT_CH_LAYOUT_2F2R,
2733 HB_INPUT_CH_LAYOUT_3F2R,
2734 HB_INPUT_CH_LAYOUT_4F2R,
2735 HB_INPUT_CH_LAYOUT_STEREO,
2736 HB_INPUT_CH_LAYOUT_STEREO,
2739 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2742 if ( codec->codec_id == CODEC_ID_AC3 )
2744 audio->config.in.codec = HB_ACODEC_AC3;
2746 else if ( codec->codec_id == CODEC_ID_DTS )
2748 audio->config.in.codec = HB_ACODEC_DCA;
2752 audio->config.in.codec = HB_ACODEC_FFMPEG;
2753 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2755 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2756 audio->config.in.samplerate = codec->sample_rate;
2757 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2760 set_audio_description( audio, lang_for_code2( st->language ) );
2762 hb_list_add( title->list_audio, audio );
2766 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2768 AVFormatContext *ic = stream->ffmpeg_ic;
2770 // 'Barebones Title'
2771 hb_title_t *title = hb_title_init( stream->path, 0 );
2772 title->type = HB_STREAM_TYPE;
2775 // Copy part of the stream path to the title name
2776 char *sep = strrchr(stream->path, '/');
2778 strcpy(title->name, sep+1);
2779 char *dot_term = strrchr(title->name, '.');
2783 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2784 title->duration = dur;
2786 title->hours = dur / 3600;
2787 title->minutes = ( dur % 3600 ) / 60;
2788 title->seconds = dur % 60;
2790 // set the title to decode the first video stream in the file
2791 title->demuxer = HB_NULL_DEMUXER;
2792 title->video_codec = 0;
2794 for (i = 0; i < ic->nb_streams; ++i )
2796 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2797 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2798 title->video_codec == 0 )
2800 title->video_id = i;
2801 stream->ffmpeg_video_id = i;
2803 // We have to use the 'internal' avcodec decoder because
2804 // it needs to share the codec context from this video
2805 // stream. The parser internal to av_read_frame
2806 // passes a bunch of state info to the decoder via the context.
2807 title->video_codec = WORK_DECAVCODECVI;
2808 title->video_codec_param = ffmpeg_codec_param( stream, i );
2810 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2811 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2813 add_ffmpeg_audio( title, stream, i );
2817 title->container_name = strdup( ic->iformat->name );
2818 title->data_rate = ic->bit_rate;
2820 hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );
2822 if( ic->nb_chapters != 0 )
2825 uint64_t duration_sum = 0;
2826 for( i = 0; i < ic->nb_chapters; i++ )
2827 if( ( m = ic->chapters[i] ) != NULL )
2829 hb_chapter_t * chapter;
2830 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2831 chapter->index = i+1;
2832 chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000 - duration_sum;
2833 duration_sum += chapter->duration;
2834 chapter->hours = chapter->duration / 90000 / 3600;
2835 chapter->minutes = ( ( chapter->duration / 90000 ) % 3600 ) / 60;
2836 chapter->seconds = ( chapter->duration / 90000 ) % 60;
2837 strcpy( chapter->title, m->title );
2838 hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
2839 chapter->index, chapter->title,
2840 chapter->duration, chapter->hours,
2841 chapter->minutes, chapter->seconds );
2842 hb_list_add( title->list_chapter, chapter );
2847 * Fill the metadata.
2849 decmetadata( title );
2851 if( hb_list_count( title->list_chapter ) == 0 )
2853 // Need at least one chapter
2854 hb_chapter_t * chapter;
2855 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2857 chapter->duration = title->duration;
2858 chapter->hours = title->hours;
2859 chapter->minutes = title->minutes;
2860 chapter->seconds = title->seconds;
2861 hb_list_add( title->list_chapter, chapter );
2867 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2869 if ( pts == AV_NOPTS_VALUE )
2871 return (int64_t)( (double)pts * conv_factor );
2874 static int ffmpeg_is_keyframe( hb_stream_t *stream )
2878 switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
2881 // XXX the VC1 codec doesn't mark key frames so to get previews
2882 // we do it ourselves here. The decoder gets messed up if it
2883 // doesn't get a SEQ header first so we consider that to be a key frame.
2884 pkt = stream->ffmpeg_pkt->data;
2885 if ( !pkt[0] && !pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
2891 // XXX the ffmpeg WMV3 codec doesn't mark key frames.
2892 // Only M$ could make I-frame detection this complicated: there
2893 // are two to four bits of unused junk ahead of the frame type
2894 // so we have to look at the sequence header to find out how much
2895 // to skip. Then there are three different ways of coding the type
2896 // depending on whether it's main or advanced profile then whether
2897 // there are bframes or not so we have to look at the sequence
2898 // header to get that.
2899 pkt = stream->ffmpeg_pkt->data;
2900 uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
2902 if ( ( seqhdr[3] & 0x02 ) == 0 )
2905 if ( ( seqhdr[3] & 0x80 ) == 0 )
2906 // no RANGEREDUCTION
2908 if ( seqhdr[3] & 0x70 )
2909 // stream has b-frames
2910 return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;
2912 return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;
2917 return ( stream->ffmpeg_pkt->flags & PKT_FLAG_KEY );
2920 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2924 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2926 // XXX the following conditional is to handle avi files that
2927 // use M$ 'packed b-frames' and occasionally have negative
2928 // sizes for the null frames these require.
2929 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2933 if ( stream->ffmpeg_pkt->size <= 0 )
2935 // M$ "invalid and inefficient" packed b-frames require 'null frames'
2936 // following them to preserve the timing (since the packing puts two
2937 // or more frames in what looks like one avi frame). The contents and
2938 // size of these null frames are ignored by the ff_h263_decode_frame
2939 // as long as they're < 20 bytes. We need a positive size so we use
2940 // one byte if we're given a zero or negative size. We don't know
2941 // if the pkt data points anywhere reasonable so we just stick a
2942 // byte of zero in our outbound buf.
2948 if ( stream->ffmpeg_pkt->size > buf->alloc )
2950 // sometimes we get absurd sizes from ffmpeg
2951 if ( stream->ffmpeg_pkt->size >= (1 << 25) )
2953 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
2954 av_free_packet( stream->ffmpeg_pkt );
2955 return ffmpeg_read( stream, buf );
2957 // need to expand buffer
2958 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2960 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2961 buf->size = stream->ffmpeg_pkt->size;
2963 buf->id = stream->ffmpeg_pkt->stream_index;
2964 if ( buf->id == stream->ffmpeg_video_id )
2966 if ( stream->need_keyframe )
2968 // we've just done a seek (generally for scan or live preview) and
2969 // want to start at a keyframe. Some ffmpeg codecs seek to a key
2970 // frame but most don't. So we spin until we either get a keyframe
2971 // or we've looked through 50 video frames without finding one.
2972 if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
2974 av_free_packet( stream->ffmpeg_pkt );
2977 stream->need_keyframe = 0;
2982 // if we haven't done it already, compute a conversion factor to go
2983 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2984 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2987 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2988 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2989 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2992 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2993 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2994 if ( buf->renderOffset >= 0 && buf->start == -1 )
2996 buf->start = buf->renderOffset;
2998 else if ( buf->renderOffset == -1 && buf->start >= 0 )
3000 buf->renderOffset = buf->start;
3004 * Check to see whether this video buffer is on a chapter
3005 * boundary, if so mark it as such in the buffer then advance
3006 * chapter_end to the end of the next chapter.
3007 * If there are no chapters, chapter_end is always initialized to INT64_MAX
3008 * (roughly 3 million years at our 90KHz clock rate) so the test
3009 * below handles both the chapters & no chapters case.
3011 if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
3013 hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
3014 stream->chapter+1 );
3018 stream->chapter_end += chapter->duration;
3019 buf->new_chap = stream->chapter + 1;
3020 hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
3021 buf->new_chap, buf->start);
3023 // Must have run out of chapters, stop looking.
3024 stream->chapter_end = INT64_MAX;
3029 av_free_packet( stream->ffmpeg_pkt );
3033 static int ffmpeg_seek( hb_stream_t *stream, float frac )
3035 AVFormatContext *ic = stream->ffmpeg_ic;
3038 int64_t pos = (double)ic->duration * (double)frac;
3039 if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
3041 pos += ic->start_time;
3043 av_seek_frame( ic, -1, pos, 0 );
3044 stream->need_keyframe = 1;
3048 av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
3053 // Assumes that we are always seeking forward
3054 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
3056 AVFormatContext *ic = stream->ffmpeg_ic;
3059 pos = ts * AV_TIME_BASE / 90000;
3060 stream->need_keyframe = 1;
3061 // Seek to the nearest timestamp before that requested where
3062 // there is an I-frame
3063 return av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );