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, 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_MPGA, CODEC_ID_DTS, "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, U, 0, 0, "SCTE 35 splice info"),
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 int64_t ts_lastpcr; /* the last pcr we found in the TS stream */
106 int64_t ts_nextpcr; /* the next pcr to put in a PS packet */
108 uint8_t *ts_packet; /* buffer for one TS packet */
109 uint8_t *ts_buf[kMaxNumberDecodeStreams];
110 int ts_pos[kMaxNumberDecodeStreams];
111 int8_t ts_foundfirst[kMaxNumberDecodeStreams];
112 int8_t ts_skipbad[kMaxNumberDecodeStreams];
113 int8_t ts_streamcont[kMaxNumberDecodeStreams];
114 int8_t ts_start[kMaxNumberDecodeStreams];
116 uint8_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
117 uint8_t *fwrite_buf_orig; /* PS buffer start (set by hb_ts_stream_decode) */
120 * Stuff before this point is dynamic state updated as we read the
121 * stream. Stuff after this point is stream description state that
122 * we learn during the initial scan but cache so it can be
123 * reused during the conversion read.
125 uint8_t ts_number_video_pids;
126 uint8_t ts_number_audio_pids;
128 int16_t ts_video_pids[kMaxNumberVideoPIDS];
129 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
131 uint8_t ts_streamid[kMaxNumberDecodeStreams];
132 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
136 hb_stream_type_t hb_stream_type;
139 AVFormatContext *ffmpeg_ic;
140 AVPacket *ffmpeg_pkt;
141 double ffmpeg_tsconv[MAX_STREAMS];
148 } a52_info[kMaxNumberAudioPIDS];
152 unsigned short program_number;
153 unsigned short program_map_PID;
154 } pat_info[kMaxNumberPMTStreams];
155 int ts_number_pat_entries;
160 unsigned char *tablebuf;
161 unsigned int tablepos;
162 unsigned char current_continuity_counter;
166 unsigned int PCR_PID;
167 int program_info_length;
168 unsigned char *progam_info_descriptor_data;
171 unsigned char stream_type;
172 unsigned short elementary_PID;
173 unsigned short ES_info_length;
174 unsigned char *es_info_descriptor_data;
175 } pmt_stream_info[kMaxNumberPMTStreams];
179 /***********************************************************************
181 **********************************************************************/
182 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
183 static void hb_ts_stream_init(hb_stream_t *stream);
184 static void hb_ts_stream_find_pids(hb_stream_t *stream);
185 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
186 static void hb_ts_stream_reset(hb_stream_t *stream);
187 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
189 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
190 static off_t align_to_next_packet(hb_stream_t *stream);
192 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
193 static void ffmpeg_close( hb_stream_t *d );
194 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
195 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
196 static int ffmpeg_seek( hb_stream_t *stream, float frac );
199 * streams have a bunch of state that's learned during the scan. We don't
200 * want to throw away the state when scan does a close then relearn
201 * everything when reader does an open. So we save the stream state on
202 * the close following a scan and reuse it when 'reader' does an open.
204 static hb_list_t *stream_state_list;
206 static hb_stream_t *hb_stream_lookup( const char *path )
208 if ( stream_state_list == NULL )
214 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
216 if ( strcmp( path, ss->path ) == 0 )
224 static void hb_stream_state_delete( hb_stream_t *ss )
226 hb_list_rem( stream_state_list, ss );
233 * these frontend hb_log because transport streams can have a lot of errors
234 * so we want to rate limit messages. this routine limits the number of
235 * messages to at most one per minute of video. other errors that occur
236 * during the minute are counted & the count is output with the next
237 * error msg we print.
239 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
241 // limit error printing to at most one per minute of video (at 30fps)
243 if ( stream->frames - stream->last_error_frame >= 30*60 )
247 vsnprintf( msg, sizeof(msg), log, args );
249 if ( stream->errors - stream->last_error_count < 10 )
251 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
255 int Edelta = stream->errors - stream->last_error_count;
256 double Epcnt = (double)Edelta * 100. /
257 (stream->frames - stream->last_error_frame);
258 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
259 Edelta, Epcnt, stream->frames, msg );
261 stream->last_error_frame = stream->frames;
262 stream->last_error_count = stream->errors;
266 static void ts_warn( hb_stream_t *stream, char *log, ... )
269 va_start( args, log );
270 ts_warn_helper( stream, log, args );
274 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
277 va_start( args, log );
278 ts_warn_helper( stream, log, args );
281 stream->ts_skipbad[curstream] = 1;
282 stream->ts_pos[curstream] = 0;
283 stream->ts_streamcont[curstream] = -1;
286 static int check_ps_sync(const uint8_t *buf)
288 // a legal MPEG program stream must start with a Pack header in the
290 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
291 (buf[2] == 0x01) && (buf[3] == 0xba);
294 static int check_ps_sys(const uint8_t *buf)
296 // a legal MPEG program stream must start with a Pack followed by a
297 // SYS. If we've already verified the pack, this skips over it and checks
298 // for the sys header.
299 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
300 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
301 (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
304 static int check_ts_sync(const uint8_t *buf)
306 // must have initial sync byte, no scrambling & a legal adaptation ctrl
307 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
310 static int have_ts_sync(const uint8_t *buf, int psize)
312 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
313 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
314 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
315 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
318 static int hb_stream_check_for_ts(const uint8_t *buf)
320 // transport streams should have a sync byte every 188 bytes.
321 // search the first 8KB of buf looking for at least 8 consecutive
322 // correctly located sync patterns.
325 for ( offset = 0; offset < 8*1024-8*188; ++offset )
327 if ( have_ts_sync( &buf[offset], 188) )
328 return 188 | (offset << 8);
329 if ( have_ts_sync( &buf[offset], 192) )
330 return 192 | (offset << 8);
331 if ( have_ts_sync( &buf[offset], 204) )
332 return 204 | (offset << 8);
333 if ( have_ts_sync( &buf[offset], 208) )
334 return 208 | (offset << 8);
339 static int hb_stream_check_for_ps(const uint8_t *buf)
341 // program streams should start with a PACK then a SYS header.
342 return check_ps_sync(buf) && check_ps_sys(buf);
345 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
347 // DVD program streams should have a Pack header every 2048 bytes.
348 // check that we have 4 of these in a row.
349 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
350 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
353 static int hb_stream_get_type(hb_stream_t *stream)
357 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
360 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
362 int offset = psize >> 8;
364 hb_log("file is MPEG Transport Stream with %d byte packets"
365 " offset %d bytes", psize, offset);
366 stream->packetsize = psize;
367 stream->hb_stream_type = transport;
368 hb_ts_stream_init(stream);
371 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
373 hb_log("file is MPEG DVD Program Stream");
374 stream->hb_stream_type = dvd_program;
377 if ( hb_stream_check_for_ps(buf) != 0 )
379 hb_log("file is MPEG Program Stream");
380 stream->hb_stream_type = program;
387 static void hb_stream_delete_dynamic( hb_stream_t *d )
391 fclose( d->file_handle );
392 d->file_handle = NULL;
399 free( d->ts_packet );
402 for (i = 0; i < kMaxNumberDecodeStreams; i++)
412 static void hb_stream_delete( hb_stream_t *d )
414 hb_stream_delete_dynamic( d );
419 /***********************************************************************
421 ***********************************************************************
423 **********************************************************************/
424 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
426 FILE *f = fopen( path, "r" );
429 hb_log( "hb_stream_open: open %s failed", path );
433 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
437 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
442 * if we're opening the stream to read & convert, we need
443 * the state we saved when we scanned the stream. if we're
444 * opening the stream to scan it we want to rebuild the state
445 * (even if we have saved state, the stream may have changed).
447 hb_stream_t *ss = hb_stream_lookup( path );
448 if ( title && ss && ss->hb_stream_type != ffmpeg )
451 * copy the saved state since we might be encoding the same stream
454 memcpy( d, ss, sizeof(*d) );
457 d->path = strdup( path );
459 if ( d->hb_stream_type == transport )
461 d->ts_packet = malloc( d->packetsize );
464 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
466 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
468 hb_stream_seek( d, 0. );
474 * opening for scan - delete any saved state then (re)scan the stream.
475 * If it's something we can deal with (MPEG2 PS or TS) return a stream
476 * reference structure & null otherwise.
480 hb_stream_state_delete( ss );
484 d->path = strdup( path );
485 if (d->path != NULL )
487 if ( hb_stream_get_type( d ) != 0 )
491 fclose( d->file_handle );
492 d->file_handle = NULL;
493 if ( ffmpeg_open( d, title ) )
498 if ( d->file_handle )
500 fclose( d->file_handle );
506 hb_log( "hb_stream_open: open %s failed", path );
511 /***********************************************************************
513 ***********************************************************************
514 * Closes and frees everything
515 **********************************************************************/
516 void hb_stream_close( hb_stream_t ** _d )
518 hb_stream_t *stream = * _d;
520 if ( stream->hb_stream_type == ffmpeg )
522 ffmpeg_close( stream );
523 hb_stream_delete( stream );
528 if ( stream->frames )
530 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
531 stream->errors, (double)stream->errors * 100. /
532 (double)stream->frames );
536 * if the stream was opened for a scan, cache the result, otherwise delete
539 if ( stream->title == NULL )
541 hb_stream_delete_dynamic( stream );
542 if ( stream_state_list == NULL )
544 stream_state_list = hb_list_init();
546 hb_list_add( stream_state_list, stream );
550 hb_stream_delete( stream );
555 /* when the file was first opened we made entries for all the audio elementary
556 * streams we found in it. Streams that were later found during the preview scan
557 * now have an audio codec, type, rate, etc., associated with them. At the end
558 * of the scan we delete all the audio entries that weren't found by the scan
559 * or don't have a format we support. This routine deletes audio entry 'indx'
560 * by copying all later entries down one slot. */
561 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
565 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
567 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
568 stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
569 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
572 --stream->ts_number_audio_pids;
575 static int index_of_pid(int pid, hb_stream_t *stream)
579 if ( pid == stream->ts_video_pids[0] )
582 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
583 if ( pid == stream->ts_audio_pids[i] )
589 /***********************************************************************
590 * hb_ps_stream_title_scan
591 ***********************************************************************
593 **********************************************************************/
594 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
596 if ( stream->hb_stream_type == ffmpeg )
597 return ffmpeg_title_scan( stream );
600 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
603 // Copy part of the stream path to the title name
604 char *sep = strrchr(stream->path, '/');
606 strcpy(aTitle->name, sep+1);
607 char *dot_term = strrchr(aTitle->name, '.');
611 // Height, width, rate and aspect ratio information is filled in when the previews are built
613 hb_stream_duration(stream, aTitle);
616 hb_chapter_t * chapter;
617 chapter = calloc( sizeof( hb_chapter_t ), 1 );
619 chapter->duration = aTitle->duration;
620 chapter->hours = aTitle->hours;
621 chapter->minutes = aTitle->minutes;
622 chapter->seconds = aTitle->seconds;
623 hb_list_add( aTitle->list_chapter, chapter );
625 // Figure out how many audio streams we really have:
626 // - For transport streams, for each PID listed in the PMT (whether
627 // or not it was an audio stream type) read the bitstream until we
628 // find an packet from that PID containing a PES header and see if
629 // the elementary stream is an audio type.
630 // - For program streams read the first 4MB and take every unique
631 // audio stream we find.
632 if (stream->hb_stream_type == transport)
636 for (i=0; i < stream->ts_number_audio_pids; i++)
638 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
639 if (audio->config.in.codec)
640 hb_list_add( aTitle->list_audio, audio );
644 hb_stream_delete_audio_entry(stream, i);
649 // add the PCR PID if we don't already have it
650 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
652 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
653 stream->pmt_info.PCR_PID;
656 // set up the video codec to use for this title
657 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
658 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
662 hb_ps_stream_find_audio_ids(stream, aTitle);
669 * read the next transport stream packet from 'stream'. Return NULL if
670 * we hit eof & a pointer to the sync byte otherwise.
672 static const uint8_t *next_packet( hb_stream_t *stream )
674 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
678 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
687 // lost sync - back up to where we started then try to re-establish.
688 off_t pos = ftello(stream->file_handle) - stream->packetsize;
689 off_t pos2 = align_to_next_packet(stream);
692 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
695 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
701 * skip to the start of the next PACK header in program stream src_stream.
703 static void skip_to_next_pack( hb_stream_t *src_stream )
705 // scan forward until we find the start of the next pack
706 uint32_t strt_code = -1;
709 flockfile( src_stream->file_handle );
710 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
712 strt_code = ( strt_code << 8 ) | c;
713 if ( strt_code == 0x000001ba )
714 // we found the start of the next pack
717 funlockfile( src_stream->file_handle );
719 // if we didn't terminate on an eof back up so the next read
720 // starts on the pack boundary.
723 fseeko( src_stream->file_handle, -4, SEEK_CUR );
728 * scan the next MB of 'stream' to find the next start packet for
729 * the Packetized Elementary Stream associated with TS PID 'pid'.
731 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
733 int npack = 300000; // max packets to read
737 const uint8_t *buf = next_packet( stream );
740 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
745 * The PES header is only in TS packets with 'start' set so we check
746 * that first then check for the right PID.
748 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
749 buf[2] != (pid & 0xff))
751 // not a start packet or not the pid we want
755 /* skip over the TS hdr to return a pointer to the PES hdr */
757 switch (buf[3] & 0x30)
759 case 0x00: // illegal
760 case 0x20: // fill packet
763 case 0x30: // adaptation
766 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
772 /* PES hdr has to begin with an mpeg start code */
773 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
783 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
785 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
786 hb_list_t *list = hb_list_init();
787 // how many blocks we read while searching for a video PES header
791 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
795 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
796 hb_demux_ps( buf, list, 0 );
798 while ( ( es = hb_list_item( list, 0 ) ) )
800 hb_list_rem( list, es );
801 if ( es->id == 0xe0 )
803 // this PES contains video - if there's a PTS we're done
804 // hb_demux_ps left the PTS in buf_es->start.
805 if ( es->start != ~0 )
812 hb_buffer_close( &es );
815 hb_list_empty( &list );
816 hb_buffer_close(&buf);
820 /***********************************************************************
822 ***********************************************************************
824 * Finding stream duration is difficult. One issue is that the video file
825 * may have chunks from several different program fragments (main feature,
826 * commercials, station id, trailers, etc.) all with their own base pts
827 * value. We can't find the piece boundaries without reading the entire
828 * file but if we compute a rate based on time stamps from two different
829 * pieces the result will be meaningless. The second issue is that the
830 * data rate of compressed video normally varies by 5-10x over the length
831 * of the video. This says that we want to compute the rate over relatively
832 * long segments to get a representative average but long segments increase
833 * the likelihood that we'll cross a piece boundary.
835 * What we do is take time stamp samples at several places in the file
836 * (currently 16) then compute the average rate (i.e., ticks of video per
837 * byte of the file) for all pairs of samples (N^2 rates computed for N
838 * samples). Some of those rates will be absurd because the samples came
839 * from different segments. Some will be way low or high because the
840 * samples came from a low or high motion part of the segment. But given
841 * that we're comparing *all* pairs the majority of the computed rates
842 * should be near the overall average. So we median filter the computed
843 * rates to pick the most representative value.
845 **********************************************************************/
847 uint64_t pos; /* file position of this PTS sample */
848 uint64_t pts; /* PTS from video stream */
851 #define NDURSAMPLES 16
853 // get one (position, timestamp) sampple from a transport or program
855 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
857 struct pts_pos pp = { 0, 0 };
859 if ( stream->hb_stream_type == transport )
862 fseeko( stream->file_handle, fpos, SEEK_SET );
863 align_to_next_packet( stream );
864 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
867 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
870 if ( ( buf[7] >> 7 ) != 1 )
872 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
875 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
876 ( (uint64_t)buf[10] << 22 ) |
877 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
878 ( (uint64_t)buf[12] << 7 ) |
879 ( (uint64_t)buf[13] >> 1 );
883 // round address down to nearest dvd sector start
884 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
885 fseeko( stream->file_handle, fpos, SEEK_SET );
886 if ( stream->hb_stream_type == program )
888 skip_to_next_pack( stream );
890 pp.pts = hb_ps_stream_getVideoPTS( stream );
892 pp.pos = ftello(stream->file_handle);
896 static int dur_compare( const void *a, const void *b )
898 const double *aval = a, *bval = b;
899 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
902 // given an array of (position, time) samples, compute a max-likelihood
903 // estimate of the average rate by computing the rate between all pairs
904 // of samples then taking the median of those rates.
905 static double compute_stream_rate( struct pts_pos *pp, int n )
908 double rates[NDURSAMPLES * NDURSAMPLES / 2];
911 // the following nested loops compute the rates between all pairs.
913 for ( i = 0; i < n-1; ++i )
915 // Bias the median filter by not including pairs that are "far"
916 // from one another. This is to handle cases where the file is
917 // made of roughly equal size pieces where a symmetric choice of
918 // pairs results in having the same number of intra-piece &
919 // inter-piece rate estimates. This would mean that the median
920 // could easily fall in the inter-piece part of the data which
921 // would give a bogus estimate. The 'ns' index creates an
922 // asymmetry that favors locality.
923 int ns = i + ( n >> 1 );
926 for ( j = i+1; j < ns; ++j )
928 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
930 *rp = ((double)( pp[j].pts - pp[i].pts )) /
931 ((double)( pp[j].pos - pp[i].pos ));
936 // now compute and return the median of all the (n*n/2) rates we computed
938 int nrates = rp - rates;
939 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
940 return rates[nrates >> 1];
943 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
945 struct pts_pos ptspos[NDURSAMPLES];
946 struct pts_pos *pp = ptspos;
949 fseeko(stream->file_handle, 0, SEEK_END);
950 uint64_t fsize = ftello(stream->file_handle);
951 uint64_t fincr = fsize / NDURSAMPLES;
952 uint64_t fpos = fincr / 2;
953 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
955 *pp++ = hb_sample_pts(stream, fpos);
957 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
958 inTitle->duration = dur;
960 inTitle->hours = dur / 3600;
961 inTitle->minutes = ( dur % 3600 ) / 60;
962 inTitle->seconds = dur % 60;
964 rewind(stream->file_handle);
967 /***********************************************************************
969 ***********************************************************************
971 **********************************************************************/
972 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
974 if ( src_stream->hb_stream_type == ffmpeg )
976 return ffmpeg_read( src_stream, b );
978 if ( src_stream->hb_stream_type == dvd_program )
980 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
981 src_stream->file_handle);
982 return (amt_read > 0);
984 if ( src_stream->hb_stream_type == program )
986 // a general program stream has arbitrary sized pack's. we're
987 // currently positioned at the start of a pack so read up to but
988 // not including the start of the next, expanding the buffer
990 uint8_t *cp = b->data;
991 uint8_t *ep = cp + b->alloc;
992 uint32_t strt_code = -1;
995 // consume the first byte of the initial pack so we don't match on
996 // it in the loop below.
997 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1002 flockfile( src_stream->file_handle );
1003 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1005 strt_code = ( strt_code << 8 ) | c;
1006 if ( strt_code == 0x000001ba )
1007 // we found the start of the next pack
1011 // need to expand the buffer
1012 int curSize = cp - b->data;
1013 hb_buffer_realloc( b, curSize * 2 );
1014 cp = b->data + curSize;
1015 ep = b->data + b->alloc;
1019 funlockfile( src_stream->file_handle );
1021 // if we didn't terminate on an eof back up so the next read
1022 // starts on the pack boundary.
1023 b->size = cp - b->data;
1026 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1031 return hb_ts_stream_decode( src_stream, b->data );
1034 /***********************************************************************
1036 ***********************************************************************
1038 **********************************************************************/
1039 int hb_stream_seek( hb_stream_t * src_stream, float f )
1041 if ( src_stream->hb_stream_type == ffmpeg )
1043 return ffmpeg_seek( src_stream, f );
1045 off_t stream_size, cur_pos, new_pos;
1046 double pos_ratio = f;
1047 cur_pos = ftello( src_stream->file_handle );
1048 fseeko( src_stream->file_handle, 0, SEEK_END );
1049 stream_size = ftello( src_stream->file_handle );
1050 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1051 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1053 int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1056 fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1060 if ( src_stream->hb_stream_type == transport )
1062 // We need to drop the current decoder output and move
1063 // forwards to the next transport stream packet.
1064 hb_ts_stream_reset(src_stream);
1066 else if ( src_stream->hb_stream_type == program )
1068 skip_to_next_pack( src_stream );
1074 static const char* make_upper( const char* s )
1076 static char name[8];
1078 char *ep = cp + sizeof(name)-1;
1080 while ( *s && cp < ep )
1082 *cp++ = islower(*s)? toupper(*s) : *s;
1089 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1092 * This is a duplicate of code in dvd.c - it should get factored out
1093 * into a common routine. We probably should only be putting the lang
1094 * code or a lang pointer into the audio config & let the common description
1095 * formatting routine in scan.c do all the stuff below.
1097 const char *codec_name;
1100 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1101 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1102 avcodec_find_decoder( cc->codec_id ) )
1104 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1105 if ( !strcmp( codec_name, "LIBFAAD" ) )
1110 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1111 avcodec_find_decoder( audio->config.in.codec_param ) )
1113 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1117 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1118 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1119 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1120 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1121 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1124 snprintf( audio->config.lang.description,
1125 sizeof( audio->config.lang.description ), "%s (%s)",
1126 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1128 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1129 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1130 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1131 "%s", lang->iso639_2);
1134 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1137 off_t cur_pos = ftello(stream->file_handle);
1138 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1141 fseeko(stream->file_handle, 0, SEEK_SET);
1142 align_to_next_packet(stream);
1143 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1145 /* check that we found a PES header */
1147 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1149 // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1150 // extended stream id (ISO 13818-1(2007)). If we cared about the
1151 // real id we'd have to look inside the PES extension to find it.
1152 // But since we remap stream id's when we generate PS packets from
1153 // the TS packets we can just ignore the actual id.
1154 if ( buf[3] == 0xbd || buf[3] == 0xfd )
1156 audio->id = 0x80bd | (aud_pid_index << 8);
1157 stype = stream->ts_stream_type[1 + aud_pid_index];
1158 if ( st2codec[stype].kind == U )
1160 // XXX assume unknown stream types are AC-3 (if they're not
1161 // audio we'll find that out during the scan but if they're
1162 // some other type of audio we'll end up ignoring them).
1164 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1166 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1168 else if ((buf[3] & 0xe0) == 0xc0)
1170 audio->id = 0xc0 | aud_pid_index;
1171 stype = stream->ts_stream_type[1 + aud_pid_index];
1172 if ( st2codec[stype].kind == U )
1174 // XXX assume unknown stream types are MPEG audio
1176 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1180 // if we found an audio stream type & HB has a codec that can decode it
1181 // finish configuring the audio so we'll add it to the title's list.
1182 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1184 stream->ts_streamid[1 + aud_pid_index] = audio->id;
1185 audio->config.in.codec = st2codec[stype].codec;
1186 audio->config.in.codec_param = st2codec[stype].codec_param;
1187 set_audio_description( audio,
1188 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1189 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1190 stream->ts_audio_pids[aud_pid_index],
1191 stype, st2codec[stype].name, audio->id);
1197 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1198 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1199 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1203 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1204 stream->ts_audio_pids[aud_pid_index],
1205 stream->ts_stream_type[1 + aud_pid_index]);
1208 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1212 static void add_audio_to_title(hb_title_t *title, int id)
1214 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1220 audio->config.in.codec = HB_ACODEC_MPGA;
1221 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1224 // type 2 is a DVD subtitle stream - just ignore it */
1228 audio->config.in.codec = HB_ACODEC_AC3;
1229 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1232 audio->config.in.codec = HB_ACODEC_LPCM;
1233 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1236 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1241 set_audio_description( audio, lang_for_code( 0 ) );
1242 hb_list_add( title->list_audio, audio );
1245 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1247 off_t cur_pos = ftello(stream->file_handle);
1248 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1249 hb_list_t *list = hb_list_init();
1250 // how many blocks we read while searching for audio streams
1251 int blksleft = 4096;
1252 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1253 // so we use a bitmap to keep track of the ones we've already seen.
1254 // Bit 'i' of smap is set if we've already added the audio for
1255 // audio substream id 'i' to the title's audio list.
1258 // start looking 20% into the file since there's occasionally no
1259 // audio at the beginning (particularly for vobs).
1260 hb_stream_seek(stream, 0.2f);
1262 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1266 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1267 hb_demux_ps( buf, list, 0 );
1269 while ( ( es = hb_list_item( list, 0 ) ) )
1271 hb_list_rem( list, es );
1272 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1274 // this PES contains some kind of audio - get the substream id
1275 // and check if we've seen it already.
1276 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1277 if ( (smap & (1 << ssid)) == 0 )
1279 // we haven't seen this stream before - add it to the
1280 // title's list of audio streams.
1281 smap |= (1 << ssid);
1282 add_audio_to_title(title, es->id);
1285 hb_buffer_close( &es );
1288 hb_list_empty( &list );
1289 hb_buffer_close(&buf);
1290 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1293 /***********************************************************************
1295 ***********************************************************************
1297 **********************************************************************/
1299 static void hb_ts_stream_init(hb_stream_t *stream)
1303 for (i=0; i < kMaxNumberDecodeStreams; i++)
1305 stream->ts_streamcont[i] = -1;
1307 stream->ts_video_pids[0] = -1;
1308 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1310 stream-> ts_audio_pids[i] = -1;
1313 stream->ts_packet = malloc( stream->packetsize );
1315 // Find the audio and video pids in the stream
1316 hb_ts_stream_find_pids(stream);
1318 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1320 // demuxing buffer for TS to PS conversion
1321 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1324 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
1327 #define MAX_HOLE 208*80
1329 static off_t align_to_next_packet(hb_stream_t *stream)
1331 uint8_t buf[MAX_HOLE];
1333 off_t start = ftello(stream->file_handle);
1335 if ( start >= stream->packetsize ) {
1336 start -= stream->packetsize;
1337 fseeko(stream->file_handle, start, SEEK_SET);
1340 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1342 const uint8_t *bp = buf;
1345 for ( i = sizeof(buf); --i >= 0; ++bp )
1347 if ( have_ts_sync( bp, stream->packetsize ) )
1354 pos = ( bp - buf ) - stream->packetsize + 188;
1359 fseeko(stream->file_handle, start+pos, SEEK_SET);
1370 static const unsigned int bitmask[] = {
1371 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1372 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1373 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1374 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1376 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1380 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1381 (bb->buf[2] << 8) | bb->buf[3];
1383 memset(bb->buf, 0, bufsize);
1386 static inline int buf_size(bitbuf_t *bb)
1388 return bb->pos >> 3;
1391 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1394 int left = 32 - (bb->pos & 31);
1398 val = (bb->val >> (left - bits)) & bitmask[bits];
1403 val = (bb->val & bitmask[left]) << (bits - left);
1407 int pos = bb->pos >> 3;
1408 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1412 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1420 // extract what useful information we can from the elementary stream
1421 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1422 // Descriptors with info we don't currently use are ignored.
1423 // The descriptor list & descriptor item formats are defined in
1424 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1425 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1426 const uint8_t *dp, uint8_t dlen)
1428 const uint8_t *ep = dp + dlen;
1434 case 10: // ISO_639_language descriptor
1435 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1445 static const char *stream_type_name (uint8_t stream_type)
1447 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1450 int decode_program_map(hb_stream_t* stream)
1453 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1455 get_bits(&bb, 8); // table_id
1457 unsigned int section_length = get_bits(&bb, 12);
1458 stream->pmt_info.section_length = section_length;
1460 unsigned int program_number = get_bits(&bb, 16);
1461 stream->pmt_info.program_number = program_number;
1463 get_bits(&bb, 5); // version_number
1465 get_bits(&bb, 8); // section_number
1466 get_bits(&bb, 8); // last_section_number
1468 unsigned int PCR_PID = get_bits(&bb, 13);
1469 stream->pmt_info.PCR_PID = PCR_PID;
1471 unsigned int program_info_length = get_bits(&bb, 12);
1472 stream->pmt_info.program_info_length = program_info_length;
1475 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1476 for (i = 0; i < program_info_length; i++)
1478 descriptor_buf[i] = get_bits(&bb, 8);
1481 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1482 int done_reading_stream_types = 0;
1483 while (!done_reading_stream_types)
1485 unsigned char stream_type = get_bits(&bb, 8);
1487 unsigned int elementary_PID = get_bits(&bb, 13);
1489 unsigned int ES_info_length = get_bits(&bb, 12);
1492 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1493 for (i=0; i < ES_info_length; i++)
1495 ES_info_buf[i] = get_bits(&bb, 8);
1499 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1501 stream->ts_video_pids[0] = elementary_PID;
1502 stream->ts_stream_type[0] = stream_type;
1503 stream->ts_number_video_pids = 1;
1507 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1508 // for mpeg audio. But content producers seem to use other
1509 // values (0x04 and 0x06 have both been observed) so at this point
1510 // we say everything that isn't a video pid is audio then at the end
1511 // of hb_stream_title_scan we'll figure out which are really audio
1512 // by looking at the PES headers.
1513 i = stream->ts_number_audio_pids;
1514 if (i < kMaxNumberAudioPIDS)
1516 stream->ts_audio_pids[i] = elementary_PID;
1517 stream->ts_stream_type[1 + i] = stream_type;
1518 if (ES_info_length > 0)
1520 decode_element_descriptors(stream, i, ES_info_buf,
1523 ++stream->ts_number_audio_pids;
1527 cur_pos += 5 /* stream header */ + ES_info_length;
1531 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1532 done_reading_stream_types = 1;
1535 free(descriptor_buf);
1539 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1541 // Get adaption header info
1543 int adaption = (buf[3] & 0x30) >> 4;
1546 else if (adaption == 0x2)
1548 else if (adaption == 0x3)
1549 adapt_len = buf[4] + 1;
1550 if (adapt_len > 184)
1553 // Get payload start indicator
1555 start = (buf[1] & 0x40) != 0;
1557 // Get pointer length - only valid in packets with a start flag
1558 int pointer_len = 0;
1559 if (start && stream->pmt_info.reading)
1561 // We just finished a bunch of packets - parse the program map details
1563 if (stream->pmt_info.tablebuf[0] == 0x02)
1564 decode_ok = decode_program_map(stream);
1565 free(stream->pmt_info.tablebuf);
1566 stream->pmt_info.tablebuf = NULL;
1567 stream->pmt_info.tablepos = 0;
1568 stream->pmt_info.reading = 0;
1575 pointer_len = buf[4 + adapt_len] + 1;
1576 stream->pmt_info.tablepos = 0;
1578 // Get Continuity Counter
1579 int continuity_counter = buf[3] & 0x0f;
1580 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1582 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1585 stream->pmt_info.current_continuity_counter = continuity_counter;
1586 stream->pmt_info.reading |= start;
1588 // Add the payload for this packet to the current buffer
1589 int amount_to_copy = 184 - adapt_len - pointer_len;
1590 if (stream->pmt_info.reading && (amount_to_copy > 0))
1592 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1594 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1595 stream->pmt_info.tablepos += amount_to_copy;
1601 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1603 unsigned char tablebuf[1024];
1604 unsigned int tablepos = 0;
1609 // Get adaption header info
1611 int adaption = (buf[3] & 0x30) >> 4;
1614 else if (adaption == 0x2)
1616 else if (adaption == 0x3)
1617 adapt_len = buf[4] + 1;
1618 if (adapt_len > 184)
1621 // Get pointer length
1622 int pointer_len = buf[4 + adapt_len] + 1;
1624 // Get payload start indicator
1626 start = (buf[1] & 0x40) != 0;
1631 // Add the payload for this packet to the current buffer
1632 if (reading && (184 - adapt_len) > 0)
1634 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1636 hb_log("decode_PAT - Bad program section length (> 1024)");
1639 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1640 tablepos += 184 - adapt_len - pointer_len;
1643 if (start && reading)
1645 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1648 unsigned int pos = 0;
1649 //while (pos < tablepos)
1652 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1654 unsigned char section_id = get_bits(&bb, 8);
1656 unsigned int section_len = get_bits(&bb, 12);
1657 get_bits(&bb, 16); // transport_id
1659 get_bits(&bb, 5); // version_num
1660 get_bits(&bb, 1); // current_next
1661 get_bits(&bb, 8); // section_num
1662 get_bits(&bb, 8); // last_section
1668 // Program Association Section
1669 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1670 section_len -= 4; // Ignore the CRC
1672 stream->ts_number_pat_entries = 0;
1673 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1675 unsigned int pkt_program_num = get_bits(&bb, 16);
1676 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1678 get_bits(&bb, 3); // Reserved
1679 if (pkt_program_num == 0)
1681 get_bits(&bb, 13); // pkt_network_id
1685 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1686 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1689 stream->ts_number_pat_entries++;
1703 pos += 3 + section_len;
1711 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1713 // align to first packet
1714 align_to_next_packet(stream);
1716 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1717 // to find the program map PID and then decode that to get the list of audio and video PIDs
1721 const uint8_t *buf = next_packet( stream );
1724 hb_log("hb_ts_stream_find_pids - end of file");
1729 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1731 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1733 decode_PAT(buf, stream);
1738 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1740 // There are some streams where the PAT table has multiple entries as if their are
1741 // multiple programs in the same transport stream, and yet there's actually only one
1742 // program really in the stream. This seems to be true for transport streams that
1743 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1744 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1745 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1746 // PAT info on export to match what's actually on the stream.
1747 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1748 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1749 // be to build a title choice popup from the PAT program number details and then select from
1750 // their - but right now the API's not capable of that.
1751 if (pid == stream->pat_info[pat_index].program_map_PID)
1753 if (build_program_map(buf, stream) > 0)
1757 // Keep going until we have a complete set of PIDs
1758 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1762 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1763 hb_log(" Video PIDS : ");
1765 for (i=0; i < stream->ts_number_video_pids; i++)
1767 hb_log( " 0x%x type %s (0x%x)",
1768 stream->ts_video_pids[i],
1769 stream_type_name(stream->ts_stream_type[i]),
1770 stream->ts_stream_type[i]);
1772 hb_log(" Audio PIDS : ");
1773 for (i = 0; i < stream->ts_number_audio_pids; i++)
1775 hb_log( " 0x%x type %s (0x%x)",
1776 stream->ts_audio_pids[i],
1777 stream_type_name(stream->ts_stream_type[i+1]),
1778 stream->ts_stream_type[i+1] );
1783 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1785 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1787 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1788 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1791 memcpy( stream->fwrite_buf, buf, size );
1792 stream->fwrite_buf += size;
1795 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1799 buf[0] = 0x00; // pack id
1804 buf[4] = 0x44 | // SCR
1805 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1806 ( ( time >> 28 ) & 3 );
1807 buf[5] = time >> 20;
1809 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1810 ( ( time >> 13 ) & 3 );
1812 buf[8] = 0x04 | ( time << 3 );
1814 buf[9] = 0x01; // SCR extension
1816 buf[10] = 384000 >> (22 - 8); // program mux rate
1817 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1818 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1820 buf[13] = 0xf8 | stuffing;
1823 for (i = 0; i < stuffing; ++i )
1826 fwrite64(stream, buf, 14 + stuffing );
1829 static void pad_buffer(hb_stream_t* stream, int pad)
1841 fwrite64(stream, buf, 6);
1844 while ( --pad >= 0 )
1846 fwrite64(stream, buf, 1);
1850 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1854 memset(buf, 0, sizeof(buf) );
1857 buf[4] = ( len + 3 ) >> 8;
1861 fwrite64(stream, buf, 9);
1864 static void generate_output_data(hb_stream_t *stream, int curstream)
1866 uint8_t *tdat = stream->ts_buf[curstream];
1869 // we always ship a PACK header plus all the data in our demux buf.
1870 // AC3 audio also always needs its substream header.
1871 len = 14 + stream->ts_pos[curstream];
1872 if ( stream->ts_stream_type[curstream] == 0x81)
1877 if ( ! stream->ts_start[curstream] )
1879 // we're in the middle of a chunk of PES data - we need to add
1880 // a 'continuation' PES header after the PACK header.
1884 // Write out pack header
1885 // If we don't have 2048 bytes we need to pad to 2048. We can
1886 // add a padding frame after our data but we need at least 7
1887 // bytes of space to do it (6 bytes of header & 1 of pad). If
1888 // we have fewer than 7 bytes left we need to fill the excess
1889 // space with stuffing bytes added to the pack header.
1891 if ( len > HB_DVD_READ_BUFFER_SIZE )
1893 hb_log( "stream ts length botch %d", len );
1895 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1897 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1899 write_pack(stream, stream->ts_nextpcr, stuffing );
1900 stream->ts_nextpcr += 10;
1902 if ( stream->ts_start[curstream] )
1904 // Start frames already have a PES header but we have modify it
1905 // to map from TS PID to PS stream id. Also, if the stream is AC3
1906 // audio we have to insert an AC3 stream header between the end of
1907 // the PES header and the start of the stream data.
1909 stream->ts_start[curstream] = 0;
1910 tdat[3] = stream->ts_streamid[curstream];
1912 uint16_t plen = stream->ts_pos[curstream] - 6;
1913 if ( stream->ts_stream_type[curstream] == 0x81)
1915 // We have to add an AC3 header in front of the data. Add its
1916 // size to the PES packet length.
1918 tdat[4] = plen >> 8;
1921 // Write out the PES header
1922 int hdrsize = 9 + tdat[8];
1923 fwrite64(stream, tdat, hdrsize);
1925 // add a four byte DVD ac3 stream header
1926 uint8_t ac3_substream_id[4];
1927 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1928 ac3_substream_id[0] = 0x80 | ssid; // substream id
1929 ac3_substream_id[1] = 0x01; // number of sync words
1930 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1931 ac3_substream_id[3] = 0x02;
1932 fwrite64(stream, ac3_substream_id, 4);
1934 // add the rest of the data
1935 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1939 // not audio - don't need to modify the stream so write what we've got
1940 tdat[4] = plen >> 8;
1942 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1947 // data without a PES start header needs a simple 'continuation'
1948 // PES header. AC3 audio also needs its substream header.
1949 if ( stream->ts_stream_type[curstream] != 0x81)
1951 make_pes_header(stream, stream->ts_pos[curstream],
1952 stream->ts_streamid[curstream]);
1956 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1957 stream->ts_streamid[curstream]);
1959 // add a four byte DVD ac3 stream header
1960 uint8_t ac3_substream_id[4];
1961 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1962 ac3_substream_id[0] = 0x80 | ssid; // substream id
1963 ac3_substream_id[1] = 0x01; // number of sync words
1964 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1965 ac3_substream_id[3] = 0x02;
1966 fwrite64(stream, ac3_substream_id, 4);
1968 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1972 int left = HB_DVD_READ_BUFFER_SIZE - len;
1975 pad_buffer(stream, left);
1978 stream->ts_pos[curstream] = 0;
1981 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1983 // For mpeg2: look for a gop start or i-frame picture start
1984 // for h.264: look for idr nal type or a slice header for an i-frame
1990 if ( stream->ts_stream_type[0] <= 2 )
1992 // This section of the code handles MPEG-1 and MPEG-2 video streams
1993 for (i = 13 + adapt_len; i < 188; i++)
1995 strid = (strid << 8) | buf[i];
1996 if ( ( strid >> 8 ) == 1 )
1998 // we found a start code
2002 case 0xB8: // group_start_code (GOP header)
2003 case 0xB3: // sequence_header code
2006 case 0x00: // picture_start_code
2007 // picture_header, let's see if it's an I-frame
2010 // check if picture_coding_type == 1
2011 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2013 // found an I-frame picture
2021 // didn't find an I-frame
2024 if ( stream->ts_stream_type[0] == 0x1b )
2026 // we have an h.264 stream
2027 for (i = 13 + adapt_len; i < 188; i++)
2029 strid = (strid << 8) | buf[i];
2030 if ( ( strid >> 8 ) == 1 )
2032 // we found a start code - remove the ref_idc from the nal type
2033 uint8_t nal_type = strid & 0x1f;
2034 if ( nal_type == 0x05 )
2035 // h.264 IDR picture start
2038 if ( nal_type == 0x01 )
2040 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2041 uint8_t id = buf[i+1];
2042 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2043 id == 0x88 || id == 0x8a )
2050 // didn't find an I-frame
2054 // we don't understand the stream type so just say "yes" otherwise
2055 // we'll discard all the video.
2059 /***********************************************************************
2060 * hb_ts_stream_decode
2061 ***********************************************************************
2063 **********************************************************************/
2064 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2067 * stash the output buffer pointer in our stream so we don't have to
2068 * pass it & its original value to everything we call.
2070 stream->fwrite_buf = obuf;
2071 stream->fwrite_buf_orig = obuf;
2073 // spin until we get a packet of data from some stream or hit eof
2076 int64_t pcr = stream->ts_lastpcr;
2079 const uint8_t *buf = next_packet(stream);
2082 // end of file - we didn't finish filling our ps write buffer
2083 // so just discard the remainder (the partial buffer is useless)
2084 hb_log("hb_ts_stream_decode - eof");
2088 /* This next section validates the packet */
2090 // Get pid and use it to find stream state.
2091 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2092 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2096 int errorbit = (buf[1] & 0x80) != 0;
2099 ts_err( stream, curstream, "packet error bit set");
2103 // Get adaption header info
2104 int adaption = (buf[3] & 0x30) >> 4;
2108 ts_err( stream, curstream, "adaptation code 0");
2111 else if (adaption == 0x2)
2113 else if (adaption == 0x3)
2115 adapt_len = buf[4] + 1;
2116 if (adapt_len > 184)
2118 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2123 // if there's an adaptation header & PCR_flag is set
2124 // get the PCR (Program Clock Reference)
2125 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2127 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2128 ( (uint64_t)buf[7] << (33 - 16) ) |
2129 ( (uint64_t)buf[8] << (33 - 24) ) |
2130 ( (uint64_t)buf[9] << (33 - 32) ) |
2132 stream->ts_nextpcr = pcr;
2134 // remember the pcr across calls to this routine
2135 stream->ts_lastpcr = pcr;
2138 // If we don't have a pcr yet, the right thing to do here would
2139 // be a 'continue' so we don't process anything until we have a
2140 // clock reference. Unfortunately the HD Home Run appears to null
2141 // out the pcr field of some streams so we keep going & substitute
2142 // the video stream dts for the pcr when there's no pcr.
2145 // Continuity only increments for adaption values of 0x3 or 0x01
2146 // and is not checked for start packets.
2148 int start = (buf[1] & 0x40) != 0;
2150 if ( (adaption & 0x01) != 0 )
2152 int continuity = (buf[3] & 0xF);
2153 if ( continuity == stream->ts_streamcont[curstream] )
2155 // we got a duplicate packet (usually used to introduce
2156 // a PCR when one is needed). The only thing that can
2157 // change in the dup is the PCR which we grabbed above
2158 // so ignore the rest.
2161 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2162 stream->ts_foundfirst[curstream] &&
2163 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2165 ts_err( stream, curstream, "continuity error: got %d expected %d",
2167 (stream->ts_streamcont[curstream] + 1) & 0xf );
2168 stream->ts_streamcont[curstream] = continuity;
2171 stream->ts_streamcont[curstream] = continuity;
2174 /* If we get here the packet is valid - process its data */
2178 // Found a random access point (now we can start a frame/audio packet..)
2180 // If we were skipping a bad packet, start fresh on this new PES packet..
2181 if (stream->ts_skipbad[curstream] == 1)
2183 // video skips to an iframe after a bad packet to minimize
2184 // screen corruption
2185 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2189 stream->ts_skipbad[curstream] = 0;
2192 // If we don't have video yet, check to see if this is an
2193 // i_frame (group of picture start)
2194 if ( curstream == 0 )
2196 if ( !stream->ts_foundfirst[0] )
2198 if ( !isIframe( stream, buf, adapt_len ) )
2200 // didn't find an I frame
2203 stream->ts_foundfirst[0] = 1;
2207 // if we don't have a pcr yet use the dts from this frame
2210 // PES must begin with an mpeg start code & contain
2212 const uint8_t *pes = buf + adapt_len + 4;
2213 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2214 ( pes[7] >> 6 ) == 0 )
2218 // if we have a dts use it otherwise use the pts
2219 pes += (pes[7] & 0x40)? 14 : 9;
2221 pcr = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2222 pcr |= ( pes[1] << 22 ) |
2223 ( ( pes[2] >> 1 ) << 15 ) |
2226 stream->ts_nextpcr = pcr;
2229 else if ( ! stream->ts_foundfirst[curstream] )
2231 // start other streams only after first video frame found.
2232 if ( ! stream->ts_foundfirst[0] )
2236 stream->ts_foundfirst[curstream] = 1;
2239 // If we have some data already on this stream, turn it into
2240 // a program stream packet. Then add the payload for this
2241 // packet to the current pid's buffer.
2242 if ( stream->ts_pos[curstream] )
2244 generate_output_data(stream, curstream);
2245 stream->ts_start[curstream] = 1;
2246 memcpy(stream->ts_buf[curstream],
2247 buf + 4 + adapt_len, 184 - adapt_len);
2248 stream->ts_pos[curstream] = 184 - adapt_len;
2251 stream->ts_start[curstream] = 1;
2254 // Add the payload for this packet to the current buffer
2255 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2256 (184 - adapt_len) > 0)
2258 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2259 buf + 4 + adapt_len, 184 - adapt_len);
2260 stream->ts_pos[curstream] += 184 - adapt_len;
2262 // if the next TS packet could possibly overflow our 2K output buffer
2263 // we need to generate a packet now. Overflow would be 184 bytes of
2264 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2265 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2267 // we have enough data to make a PS packet
2268 generate_output_data(stream, curstream);
2275 static void hb_ts_stream_reset(hb_stream_t *stream)
2279 for (i=0; i < kMaxNumberDecodeStreams; i++)
2281 stream->ts_pos[i] = 0;
2282 stream->ts_foundfirst[i] = 0;
2283 stream->ts_skipbad[i] = 0;
2284 stream->ts_streamcont[i] = -1;
2285 stream->ts_start[i] = 0;
2288 stream->ts_lastpcr = -1;
2289 stream->ts_nextpcr = -1;
2293 stream->last_error_frame = -10000;
2294 stream->last_error_count = 0;
2296 align_to_next_packet(stream);
2299 // ------------------------------------------------------------------
2300 // Support for reading media files via the ffmpeg libraries.
2302 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2304 // add a codec to the context here so it will be there when we
2305 // read the first packet.
2306 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2307 context->workaround_bugs = FF_BUG_AUTODETECT;
2308 context->error_resilience = 1;
2309 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2310 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2311 avcodec_open( context, codec );
2314 // The ffmpeg stream reader / parser shares a lot of state with the
2315 // decoder via a codec context kept in the AVStream of the reader's
2316 // AVFormatContext. Since decoding is done in a different thread we
2317 // have to somehow pass this codec context to the decoder and we have
2318 // to do it before the first packet is read (so we can't put the info
2319 // in the buf we'll send downstream). Decoders don't have any way to
2320 // get to the stream directly (they're not passed the title or job
2321 // pointers during a scan) so this is a back door for the decoder to
2322 // get the codec context. We just stick the stream pointer in the next
2323 // slot an array of pointers maintained as a circular list then return
2324 // the index into the list combined with the ffmpeg stream index as the
2325 // codec_param that will be passed to the decoder init routine. We make
2326 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2327 // so that we don't have to do a complicated allocator or worry about
2328 // deleting entries on close.
2330 // Entries can only be added to this list during a scan and are never
2331 // deleted so the list access doesn't require locking.
2332 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2333 static int ffmpeg_stream_cur; // where we put the last stream pointer
2334 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2335 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2337 // add a stream to the list & return the appropriate codec_param to access it
2338 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2340 if ( !ffmpeg_streams )
2342 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2345 // the title scan adds all the ffmpeg media streams at once so we
2346 // only add a new entry to our stream list if the stream is different
2348 int slot = ffmpeg_stream_cur;
2349 if ( ffmpeg_streams[slot] != stream )
2351 // new stream - put it in the next slot of the stream list
2352 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2353 ffmpeg_streams[slot] = stream;
2356 ffmpeg_add_codec( stream, stream_index );
2358 return ( stream_index << ffmpeg_sl_bits ) | slot;
2361 // we're about to open 'title' to convert it - remap the stream associated
2362 // with the video & audio codec params of the title to refer to 'stream'
2363 // (the original scan stream was closed and no longer exists).
2364 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2366 // tell ffmpeg we want a pts on every frame it returns
2367 stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2369 // all the video & audio came from the same stream so remapping
2370 // the video's stream slot takes care of everything.
2371 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2372 ffmpeg_streams[slot] = stream;
2374 // add codecs for all the streams used by the title
2375 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2379 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2381 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2383 ffmpeg_add_codec( stream,
2384 audio->config.in.codec_param >> ffmpeg_sl_bits );
2389 void *hb_ffmpeg_context( int codec_param )
2391 int slot = codec_param & (ffmpeg_sl_size - 1);
2392 int stream_index = codec_param >> ffmpeg_sl_bits;
2393 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2396 void *hb_ffmpeg_avstream( int codec_param )
2398 int slot = codec_param & (ffmpeg_sl_size - 1);
2399 int stream_index = codec_param >> ffmpeg_sl_bits;
2400 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2403 static AVFormatContext *ffmpeg_deferred_close;
2405 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2407 if ( ffmpeg_deferred_close )
2409 av_close_input_file( ffmpeg_deferred_close );
2410 ffmpeg_deferred_close = NULL;
2412 AVFormatContext *ic;
2414 av_log_set_level( AV_LOG_ERROR );
2415 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2419 if ( av_find_stream_info( ic ) < 0 )
2422 stream->ffmpeg_ic = ic;
2423 stream->hb_stream_type = ffmpeg;
2424 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2425 av_init_packet( stream->ffmpeg_pkt );
2429 // we're opening for read. scan passed out codec params that
2430 // indexed its stream so we need to remap them so they point
2432 ffmpeg_remap_stream( stream, title );
2433 ffmpeg_seek( stream, 0. );
2434 av_log_set_level( AV_LOG_ERROR );
2438 // we're opening for scan. let ffmpeg put some info into the
2439 // log about what we've got.
2440 av_log_set_level( AV_LOG_INFO );
2441 dump_format( ic, 0, stream->path, 0 );
2442 av_log_set_level( AV_LOG_ERROR );
2444 // accept this file if it has at least one video stream we can decode
2446 for (i = 0; i < ic->nb_streams; ++i )
2448 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2453 if ( i >= ic->nb_streams )
2459 av_close_input_file( ic );
2463 static void ffmpeg_close( hb_stream_t *d )
2465 // XXX since we're sharing the CodecContext with the downstream
2466 // decoder proc we can't close the stream. We need to reference count
2467 // this so we can close it when both are done with their instance but
2468 // for now just defer the close until the next stream open or close.
2469 if ( ffmpeg_deferred_close )
2471 av_close_input_file( ffmpeg_deferred_close );
2473 ffmpeg_deferred_close = d->ffmpeg_ic;
2474 if ( d->ffmpeg_pkt != NULL )
2476 free( d->ffmpeg_pkt );
2477 d->ffmpeg_pkt = NULL;
2481 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2483 AVStream *st = stream->ffmpeg_ic->streams[id];
2484 AVCodecContext *codec = st->codec;
2486 // scan will ignore any audio without a bitrate. Since we've already
2487 // typed the audio in order to determine its codec we set up the audio
2489 if ( codec->bit_rate || codec->sample_rate )
2491 static const int chan2layout[] = {
2492 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2493 HB_INPUT_CH_LAYOUT_MONO,
2494 HB_INPUT_CH_LAYOUT_STEREO,
2495 HB_INPUT_CH_LAYOUT_2F1R,
2496 HB_INPUT_CH_LAYOUT_2F2R,
2497 HB_INPUT_CH_LAYOUT_3F2R,
2498 HB_INPUT_CH_LAYOUT_4F2R,
2499 HB_INPUT_CH_LAYOUT_STEREO,
2500 HB_INPUT_CH_LAYOUT_STEREO,
2503 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2506 if ( codec->codec_id == CODEC_ID_AC3 )
2508 audio->config.in.codec = HB_ACODEC_AC3;
2512 audio->config.in.codec = HB_ACODEC_FFMPEG;
2513 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2515 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2516 audio->config.in.samplerate = codec->sample_rate;
2517 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2520 set_audio_description( audio, lang_for_code2( st->language ) );
2522 hb_list_add( title->list_audio, audio );
2526 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2528 AVFormatContext *ic = stream->ffmpeg_ic;
2530 // 'Barebones Title'
2531 hb_title_t *title = hb_title_init( stream->path, 0 );
2534 // Copy part of the stream path to the title name
2535 char *sep = strrchr(stream->path, '/');
2537 strcpy(title->name, sep+1);
2538 char *dot_term = strrchr(title->name, '.');
2542 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2543 title->duration = dur;
2545 title->hours = dur / 3600;
2546 title->minutes = ( dur % 3600 ) / 60;
2547 title->seconds = dur % 60;
2550 hb_chapter_t * chapter;
2551 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2553 chapter->duration = title->duration;
2554 chapter->hours = title->hours;
2555 chapter->minutes = title->minutes;
2556 chapter->seconds = title->seconds;
2557 hb_list_add( title->list_chapter, chapter );
2559 // set the title to decode the first video stream in the file
2560 title->demuxer = HB_NULL_DEMUXER;
2561 title->video_codec = 0;
2563 for (i = 0; i < ic->nb_streams; ++i )
2565 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2566 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2567 title->video_codec == 0 )
2569 title->video_id = i;
2571 // We have to use the 'internal' avcodec decoder because
2572 // it needs to share the codec context from this video
2573 // stream. The parser internal to av_read_frame
2574 // passes a bunch of state info to the decoder via the context.
2575 title->video_codec = WORK_DECAVCODECVI;
2576 title->video_codec_param = ffmpeg_codec_param( stream, i );
2578 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2579 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2581 add_ffmpeg_audio( title, stream, i );
2585 title->container_name = strdup( ic->iformat->name );
2586 title->data_rate = ic->bit_rate;
2591 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2593 if ( pts == AV_NOPTS_VALUE )
2595 return (int64_t)( (double)pts * conv_factor );
2598 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2601 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2603 // XXX the following conditional is to handle avi files that
2604 // use M$ 'packed b-frames' and occasionally have negative
2605 // sizes for the null frames these require.
2606 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2610 if ( stream->ffmpeg_pkt->size <= 0 )
2612 // M$ "invalid and inefficient" packed b-frames require 'null frames'
2613 // following them to preserve the timing (since the packing puts two
2614 // or more frames in what looks like one avi frame). The contents and
2615 // size of these null frames are ignored by the ff_h263_decode_frame
2616 // as long as they're < 20 bytes. We need a positive size so we use
2617 // one byte if we're given a zero or negative size. We don't know
2618 // if the pkt data points anywhere reasonable so we just stick a
2619 // byte of zero in our outbound buf.
2625 if ( stream->ffmpeg_pkt->size > buf->alloc )
2627 // need to expand buffer
2628 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2630 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2631 buf->size = stream->ffmpeg_pkt->size;
2633 buf->id = stream->ffmpeg_pkt->stream_index;
2635 // if we haven't done it already, compute a conversion factor to go
2636 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2637 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2640 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2641 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2642 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2645 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2646 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2647 if ( buf->renderOffset >= 0 && buf->start == -1 )
2649 buf->start = buf->renderOffset;
2651 av_free_packet( stream->ffmpeg_pkt );
2655 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2657 AVFormatContext *ic = stream->ffmpeg_ic;
2658 int64_t pos = (double)ic->duration * (double)frac;
2659 av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );