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"
16 #include "mp4v2/mp4v2.h"
18 #define min(a, b) a < b ? a : b
21 * This table defines how ISO MPEG stream type codes map to HandBrake
22 * codecs. It is indexed by the 8 bit stream type and contains the codec
23 * worker object id and a parameter for that worker proc (ignored except
24 * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
26 * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
27 * doesn't handle the stream type.
30 enum { U = 1, A, V } kind; /* unknown / audio / video */
31 int codec; /* HB worker object id of codec */
32 int codec_param; /* param for codec (usually ffmpeg codec id) */
33 const char* name; /* description of type */
36 #define st(id, kind, codec, codec_param, name) \
37 [id] = { kind, codec, codec_param, name }
39 static const stream2codec_t st2codec[256] = {
40 st(0x01, V, WORK_DECMPEG2, 0, "MPEG1"),
41 st(0x02, V, WORK_DECMPEG2, 0, "MPEG2"),
42 st(0x03, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG1"),
43 st(0x04, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG2"),
44 st(0x05, U, 0, 0, "ISO 13818-1 private section"),
45 st(0x06, U, 0, 0, "ISO 13818-1 PES private data"),
46 st(0x07, U, 0, 0, "ISO 13522 MHEG"),
47 st(0x08, U, 0, 0, "ISO 13818-1 DSM-CC"),
48 st(0x09, U, 0, 0, "ISO 13818-1 auxiliary"),
49 st(0x0a, U, 0, 0, "ISO 13818-6 encap"),
50 st(0x0b, U, 0, 0, "ISO 13818-6 DSM-CC U-N msgs"),
51 st(0x0c, U, 0, 0, "ISO 13818-6 Stream descriptors"),
52 st(0x0d, U, 0, 0, "ISO 13818-6 Sections"),
53 st(0x0e, U, 0, 0, "ISO 13818-1 auxiliary"),
54 st(0x0f, A, HB_ACODEC_MPGA, CODEC_ID_AAC, "ISO 13818-7 AAC Audio"),
55 st(0x10, V, WORK_DECAVCODECV, CODEC_ID_MPEG4, "MPEG4"),
56 st(0x11, A, HB_ACODEC_MPGA, CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
57 st(0x12, U, 0, 0, "MPEG4 generic"),
59 st(0x14, U, 0, 0, "ISO 13818-6 DSM-CC download"),
61 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
63 //st(0x80, U, 0, 0, "DigiCipher II Video"),
64 st(0x81, A, HB_ACODEC_AC3, 0, "AC-3"),
65 st(0x82, A, HB_ACODEC_DCA, 0, "HDMV DTS"),
66 st(0x83, A, HB_ACODEC_LPCM, 0, "LPCM"),
67 st(0x84, A, 0, 0, "SDDS"),
68 st(0x85, U, 0, 0, "ATSC Program ID"),
69 st(0x86, A, HB_ACODEC_DCA, 0, "DTS-HD"),
70 st(0x87, A, 0, 0, "E-AC-3"),
72 st(0x8a, A, HB_ACODEC_DCA, 0, "DTS"),
74 st(0x91, A, HB_ACODEC_AC3, 0, "AC-3"),
75 st(0x92, U, 0, 0, "Subtitle"),
77 st(0x94, A, 0, 0, "SDDS"),
78 st(0xa0, V, 0, 0, "MSCODEC"),
80 st(0xea, V, WORK_DECAVCODECV, CODEC_ID_VC1, "VC1"),
85 hb_stream_type_unknown = 0,
92 #define kMaxNumberVideoPIDS 1
93 #define kMaxNumberAudioPIDS 15
94 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
95 #define kMaxNumberPMTStreams 32
100 int frames; /* video frames so far */
101 int errors; /* total errors so far */
102 int last_error_frame; /* frame # at last error message */
103 int last_error_count; /* # errors at last error message */
104 int packetsize; /* Transport Stream packet size */
106 int8_t need_keyframe; // non-zero if want to start at a keyframe
107 int8_t ts_no_RAP; // non-zero if there are no random access points
109 int8_t ts_found_pcr; // non-zero if we've found at least one input pcr
110 int ts_pcr_out; // sequence number of most recent output pcr
111 int ts_pcr_in; // sequence number of most recent input pcr
112 int64_t ts_pcr; // most recent input pcr
113 int64_t ts_pcrhist[4]; // circular buffer of output pcrs
115 uint8_t *ts_packet; /* buffer for one TS packet */
116 hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
117 int ts_pos[kMaxNumberDecodeStreams];
118 int8_t ts_skipbad[kMaxNumberDecodeStreams];
119 int8_t ts_streamcont[kMaxNumberDecodeStreams];
121 hb_buffer_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
123 int chapter; /* Chapter that we are currently in */
124 uint64_t chapter_end; /* HB time that the current chapter ends */
127 * Stuff before this point is dynamic state updated as we read the
128 * stream. Stuff after this point is stream description state that
129 * we learn during the initial scan but cache so it can be
130 * reused during the conversion read.
132 uint8_t ts_number_video_pids;
133 uint8_t ts_number_audio_pids;
135 int16_t ts_video_pids[kMaxNumberVideoPIDS];
136 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
138 uint32_t ts_format_id[kMaxNumberDecodeStreams];
139 #define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
140 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
141 uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
145 hb_stream_type_t hb_stream_type;
148 AVFormatContext *ffmpeg_ic;
149 AVPacket *ffmpeg_pkt;
150 double ffmpeg_tsconv[MAX_STREAMS];
151 uint8_t ffmpeg_video_id;
158 } a52_info[kMaxNumberAudioPIDS];
162 unsigned short program_number;
163 unsigned short program_map_PID;
164 } pat_info[kMaxNumberPMTStreams];
165 int ts_number_pat_entries;
170 unsigned char *tablebuf;
171 unsigned int tablepos;
172 unsigned char current_continuity_counter;
176 unsigned int PCR_PID;
177 int program_info_length;
178 unsigned char *progam_info_descriptor_data;
181 unsigned char stream_type;
182 unsigned short elementary_PID;
183 unsigned short ES_info_length;
184 unsigned char *es_info_descriptor_data;
185 } pmt_stream_info[kMaxNumberPMTStreams];
189 /***********************************************************************
191 **********************************************************************/
192 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
193 static void hb_ts_stream_init(hb_stream_t *stream);
194 static void hb_ts_stream_find_pids(hb_stream_t *stream);
195 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
196 static void hb_ts_stream_reset(hb_stream_t *stream);
197 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
199 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
200 static off_t align_to_next_packet(hb_stream_t *stream);
202 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
203 static void ffmpeg_close( hb_stream_t *d );
204 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
205 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
206 static int ffmpeg_seek( hb_stream_t *stream, float frac );
209 * streams have a bunch of state that's learned during the scan. We don't
210 * want to throw away the state when scan does a close then relearn
211 * everything when reader does an open. So we save the stream state on
212 * the close following a scan and reuse it when 'reader' does an open.
214 static hb_list_t *stream_state_list;
216 static hb_stream_t *hb_stream_lookup( const char *path )
218 if ( stream_state_list == NULL )
224 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
226 if ( strcmp( path, ss->path ) == 0 )
234 static void hb_stream_state_delete( hb_stream_t *ss )
236 hb_list_rem( stream_state_list, ss );
243 * these frontend hb_log because transport streams can have a lot of errors
244 * so we want to rate limit messages. this routine limits the number of
245 * messages to at most one per minute of video. other errors that occur
246 * during the minute are counted & the count is output with the next
247 * error msg we print.
249 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
251 // limit error printing to at most one per minute of video (at 30fps)
253 if ( stream->frames - stream->last_error_frame >= 30*60 )
257 vsnprintf( msg, sizeof(msg), log, args );
259 if ( stream->errors - stream->last_error_count < 10 )
261 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
265 int Edelta = stream->errors - stream->last_error_count;
266 double Epcnt = (double)Edelta * 100. /
267 (stream->frames - stream->last_error_frame);
268 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
269 Edelta, Epcnt, stream->frames, msg );
271 stream->last_error_frame = stream->frames;
272 stream->last_error_count = stream->errors;
276 static void ts_warn( hb_stream_t *stream, char *log, ... )
279 va_start( args, log );
280 ts_warn_helper( stream, log, args );
284 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
287 va_start( args, log );
288 ts_warn_helper( stream, log, args );
291 stream->ts_skipbad[curstream] = 1;
292 stream->ts_pos[curstream] = 0;
293 stream->ts_streamcont[curstream] = -1;
296 static int check_ps_sync(const uint8_t *buf)
298 // a legal MPEG program stream must start with a Pack header in the
300 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
301 (buf[2] == 0x01) && (buf[3] == 0xba);
304 static int check_ps_sys(const uint8_t *buf)
306 // a legal MPEG program stream must start with a Pack followed by a
307 // SYS. If we've already verified the pack, this skips over it and checks
308 // for the sys header.
309 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
310 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
311 (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
314 static int check_ts_sync(const uint8_t *buf)
316 // must have initial sync byte, no scrambling & a legal adaptation ctrl
317 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
320 static int have_ts_sync(const uint8_t *buf, int psize)
322 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
323 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
324 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
325 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
328 static int hb_stream_check_for_ts(const uint8_t *buf)
330 // transport streams should have a sync byte every 188 bytes.
331 // search the first 8KB of buf looking for at least 8 consecutive
332 // correctly located sync patterns.
335 for ( offset = 0; offset < 8*1024-8*188; ++offset )
337 if ( have_ts_sync( &buf[offset], 188) )
338 return 188 | (offset << 8);
339 if ( have_ts_sync( &buf[offset], 192) )
340 return 192 | (offset << 8);
341 if ( have_ts_sync( &buf[offset], 204) )
342 return 204 | (offset << 8);
343 if ( have_ts_sync( &buf[offset], 208) )
344 return 208 | (offset << 8);
349 static int hb_stream_check_for_ps(const uint8_t *buf)
351 // program streams should start with a PACK then a SYS header.
352 return check_ps_sync(buf) && check_ps_sys(buf);
355 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
357 // DVD program streams should have a Pack header every 2048 bytes.
358 // check that we have 4 of these in a row.
359 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
360 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
363 static int hb_stream_get_type(hb_stream_t *stream)
367 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
370 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
372 int offset = psize >> 8;
374 hb_log("file is MPEG Transport Stream with %d byte packets"
375 " offset %d bytes", psize, offset);
376 stream->packetsize = psize;
377 stream->hb_stream_type = transport;
378 hb_ts_stream_init(stream);
379 if ( !stream->ts_number_video_pids || !stream->ts_number_audio_pids )
385 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
387 hb_log("file is MPEG DVD Program Stream");
388 stream->hb_stream_type = dvd_program;
391 if ( hb_stream_check_for_ps(buf) != 0 )
393 hb_log("file is MPEG Program Stream");
394 stream->hb_stream_type = program;
401 static void hb_stream_delete_dynamic( hb_stream_t *d )
405 fclose( d->file_handle );
406 d->file_handle = NULL;
413 free( d->ts_packet );
416 for (i = 0; i < kMaxNumberDecodeStreams; i++)
420 hb_buffer_close(&(d->ts_buf[i]));
426 static void hb_stream_delete( hb_stream_t *d )
428 hb_stream_delete_dynamic( d );
433 /***********************************************************************
435 ***********************************************************************
437 **********************************************************************/
438 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
440 FILE *f = fopen( path, "r" );
443 hb_log( "hb_stream_open: open %s failed", path );
447 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
451 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
456 * if we're opening the stream to read & convert, we need
457 * the state we saved when we scanned the stream. if we're
458 * opening the stream to scan it we want to rebuild the state
459 * (even if we have saved state, the stream may have changed).
461 hb_stream_t *ss = hb_stream_lookup( path );
462 if ( title && ss && ss->hb_stream_type != ffmpeg )
465 * copy the saved state since we might be encoding the same stream
468 memcpy( d, ss, sizeof(*d) );
471 d->path = strdup( path );
473 if ( d->hb_stream_type == transport )
475 d->ts_packet = malloc( d->packetsize );
478 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
480 d->ts_buf[i] = hb_buffer_init(d->packetsize);
481 d->ts_buf[i]->size = 0;
483 hb_stream_seek( d, 0. );
485 if ( d->packetsize == 188 )
487 // Assume that an over-the-air transport stream can lose PCR
488 // packets and try to filter out the timing inconsistencies.
489 title->flaky_clock = 1;
496 * opening for scan - delete any saved state then (re)scan the stream.
497 * If it's something we can deal with (MPEG2 PS or TS) return a stream
498 * reference structure & null otherwise.
502 hb_stream_state_delete( ss );
506 d->path = strdup( path );
507 if (d->path != NULL )
509 if ( hb_stream_get_type( d ) != 0 )
513 fclose( d->file_handle );
514 d->file_handle = NULL;
515 if ( ffmpeg_open( d, title ) )
520 if ( d->file_handle )
522 fclose( d->file_handle );
528 hb_log( "hb_stream_open: open %s failed", path );
533 /***********************************************************************
535 ***********************************************************************
536 * Closes and frees everything
537 **********************************************************************/
538 void hb_stream_close( hb_stream_t ** _d )
540 hb_stream_t *stream = * _d;
542 if ( stream->hb_stream_type == ffmpeg )
544 ffmpeg_close( stream );
545 hb_stream_delete( stream );
550 if ( stream->frames )
552 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
553 stream->errors, (double)stream->errors * 100. /
554 (double)stream->frames );
558 * if the stream was opened for a scan, cache the result, otherwise delete
561 if ( stream->title == NULL )
563 hb_stream_delete_dynamic( stream );
564 if ( stream_state_list == NULL )
566 stream_state_list = hb_list_init();
568 hb_list_add( stream_state_list, stream );
572 hb_stream_delete( stream );
577 /* when the file was first opened we made entries for all the audio elementary
578 * streams we found in it. Streams that were later found during the preview scan
579 * now have an audio codec, type, rate, etc., associated with them. At the end
580 * of the scan we delete all the audio entries that weren't found by the scan
581 * or don't have a format we support. This routine deletes audio entry 'indx'
582 * by setting its PID to an invalid value so no packet will match it. (We can't
583 * move any of the entries since the index of the entry is used as the id
584 * of the media stream for HB. */
585 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
587 stream->ts_audio_pids[indx] = -stream->ts_audio_pids[indx];
590 static int index_of_pid(int pid, hb_stream_t *stream)
594 if ( pid == stream->ts_video_pids[0] )
597 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
598 if ( pid == stream->ts_audio_pids[i] )
604 /***********************************************************************
605 * hb_ps_stream_title_scan
606 ***********************************************************************
608 **********************************************************************/
609 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
611 if ( stream->hb_stream_type == ffmpeg )
612 return ffmpeg_title_scan( stream );
615 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
618 // Copy part of the stream path to the title name
619 char *sep = strrchr(stream->path, '/');
621 strcpy(aTitle->name, sep+1);
622 char *dot_term = strrchr(aTitle->name, '.');
626 // Height, width, rate and aspect ratio information is filled in when the previews are built
628 hb_stream_duration(stream, aTitle);
631 hb_chapter_t * chapter;
632 chapter = calloc( sizeof( hb_chapter_t ), 1 );
634 chapter->duration = aTitle->duration;
635 chapter->hours = aTitle->hours;
636 chapter->minutes = aTitle->minutes;
637 chapter->seconds = aTitle->seconds;
638 hb_list_add( aTitle->list_chapter, chapter );
640 // Figure out how many audio streams we really have:
641 // - For transport streams, for each PID listed in the PMT (whether
642 // or not it was an audio stream type) read the bitstream until we
643 // find an packet from that PID containing a PES header and see if
644 // the elementary stream is an audio type.
645 // - For program streams read the first 4MB and take every unique
646 // audio stream we find.
647 if (stream->hb_stream_type == transport)
651 for (i=0; i < stream->ts_number_audio_pids; i++)
653 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
654 if (audio->config.in.codec)
655 hb_list_add( aTitle->list_audio, audio );
659 hb_stream_delete_audio_entry(stream, i);
663 // make sure we're grabbing the PCR PID
664 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
666 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
667 stream->pmt_info.PCR_PID;
670 // set the video id, codec & muxer
671 aTitle->video_id = 0;
672 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
673 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
674 aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
678 hb_ps_stream_find_audio_ids(stream, aTitle);
685 * read the next transport stream packet from 'stream'. Return NULL if
686 * we hit eof & a pointer to the sync byte otherwise.
688 static const uint8_t *next_packet( hb_stream_t *stream )
690 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
694 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
703 // lost sync - back up to where we started then try to re-establish.
704 off_t pos = ftello(stream->file_handle) - stream->packetsize;
705 off_t pos2 = align_to_next_packet(stream);
708 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
711 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
717 * skip to the start of the next PACK header in program stream src_stream.
719 static void skip_to_next_pack( hb_stream_t *src_stream )
721 // scan forward until we find the start of the next pack
722 uint32_t strt_code = -1;
725 flockfile( src_stream->file_handle );
726 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
728 strt_code = ( strt_code << 8 ) | c;
729 if ( strt_code == 0x000001ba )
730 // we found the start of the next pack
733 funlockfile( src_stream->file_handle );
735 // if we didn't terminate on an eof back up so the next read
736 // starts on the pack boundary.
739 fseeko( src_stream->file_handle, -4, SEEK_CUR );
744 * scan the next MB of 'stream' to try to find a random access point
746 static void hb_ts_stream_find_RAP( hb_stream_t *stream )
748 off_t starting_point = ftello(stream->file_handle);
749 int npack = 300000; // max packets to read
753 off_t cur = ftello(stream->file_handle);
754 const uint8_t *buf = next_packet( stream );
759 switch (buf[3] & 0x30)
761 case 0x00: // illegal
764 case 0x20: // fill packet
765 case 0x30: // adaptation
768 // found a random access point
769 fseeko( stream->file_handle, cur, SEEK_SET );
777 fseeko( stream->file_handle, starting_point, SEEK_SET );
778 stream->ts_no_RAP = 1;
782 * scan the next MB of 'stream' to find the next start packet for
783 * the Packetized Elementary Stream associated with TS PID 'pid'.
785 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
787 int npack = 300000; // max packets to read
791 const uint8_t *buf = next_packet( stream );
794 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
799 * The PES header is only in TS packets with 'start' set so we check
800 * that first then check for the right PID.
802 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
803 buf[2] != (pid & 0xff))
805 // not a start packet or not the pid we want
809 /* skip over the TS hdr to return a pointer to the PES hdr */
811 switch (buf[3] & 0x30)
813 case 0x00: // illegal
814 case 0x20: // fill packet
817 case 0x30: // adaptation
820 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
826 /* PES hdr has to begin with an mpeg start code */
827 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
837 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
839 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
840 hb_list_t *list = hb_list_init();
841 // how many blocks we read while searching for a video PES header
845 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
849 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
850 hb_demux_ps( buf, list, 0 );
852 while ( ( es = hb_list_item( list, 0 ) ) )
854 hb_list_rem( list, es );
855 if ( es->id == 0xe0 )
857 // this PES contains video - if there's a PTS we're done
858 // hb_demux_ps left the PTS in buf_es->start.
859 if ( es->start != ~0 )
866 hb_buffer_close( &es );
869 hb_list_empty( &list );
870 hb_buffer_close(&buf);
874 /***********************************************************************
876 ***********************************************************************
878 * Finding stream duration is difficult. One issue is that the video file
879 * may have chunks from several different program fragments (main feature,
880 * commercials, station id, trailers, etc.) all with their own base pts
881 * value. We can't find the piece boundaries without reading the entire
882 * file but if we compute a rate based on time stamps from two different
883 * pieces the result will be meaningless. The second issue is that the
884 * data rate of compressed video normally varies by 5-10x over the length
885 * of the video. This says that we want to compute the rate over relatively
886 * long segments to get a representative average but long segments increase
887 * the likelihood that we'll cross a piece boundary.
889 * What we do is take time stamp samples at several places in the file
890 * (currently 16) then compute the average rate (i.e., ticks of video per
891 * byte of the file) for all pairs of samples (N^2 rates computed for N
892 * samples). Some of those rates will be absurd because the samples came
893 * from different segments. Some will be way low or high because the
894 * samples came from a low or high motion part of the segment. But given
895 * that we're comparing *all* pairs the majority of the computed rates
896 * should be near the overall average. So we median filter the computed
897 * rates to pick the most representative value.
899 **********************************************************************/
901 uint64_t pos; /* file position of this PTS sample */
902 uint64_t pts; /* PTS from video stream */
905 #define NDURSAMPLES 16
907 // get one (position, timestamp) sampple from a transport or program
909 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
911 struct pts_pos pp = { 0, 0 };
913 if ( stream->hb_stream_type == transport )
916 fseeko( stream->file_handle, fpos, SEEK_SET );
917 align_to_next_packet( stream );
918 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
921 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
924 if ( ( buf[7] >> 7 ) != 1 )
926 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
929 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
930 ( (uint64_t)buf[10] << 22 ) |
931 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
932 ( (uint64_t)buf[12] << 7 ) |
933 ( (uint64_t)buf[13] >> 1 );
937 // round address down to nearest dvd sector start
938 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
939 fseeko( stream->file_handle, fpos, SEEK_SET );
940 if ( stream->hb_stream_type == program )
942 skip_to_next_pack( stream );
944 pp.pts = hb_ps_stream_getVideoPTS( stream );
946 pp.pos = ftello(stream->file_handle);
950 static int dur_compare( const void *a, const void *b )
952 const double *aval = a, *bval = b;
953 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
956 // given an array of (position, time) samples, compute a max-likelihood
957 // estimate of the average rate by computing the rate between all pairs
958 // of samples then taking the median of those rates.
959 static double compute_stream_rate( struct pts_pos *pp, int n )
962 double rates[NDURSAMPLES * NDURSAMPLES / 2];
965 // the following nested loops compute the rates between all pairs.
967 for ( i = 0; i < n-1; ++i )
969 // Bias the median filter by not including pairs that are "far"
970 // from one another. This is to handle cases where the file is
971 // made of roughly equal size pieces where a symmetric choice of
972 // pairs results in having the same number of intra-piece &
973 // inter-piece rate estimates. This would mean that the median
974 // could easily fall in the inter-piece part of the data which
975 // would give a bogus estimate. The 'ns' index creates an
976 // asymmetry that favors locality.
977 int ns = i + ( n >> 1 );
980 for ( j = i+1; j < ns; ++j )
982 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
984 *rp = ((double)( pp[j].pts - pp[i].pts )) /
985 ((double)( pp[j].pos - pp[i].pos ));
990 // now compute and return the median of all the (n*n/2) rates we computed
992 int nrates = rp - rates;
993 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
994 return rates[nrates >> 1];
997 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
999 struct pts_pos ptspos[NDURSAMPLES];
1000 struct pts_pos *pp = ptspos;
1003 fseeko(stream->file_handle, 0, SEEK_END);
1004 uint64_t fsize = ftello(stream->file_handle);
1005 uint64_t fincr = fsize / NDURSAMPLES;
1006 uint64_t fpos = fincr / 2;
1007 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1009 *pp++ = hb_sample_pts(stream, fpos);
1011 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1012 inTitle->duration = dur;
1014 inTitle->hours = dur / 3600;
1015 inTitle->minutes = ( dur % 3600 ) / 60;
1016 inTitle->seconds = dur % 60;
1018 rewind(stream->file_handle);
1021 /***********************************************************************
1023 ***********************************************************************
1025 **********************************************************************/
1026 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1028 if ( src_stream->hb_stream_type == ffmpeg )
1030 return ffmpeg_read( src_stream, b );
1032 if ( src_stream->hb_stream_type == dvd_program )
1034 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1035 src_stream->file_handle);
1036 return (amt_read > 0);
1038 if ( src_stream->hb_stream_type == program )
1040 // a general program stream has arbitrary sized pack's. we're
1041 // currently positioned at the start of a pack so read up to but
1042 // not including the start of the next, expanding the buffer
1044 uint8_t *cp = b->data;
1045 uint8_t *ep = cp + b->alloc;
1046 uint32_t strt_code = -1;
1049 // consume the first byte of the initial pack so we don't match on
1050 // it in the loop below.
1051 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1056 flockfile( src_stream->file_handle );
1057 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1059 strt_code = ( strt_code << 8 ) | c;
1060 if ( strt_code == 0x000001ba )
1061 // we found the start of the next pack
1065 // need to expand the buffer
1066 int curSize = cp - b->data;
1067 hb_buffer_realloc( b, curSize * 2 );
1068 cp = b->data + curSize;
1069 ep = b->data + b->alloc;
1073 funlockfile( src_stream->file_handle );
1075 // if we didn't terminate on an eof back up so the next read
1076 // starts on the pack boundary.
1077 b->size = cp - b->data;
1080 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1085 return hb_ts_stream_decode( src_stream, b );
1088 /***********************************************************************
1089 * hb_stream_seek_chapter
1090 ***********************************************************************
1092 **********************************************************************/
1093 int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
1095 AVFormatContext *ic = stream->ffmpeg_ic;
1096 uint64_t end_offset = 0;
1097 uint64_t start_offset = 0;
1099 hb_chapter_t *chapter = NULL;
1102 if( !stream || !stream->title )
1107 for( i = 0; i < chapter_num; i++)
1109 chapter = hb_list_item( stream->title->list_chapter,
1115 * Seeking to a chapter means that we are in that chapter,
1116 * so track which chapter we are in so that we can output
1117 * the correct chapter numbers in buf->new_chap
1119 start_offset = end_offset;
1120 end_offset += chapter->duration;
1121 stream->chapter = i;
1122 stream->chapter_end = end_offset;
1129 * Is the the correct way to convert timebases? It seems to get it pretty
1130 * much right - plus a few seconds, which is odd.
1132 pos = ((start_offset * AV_TIME_BASE) / 90000);
1134 hb_deep_log( 2, "Seeking to chapter %d time (starts: %lld ends %lld) AV pos %lld", chapter_num-1, start_offset, end_offset, pos);
1136 av_seek_frame( ic, -1, pos, 0);
1141 /***********************************************************************
1143 ***********************************************************************
1144 * Return the number of the chapter that we are currently in. We store
1145 * the chapter number starting from 0, so + 1 for the real chpater num.
1146 **********************************************************************/
1147 int hb_stream_chapter( hb_stream_t * src_stream )
1149 return( src_stream->chapter + 1 );
1152 /***********************************************************************
1154 ***********************************************************************
1156 **********************************************************************/
1157 int hb_stream_seek( hb_stream_t * stream, float f )
1159 if ( stream->hb_stream_type == ffmpeg )
1161 return ffmpeg_seek( stream, f );
1163 off_t stream_size, cur_pos, new_pos;
1164 double pos_ratio = f;
1165 cur_pos = ftello( stream->file_handle );
1166 fseeko( stream->file_handle, 0, SEEK_END );
1167 stream_size = ftello( stream->file_handle );
1168 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1169 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1171 int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1174 fseeko( stream->file_handle, cur_pos, SEEK_SET );
1178 if ( stream->hb_stream_type == transport )
1180 // We need to drop the current decoder output and move
1181 // forwards to the next transport stream packet.
1182 hb_ts_stream_reset(stream);
1185 if ( !stream->ts_no_RAP )
1187 // we're not at the beginning - try to find a random access point
1188 hb_ts_stream_find_RAP( stream );
1190 stream->need_keyframe = 1;
1194 // we're at the beginning - say we have video sync so that we
1195 // won't drop initial SPS & PPS data on an AVC stream.
1196 stream->need_keyframe = 0;
1199 else if ( stream->hb_stream_type == program )
1201 skip_to_next_pack( stream );
1207 static const char* make_upper( const char* s )
1209 static char name[8];
1211 char *ep = cp + sizeof(name)-1;
1213 while ( *s && cp < ep )
1215 *cp++ = islower(*s)? toupper(*s) : *s;
1222 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1225 * This is a duplicate of code in dvd.c - it should get factored out
1226 * into a common routine. We probably should only be putting the lang
1227 * code or a lang pointer into the audio config & let the common description
1228 * formatting routine in scan.c do all the stuff below.
1230 const char *codec_name;
1233 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1234 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1235 avcodec_find_decoder( cc->codec_id ) )
1237 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1238 if ( !strcmp( codec_name, "LIBFAAD" ) )
1243 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1244 avcodec_find_decoder( audio->config.in.codec_param ) )
1246 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1250 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1251 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1252 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1253 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1254 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1257 snprintf( audio->config.lang.description,
1258 sizeof( audio->config.lang.description ), "%s (%s)",
1259 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1261 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1262 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1263 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1264 "%s", lang->iso639_2);
1267 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1270 off_t cur_pos = ftello(stream->file_handle);
1271 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1274 fseeko(stream->file_handle, 0, SEEK_SET);
1275 align_to_next_packet(stream);
1276 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1278 /* check that we found a PES header */
1280 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1282 stype = stream->ts_stream_type[1 + aud_pid_index];
1284 // 0xbd ("private stream 1") is the normal container for non-ISO
1285 // media - AC3/DCA/PCM/etc.
1286 if ( buf[3] == 0xbd )
1288 if ( st2codec[stype].kind == U )
1290 // XXX assume unknown stream types are AC-3 (if they're not
1291 // audio we'll find that out during the scan but if they're
1292 // some other type of audio we'll end up ignoring them).
1294 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1297 else if ( buf[3] == 0xfd )
1299 // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1300 // the blu ray consortium apparently forgot to read the portion
1301 // of the MPEG spec that says one PID should map to one media
1302 // stream and multiplexed multiple types of audio into one PID
1303 // using the extended stream identifier of the PES header to
1304 // distinguish them. So we have to check if that's happening and
1305 // if so tell the runtime what esid we want.
1306 if ( st2codec[stype].kind == A && stype == 0x83 &&
1307 stream->ts_format_id[1 + aud_pid_index] == TS_FORMAT_ID_AC3 )
1309 // This is an interleaved TrueHD/AC-3 stream and the esid of
1311 stream->ts_multiplexed[1 + aud_pid_index] = 0x76;
1313 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1315 if ( st2codec[stype].kind == A && stype == 0x86 )
1317 // This is an interleaved DTS-HD/DTS stream and the esid of
1319 stream->ts_multiplexed[1 + aud_pid_index] = 0x71;
1321 stream->ts_stream_type[1 + aud_pid_index] = 0x82;
1324 else if ((buf[3] & 0xe0) == 0xc0)
1326 // 0xC0 - 0xCF are the normal containers for ISO-standard
1327 // media (mpeg2 audio and mpeg4 AAC).
1328 if ( st2codec[stype].kind == U )
1330 // XXX assume unknown stream types are MPEG audio
1332 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1340 // if we found an audio stream type & HB has a codec that can decode it
1341 // finish configuring the audio so we'll add it to the title's list.
1342 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1344 audio->id = 1 + aud_pid_index;
1345 audio->config.in.codec = st2codec[stype].codec;
1346 audio->config.in.codec_param = st2codec[stype].codec_param;
1347 set_audio_description( audio,
1348 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1349 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1350 stream->ts_audio_pids[aud_pid_index],
1351 stype, st2codec[stype].name, audio->id);
1357 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1358 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1359 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1363 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1364 stream->ts_audio_pids[aud_pid_index],
1365 stream->ts_stream_type[1 + aud_pid_index]);
1368 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1372 static void add_audio_to_title(hb_title_t *title, int id)
1374 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1380 audio->config.in.codec = HB_ACODEC_MPGA;
1381 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1384 // type 2 is a DVD subtitle stream - just ignore it */
1388 audio->config.in.codec = HB_ACODEC_AC3;
1389 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1392 audio->config.in.codec = HB_ACODEC_LPCM;
1393 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1396 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1401 set_audio_description( audio, lang_for_code( 0 ) );
1402 hb_list_add( title->list_audio, audio );
1405 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1407 off_t cur_pos = ftello(stream->file_handle);
1408 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1409 hb_list_t *list = hb_list_init();
1410 // how many blocks we read while searching for audio streams
1411 int blksleft = 4096;
1412 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1413 // so we use a bitmap to keep track of the ones we've already seen.
1414 // Bit 'i' of smap is set if we've already added the audio for
1415 // audio substream id 'i' to the title's audio list.
1418 // start looking 20% into the file since there's occasionally no
1419 // audio at the beginning (particularly for vobs).
1420 hb_stream_seek(stream, 0.2f);
1422 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1426 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1427 hb_demux_ps( buf, list, 0 );
1429 while ( ( es = hb_list_item( list, 0 ) ) )
1431 hb_list_rem( list, es );
1432 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1434 // this PES contains some kind of audio - get the substream id
1435 // and check if we've seen it already.
1436 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1437 if ( (smap & (1 << ssid)) == 0 )
1439 // we haven't seen this stream before - add it to the
1440 // title's list of audio streams.
1441 smap |= (1 << ssid);
1442 add_audio_to_title(title, es->id);
1445 hb_buffer_close( &es );
1448 hb_list_empty( &list );
1449 hb_buffer_close(&buf);
1450 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1453 /***********************************************************************
1455 ***********************************************************************
1457 **********************************************************************/
1459 static void hb_ts_stream_init(hb_stream_t *stream)
1463 for (i=0; i < kMaxNumberDecodeStreams; i++)
1465 stream->ts_streamcont[i] = -1;
1467 stream->ts_video_pids[0] = -1;
1468 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1470 stream-> ts_audio_pids[i] = -1;
1473 stream->ts_packet = malloc( stream->packetsize );
1475 // Find the audio and video pids in the stream
1476 hb_ts_stream_find_pids(stream);
1478 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1480 // demuxing buffer for TS to PS conversion
1481 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1482 stream->ts_buf[i]->size = 0;
1486 #define MAX_HOLE 208*80
1488 static off_t align_to_next_packet(hb_stream_t *stream)
1490 uint8_t buf[MAX_HOLE];
1492 off_t start = ftello(stream->file_handle);
1494 if ( start >= stream->packetsize ) {
1495 start -= stream->packetsize;
1496 fseeko(stream->file_handle, start, SEEK_SET);
1499 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1501 const uint8_t *bp = buf;
1504 for ( i = sizeof(buf); --i >= 0; ++bp )
1506 if ( have_ts_sync( bp, stream->packetsize ) )
1513 pos = ( bp - buf ) - stream->packetsize + 188;
1518 fseeko(stream->file_handle, start+pos, SEEK_SET);
1529 static const unsigned int bitmask[] = {
1530 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1531 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1532 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1533 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1535 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1539 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1540 (bb->buf[2] << 8) | bb->buf[3];
1542 memset(bb->buf, 0, bufsize);
1545 static inline int buf_size(bitbuf_t *bb)
1547 return bb->pos >> 3;
1550 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1553 int left = 32 - (bb->pos & 31);
1557 val = (bb->val >> (left - bits)) & bitmask[bits];
1562 val = (bb->val & bitmask[left]) << (bits - left);
1566 int pos = bb->pos >> 3;
1567 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1571 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1579 // extract what useful information we can from the elementary stream
1580 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1581 // Descriptors with info we don't currently use are ignored.
1582 // The descriptor list & descriptor item formats are defined in
1583 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1584 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1585 const uint8_t *dp, uint8_t dlen)
1587 const uint8_t *ep = dp + dlen;
1593 case 5: // Registration descriptor
1594 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1595 (dp[4] << 8) | dp[5];
1598 case 10: // ISO_639_language descriptor
1599 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1609 static const char *stream_type_name (uint8_t stream_type)
1611 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1614 int decode_program_map(hb_stream_t* stream)
1617 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1619 get_bits(&bb, 8); // table_id
1621 unsigned int section_length = get_bits(&bb, 12);
1622 stream->pmt_info.section_length = section_length;
1624 unsigned int program_number = get_bits(&bb, 16);
1625 stream->pmt_info.program_number = program_number;
1627 get_bits(&bb, 5); // version_number
1629 get_bits(&bb, 8); // section_number
1630 get_bits(&bb, 8); // last_section_number
1632 unsigned int PCR_PID = get_bits(&bb, 13);
1633 stream->pmt_info.PCR_PID = PCR_PID;
1635 unsigned int program_info_length = get_bits(&bb, 12);
1636 stream->pmt_info.program_info_length = program_info_length;
1639 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1640 for (i = 0; i < program_info_length; i++)
1642 descriptor_buf[i] = get_bits(&bb, 8);
1645 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1646 int done_reading_stream_types = 0;
1647 while (!done_reading_stream_types)
1649 unsigned char stream_type = get_bits(&bb, 8);
1651 unsigned int elementary_PID = get_bits(&bb, 13);
1653 unsigned int ES_info_length = get_bits(&bb, 12);
1656 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1657 for (i=0; i < ES_info_length; i++)
1659 ES_info_buf[i] = get_bits(&bb, 8);
1663 if ( index_of_pid( elementary_PID, stream ) < 0 )
1665 // already have this pid - do nothing
1667 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1669 stream->ts_video_pids[0] = elementary_PID;
1670 stream->ts_stream_type[0] = stream_type;
1671 stream->ts_number_video_pids = 1;
1675 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1676 // for mpeg audio. But content producers seem to use other
1677 // values (0x04 and 0x06 have both been observed) so at this point
1678 // we say everything that isn't a video pid is audio then at the end
1679 // of hb_stream_title_scan we'll figure out which are really audio
1680 // by looking at the PES headers.
1681 i = stream->ts_number_audio_pids;
1682 if (i < kMaxNumberAudioPIDS)
1684 stream->ts_audio_pids[i] = elementary_PID;
1685 stream->ts_stream_type[1 + i] = stream_type;
1686 if (ES_info_length > 0)
1688 decode_element_descriptors(stream, i, ES_info_buf,
1691 ++stream->ts_number_audio_pids;
1695 cur_pos += 5 /* stream header */ + ES_info_length;
1699 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1700 done_reading_stream_types = 1;
1703 free(descriptor_buf);
1707 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1709 // Get adaption header info
1711 int adaption = (buf[3] & 0x30) >> 4;
1714 else if (adaption == 0x2)
1716 else if (adaption == 0x3)
1717 adapt_len = buf[4] + 1;
1718 if (adapt_len > 184)
1721 // Get payload start indicator
1723 start = (buf[1] & 0x40) != 0;
1725 // Get pointer length - only valid in packets with a start flag
1726 int pointer_len = 0;
1730 pointer_len = buf[4 + adapt_len] + 1;
1731 stream->pmt_info.tablepos = 0;
1733 // Get Continuity Counter
1734 int continuity_counter = buf[3] & 0x0f;
1735 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1737 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1740 stream->pmt_info.current_continuity_counter = continuity_counter;
1741 stream->pmt_info.reading |= start;
1743 // Add the payload for this packet to the current buffer
1744 int amount_to_copy = 184 - adapt_len - pointer_len;
1745 if (stream->pmt_info.reading && (amount_to_copy > 0))
1747 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1749 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1750 stream->pmt_info.tablepos += amount_to_copy;
1752 if (stream->pmt_info.tablepos > 3)
1754 // We have enough to check the section length
1756 length = ((stream->pmt_info.tablebuf[1] << 8) +
1757 stream->pmt_info.tablebuf[2]) & 0xFFF;
1758 if (stream->pmt_info.tablepos > length + 1)
1760 // We just finished a bunch of packets - parse the program map details
1762 if (stream->pmt_info.tablebuf[0] == 0x02)
1763 decode_ok = decode_program_map(stream);
1764 free(stream->pmt_info.tablebuf);
1765 stream->pmt_info.tablebuf = NULL;
1766 stream->pmt_info.tablepos = 0;
1767 stream->pmt_info.reading = 0;
1777 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1779 unsigned char tablebuf[1024];
1780 unsigned int tablepos = 0;
1785 // Get adaption header info
1787 int adaption = (buf[3] & 0x30) >> 4;
1790 else if (adaption == 0x2)
1792 else if (adaption == 0x3)
1793 adapt_len = buf[4] + 1;
1794 if (adapt_len > 184)
1797 // Get pointer length
1798 int pointer_len = buf[4 + adapt_len] + 1;
1800 // Get payload start indicator
1802 start = (buf[1] & 0x40) != 0;
1807 // Add the payload for this packet to the current buffer
1808 if (reading && (184 - adapt_len) > 0)
1810 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1812 hb_log("decode_PAT - Bad program section length (> 1024)");
1815 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1816 tablepos += 184 - adapt_len - pointer_len;
1819 if (start && reading)
1821 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1824 unsigned int pos = 0;
1825 //while (pos < tablepos)
1828 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1830 unsigned char section_id = get_bits(&bb, 8);
1832 unsigned int section_len = get_bits(&bb, 12);
1833 get_bits(&bb, 16); // transport_id
1835 get_bits(&bb, 5); // version_num
1836 get_bits(&bb, 1); // current_next
1837 get_bits(&bb, 8); // section_num
1838 get_bits(&bb, 8); // last_section
1844 // Program Association Section
1845 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1846 section_len -= 4; // Ignore the CRC
1848 stream->ts_number_pat_entries = 0;
1849 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1851 unsigned int pkt_program_num = get_bits(&bb, 16);
1852 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1854 get_bits(&bb, 3); // Reserved
1855 if (pkt_program_num == 0)
1857 get_bits(&bb, 13); // pkt_network_id
1861 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1862 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1865 stream->ts_number_pat_entries++;
1879 pos += 3 + section_len;
1887 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1889 // align to first packet
1890 align_to_next_packet(stream);
1892 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1893 // to find the program map PID and then decode that to get the list of audio and video PIDs
1897 const uint8_t *buf = next_packet( stream );
1901 hb_log("hb_ts_stream_find_pids - end of file");
1906 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1908 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1910 decode_PAT(buf, stream);
1915 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1917 // There are some streams where the PAT table has multiple entries as if their are
1918 // multiple programs in the same transport stream, and yet there's actually only one
1919 // program really in the stream. This seems to be true for transport streams that
1920 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1921 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1922 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1923 // PAT info on export to match what's actually on the stream.
1924 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1925 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1926 // be to build a title choice popup from the PAT program number details and then select from
1927 // their - but right now the API's not capable of that.
1928 if (stream->pat_info[pat_index].program_number != 0 &&
1929 pid == stream->pat_info[pat_index].program_map_PID)
1931 if (build_program_map(buf, stream) > 0)
1935 // Keep going until we have a complete set of PIDs
1936 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1939 // XXX - until we figure out how to handle VC1 just bail when we find it so
1940 // that ffmpeg will claim the input stream.
1941 if ( stream->ts_stream_type[0] == 0xea )
1943 stream->ts_number_video_pids = 0;
1944 stream->ts_number_audio_pids = 0;
1948 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1949 hb_log(" Video PIDS : ");
1951 for (i=0; i < stream->ts_number_video_pids; i++)
1953 hb_log( " 0x%x type %s (0x%x)",
1954 stream->ts_video_pids[i],
1955 stream_type_name(stream->ts_stream_type[i]),
1956 stream->ts_stream_type[i]);
1958 hb_log(" Audio PIDS : ");
1959 for (i = 0; i < stream->ts_number_audio_pids; i++)
1961 hb_log( " 0x%x type %s (0x%x)",
1962 stream->ts_audio_pids[i],
1963 stream_type_name(stream->ts_stream_type[i+1]),
1964 stream->ts_stream_type[i+1] );
1969 static void fwrite64( hb_stream_t *stream, void *buf, int len )
1973 pos = stream->fwrite_buf->size;
1974 if ( pos + len > stream->fwrite_buf->alloc )
1976 int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
1977 hb_buffer_realloc(stream->fwrite_buf, size);
1979 memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
1980 stream->fwrite_buf->size += len;
1983 // convert a PES PTS or DTS to an int64
1984 static int64_t pes_timestamp( const uint8_t *pes )
1986 int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
1987 ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
1988 ( pes[3] << 7 ) | ( pes[4] >> 1 );
1992 static void generate_output_data(hb_stream_t *stream, int curstream)
1994 hb_buffer_t *buf = stream->fwrite_buf;
1995 uint8_t *tdat = stream->ts_buf[curstream]->data;
1997 buf->id = curstream;
1999 // check if this packet was referenced to an older pcr and if that
2000 // pcr was significantly different than the one we're using now.
2001 // (the reason for the uint cast on the pcr difference is that the
2002 // difference is significant if it advanced by more than 200ms or if
2003 // it went backwards by any amount. The negative numbers look like huge
2004 // unsigned ints so the cast allows both conditions to be checked at once.
2005 int bufpcr = stream->ts_buf[curstream]->cur;
2006 int curpcr = stream->ts_pcr_out;
2007 if ( bufpcr && bufpcr < curpcr &&
2008 (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2010 // we've sent up a new pcr but have a packet referenced to an
2011 // old pcr and the difference was enough to trigger a discontinuity
2012 // correction. smash the timestamps or we'll mess up the correction.
2014 buf->renderOffset = -1;
2018 if ( stream->ts_pcr_out != stream->ts_pcr_in )
2020 // we have a new pcr
2021 stream->ts_pcr_out = stream->ts_pcr_in;
2022 buf->stop = stream->ts_pcr;
2023 stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2030 // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2031 // off the PES header.
2032 if ( tdat[7] & 0xc0 )
2034 buf->start = pes_timestamp( tdat + 9 );
2035 buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2041 buf->renderOffset = -1;
2044 int hlen = tdat[8] + 9;
2046 fwrite64( stream, tdat + hlen, stream->ts_pos[curstream] - hlen );
2048 stream->ts_pos[curstream] = 0;
2049 stream->ts_buf[curstream]->size = 0;
2052 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
2054 // For mpeg2: look for a gop start or i-frame picture start
2055 // for h.264: look for idr nal type or a slice header for an i-frame
2061 if ( stream->ts_stream_type[0] <= 2 )
2063 // This section of the code handles MPEG-1 and MPEG-2 video streams
2064 for (i = 13 + adapt_len; i < 188; i++)
2066 strid = (strid << 8) | buf[i];
2067 if ( ( strid >> 8 ) == 1 )
2069 // we found a start code
2073 case 0xB8: // group_start_code (GOP header)
2074 case 0xB3: // sequence_header code
2077 case 0x00: // picture_start_code
2078 // picture_header, let's see if it's an I-frame
2081 // check if picture_coding_type == 1
2082 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2084 // found an I-frame picture
2092 // didn't find an I-frame
2095 if ( stream->ts_stream_type[0] == 0x1b )
2097 // we have an h.264 stream
2098 for (i = 13 + adapt_len; i < 188; i++)
2100 strid = (strid << 8) | buf[i];
2101 if ( ( strid >> 8 ) == 1 )
2103 // we found a start code - remove the ref_idc from the nal type
2104 uint8_t nal_type = strid & 0x1f;
2105 if ( nal_type == 0x05 )
2106 // h.264 IDR picture start
2109 if ( stream->packetsize == 192 )
2111 // m2ts files have idr frames so keep looking for one
2115 // h.264 in ts files (ATSC or DVB video) often seem to be
2116 // missing IDR frames so look for at least an I
2117 if ( nal_type == 0x01 )
2119 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2120 uint8_t id = buf[i+1];
2121 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2122 id == 0x88 || id == 0x8a )
2129 // didn't find an I-frame
2133 // we don't understand the stream type so just say "yes" otherwise
2134 // we'll discard all the video.
2138 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2140 if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2144 size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2145 hb_buffer_realloc(stream->ts_buf[idx], size);
2147 memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2148 stream->ts_pos[idx] += len;
2149 stream->ts_buf[idx]->size += len;
2152 /***********************************************************************
2153 * hb_ts_stream_decode
2154 ***********************************************************************
2156 **********************************************************************/
2157 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2160 * stash the output buffer pointer in our stream so we don't have to
2161 * pass it & its original value to everything we call.
2164 stream->fwrite_buf = obuf;
2166 // spin until we get a packet of data from some stream or hit eof
2171 const uint8_t *buf = next_packet(stream);
2174 // end of file - we didn't finish filling our ps write buffer
2175 // so just discard the remainder (the partial buffer is useless)
2176 hb_log("hb_ts_stream_decode - eof");
2180 /* This next section validates the packet */
2182 // Get pid and use it to find stream state.
2183 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2184 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2188 int errorbit = (buf[1] & 0x80) != 0;
2191 ts_err( stream, curstream, "packet error bit set");
2195 // Get adaption header info
2196 int adaption = (buf[3] & 0x30) >> 4;
2200 ts_err( stream, curstream, "adaptation code 0");
2203 else if (adaption == 0x2)
2205 else if (adaption == 0x3)
2207 adapt_len = buf[4] + 1;
2208 if (adapt_len > 184)
2210 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2215 if ( adapt_len > 0 )
2217 if ( buf[5] & 0x40 )
2219 // found a random access point
2221 // if there's an adaptation header & PCR_flag is set
2222 // get the PCR (Program Clock Reference)
2223 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2225 stream->ts_pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2226 ( (uint64_t)buf[7] << (33 - 16) ) |
2227 ( (uint64_t)buf[8] << (33 - 24) ) |
2228 ( (uint64_t)buf[9] << (33 - 32) ) |
2230 ++stream->ts_pcr_in;
2231 stream->ts_found_pcr = 1;
2235 // If we don't have a pcr yet, the right thing to do here would
2236 // be a 'continue' so we don't process anything until we have a
2237 // clock reference. Unfortunately the HD Home Run appears to null
2238 // out the pcr field of some streams so we keep going & substitute
2239 // the video stream dts for the pcr when there's no pcr.
2242 // Continuity only increments for adaption values of 0x3 or 0x01
2243 // and is not checked for start packets.
2245 int start = (buf[1] & 0x40) != 0;
2247 if ( (adaption & 0x01) != 0 )
2249 int continuity = (buf[3] & 0xF);
2250 if ( continuity == stream->ts_streamcont[curstream] )
2252 // we got a duplicate packet (usually used to introduce
2253 // a PCR when one is needed). The only thing that can
2254 // change in the dup is the PCR which we grabbed above
2255 // so ignore the rest.
2258 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2259 !stream->ts_skipbad[curstream] &&
2260 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2262 ts_err( stream, curstream, "continuity error: got %d expected %d",
2264 (stream->ts_streamcont[curstream] + 1) & 0xf );
2265 stream->ts_streamcont[curstream] = continuity;
2268 stream->ts_streamcont[curstream] = continuity;
2271 /* If we get here the packet is valid - process its data */
2275 // Found a random access point (now we can start a frame/audio packet..)
2277 if ( stream->need_keyframe )
2279 // we're looking for the first video frame because we're
2280 // doing random access during 'scan'
2281 if (curstream != 0 || !isIframe( stream, buf, adapt_len ) )
2283 // not the video stream or didn't find an I frame
2286 stream->need_keyframe = 0;
2289 // If we were skipping a bad packet, start fresh on this new PES packet..
2290 if (stream->ts_skipbad[curstream] == 1)
2292 stream->ts_skipbad[curstream] = 0;
2295 if ( curstream == 0 )
2299 // if we don't have a pcr yet use the dts from this frame
2300 if ( !stream->ts_found_pcr )
2302 // PES must begin with an mpeg start code & contain
2304 const uint8_t *pes = buf + adapt_len + 4;
2305 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2306 ( pes[7] >> 6 ) == 0 )
2310 // if we have a dts use it otherwise use the pts
2311 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40? 14 : 9 ) );
2312 ++stream->ts_pcr_in;
2316 // if this is a multiplexed stream make sure this is the
2317 // substream we want.
2318 if ( stream->ts_multiplexed[curstream] )
2320 // PES must begin with an mpeg start code & contain
2322 const uint8_t *pes = buf + adapt_len + 4;
2323 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2326 stream->ts_skipbad[curstream] = 1;
2329 // the last byte of the header is the extension id. see if
2330 // it's the one we want.
2331 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2333 stream->ts_skipbad[curstream] = 1;
2338 // If we have some data already on this stream, turn it into
2339 // a program stream packet. Then add the payload for this
2340 // packet to the current pid's buffer.
2341 if ( stream->ts_pos[curstream] )
2343 // we have to ship the old packet before updating the pcr
2344 // since the packet we've been accumulating is referenced
2346 generate_output_data(stream, curstream);
2348 // remember the pcr that was in effect when we started
2350 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2351 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2355 // remember the pcr that was in effect when we started this packet.
2356 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2359 // Add the payload for this packet to the current buffer
2360 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2362 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2364 // see if we've hit the end of this PES packet
2365 const uint8_t *pes = stream->ts_buf[curstream]->data;
2366 int len = ( pes[4] << 8 ) + pes[5] + 6;
2367 if ( len > 6 && stream->ts_pos[curstream] == len &&
2368 pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2370 generate_output_data(stream, curstream);
2377 static void hb_ts_stream_reset(hb_stream_t *stream)
2381 for (i=0; i < kMaxNumberDecodeStreams; i++)
2383 stream->ts_pos[i] = 0;
2384 stream->ts_skipbad[i] = 1;
2385 stream->ts_streamcont[i] = -1;
2388 stream->need_keyframe = 0;
2390 stream->ts_found_pcr = 0;
2391 stream->ts_pcr_out = 0;
2392 stream->ts_pcr_in = 0;
2397 stream->last_error_frame = -10000;
2398 stream->last_error_count = 0;
2400 align_to_next_packet(stream);
2403 // ------------------------------------------------------------------
2404 // Support for reading media files via the ffmpeg libraries.
2406 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2408 // add a codec to the context here so it will be there when we
2409 // read the first packet.
2410 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2411 context->workaround_bugs = FF_BUG_AUTODETECT;
2412 context->error_recognition = 1;
2413 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2414 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2415 avcodec_open( context, codec );
2418 // The ffmpeg stream reader / parser shares a lot of state with the
2419 // decoder via a codec context kept in the AVStream of the reader's
2420 // AVFormatContext. Since decoding is done in a different thread we
2421 // have to somehow pass this codec context to the decoder and we have
2422 // to do it before the first packet is read (so we can't put the info
2423 // in the buf we'll send downstream). Decoders don't have any way to
2424 // get to the stream directly (they're not passed the title or job
2425 // pointers during a scan) so this is a back door for the decoder to
2426 // get the codec context. We just stick the stream pointer in the next
2427 // slot an array of pointers maintained as a circular list then return
2428 // the index into the list combined with the ffmpeg stream index as the
2429 // codec_param that will be passed to the decoder init routine. We make
2430 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2431 // so that we don't have to do a complicated allocator or worry about
2432 // deleting entries on close.
2434 // Entries can only be added to this list during a scan and are never
2435 // deleted so the list access doesn't require locking.
2436 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2437 static int ffmpeg_stream_cur; // where we put the last stream pointer
2438 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2439 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2441 // add a stream to the list & return the appropriate codec_param to access it
2442 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2444 if ( !ffmpeg_streams )
2446 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2449 // the title scan adds all the ffmpeg media streams at once so we
2450 // only add a new entry to our stream list if the stream is different
2452 int slot = ffmpeg_stream_cur;
2453 if ( ffmpeg_streams[slot] != stream )
2455 // new stream - put it in the next slot of the stream list
2456 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2457 ffmpeg_streams[slot] = stream;
2460 ffmpeg_add_codec( stream, stream_index );
2462 return ( stream_index << ffmpeg_sl_bits ) | slot;
2465 // we're about to open 'title' to convert it - remap the stream associated
2466 // with the video & audio codec params of the title to refer to 'stream'
2467 // (the original scan stream was closed and no longer exists).
2468 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2470 // tell ffmpeg we want a pts on every frame it returns
2471 stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2473 // all the video & audio came from the same stream so remapping
2474 // the video's stream slot takes care of everything.
2475 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2476 ffmpeg_streams[slot] = stream;
2478 // add codecs for all the streams used by the title
2479 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2483 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2485 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2487 ffmpeg_add_codec( stream,
2488 audio->config.in.codec_param >> ffmpeg_sl_bits );
2493 void *hb_ffmpeg_context( int codec_param )
2495 int slot = codec_param & (ffmpeg_sl_size - 1);
2496 int stream_index = codec_param >> ffmpeg_sl_bits;
2497 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2500 void *hb_ffmpeg_avstream( int codec_param )
2502 int slot = codec_param & (ffmpeg_sl_size - 1);
2503 int stream_index = codec_param >> ffmpeg_sl_bits;
2504 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2507 static AVFormatContext *ffmpeg_deferred_close;
2509 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2511 if ( ffmpeg_deferred_close )
2513 av_close_input_file( ffmpeg_deferred_close );
2514 ffmpeg_deferred_close = NULL;
2516 AVFormatContext *ic;
2518 av_log_set_level( AV_LOG_ERROR );
2519 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2523 if ( av_find_stream_info( ic ) < 0 )
2526 stream->ffmpeg_ic = ic;
2527 stream->hb_stream_type = ffmpeg;
2528 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2529 av_init_packet( stream->ffmpeg_pkt );
2533 // we're opening for read. scan passed out codec params that
2534 // indexed its stream so we need to remap them so they point
2536 ffmpeg_remap_stream( stream, title );
2537 av_log_set_level( AV_LOG_ERROR );
2541 // we're opening for scan. let ffmpeg put some info into the
2542 // log about what we've got.
2543 av_log_set_level( AV_LOG_INFO );
2544 dump_format( ic, 0, stream->path, 0 );
2545 av_log_set_level( AV_LOG_ERROR );
2547 // accept this file if it has at least one video stream we can decode
2549 for (i = 0; i < ic->nb_streams; ++i )
2551 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2556 if ( i >= ic->nb_streams )
2562 av_close_input_file( ic );
2566 static void ffmpeg_close( hb_stream_t *d )
2568 // XXX since we're sharing the CodecContext with the downstream
2569 // decoder proc we can't close the stream. We need to reference count
2570 // this so we can close it when both are done with their instance but
2571 // for now just defer the close until the next stream open or close.
2572 if ( ffmpeg_deferred_close )
2574 av_close_input_file( ffmpeg_deferred_close );
2576 ffmpeg_deferred_close = d->ffmpeg_ic;
2577 if ( d->ffmpeg_pkt != NULL )
2579 free( d->ffmpeg_pkt );
2580 d->ffmpeg_pkt = NULL;
2584 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2586 AVStream *st = stream->ffmpeg_ic->streams[id];
2587 AVCodecContext *codec = st->codec;
2589 // scan will ignore any audio without a bitrate. Since we've already
2590 // typed the audio in order to determine its codec we set up the audio
2592 if ( codec->bit_rate || codec->sample_rate )
2594 static const int chan2layout[] = {
2595 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2596 HB_INPUT_CH_LAYOUT_MONO,
2597 HB_INPUT_CH_LAYOUT_STEREO,
2598 HB_INPUT_CH_LAYOUT_2F1R,
2599 HB_INPUT_CH_LAYOUT_2F2R,
2600 HB_INPUT_CH_LAYOUT_3F2R,
2601 HB_INPUT_CH_LAYOUT_4F2R,
2602 HB_INPUT_CH_LAYOUT_STEREO,
2603 HB_INPUT_CH_LAYOUT_STEREO,
2606 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2609 if ( codec->codec_id == CODEC_ID_AC3 )
2611 audio->config.in.codec = HB_ACODEC_AC3;
2613 else if ( codec->codec_id == CODEC_ID_DTS )
2615 audio->config.in.codec = HB_ACODEC_DCA;
2619 audio->config.in.codec = HB_ACODEC_FFMPEG;
2620 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2622 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2623 audio->config.in.samplerate = codec->sample_rate;
2624 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2627 set_audio_description( audio, lang_for_code2( st->language ) );
2629 hb_list_add( title->list_audio, audio );
2633 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2635 AVFormatContext *ic = stream->ffmpeg_ic;
2637 // 'Barebones Title'
2638 hb_title_t *title = hb_title_init( stream->path, 0 );
2641 // Copy part of the stream path to the title name
2642 char *sep = strrchr(stream->path, '/');
2644 strcpy(title->name, sep+1);
2645 char *dot_term = strrchr(title->name, '.');
2649 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2650 title->duration = dur;
2652 title->hours = dur / 3600;
2653 title->minutes = ( dur % 3600 ) / 60;
2654 title->seconds = dur % 60;
2656 // set the title to decode the first video stream in the file
2657 title->demuxer = HB_NULL_DEMUXER;
2658 title->video_codec = 0;
2660 for (i = 0; i < ic->nb_streams; ++i )
2662 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2663 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2664 title->video_codec == 0 )
2666 title->video_id = i;
2667 stream->ffmpeg_video_id = i;
2669 // We have to use the 'internal' avcodec decoder because
2670 // it needs to share the codec context from this video
2671 // stream. The parser internal to av_read_frame
2672 // passes a bunch of state info to the decoder via the context.
2673 title->video_codec = WORK_DECAVCODECVI;
2674 title->video_codec_param = ffmpeg_codec_param( stream, i );
2676 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2677 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2679 add_ffmpeg_audio( title, stream, i );
2683 title->container_name = strdup( ic->iformat->name );
2684 title->data_rate = ic->bit_rate;
2686 hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name);
2689 * Fill the metadata.
2691 decmetadata( title );
2693 if( hb_list_count( title->list_chapter ) == 0 )
2695 // Need at least one chapter
2696 hb_chapter_t * chapter;
2697 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2699 chapter->duration = title->duration;
2700 chapter->hours = title->hours;
2701 chapter->minutes = title->minutes;
2702 chapter->seconds = title->seconds;
2703 hb_list_add( title->list_chapter, chapter );
2709 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2711 if ( pts == AV_NOPTS_VALUE )
2713 return (int64_t)( (double)pts * conv_factor );
2716 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2720 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2722 // XXX the following conditional is to handle avi files that
2723 // use M$ 'packed b-frames' and occasionally have negative
2724 // sizes for the null frames these require.
2725 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2729 if ( stream->ffmpeg_pkt->size <= 0 )
2731 // M$ "invalid and inefficient" packed b-frames require 'null frames'
2732 // following them to preserve the timing (since the packing puts two
2733 // or more frames in what looks like one avi frame). The contents and
2734 // size of these null frames are ignored by the ff_h263_decode_frame
2735 // as long as they're < 20 bytes. We need a positive size so we use
2736 // one byte if we're given a zero or negative size. We don't know
2737 // if the pkt data points anywhere reasonable so we just stick a
2738 // byte of zero in our outbound buf.
2744 if ( stream->ffmpeg_pkt->size > buf->alloc )
2746 // sometimes we get absurd sizes from ffmpeg
2747 if ( stream->ffmpeg_pkt->size >= (1 << 25) )
2749 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
2750 av_free_packet( stream->ffmpeg_pkt );
2751 return ffmpeg_read( stream, buf );
2753 // need to expand buffer
2754 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2756 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2757 buf->size = stream->ffmpeg_pkt->size;
2759 buf->id = stream->ffmpeg_pkt->stream_index;
2760 if ( buf->id == stream->ffmpeg_video_id )
2762 if ( stream->need_keyframe &&
2763 stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id ==
2766 // XXX the VC1 codec doesn't seek to key frames so to get previews
2767 // we do it ourselves here. The decoder gets messed up if it
2768 // doesn't get a SEQ header first so we consider that to be a key frame.
2769 uint8_t *pkt = stream->ffmpeg_pkt->data;
2770 if ( pkt[0] || pkt[1] || pkt[2] != 1 || pkt[3] != 0x0f )
2774 stream->need_keyframe = 0;
2779 // if we haven't done it already, compute a conversion factor to go
2780 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2781 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2784 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2785 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2786 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2789 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2790 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2791 if ( buf->renderOffset >= 0 && buf->start == -1 )
2793 buf->start = buf->renderOffset;
2797 * Check to see whether this video buffer is on a chapter
2798 * boundary, if so mark it as such in the buffer. The chapters for
2799 * a stream have a simple duration for each chapter. So we keep
2800 * track of what chapter we are in currently, and when it is due
2803 hb_deep_log( 3, "title=0x%x, job=0x%x, chapter_markers=%d, time=%lld, chapter=%d, end_chapter=%lld",
2805 stream->title ? (stream->title->job ? stream->title->job : 0x0) : 0x0,
2806 stream->title ? (stream->title->job ? stream->title->job->chapter_markers : 2) : 0x0,
2807 buf->start, stream->chapter, stream->chapter_end);
2809 if( stream->title &&
2810 stream->title->job &&
2811 stream->title->job->chapter_markers &&
2812 buf->id == stream->ffmpeg_video_id &&
2813 buf->start >= stream->chapter_end )
2815 hb_chapter_t *chapter = NULL;
2818 * Store when this chapter ends using HB time.
2820 chapter = hb_list_item( stream->title->list_chapter,
2825 if( stream->chapter != 0 )
2827 buf->new_chap = stream->chapter + 2;
2830 hb_deep_log( 2, "Starting chapter %i at %lld", buf->new_chap, buf->start);
2831 stream->chapter_end += chapter->duration;
2833 hb_deep_log( 2, "Looking for chapter %i at %lld", stream->chapter+1, stream->chapter_end );
2836 * Must have run out of chapters, stop looking.
2838 stream->chapter_end = -1;
2843 av_free_packet( stream->ffmpeg_pkt );
2847 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2849 AVFormatContext *ic = stream->ffmpeg_ic;
2850 int64_t pos = (double)ic->duration * (double)frac;
2853 av_seek_frame( ic, -1, pos, 0 );
2854 stream->need_keyframe = 1;
2858 av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );