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. */
13 #include "a52dec/a52.h"
14 #include "libavcodec/avcodec.h"
15 #include "libavformat/avformat.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 { U = 1, A, V } kind; /* 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, U, 0, 0, "ISO 13818-1 private section"),
44 st(0x06, U, 0, 0, "ISO 13818-1 PES private data"),
45 st(0x07, U, 0, 0, "ISO 13522 MHEG"),
46 st(0x08, U, 0, 0, "ISO 13818-1 DSM-CC"),
47 st(0x09, U, 0, 0, "ISO 13818-1 auxiliary"),
48 st(0x0a, U, 0, 0, "ISO 13818-6 encap"),
49 st(0x0b, U, 0, 0, "ISO 13818-6 DSM-CC U-N msgs"),
50 st(0x0c, U, 0, 0, "ISO 13818-6 Stream descriptors"),
51 st(0x0d, U, 0, 0, "ISO 13818-6 Sections"),
52 st(0x0e, U, 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, U, 0, 0, "ISO 13818-6 DSM-CC download"),
60 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
62 //st(0x80, U, 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, U, 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 15
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 int8_t need_keyframe; // non-zero if want to start at a keyframe
106 int8_t ts_no_RAP; // non-zero if there are no random access points
108 int8_t ts_found_pcr; // non-zero if we've found at least one input pcr
109 int ts_pcr_out; // sequence number of most recent output pcr
110 int ts_pcr_in; // sequence number of most recent input pcr
111 int64_t ts_pcr; // most recent input pcr
112 int64_t ts_pcrhist[4]; // circular buffer of output pcrs
114 uint8_t *ts_packet; /* buffer for one TS packet */
115 hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
116 int ts_pos[kMaxNumberDecodeStreams];
117 int8_t ts_skipbad[kMaxNumberDecodeStreams];
118 int8_t ts_streamcont[kMaxNumberDecodeStreams];
120 hb_buffer_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
123 * Stuff before this point is dynamic state updated as we read the
124 * stream. Stuff after this point is stream description state that
125 * we learn during the initial scan but cache so it can be
126 * reused during the conversion read.
128 uint8_t ts_number_video_pids;
129 uint8_t ts_number_audio_pids;
131 int16_t ts_video_pids[kMaxNumberVideoPIDS];
132 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
134 uint32_t ts_format_id[kMaxNumberDecodeStreams];
135 #define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
136 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
137 uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
141 hb_stream_type_t hb_stream_type;
144 AVFormatContext *ffmpeg_ic;
145 AVPacket *ffmpeg_pkt;
146 double ffmpeg_tsconv[MAX_STREAMS];
147 uint8_t ffmpeg_video_id;
154 } a52_info[kMaxNumberAudioPIDS];
158 unsigned short program_number;
159 unsigned short program_map_PID;
160 } pat_info[kMaxNumberPMTStreams];
161 int ts_number_pat_entries;
166 unsigned char *tablebuf;
167 unsigned int tablepos;
168 unsigned char current_continuity_counter;
172 unsigned int PCR_PID;
173 int program_info_length;
174 unsigned char *progam_info_descriptor_data;
177 unsigned char stream_type;
178 unsigned short elementary_PID;
179 unsigned short ES_info_length;
180 unsigned char *es_info_descriptor_data;
181 } pmt_stream_info[kMaxNumberPMTStreams];
185 /***********************************************************************
187 **********************************************************************/
188 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
189 static void hb_ts_stream_init(hb_stream_t *stream);
190 static void hb_ts_stream_find_pids(hb_stream_t *stream);
191 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
192 static void hb_ts_stream_reset(hb_stream_t *stream);
193 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
195 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
196 static off_t align_to_next_packet(hb_stream_t *stream);
198 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
199 static void ffmpeg_close( hb_stream_t *d );
200 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
201 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
202 static int ffmpeg_seek( hb_stream_t *stream, float frac );
205 * streams have a bunch of state that's learned during the scan. We don't
206 * want to throw away the state when scan does a close then relearn
207 * everything when reader does an open. So we save the stream state on
208 * the close following a scan and reuse it when 'reader' does an open.
210 static hb_list_t *stream_state_list;
212 static hb_stream_t *hb_stream_lookup( const char *path )
214 if ( stream_state_list == NULL )
220 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
222 if ( strcmp( path, ss->path ) == 0 )
230 static void hb_stream_state_delete( hb_stream_t *ss )
232 hb_list_rem( stream_state_list, ss );
239 * these frontend hb_log because transport streams can have a lot of errors
240 * so we want to rate limit messages. this routine limits the number of
241 * messages to at most one per minute of video. other errors that occur
242 * during the minute are counted & the count is output with the next
243 * error msg we print.
245 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
247 // limit error printing to at most one per minute of video (at 30fps)
249 if ( stream->frames - stream->last_error_frame >= 30*60 )
253 vsnprintf( msg, sizeof(msg), log, args );
255 if ( stream->errors - stream->last_error_count < 10 )
257 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
261 int Edelta = stream->errors - stream->last_error_count;
262 double Epcnt = (double)Edelta * 100. /
263 (stream->frames - stream->last_error_frame);
264 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
265 Edelta, Epcnt, stream->frames, msg );
267 stream->last_error_frame = stream->frames;
268 stream->last_error_count = stream->errors;
272 static void ts_warn( hb_stream_t *stream, char *log, ... )
275 va_start( args, log );
276 ts_warn_helper( stream, log, args );
280 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
283 va_start( args, log );
284 ts_warn_helper( stream, log, args );
287 stream->ts_skipbad[curstream] = 1;
288 stream->ts_pos[curstream] = 0;
289 stream->ts_streamcont[curstream] = -1;
292 static int check_ps_sync(const uint8_t *buf)
294 // a legal MPEG program stream must start with a Pack header in the
296 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
297 (buf[2] == 0x01) && (buf[3] == 0xba);
300 static int check_ps_sys(const uint8_t *buf)
302 // a legal MPEG program stream must start with a Pack followed by a
303 // SYS. If we've already verified the pack, this skips over it and checks
304 // for the sys header.
305 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
306 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
307 (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
310 static int check_ts_sync(const uint8_t *buf)
312 // must have initial sync byte, no scrambling & a legal adaptation ctrl
313 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
316 static int have_ts_sync(const uint8_t *buf, int psize)
318 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
319 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
320 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
321 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
324 static int hb_stream_check_for_ts(const uint8_t *buf)
326 // transport streams should have a sync byte every 188 bytes.
327 // search the first 8KB of buf looking for at least 8 consecutive
328 // correctly located sync patterns.
331 for ( offset = 0; offset < 8*1024-8*188; ++offset )
333 if ( have_ts_sync( &buf[offset], 188) )
334 return 188 | (offset << 8);
335 if ( have_ts_sync( &buf[offset], 192) )
336 return 192 | (offset << 8);
337 if ( have_ts_sync( &buf[offset], 204) )
338 return 204 | (offset << 8);
339 if ( have_ts_sync( &buf[offset], 208) )
340 return 208 | (offset << 8);
345 static int hb_stream_check_for_ps(const uint8_t *buf)
347 // program streams should start with a PACK then a SYS header.
348 return check_ps_sync(buf) && check_ps_sys(buf);
351 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
353 // DVD program streams should have a Pack header every 2048 bytes.
354 // check that we have 4 of these in a row.
355 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
356 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
359 static int hb_stream_get_type(hb_stream_t *stream)
363 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
366 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
368 int offset = psize >> 8;
370 hb_log("file is MPEG Transport Stream with %d byte packets"
371 " offset %d bytes", psize, offset);
372 stream->packetsize = psize;
373 stream->hb_stream_type = transport;
374 hb_ts_stream_init(stream);
375 if ( !stream->ts_number_video_pids || !stream->ts_number_audio_pids )
381 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
383 hb_log("file is MPEG DVD Program Stream");
384 stream->hb_stream_type = dvd_program;
387 if ( hb_stream_check_for_ps(buf) != 0 )
389 hb_log("file is MPEG Program Stream");
390 stream->hb_stream_type = program;
397 static void hb_stream_delete_dynamic( hb_stream_t *d )
401 fclose( d->file_handle );
402 d->file_handle = NULL;
409 free( d->ts_packet );
412 for (i = 0; i < kMaxNumberDecodeStreams; i++)
416 hb_buffer_close(&(d->ts_buf[i]));
422 static void hb_stream_delete( hb_stream_t *d )
424 hb_stream_delete_dynamic( d );
429 /***********************************************************************
431 ***********************************************************************
433 **********************************************************************/
434 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
436 FILE *f = fopen( path, "r" );
439 hb_log( "hb_stream_open: open %s failed", path );
443 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
447 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
452 * if we're opening the stream to read & convert, we need
453 * the state we saved when we scanned the stream. if we're
454 * opening the stream to scan it we want to rebuild the state
455 * (even if we have saved state, the stream may have changed).
457 hb_stream_t *ss = hb_stream_lookup( path );
458 if ( title && ss && ss->hb_stream_type != ffmpeg )
461 * copy the saved state since we might be encoding the same stream
464 memcpy( d, ss, sizeof(*d) );
467 d->path = strdup( path );
469 if ( d->hb_stream_type == transport )
471 d->ts_packet = malloc( d->packetsize );
474 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
476 d->ts_buf[i] = hb_buffer_init(d->packetsize);
477 d->ts_buf[i]->size = 0;
479 hb_stream_seek( d, 0. );
481 if ( d->packetsize == 188 )
483 // Assume that an over-the-air transport stream can lose PCR
484 // packets and try to filter out the timing inconsistencies.
485 title->flaky_clock = 1;
492 * opening for scan - delete any saved state then (re)scan the stream.
493 * If it's something we can deal with (MPEG2 PS or TS) return a stream
494 * reference structure & null otherwise.
498 hb_stream_state_delete( ss );
502 d->path = strdup( path );
503 if (d->path != NULL )
505 if ( hb_stream_get_type( d ) != 0 )
509 fclose( d->file_handle );
510 d->file_handle = NULL;
511 if ( ffmpeg_open( d, title ) )
516 if ( d->file_handle )
518 fclose( d->file_handle );
524 hb_log( "hb_stream_open: open %s failed", path );
529 /***********************************************************************
531 ***********************************************************************
532 * Closes and frees everything
533 **********************************************************************/
534 void hb_stream_close( hb_stream_t ** _d )
536 hb_stream_t *stream = * _d;
538 if ( stream->hb_stream_type == ffmpeg )
540 ffmpeg_close( stream );
541 hb_stream_delete( stream );
546 if ( stream->frames )
548 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
549 stream->errors, (double)stream->errors * 100. /
550 (double)stream->frames );
554 * if the stream was opened for a scan, cache the result, otherwise delete
557 if ( stream->title == NULL )
559 hb_stream_delete_dynamic( stream );
560 if ( stream_state_list == NULL )
562 stream_state_list = hb_list_init();
564 hb_list_add( stream_state_list, stream );
568 hb_stream_delete( stream );
573 /* when the file was first opened we made entries for all the audio elementary
574 * streams we found in it. Streams that were later found during the preview scan
575 * now have an audio codec, type, rate, etc., associated with them. At the end
576 * of the scan we delete all the audio entries that weren't found by the scan
577 * or don't have a format we support. This routine deletes audio entry 'indx'
578 * by setting its PID to an invalid value so no packet will match it. (We can't
579 * move any of the entries since the index of the entry is used as the id
580 * of the media stream for HB. */
581 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
583 stream->ts_audio_pids[indx] = -stream->ts_audio_pids[indx];
586 static int index_of_pid(int pid, hb_stream_t *stream)
590 if ( pid == stream->ts_video_pids[0] )
593 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
594 if ( pid == stream->ts_audio_pids[i] )
600 /***********************************************************************
601 * hb_ps_stream_title_scan
602 ***********************************************************************
604 **********************************************************************/
605 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
607 if ( stream->hb_stream_type == ffmpeg )
608 return ffmpeg_title_scan( stream );
611 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
614 // Copy part of the stream path to the title name
615 char *sep = strrchr(stream->path, '/');
617 strcpy(aTitle->name, sep+1);
618 char *dot_term = strrchr(aTitle->name, '.');
622 // Height, width, rate and aspect ratio information is filled in when the previews are built
624 hb_stream_duration(stream, aTitle);
627 hb_chapter_t * chapter;
628 chapter = calloc( sizeof( hb_chapter_t ), 1 );
630 chapter->duration = aTitle->duration;
631 chapter->hours = aTitle->hours;
632 chapter->minutes = aTitle->minutes;
633 chapter->seconds = aTitle->seconds;
634 hb_list_add( aTitle->list_chapter, chapter );
636 // Figure out how many audio streams we really have:
637 // - For transport streams, for each PID listed in the PMT (whether
638 // or not it was an audio stream type) read the bitstream until we
639 // find an packet from that PID containing a PES header and see if
640 // the elementary stream is an audio type.
641 // - For program streams read the first 4MB and take every unique
642 // audio stream we find.
643 if (stream->hb_stream_type == transport)
647 for (i=0; i < stream->ts_number_audio_pids; i++)
649 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
650 if (audio->config.in.codec)
651 hb_list_add( aTitle->list_audio, audio );
655 hb_stream_delete_audio_entry(stream, i);
659 // make sure we're grabbing the PCR PID
660 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
662 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
663 stream->pmt_info.PCR_PID;
666 // set the video id, codec & muxer
667 aTitle->video_id = 0;
668 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
669 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
670 aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
674 hb_ps_stream_find_audio_ids(stream, aTitle);
681 * read the next transport stream packet from 'stream'. Return NULL if
682 * we hit eof & a pointer to the sync byte otherwise.
684 static const uint8_t *next_packet( hb_stream_t *stream )
686 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
690 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
699 // lost sync - back up to where we started then try to re-establish.
700 off_t pos = ftello(stream->file_handle) - stream->packetsize;
701 off_t pos2 = align_to_next_packet(stream);
704 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
707 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
713 * skip to the start of the next PACK header in program stream src_stream.
715 static void skip_to_next_pack( hb_stream_t *src_stream )
717 // scan forward until we find the start of the next pack
718 uint32_t strt_code = -1;
721 flockfile( src_stream->file_handle );
722 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
724 strt_code = ( strt_code << 8 ) | c;
725 if ( strt_code == 0x000001ba )
726 // we found the start of the next pack
729 funlockfile( src_stream->file_handle );
731 // if we didn't terminate on an eof back up so the next read
732 // starts on the pack boundary.
735 fseeko( src_stream->file_handle, -4, SEEK_CUR );
740 * scan the next MB of 'stream' to try to find a random access point
742 static void hb_ts_stream_find_RAP( hb_stream_t *stream )
744 off_t starting_point = ftello(stream->file_handle);
745 int npack = 300000; // max packets to read
749 off_t cur = ftello(stream->file_handle);
750 const uint8_t *buf = next_packet( stream );
755 switch (buf[3] & 0x30)
757 case 0x00: // illegal
760 case 0x20: // fill packet
761 case 0x30: // adaptation
764 // found a random access point
765 fseeko( stream->file_handle, cur, SEEK_SET );
773 fseeko( stream->file_handle, starting_point, SEEK_SET );
774 stream->ts_no_RAP = 1;
778 * scan the next MB of 'stream' to find the next start packet for
779 * the Packetized Elementary Stream associated with TS PID 'pid'.
781 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
783 int npack = 300000; // max packets to read
787 const uint8_t *buf = next_packet( stream );
790 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
795 * The PES header is only in TS packets with 'start' set so we check
796 * that first then check for the right PID.
798 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
799 buf[2] != (pid & 0xff))
801 // not a start packet or not the pid we want
805 /* skip over the TS hdr to return a pointer to the PES hdr */
807 switch (buf[3] & 0x30)
809 case 0x00: // illegal
810 case 0x20: // fill packet
813 case 0x30: // adaptation
816 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
822 /* PES hdr has to begin with an mpeg start code */
823 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
833 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
835 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
836 hb_list_t *list = hb_list_init();
837 // how many blocks we read while searching for a video PES header
841 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
845 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
846 hb_demux_ps( buf, list, 0 );
848 while ( ( es = hb_list_item( list, 0 ) ) )
850 hb_list_rem( list, es );
851 if ( es->id == 0xe0 )
853 // this PES contains video - if there's a PTS we're done
854 // hb_demux_ps left the PTS in buf_es->start.
855 if ( es->start != ~0 )
862 hb_buffer_close( &es );
865 hb_list_empty( &list );
866 hb_buffer_close(&buf);
870 /***********************************************************************
872 ***********************************************************************
874 * Finding stream duration is difficult. One issue is that the video file
875 * may have chunks from several different program fragments (main feature,
876 * commercials, station id, trailers, etc.) all with their own base pts
877 * value. We can't find the piece boundaries without reading the entire
878 * file but if we compute a rate based on time stamps from two different
879 * pieces the result will be meaningless. The second issue is that the
880 * data rate of compressed video normally varies by 5-10x over the length
881 * of the video. This says that we want to compute the rate over relatively
882 * long segments to get a representative average but long segments increase
883 * the likelihood that we'll cross a piece boundary.
885 * What we do is take time stamp samples at several places in the file
886 * (currently 16) then compute the average rate (i.e., ticks of video per
887 * byte of the file) for all pairs of samples (N^2 rates computed for N
888 * samples). Some of those rates will be absurd because the samples came
889 * from different segments. Some will be way low or high because the
890 * samples came from a low or high motion part of the segment. But given
891 * that we're comparing *all* pairs the majority of the computed rates
892 * should be near the overall average. So we median filter the computed
893 * rates to pick the most representative value.
895 **********************************************************************/
897 uint64_t pos; /* file position of this PTS sample */
898 uint64_t pts; /* PTS from video stream */
901 #define NDURSAMPLES 16
903 // get one (position, timestamp) sampple from a transport or program
905 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
907 struct pts_pos pp = { 0, 0 };
909 if ( stream->hb_stream_type == transport )
912 fseeko( stream->file_handle, fpos, SEEK_SET );
913 align_to_next_packet( stream );
914 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
917 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
920 if ( ( buf[7] >> 7 ) != 1 )
922 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
925 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
926 ( (uint64_t)buf[10] << 22 ) |
927 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
928 ( (uint64_t)buf[12] << 7 ) |
929 ( (uint64_t)buf[13] >> 1 );
933 // round address down to nearest dvd sector start
934 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
935 fseeko( stream->file_handle, fpos, SEEK_SET );
936 if ( stream->hb_stream_type == program )
938 skip_to_next_pack( stream );
940 pp.pts = hb_ps_stream_getVideoPTS( stream );
942 pp.pos = ftello(stream->file_handle);
946 static int dur_compare( const void *a, const void *b )
948 const double *aval = a, *bval = b;
949 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
952 // given an array of (position, time) samples, compute a max-likelihood
953 // estimate of the average rate by computing the rate between all pairs
954 // of samples then taking the median of those rates.
955 static double compute_stream_rate( struct pts_pos *pp, int n )
958 double rates[NDURSAMPLES * NDURSAMPLES / 2];
961 // the following nested loops compute the rates between all pairs.
963 for ( i = 0; i < n-1; ++i )
965 // Bias the median filter by not including pairs that are "far"
966 // from one another. This is to handle cases where the file is
967 // made of roughly equal size pieces where a symmetric choice of
968 // pairs results in having the same number of intra-piece &
969 // inter-piece rate estimates. This would mean that the median
970 // could easily fall in the inter-piece part of the data which
971 // would give a bogus estimate. The 'ns' index creates an
972 // asymmetry that favors locality.
973 int ns = i + ( n >> 1 );
976 for ( j = i+1; j < ns; ++j )
978 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
980 *rp = ((double)( pp[j].pts - pp[i].pts )) /
981 ((double)( pp[j].pos - pp[i].pos ));
986 // now compute and return the median of all the (n*n/2) rates we computed
988 int nrates = rp - rates;
989 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
990 return rates[nrates >> 1];
993 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
995 struct pts_pos ptspos[NDURSAMPLES];
996 struct pts_pos *pp = ptspos;
999 fseeko(stream->file_handle, 0, SEEK_END);
1000 uint64_t fsize = ftello(stream->file_handle);
1001 uint64_t fincr = fsize / NDURSAMPLES;
1002 uint64_t fpos = fincr / 2;
1003 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1005 *pp++ = hb_sample_pts(stream, fpos);
1007 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1008 inTitle->duration = dur;
1010 inTitle->hours = dur / 3600;
1011 inTitle->minutes = ( dur % 3600 ) / 60;
1012 inTitle->seconds = dur % 60;
1014 rewind(stream->file_handle);
1017 /***********************************************************************
1019 ***********************************************************************
1021 **********************************************************************/
1022 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1024 if ( src_stream->hb_stream_type == ffmpeg )
1026 return ffmpeg_read( src_stream, b );
1028 if ( src_stream->hb_stream_type == dvd_program )
1030 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1031 src_stream->file_handle);
1032 return (amt_read > 0);
1034 if ( src_stream->hb_stream_type == program )
1036 // a general program stream has arbitrary sized pack's. we're
1037 // currently positioned at the start of a pack so read up to but
1038 // not including the start of the next, expanding the buffer
1040 uint8_t *cp = b->data;
1041 uint8_t *ep = cp + b->alloc;
1042 uint32_t strt_code = -1;
1045 // consume the first byte of the initial pack so we don't match on
1046 // it in the loop below.
1047 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1052 flockfile( src_stream->file_handle );
1053 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1055 strt_code = ( strt_code << 8 ) | c;
1056 if ( strt_code == 0x000001ba )
1057 // we found the start of the next pack
1061 // need to expand the buffer
1062 int curSize = cp - b->data;
1063 hb_buffer_realloc( b, curSize * 2 );
1064 cp = b->data + curSize;
1065 ep = b->data + b->alloc;
1069 funlockfile( src_stream->file_handle );
1071 // if we didn't terminate on an eof back up so the next read
1072 // starts on the pack boundary.
1073 b->size = cp - b->data;
1076 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1081 return hb_ts_stream_decode( src_stream, b );
1084 /***********************************************************************
1086 ***********************************************************************
1088 **********************************************************************/
1089 int hb_stream_seek( hb_stream_t * stream, float f )
1091 if ( stream->hb_stream_type == ffmpeg )
1093 return ffmpeg_seek( stream, f );
1095 off_t stream_size, cur_pos, new_pos;
1096 double pos_ratio = f;
1097 cur_pos = ftello( stream->file_handle );
1098 fseeko( stream->file_handle, 0, SEEK_END );
1099 stream_size = ftello( stream->file_handle );
1100 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1101 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1103 int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1106 fseeko( stream->file_handle, cur_pos, SEEK_SET );
1110 if ( stream->hb_stream_type == transport )
1112 // We need to drop the current decoder output and move
1113 // forwards to the next transport stream packet.
1114 hb_ts_stream_reset(stream);
1117 if ( !stream->ts_no_RAP )
1119 // we're not at the beginning - try to find a random access point
1120 hb_ts_stream_find_RAP( stream );
1122 stream->need_keyframe = 1;
1126 // we're at the beginning - say we have video sync so that we
1127 // won't drop initial SPS & PPS data on an AVC stream.
1128 stream->need_keyframe = 0;
1131 else if ( stream->hb_stream_type == program )
1133 skip_to_next_pack( stream );
1139 static const char* make_upper( const char* s )
1141 static char name[8];
1143 char *ep = cp + sizeof(name)-1;
1145 while ( *s && cp < ep )
1147 *cp++ = islower(*s)? toupper(*s) : *s;
1154 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1157 * This is a duplicate of code in dvd.c - it should get factored out
1158 * into a common routine. We probably should only be putting the lang
1159 * code or a lang pointer into the audio config & let the common description
1160 * formatting routine in scan.c do all the stuff below.
1162 const char *codec_name;
1165 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1166 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1167 avcodec_find_decoder( cc->codec_id ) )
1169 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1170 if ( !strcmp( codec_name, "LIBFAAD" ) )
1175 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1176 avcodec_find_decoder( audio->config.in.codec_param ) )
1178 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1182 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1183 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1184 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1185 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1186 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1189 snprintf( audio->config.lang.description,
1190 sizeof( audio->config.lang.description ), "%s (%s)",
1191 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1193 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1194 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1195 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1196 "%s", lang->iso639_2);
1199 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1202 off_t cur_pos = ftello(stream->file_handle);
1203 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1206 fseeko(stream->file_handle, 0, SEEK_SET);
1207 align_to_next_packet(stream);
1208 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1210 /* check that we found a PES header */
1212 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1214 stype = stream->ts_stream_type[1 + aud_pid_index];
1216 // 0xbd ("private stream 1") is the normal container for non-ISO
1217 // media - AC3/DCA/PCM/etc.
1218 if ( buf[3] == 0xbd )
1220 if ( st2codec[stype].kind == U )
1222 // XXX assume unknown stream types are AC-3 (if they're not
1223 // audio we'll find that out during the scan but if they're
1224 // some other type of audio we'll end up ignoring them).
1226 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1229 else if ( buf[3] == 0xfd )
1231 // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1232 // the blu ray consortium apparently forgot to read the portion
1233 // of the MPEG spec that says one PID should map to one media
1234 // stream and multiplexed multiple types of audio into one PID
1235 // using the extended stream identifier of the PES header to
1236 // distinguish them. So we have to check if that's happening and
1237 // if so tell the runtime what esid we want.
1238 if ( st2codec[stype].kind == A && stype == 0x83 &&
1239 stream->ts_format_id[1 + aud_pid_index] == TS_FORMAT_ID_AC3 )
1241 // This is an interleaved TrueHD/AC-3 stream and the esid of
1243 stream->ts_multiplexed[1 + aud_pid_index] = 0x76;
1245 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1247 if ( st2codec[stype].kind == A && stype == 0x86 )
1249 // This is an interleaved DTS-HD/DTS stream and the esid of
1251 stream->ts_multiplexed[1 + aud_pid_index] = 0x71;
1253 stream->ts_stream_type[1 + aud_pid_index] = 0x82;
1256 else if ((buf[3] & 0xe0) == 0xc0)
1258 // 0xC0 - 0xCF are the normal containers for ISO-standard
1259 // media (mpeg2 audio and mpeg4 AAC).
1260 if ( st2codec[stype].kind == U )
1262 // XXX assume unknown stream types are MPEG audio
1264 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1272 // if we found an audio stream type & HB has a codec that can decode it
1273 // finish configuring the audio so we'll add it to the title's list.
1274 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1276 audio->id = 1 + aud_pid_index;
1277 audio->config.in.codec = st2codec[stype].codec;
1278 audio->config.in.codec_param = st2codec[stype].codec_param;
1279 set_audio_description( audio,
1280 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1281 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1282 stream->ts_audio_pids[aud_pid_index],
1283 stype, st2codec[stype].name, audio->id);
1289 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1290 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1291 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1295 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1296 stream->ts_audio_pids[aud_pid_index],
1297 stream->ts_stream_type[1 + aud_pid_index]);
1300 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1304 static void add_audio_to_title(hb_title_t *title, int id)
1306 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1312 audio->config.in.codec = HB_ACODEC_MPGA;
1313 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1316 // type 2 is a DVD subtitle stream - just ignore it */
1320 audio->config.in.codec = HB_ACODEC_AC3;
1321 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1324 audio->config.in.codec = HB_ACODEC_LPCM;
1325 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1328 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1333 set_audio_description( audio, lang_for_code( 0 ) );
1334 hb_list_add( title->list_audio, audio );
1337 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1339 off_t cur_pos = ftello(stream->file_handle);
1340 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1341 hb_list_t *list = hb_list_init();
1342 // how many blocks we read while searching for audio streams
1343 int blksleft = 4096;
1344 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1345 // so we use a bitmap to keep track of the ones we've already seen.
1346 // Bit 'i' of smap is set if we've already added the audio for
1347 // audio substream id 'i' to the title's audio list.
1350 // start looking 20% into the file since there's occasionally no
1351 // audio at the beginning (particularly for vobs).
1352 hb_stream_seek(stream, 0.2f);
1354 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1358 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1359 hb_demux_ps( buf, list, 0 );
1361 while ( ( es = hb_list_item( list, 0 ) ) )
1363 hb_list_rem( list, es );
1364 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1366 // this PES contains some kind of audio - get the substream id
1367 // and check if we've seen it already.
1368 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1369 if ( (smap & (1 << ssid)) == 0 )
1371 // we haven't seen this stream before - add it to the
1372 // title's list of audio streams.
1373 smap |= (1 << ssid);
1374 add_audio_to_title(title, es->id);
1377 hb_buffer_close( &es );
1380 hb_list_empty( &list );
1381 hb_buffer_close(&buf);
1382 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1385 /***********************************************************************
1387 ***********************************************************************
1389 **********************************************************************/
1391 static void hb_ts_stream_init(hb_stream_t *stream)
1395 for (i=0; i < kMaxNumberDecodeStreams; i++)
1397 stream->ts_streamcont[i] = -1;
1399 stream->ts_video_pids[0] = -1;
1400 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1402 stream-> ts_audio_pids[i] = -1;
1405 stream->ts_packet = malloc( stream->packetsize );
1407 // Find the audio and video pids in the stream
1408 hb_ts_stream_find_pids(stream);
1410 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1412 // demuxing buffer for TS to PS conversion
1413 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1414 stream->ts_buf[i]->size = 0;
1418 #define MAX_HOLE 208*80
1420 static off_t align_to_next_packet(hb_stream_t *stream)
1422 uint8_t buf[MAX_HOLE];
1424 off_t start = ftello(stream->file_handle);
1426 if ( start >= stream->packetsize ) {
1427 start -= stream->packetsize;
1428 fseeko(stream->file_handle, start, SEEK_SET);
1431 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1433 const uint8_t *bp = buf;
1436 for ( i = sizeof(buf); --i >= 0; ++bp )
1438 if ( have_ts_sync( bp, stream->packetsize ) )
1445 pos = ( bp - buf ) - stream->packetsize + 188;
1450 fseeko(stream->file_handle, start+pos, SEEK_SET);
1461 static const unsigned int bitmask[] = {
1462 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1463 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1464 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1465 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1467 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1471 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1472 (bb->buf[2] << 8) | bb->buf[3];
1474 memset(bb->buf, 0, bufsize);
1477 static inline int buf_size(bitbuf_t *bb)
1479 return bb->pos >> 3;
1482 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1485 int left = 32 - (bb->pos & 31);
1489 val = (bb->val >> (left - bits)) & bitmask[bits];
1494 val = (bb->val & bitmask[left]) << (bits - left);
1498 int pos = bb->pos >> 3;
1499 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1503 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1511 // extract what useful information we can from the elementary stream
1512 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1513 // Descriptors with info we don't currently use are ignored.
1514 // The descriptor list & descriptor item formats are defined in
1515 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1516 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1517 const uint8_t *dp, uint8_t dlen)
1519 const uint8_t *ep = dp + dlen;
1525 case 5: // Registration descriptor
1526 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1527 (dp[4] << 8) | dp[5];
1530 case 10: // ISO_639_language descriptor
1531 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1541 static const char *stream_type_name (uint8_t stream_type)
1543 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1546 int decode_program_map(hb_stream_t* stream)
1549 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1551 get_bits(&bb, 8); // table_id
1553 unsigned int section_length = get_bits(&bb, 12);
1554 stream->pmt_info.section_length = section_length;
1556 unsigned int program_number = get_bits(&bb, 16);
1557 stream->pmt_info.program_number = program_number;
1559 get_bits(&bb, 5); // version_number
1561 get_bits(&bb, 8); // section_number
1562 get_bits(&bb, 8); // last_section_number
1564 unsigned int PCR_PID = get_bits(&bb, 13);
1565 stream->pmt_info.PCR_PID = PCR_PID;
1567 unsigned int program_info_length = get_bits(&bb, 12);
1568 stream->pmt_info.program_info_length = program_info_length;
1571 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1572 for (i = 0; i < program_info_length; i++)
1574 descriptor_buf[i] = get_bits(&bb, 8);
1577 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1578 int done_reading_stream_types = 0;
1579 while (!done_reading_stream_types)
1581 unsigned char stream_type = get_bits(&bb, 8);
1583 unsigned int elementary_PID = get_bits(&bb, 13);
1585 unsigned int ES_info_length = get_bits(&bb, 12);
1588 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1589 for (i=0; i < ES_info_length; i++)
1591 ES_info_buf[i] = get_bits(&bb, 8);
1595 if ( index_of_pid( elementary_PID, stream ) < 0 )
1597 // already have this pid - do nothing
1599 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1601 stream->ts_video_pids[0] = elementary_PID;
1602 stream->ts_stream_type[0] = stream_type;
1603 stream->ts_number_video_pids = 1;
1607 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1608 // for mpeg audio. But content producers seem to use other
1609 // values (0x04 and 0x06 have both been observed) so at this point
1610 // we say everything that isn't a video pid is audio then at the end
1611 // of hb_stream_title_scan we'll figure out which are really audio
1612 // by looking at the PES headers.
1613 i = stream->ts_number_audio_pids;
1614 if (i < kMaxNumberAudioPIDS)
1616 stream->ts_audio_pids[i] = elementary_PID;
1617 stream->ts_stream_type[1 + i] = stream_type;
1618 if (ES_info_length > 0)
1620 decode_element_descriptors(stream, i, ES_info_buf,
1623 ++stream->ts_number_audio_pids;
1627 cur_pos += 5 /* stream header */ + ES_info_length;
1631 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1632 done_reading_stream_types = 1;
1635 free(descriptor_buf);
1639 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1641 // Get adaption header info
1643 int adaption = (buf[3] & 0x30) >> 4;
1646 else if (adaption == 0x2)
1648 else if (adaption == 0x3)
1649 adapt_len = buf[4] + 1;
1650 if (adapt_len > 184)
1653 // Get payload start indicator
1655 start = (buf[1] & 0x40) != 0;
1657 // Get pointer length - only valid in packets with a start flag
1658 int pointer_len = 0;
1662 pointer_len = buf[4 + adapt_len] + 1;
1663 stream->pmt_info.tablepos = 0;
1665 // Get Continuity Counter
1666 int continuity_counter = buf[3] & 0x0f;
1667 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1669 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1672 stream->pmt_info.current_continuity_counter = continuity_counter;
1673 stream->pmt_info.reading |= start;
1675 // Add the payload for this packet to the current buffer
1676 int amount_to_copy = 184 - adapt_len - pointer_len;
1677 if (stream->pmt_info.reading && (amount_to_copy > 0))
1679 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1681 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1682 stream->pmt_info.tablepos += amount_to_copy;
1684 if (stream->pmt_info.tablepos > 3)
1686 // We have enough to check the section length
1688 length = ((stream->pmt_info.tablebuf[1] << 8) +
1689 stream->pmt_info.tablebuf[2]) & 0xFFF;
1690 if (stream->pmt_info.tablepos > length + 1)
1692 // We just finished a bunch of packets - parse the program map details
1694 if (stream->pmt_info.tablebuf[0] == 0x02)
1695 decode_ok = decode_program_map(stream);
1696 free(stream->pmt_info.tablebuf);
1697 stream->pmt_info.tablebuf = NULL;
1698 stream->pmt_info.tablepos = 0;
1699 stream->pmt_info.reading = 0;
1709 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1711 unsigned char tablebuf[1024];
1712 unsigned int tablepos = 0;
1717 // Get adaption header info
1719 int adaption = (buf[3] & 0x30) >> 4;
1722 else if (adaption == 0x2)
1724 else if (adaption == 0x3)
1725 adapt_len = buf[4] + 1;
1726 if (adapt_len > 184)
1729 // Get pointer length
1730 int pointer_len = buf[4 + adapt_len] + 1;
1732 // Get payload start indicator
1734 start = (buf[1] & 0x40) != 0;
1739 // Add the payload for this packet to the current buffer
1740 if (reading && (184 - adapt_len) > 0)
1742 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1744 hb_log("decode_PAT - Bad program section length (> 1024)");
1747 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1748 tablepos += 184 - adapt_len - pointer_len;
1751 if (start && reading)
1753 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1756 unsigned int pos = 0;
1757 //while (pos < tablepos)
1760 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1762 unsigned char section_id = get_bits(&bb, 8);
1764 unsigned int section_len = get_bits(&bb, 12);
1765 get_bits(&bb, 16); // transport_id
1767 get_bits(&bb, 5); // version_num
1768 get_bits(&bb, 1); // current_next
1769 get_bits(&bb, 8); // section_num
1770 get_bits(&bb, 8); // last_section
1776 // Program Association Section
1777 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1778 section_len -= 4; // Ignore the CRC
1780 stream->ts_number_pat_entries = 0;
1781 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1783 unsigned int pkt_program_num = get_bits(&bb, 16);
1784 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1786 get_bits(&bb, 3); // Reserved
1787 if (pkt_program_num == 0)
1789 get_bits(&bb, 13); // pkt_network_id
1793 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1794 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1797 stream->ts_number_pat_entries++;
1811 pos += 3 + section_len;
1819 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1821 // align to first packet
1822 align_to_next_packet(stream);
1824 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1825 // to find the program map PID and then decode that to get the list of audio and video PIDs
1829 const uint8_t *buf = next_packet( stream );
1833 hb_log("hb_ts_stream_find_pids - end of file");
1838 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1840 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1842 decode_PAT(buf, stream);
1847 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1849 // There are some streams where the PAT table has multiple entries as if their are
1850 // multiple programs in the same transport stream, and yet there's actually only one
1851 // program really in the stream. This seems to be true for transport streams that
1852 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1853 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1854 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1855 // PAT info on export to match what's actually on the stream.
1856 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1857 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1858 // be to build a title choice popup from the PAT program number details and then select from
1859 // their - but right now the API's not capable of that.
1860 if (stream->pat_info[pat_index].program_number != 0 &&
1861 pid == stream->pat_info[pat_index].program_map_PID)
1863 if (build_program_map(buf, stream) > 0)
1867 // Keep going until we have a complete set of PIDs
1868 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1871 // XXX - until we figure out how to handle VC1 just bail when we find it so
1872 // that ffmpeg will claim the input stream.
1873 if ( stream->ts_stream_type[0] == 0xea )
1875 stream->ts_number_video_pids = 0;
1876 stream->ts_number_audio_pids = 0;
1880 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1881 hb_log(" Video PIDS : ");
1883 for (i=0; i < stream->ts_number_video_pids; i++)
1885 hb_log( " 0x%x type %s (0x%x)",
1886 stream->ts_video_pids[i],
1887 stream_type_name(stream->ts_stream_type[i]),
1888 stream->ts_stream_type[i]);
1890 hb_log(" Audio PIDS : ");
1891 for (i = 0; i < stream->ts_number_audio_pids; i++)
1893 hb_log( " 0x%x type %s (0x%x)",
1894 stream->ts_audio_pids[i],
1895 stream_type_name(stream->ts_stream_type[i+1]),
1896 stream->ts_stream_type[i+1] );
1901 static void fwrite64( hb_stream_t *stream, void *buf, int len )
1905 pos = stream->fwrite_buf->size;
1906 if ( pos + len > stream->fwrite_buf->alloc )
1908 int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
1909 hb_buffer_realloc(stream->fwrite_buf, size);
1911 memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
1912 stream->fwrite_buf->size += len;
1915 // convert a PES PTS or DTS to an int64
1916 static int64_t pes_timestamp( const uint8_t *pes )
1918 int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
1919 ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
1920 ( pes[3] << 7 ) | ( pes[4] >> 1 );
1924 static void generate_output_data(hb_stream_t *stream, int curstream)
1926 hb_buffer_t *buf = stream->fwrite_buf;
1927 uint8_t *tdat = stream->ts_buf[curstream]->data;
1929 buf->id = curstream;
1931 // check if this packet was referenced to an older pcr and if that
1932 // pcr was significantly different than the one we're using now.
1933 // (the reason for the uint cast on the pcr difference is that the
1934 // difference is significant if it advanced by more than 200ms or if
1935 // it went backwards by any amount. The negative numbers look like huge
1936 // unsigned ints so the cast allows both conditions to be checked at once.
1937 int bufpcr = stream->ts_buf[curstream]->cur;
1938 int curpcr = stream->ts_pcr_out;
1939 if ( bufpcr && bufpcr < curpcr &&
1940 (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
1942 // we've sent up a new pcr but have a packet referenced to an
1943 // old pcr and the difference was enough to trigger a discontinuity
1944 // correction. smash the timestamps or we'll mess up the correction.
1946 buf->renderOffset = -1;
1950 if ( stream->ts_pcr_out != stream->ts_pcr_in )
1952 // we have a new pcr
1953 stream->ts_pcr_out = stream->ts_pcr_in;
1954 buf->stop = stream->ts_pcr;
1955 stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
1962 // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
1963 // off the PES header.
1964 if ( tdat[7] & 0xc0 )
1966 buf->start = pes_timestamp( tdat + 9 );
1967 buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
1973 buf->renderOffset = -1;
1976 int hlen = tdat[8] + 9;
1978 fwrite64( stream, tdat + hlen, stream->ts_pos[curstream] - hlen );
1980 stream->ts_pos[curstream] = 0;
1981 stream->ts_buf[curstream]->size = 0;
1984 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1986 // For mpeg2: look for a gop start or i-frame picture start
1987 // for h.264: look for idr nal type or a slice header for an i-frame
1993 if ( stream->ts_stream_type[0] <= 2 )
1995 // This section of the code handles MPEG-1 and MPEG-2 video streams
1996 for (i = 13 + adapt_len; i < 188; i++)
1998 strid = (strid << 8) | buf[i];
1999 if ( ( strid >> 8 ) == 1 )
2001 // we found a start code
2005 case 0xB8: // group_start_code (GOP header)
2006 case 0xB3: // sequence_header code
2009 case 0x00: // picture_start_code
2010 // picture_header, let's see if it's an I-frame
2013 // check if picture_coding_type == 1
2014 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2016 // found an I-frame picture
2024 // didn't find an I-frame
2027 if ( stream->ts_stream_type[0] == 0x1b )
2029 // we have an h.264 stream
2030 for (i = 13 + adapt_len; i < 188; i++)
2032 strid = (strid << 8) | buf[i];
2033 if ( ( strid >> 8 ) == 1 )
2035 // we found a start code - remove the ref_idc from the nal type
2036 uint8_t nal_type = strid & 0x1f;
2037 if ( nal_type == 0x05 )
2038 // h.264 IDR picture start
2041 if ( stream->packetsize == 192 )
2043 // m2ts files have idr frames so keep looking for one
2047 // h.264 in ts files (ATSC or DVB video) often seem to be
2048 // missing IDR frames so look for at least an I
2049 if ( nal_type == 0x01 )
2051 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2052 uint8_t id = buf[i+1];
2053 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2054 id == 0x88 || id == 0x8a )
2061 // didn't find an I-frame
2065 // we don't understand the stream type so just say "yes" otherwise
2066 // we'll discard all the video.
2070 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2072 if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2076 size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2077 hb_buffer_realloc(stream->ts_buf[idx], size);
2079 memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2080 stream->ts_pos[idx] += len;
2081 stream->ts_buf[idx]->size += len;
2084 /***********************************************************************
2085 * hb_ts_stream_decode
2086 ***********************************************************************
2088 **********************************************************************/
2089 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2092 * stash the output buffer pointer in our stream so we don't have to
2093 * pass it & its original value to everything we call.
2096 stream->fwrite_buf = obuf;
2098 // spin until we get a packet of data from some stream or hit eof
2103 const uint8_t *buf = next_packet(stream);
2106 // end of file - we didn't finish filling our ps write buffer
2107 // so just discard the remainder (the partial buffer is useless)
2108 hb_log("hb_ts_stream_decode - eof");
2112 /* This next section validates the packet */
2114 // Get pid and use it to find stream state.
2115 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2116 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2120 int errorbit = (buf[1] & 0x80) != 0;
2123 ts_err( stream, curstream, "packet error bit set");
2127 // Get adaption header info
2128 int adaption = (buf[3] & 0x30) >> 4;
2132 ts_err( stream, curstream, "adaptation code 0");
2135 else if (adaption == 0x2)
2137 else if (adaption == 0x3)
2139 adapt_len = buf[4] + 1;
2140 if (adapt_len > 184)
2142 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2147 if ( adapt_len > 0 )
2149 if ( buf[5] & 0x40 )
2151 // found a random access point
2153 // if there's an adaptation header & PCR_flag is set
2154 // get the PCR (Program Clock Reference)
2155 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2157 stream->ts_pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2158 ( (uint64_t)buf[7] << (33 - 16) ) |
2159 ( (uint64_t)buf[8] << (33 - 24) ) |
2160 ( (uint64_t)buf[9] << (33 - 32) ) |
2162 ++stream->ts_pcr_in;
2163 stream->ts_found_pcr = 1;
2167 // If we don't have a pcr yet, the right thing to do here would
2168 // be a 'continue' so we don't process anything until we have a
2169 // clock reference. Unfortunately the HD Home Run appears to null
2170 // out the pcr field of some streams so we keep going & substitute
2171 // the video stream dts for the pcr when there's no pcr.
2174 // Continuity only increments for adaption values of 0x3 or 0x01
2175 // and is not checked for start packets.
2177 int start = (buf[1] & 0x40) != 0;
2179 if ( (adaption & 0x01) != 0 )
2181 int continuity = (buf[3] & 0xF);
2182 if ( continuity == stream->ts_streamcont[curstream] )
2184 // we got a duplicate packet (usually used to introduce
2185 // a PCR when one is needed). The only thing that can
2186 // change in the dup is the PCR which we grabbed above
2187 // so ignore the rest.
2190 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2191 !stream->ts_skipbad[curstream] &&
2192 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2194 ts_err( stream, curstream, "continuity error: got %d expected %d",
2196 (stream->ts_streamcont[curstream] + 1) & 0xf );
2197 stream->ts_streamcont[curstream] = continuity;
2200 stream->ts_streamcont[curstream] = continuity;
2203 /* If we get here the packet is valid - process its data */
2207 // Found a random access point (now we can start a frame/audio packet..)
2209 if ( stream->need_keyframe )
2211 // we're looking for the first video frame because we're
2212 // doing random access during 'scan'
2213 if (curstream != 0 || !isIframe( stream, buf, adapt_len ) )
2215 // not the video stream or didn't find an I frame
2218 stream->need_keyframe = 0;
2221 // If we were skipping a bad packet, start fresh on this new PES packet..
2222 if (stream->ts_skipbad[curstream] == 1)
2224 stream->ts_skipbad[curstream] = 0;
2227 if ( curstream == 0 )
2231 // if we don't have a pcr yet use the dts from this frame
2232 if ( !stream->ts_found_pcr )
2234 // PES must begin with an mpeg start code & contain
2236 const uint8_t *pes = buf + adapt_len + 4;
2237 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2238 ( pes[7] >> 6 ) == 0 )
2242 // if we have a dts use it otherwise use the pts
2243 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40? 14 : 9 ) );
2244 ++stream->ts_pcr_in;
2248 // if this is a multiplexed stream make sure this is the
2249 // substream we want.
2250 if ( stream->ts_multiplexed[curstream] )
2252 // PES must begin with an mpeg start code & contain
2254 const uint8_t *pes = buf + adapt_len + 4;
2255 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2258 stream->ts_skipbad[curstream] = 1;
2261 // the last byte of the header is the extension id. see if
2262 // it's the one we want.
2263 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2265 stream->ts_skipbad[curstream] = 1;
2270 // If we have some data already on this stream, turn it into
2271 // a program stream packet. Then add the payload for this
2272 // packet to the current pid's buffer.
2273 if ( stream->ts_pos[curstream] )
2275 // we have to ship the old packet before updating the pcr
2276 // since the packet we've been accumulating is referenced
2278 generate_output_data(stream, curstream);
2280 // remember the pcr that was in effect when we started
2282 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2283 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2287 // remember the pcr that was in effect when we started this packet.
2288 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2291 // Add the payload for this packet to the current buffer
2292 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2294 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2296 // see if we've hit the end of this PES packet
2297 const uint8_t *pes = stream->ts_buf[curstream]->data;
2298 int len = ( pes[4] << 8 ) + pes[5] + 6;
2299 if ( len > 6 && stream->ts_pos[curstream] == len &&
2300 pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2302 generate_output_data(stream, curstream);
2309 static void hb_ts_stream_reset(hb_stream_t *stream)
2313 for (i=0; i < kMaxNumberDecodeStreams; i++)
2315 stream->ts_pos[i] = 0;
2316 stream->ts_skipbad[i] = 1;
2317 stream->ts_streamcont[i] = -1;
2320 stream->need_keyframe = 0;
2322 stream->ts_found_pcr = 0;
2323 stream->ts_pcr_out = 0;
2324 stream->ts_pcr_in = 0;
2329 stream->last_error_frame = -10000;
2330 stream->last_error_count = 0;
2332 align_to_next_packet(stream);
2335 // ------------------------------------------------------------------
2336 // Support for reading media files via the ffmpeg libraries.
2338 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2340 // add a codec to the context here so it will be there when we
2341 // read the first packet.
2342 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2343 context->workaround_bugs = FF_BUG_AUTODETECT;
2344 context->error_recognition = 1;
2345 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2346 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2347 avcodec_open( context, codec );
2350 // The ffmpeg stream reader / parser shares a lot of state with the
2351 // decoder via a codec context kept in the AVStream of the reader's
2352 // AVFormatContext. Since decoding is done in a different thread we
2353 // have to somehow pass this codec context to the decoder and we have
2354 // to do it before the first packet is read (so we can't put the info
2355 // in the buf we'll send downstream). Decoders don't have any way to
2356 // get to the stream directly (they're not passed the title or job
2357 // pointers during a scan) so this is a back door for the decoder to
2358 // get the codec context. We just stick the stream pointer in the next
2359 // slot an array of pointers maintained as a circular list then return
2360 // the index into the list combined with the ffmpeg stream index as the
2361 // codec_param that will be passed to the decoder init routine. We make
2362 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2363 // so that we don't have to do a complicated allocator or worry about
2364 // deleting entries on close.
2366 // Entries can only be added to this list during a scan and are never
2367 // deleted so the list access doesn't require locking.
2368 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2369 static int ffmpeg_stream_cur; // where we put the last stream pointer
2370 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2371 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2373 // add a stream to the list & return the appropriate codec_param to access it
2374 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2376 if ( !ffmpeg_streams )
2378 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2381 // the title scan adds all the ffmpeg media streams at once so we
2382 // only add a new entry to our stream list if the stream is different
2384 int slot = ffmpeg_stream_cur;
2385 if ( ffmpeg_streams[slot] != stream )
2387 // new stream - put it in the next slot of the stream list
2388 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2389 ffmpeg_streams[slot] = stream;
2392 ffmpeg_add_codec( stream, stream_index );
2394 return ( stream_index << ffmpeg_sl_bits ) | slot;
2397 // we're about to open 'title' to convert it - remap the stream associated
2398 // with the video & audio codec params of the title to refer to 'stream'
2399 // (the original scan stream was closed and no longer exists).
2400 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2402 // tell ffmpeg we want a pts on every frame it returns
2403 stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2405 // all the video & audio came from the same stream so remapping
2406 // the video's stream slot takes care of everything.
2407 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2408 ffmpeg_streams[slot] = stream;
2410 // add codecs for all the streams used by the title
2411 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2415 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2417 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2419 ffmpeg_add_codec( stream,
2420 audio->config.in.codec_param >> ffmpeg_sl_bits );
2425 void *hb_ffmpeg_context( int codec_param )
2427 int slot = codec_param & (ffmpeg_sl_size - 1);
2428 int stream_index = codec_param >> ffmpeg_sl_bits;
2429 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2432 void *hb_ffmpeg_avstream( int codec_param )
2434 int slot = codec_param & (ffmpeg_sl_size - 1);
2435 int stream_index = codec_param >> ffmpeg_sl_bits;
2436 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2439 static AVFormatContext *ffmpeg_deferred_close;
2441 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2443 if ( ffmpeg_deferred_close )
2445 av_close_input_file( ffmpeg_deferred_close );
2446 ffmpeg_deferred_close = NULL;
2448 AVFormatContext *ic;
2450 av_log_set_level( AV_LOG_ERROR );
2451 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2455 if ( av_find_stream_info( ic ) < 0 )
2458 stream->ffmpeg_ic = ic;
2459 stream->hb_stream_type = ffmpeg;
2460 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2461 av_init_packet( stream->ffmpeg_pkt );
2465 // we're opening for read. scan passed out codec params that
2466 // indexed its stream so we need to remap them so they point
2468 ffmpeg_remap_stream( stream, title );
2469 av_log_set_level( AV_LOG_ERROR );
2473 // we're opening for scan. let ffmpeg put some info into the
2474 // log about what we've got.
2475 av_log_set_level( AV_LOG_INFO );
2476 dump_format( ic, 0, stream->path, 0 );
2477 av_log_set_level( AV_LOG_ERROR );
2479 // accept this file if it has at least one video stream we can decode
2481 for (i = 0; i < ic->nb_streams; ++i )
2483 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2488 if ( i >= ic->nb_streams )
2494 av_close_input_file( ic );
2498 static void ffmpeg_close( hb_stream_t *d )
2500 // XXX since we're sharing the CodecContext with the downstream
2501 // decoder proc we can't close the stream. We need to reference count
2502 // this so we can close it when both are done with their instance but
2503 // for now just defer the close until the next stream open or close.
2504 if ( ffmpeg_deferred_close )
2506 av_close_input_file( ffmpeg_deferred_close );
2508 ffmpeg_deferred_close = d->ffmpeg_ic;
2509 if ( d->ffmpeg_pkt != NULL )
2511 free( d->ffmpeg_pkt );
2512 d->ffmpeg_pkt = NULL;
2516 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2518 AVStream *st = stream->ffmpeg_ic->streams[id];
2519 AVCodecContext *codec = st->codec;
2521 // scan will ignore any audio without a bitrate. Since we've already
2522 // typed the audio in order to determine its codec we set up the audio
2524 if ( codec->bit_rate || codec->sample_rate )
2526 static const int chan2layout[] = {
2527 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2528 HB_INPUT_CH_LAYOUT_MONO,
2529 HB_INPUT_CH_LAYOUT_STEREO,
2530 HB_INPUT_CH_LAYOUT_2F1R,
2531 HB_INPUT_CH_LAYOUT_2F2R,
2532 HB_INPUT_CH_LAYOUT_3F2R,
2533 HB_INPUT_CH_LAYOUT_4F2R,
2534 HB_INPUT_CH_LAYOUT_STEREO,
2535 HB_INPUT_CH_LAYOUT_STEREO,
2538 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2541 if ( codec->codec_id == CODEC_ID_AC3 )
2543 audio->config.in.codec = HB_ACODEC_AC3;
2545 else if ( codec->codec_id == CODEC_ID_DTS )
2547 audio->config.in.codec = HB_ACODEC_DCA;
2551 audio->config.in.codec = HB_ACODEC_FFMPEG;
2552 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2554 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2555 audio->config.in.samplerate = codec->sample_rate;
2556 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2559 set_audio_description( audio, lang_for_code2( st->language ) );
2561 hb_list_add( title->list_audio, audio );
2565 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2567 AVFormatContext *ic = stream->ffmpeg_ic;
2569 // 'Barebones Title'
2570 hb_title_t *title = hb_title_init( stream->path, 0 );
2573 // Copy part of the stream path to the title name
2574 char *sep = strrchr(stream->path, '/');
2576 strcpy(title->name, sep+1);
2577 char *dot_term = strrchr(title->name, '.');
2581 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2582 title->duration = dur;
2584 title->hours = dur / 3600;
2585 title->minutes = ( dur % 3600 ) / 60;
2586 title->seconds = dur % 60;
2589 hb_chapter_t * chapter;
2590 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2592 chapter->duration = title->duration;
2593 chapter->hours = title->hours;
2594 chapter->minutes = title->minutes;
2595 chapter->seconds = title->seconds;
2596 hb_list_add( title->list_chapter, chapter );
2598 // set the title to decode the first video stream in the file
2599 title->demuxer = HB_NULL_DEMUXER;
2600 title->video_codec = 0;
2602 for (i = 0; i < ic->nb_streams; ++i )
2604 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2605 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2606 title->video_codec == 0 )
2608 title->video_id = i;
2609 stream->ffmpeg_video_id = i;
2611 // We have to use the 'internal' avcodec decoder because
2612 // it needs to share the codec context from this video
2613 // stream. The parser internal to av_read_frame
2614 // passes a bunch of state info to the decoder via the context.
2615 title->video_codec = WORK_DECAVCODECVI;
2616 title->video_codec_param = ffmpeg_codec_param( stream, i );
2618 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2619 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2621 add_ffmpeg_audio( title, stream, i );
2625 title->container_name = strdup( ic->iformat->name );
2626 title->data_rate = ic->bit_rate;
2631 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2633 if ( pts == AV_NOPTS_VALUE )
2635 return (int64_t)( (double)pts * conv_factor );
2638 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2642 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2644 // XXX the following conditional is to handle avi files that
2645 // use M$ 'packed b-frames' and occasionally have negative
2646 // sizes for the null frames these require.
2647 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2651 if ( stream->ffmpeg_pkt->size <= 0 )
2653 // M$ "invalid and inefficient" packed b-frames require 'null frames'
2654 // following them to preserve the timing (since the packing puts two
2655 // or more frames in what looks like one avi frame). The contents and
2656 // size of these null frames are ignored by the ff_h263_decode_frame
2657 // as long as they're < 20 bytes. We need a positive size so we use
2658 // one byte if we're given a zero or negative size. We don't know
2659 // if the pkt data points anywhere reasonable so we just stick a
2660 // byte of zero in our outbound buf.
2666 if ( stream->ffmpeg_pkt->size > buf->alloc )
2668 // sometimes we get absurd sizes from ffmpeg
2669 if ( stream->ffmpeg_pkt->size >= (1 << 25) )
2671 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
2672 av_free_packet( stream->ffmpeg_pkt );
2673 return ffmpeg_read( stream, buf );
2675 // need to expand buffer
2676 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2678 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2679 buf->size = stream->ffmpeg_pkt->size;
2681 buf->id = stream->ffmpeg_pkt->stream_index;
2682 if ( buf->id == stream->ffmpeg_video_id )
2684 if ( stream->need_keyframe &&
2685 stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id ==
2688 // XXX the VC1 codec doesn't seek to key frames so to get previews
2689 // we do it ourselves here. The decoder gets messed up if it
2690 // doesn't get a SEQ header first so we consider that to be a key frame.
2691 uint8_t *pkt = stream->ffmpeg_pkt->data;
2692 if ( pkt[0] || pkt[1] || pkt[2] != 1 || pkt[3] != 0x0f )
2696 stream->need_keyframe = 0;
2701 // if we haven't done it already, compute a conversion factor to go
2702 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2703 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2706 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2707 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2708 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2711 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2712 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2713 if ( buf->renderOffset >= 0 && buf->start == -1 )
2715 buf->start = buf->renderOffset;
2717 av_free_packet( stream->ffmpeg_pkt );
2721 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2723 AVFormatContext *ic = stream->ffmpeg_ic;
2724 int64_t pos = (double)ic->duration * (double)frac;
2727 av_seek_frame( ic, -1, pos, 0 );
2728 stream->need_keyframe = 1;
2732 av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );