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. */
9 #include "a52dec/a52.h"
10 #include "libavcodec/avcodec.h"
11 #include "libavformat/avformat.h"
16 #define min(a, b) a < b ? a : b
19 * This table defines how ISO MPEG stream type codes map to HandBrake
20 * codecs. It is indexed by the 8 bit stream type and contains the codec
21 * worker object id and a parameter for that worker proc (ignored except
22 * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
24 * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
25 * doesn't handle the stream type.
28 enum { U, A, V } kind; /* unknown / audio / video */
29 int codec; /* HB worker object id of codec */
30 int codec_param; /* param for codec (usually ffmpeg codec id) */
31 const char* name; /* description of type */
34 #define st(id, kind, codec, codec_param, name) \
35 [id] = { kind, codec, codec_param, name }
37 static const stream2codec_t st2codec[256] = {
38 st(0x01, V, WORK_DECMPEG2, 0, "MPEG1"),
39 st(0x02, V, WORK_DECMPEG2, 0, "MPEG2"),
40 st(0x03, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG1"),
41 st(0x04, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG2"),
42 st(0x05, U, 0, 0, "ISO 13818-1 private section"),
43 st(0x06, U, 0, 0, "ISO 13818-1 PES private data"),
44 st(0x07, U, 0, 0, "ISO 13522 MHEG"),
45 st(0x08, U, 0, 0, "ISO 13818-1 DSM-CC"),
46 st(0x09, U, 0, 0, "ISO 13818-1 auxiliary"),
47 st(0x0a, U, 0, 0, "ISO 13818-6 encap"),
48 st(0x0b, U, 0, 0, "ISO 13818-6 DSM-CC U-N msgs"),
49 st(0x0c, U, 0, 0, "ISO 13818-6 Stream descriptors"),
50 st(0x0d, U, 0, 0, "ISO 13818-6 Sections"),
51 st(0x0e, U, 0, 0, "ISO 13818-1 auxiliary"),
52 st(0x0f, A, HB_ACODEC_MPGA, CODEC_ID_AAC, "ISO 13818-7 AAC Audio"),
53 st(0x10, V, WORK_DECAVCODECV, CODEC_ID_MPEG4, "MPEG4"),
54 st(0x11, A, HB_ACODEC_MPGA, CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
55 st(0x12, U, 0, 0, "MPEG4 generic"),
57 st(0x14, U, 0, 0, "ISO 13818-6 DSM-CC download"),
59 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
61 st(0x80, U, 0, 0, "DigiCipher II Video"),
62 st(0x81, A, HB_ACODEC_AC3, 0, "AC-3"),
63 st(0x82, A, HB_ACODEC_MPGA, CODEC_ID_DTS, "HDMV DTS"),
64 st(0x83, A, HB_ACODEC_LPCM, 0, "LPCM"),
65 st(0x84, A, 0, 0, "SDDS"),
66 st(0x85, U, 0, 0, "ATSC Program ID"),
67 st(0x86, U, 0, 0, "SCTE 35 splice info"),
68 st(0x87, A, 0, 0, "E-AC-3"),
70 st(0x8a, A, HB_ACODEC_DCA, 0, "DTS"),
72 st(0x91, A, HB_ACODEC_AC3, 0, "AC-3"),
73 st(0x92, U, 0, 0, "Subtitle"),
75 st(0x94, A, 0, 0, "SDDS"),
76 st(0xa0, V, 0, 0, "MSCODEC"),
78 st(0xea, V, WORK_DECAVCODECV, CODEC_ID_VC1, "VC1"),
83 hb_stream_type_unknown = 0,
90 #define kMaxNumberVideoPIDS 1
91 #define kMaxNumberAudioPIDS 15
92 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
93 #define kMaxNumberPMTStreams 32
98 int frames; /* video frames so far */
99 int errors; /* total errors so far */
100 int last_error_frame; /* frame # at last error message */
101 int last_error_count; /* # errors at last error message */
102 int packetsize; /* Transport Stream packet size */
104 int64_t ts_lastpcr; /* the last pcr we found in the TS stream */
105 int64_t ts_nextpcr; /* the next pcr to put in a PS packet */
107 uint8_t *ts_packet; /* buffer for one TS packet */
108 uint8_t *ts_buf[kMaxNumberDecodeStreams];
109 int ts_pos[kMaxNumberDecodeStreams];
110 int8_t ts_foundfirst[kMaxNumberDecodeStreams];
111 int8_t ts_skipbad[kMaxNumberDecodeStreams];
112 int8_t ts_streamcont[kMaxNumberDecodeStreams];
113 int8_t ts_start[kMaxNumberDecodeStreams];
115 uint8_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
116 uint8_t *fwrite_buf_orig; /* PS buffer start (set by hb_ts_stream_decode) */
119 * Stuff before this point is dynamic state updated as we read the
120 * stream. Stuff after this point is stream description state that
121 * we learn during the initial scan but cache so it can be
122 * reused during the conversion read.
124 uint8_t ts_number_video_pids;
125 uint8_t ts_number_audio_pids;
127 int16_t ts_video_pids[kMaxNumberVideoPIDS];
128 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
130 uint8_t ts_streamid[kMaxNumberDecodeStreams];
131 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
135 hb_stream_type_t hb_stream_type;
138 AVFormatContext *ffmpeg_ic;
145 } a52_info[kMaxNumberAudioPIDS];
149 unsigned short program_number;
150 unsigned short program_map_PID;
151 } pat_info[kMaxNumberPMTStreams];
152 int ts_number_pat_entries;
157 unsigned char *tablebuf;
158 unsigned int tablepos;
159 unsigned char current_continuity_counter;
163 unsigned int PCR_PID;
164 int program_info_length;
165 unsigned char *progam_info_descriptor_data;
168 unsigned char stream_type;
169 unsigned short elementary_PID;
170 unsigned short ES_info_length;
171 unsigned char *es_info_descriptor_data;
172 } pmt_stream_info[kMaxNumberPMTStreams];
176 /***********************************************************************
178 **********************************************************************/
179 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
180 static void hb_ts_stream_init(hb_stream_t *stream);
181 static void hb_ts_stream_find_pids(hb_stream_t *stream);
182 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
183 static void hb_ts_stream_reset(hb_stream_t *stream);
184 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
186 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
187 static off_t align_to_next_packet(hb_stream_t *stream);
189 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
190 static void ffmpeg_close( hb_stream_t *d );
191 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
192 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
193 static int ffmpeg_seek( hb_stream_t *stream, float frac );
196 * streams have a bunch of state that's learned during the scan. We don't
197 * want to throw away the state when scan does a close then relearn
198 * everything when reader does an open. So we save the stream state on
199 * the close following a scan and reuse it when 'reader' does an open.
201 static hb_list_t *stream_state_list;
203 static hb_stream_t *hb_stream_lookup( const char *path )
205 if ( stream_state_list == NULL )
211 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
213 if ( strcmp( path, ss->path ) == 0 )
221 static void hb_stream_state_delete( hb_stream_t *ss )
223 hb_list_rem( stream_state_list, ss );
230 * these frontend hb_log because transport streams can have a lot of errors
231 * so we want to rate limit messages. this routine limits the number of
232 * messages to at most one per minute of video. other errors that occur
233 * during the minute are counted & the count is output with the next
234 * error msg we print.
236 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
238 // limit error printing to at most one per minute of video (at 30fps)
240 if ( stream->frames - stream->last_error_frame >= 30*60 )
244 vsnprintf( msg, sizeof(msg), log, args );
246 if ( stream->errors - stream->last_error_count < 10 )
248 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
252 int Edelta = stream->errors - stream->last_error_count;
253 double Epcnt = (double)Edelta * 100. /
254 (stream->frames - stream->last_error_frame);
255 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
256 Edelta, Epcnt, stream->frames, msg );
258 stream->last_error_frame = stream->frames;
259 stream->last_error_count = stream->errors;
263 static void ts_warn( hb_stream_t *stream, char *log, ... )
266 va_start( args, log );
267 ts_warn_helper( stream, log, args );
271 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
274 va_start( args, log );
275 ts_warn_helper( stream, log, args );
278 stream->ts_skipbad[curstream] = 1;
279 stream->ts_pos[curstream] = 0;
280 stream->ts_streamcont[curstream] = -1;
283 static int check_ps_sync(const uint8_t *buf)
285 // a legal MPEG program stream must start with a Pack header in the
287 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
288 (buf[2] == 0x01) && (buf[3] == 0xba);
291 static int check_ps_sys(const uint8_t *buf)
293 // a legal MPEG program stream must start with a Pack followed by a
294 // SYS. If we've already verified the pack, this skips over it and checks
295 // for the sys header.
296 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
297 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
298 (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
301 static int check_ts_sync(const uint8_t *buf)
303 // must have initial sync byte, no scrambling & a legal adaptation ctrl
304 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
307 static int have_ts_sync(const uint8_t *buf, int psize)
309 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
310 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
311 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
312 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
315 static int hb_stream_check_for_ts(const uint8_t *buf)
317 // transport streams should have a sync byte every 188 bytes.
318 // search the first 8KB of buf looking for at least 8 consecutive
319 // correctly located sync patterns.
322 for ( offset = 0; offset < 8*1024-8*188; ++offset )
324 if ( have_ts_sync( &buf[offset], 188) )
325 return 188 | (offset << 8);
326 if ( have_ts_sync( &buf[offset], 192) )
327 return 192 | (offset << 8);
328 if ( have_ts_sync( &buf[offset], 204) )
329 return 204 | (offset << 8);
330 if ( have_ts_sync( &buf[offset], 208) )
331 return 208 | (offset << 8);
336 static int hb_stream_check_for_ps(const uint8_t *buf)
338 // program streams should start with a PACK then a SYS header.
339 return check_ps_sync(buf) && check_ps_sys(buf);
342 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
344 // DVD program streams should have a Pack header every 2048 bytes.
345 // check that we have 4 of these in a row.
346 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
347 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
350 static int hb_stream_get_type(hb_stream_t *stream)
354 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
357 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
359 int offset = psize >> 8;
361 hb_log("file is MPEG Transport Stream with %d byte packets"
362 " offset %d bytes", psize, offset);
363 stream->packetsize = psize;
364 stream->hb_stream_type = transport;
365 hb_ts_stream_init(stream);
368 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
370 hb_log("file is MPEG DVD Program Stream");
371 stream->hb_stream_type = dvd_program;
374 if ( hb_stream_check_for_ps(buf) != 0 )
376 hb_log("file is MPEG Program Stream");
377 stream->hb_stream_type = program;
384 static void hb_stream_delete_dynamic( hb_stream_t *d )
388 fclose( d->file_handle );
389 d->file_handle = NULL;
396 free( d->ts_packet );
399 for (i = 0; i < kMaxNumberDecodeStreams; i++)
409 static void hb_stream_delete( hb_stream_t *d )
411 hb_stream_delete_dynamic( d );
416 /***********************************************************************
418 ***********************************************************************
420 **********************************************************************/
421 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
423 FILE *f = fopen( path, "r" );
426 hb_log( "hb_stream_open: open %s failed", path );
430 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
434 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
439 * if we're opening the stream to read & convert, we need
440 * the state we saved when we scanned the stream. if we're
441 * opening the stream to scan it we want to rebuild the state
442 * (even if we have saved state, the stream may have changed).
444 hb_stream_t *ss = hb_stream_lookup( path );
445 if ( title && ss && ss->hb_stream_type != ffmpeg )
448 * copy the saved state since we might be encoding the same stream
451 memcpy( d, ss, sizeof(*d) );
454 d->path = strdup( path );
456 if ( d->hb_stream_type == transport )
458 d->ts_packet = malloc( d->packetsize );
461 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
463 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
465 hb_stream_seek( d, 0. );
471 * opening for scan - delete any saved state then (re)scan the stream.
472 * If it's something we can deal with (MPEG2 PS or TS) return a stream
473 * reference structure & null otherwise.
477 hb_stream_state_delete( ss );
481 d->path = strdup( path );
482 if (d->path != NULL )
484 if ( hb_stream_get_type( d ) != 0 )
488 fclose( d->file_handle );
489 d->file_handle = NULL;
490 if ( ffmpeg_open( d, title ) )
495 if ( d->file_handle )
497 fclose( d->file_handle );
503 hb_log( "hb_stream_open: open %s failed", path );
508 /***********************************************************************
510 ***********************************************************************
511 * Closes and frees everything
512 **********************************************************************/
513 void hb_stream_close( hb_stream_t ** _d )
515 hb_stream_t *stream = * _d;
517 if ( stream->hb_stream_type == ffmpeg )
519 ffmpeg_close( stream );
520 hb_stream_delete( stream );
525 if ( stream->frames )
527 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
528 stream->errors, (double)stream->errors * 100. /
529 (double)stream->frames );
533 * if the stream was opened for a scan, cache the result, otherwise delete
536 if ( stream->title == NULL )
538 hb_stream_delete_dynamic( stream );
539 if ( stream_state_list == NULL )
541 stream_state_list = hb_list_init();
543 hb_list_add( stream_state_list, stream );
547 hb_stream_delete( stream );
552 /* when the file was first opened we made entries for all the audio elementary
553 * streams we found in it. Streams that were later found during the preview scan
554 * now have an audio codec, type, rate, etc., associated with them. At the end
555 * of the scan we delete all the audio entries that weren't found by the scan
556 * or don't have a format we support. This routine deletes audio entry 'indx'
557 * by copying all later entries down one slot. */
558 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
562 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
564 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
565 stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
566 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
569 --stream->ts_number_audio_pids;
572 static int index_of_pid(int pid, hb_stream_t *stream)
576 if ( pid == stream->ts_video_pids[0] )
579 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
580 if ( pid == stream->ts_audio_pids[i] )
586 /***********************************************************************
587 * hb_ps_stream_title_scan
588 ***********************************************************************
590 **********************************************************************/
591 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
593 if ( stream->hb_stream_type == ffmpeg )
594 return ffmpeg_title_scan( stream );
597 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
600 // Copy part of the stream path to the title name
601 char *sep = strrchr(stream->path, '/');
603 strcpy(aTitle->name, sep+1);
604 char *dot_term = strrchr(aTitle->name, '.');
608 // Height, width, rate and aspect ratio information is filled in when the previews are built
610 hb_stream_duration(stream, aTitle);
613 hb_chapter_t * chapter;
614 chapter = calloc( sizeof( hb_chapter_t ), 1 );
616 chapter->duration = aTitle->duration;
617 chapter->hours = aTitle->hours;
618 chapter->minutes = aTitle->minutes;
619 chapter->seconds = aTitle->seconds;
620 hb_list_add( aTitle->list_chapter, chapter );
622 // Figure out how many audio streams we really have:
623 // - For transport streams, for each PID listed in the PMT (whether
624 // or not it was an audio stream type) read the bitstream until we
625 // find an packet from that PID containing a PES header and see if
626 // the elementary stream is an audio type.
627 // - For program streams read the first 4MB and take every unique
628 // audio stream we find.
629 if (stream->hb_stream_type == transport)
633 for (i=0; i < stream->ts_number_audio_pids; i++)
635 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
636 if (audio->config.in.codec)
637 hb_list_add( aTitle->list_audio, audio );
641 hb_stream_delete_audio_entry(stream, i);
646 // add the PCR PID if we don't already have it
647 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
649 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
650 stream->pmt_info.PCR_PID;
653 // set up the video codec to use for this title
654 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
655 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
659 hb_ps_stream_find_audio_ids(stream, aTitle);
666 * read the next transport stream packet from 'stream'. Return NULL if
667 * we hit eof & a pointer to the sync byte otherwise.
669 static const uint8_t *next_packet( hb_stream_t *stream )
671 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
675 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
684 // lost sync - back up to where we started then try to re-establish.
685 off_t pos = ftello(stream->file_handle) - stream->packetsize;
686 off_t pos2 = align_to_next_packet(stream);
689 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
692 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
698 * skip to the start of the next PACK header in program stream src_stream.
700 static void skip_to_next_pack( hb_stream_t *src_stream )
702 // scan forward until we find the start of the next pack
703 uint32_t strt_code = -1;
706 flockfile( src_stream->file_handle );
707 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
709 strt_code = ( strt_code << 8 ) | c;
710 if ( strt_code == 0x000001ba )
711 // we found the start of the next pack
714 funlockfile( src_stream->file_handle );
716 // if we didn't terminate on an eof back up so the next read
717 // starts on the pack boundary.
720 fseeko( src_stream->file_handle, -4, SEEK_CUR );
725 * scan the next MB of 'stream' to find the next start packet for
726 * the Packetized Elementary Stream associated with TS PID 'pid'.
728 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
730 int npack = 300000; // max packets to read
734 const uint8_t *buf = next_packet( stream );
737 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
742 * The PES header is only in TS packets with 'start' set so we check
743 * that first then check for the right PID.
745 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
746 buf[2] != (pid & 0xff))
748 // not a start packet or not the pid we want
752 /* skip over the TS hdr to return a pointer to the PES hdr */
754 switch (buf[3] & 0x30)
756 case 0x00: // illegal
757 case 0x20: // fill packet
760 case 0x30: // adaptation
763 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
769 /* PES hdr has to begin with an mpeg start code */
770 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
780 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
782 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
783 hb_list_t *list = hb_list_init();
784 // how many blocks we read while searching for a video PES header
788 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
792 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
793 hb_demux_ps( buf, list, 0 );
795 while ( ( es = hb_list_item( list, 0 ) ) )
797 hb_list_rem( list, es );
798 if ( es->id == 0xe0 )
800 // this PES contains video - if there's a PTS we're done
801 // hb_demux_ps left the PTS in buf_es->start.
802 if ( es->start != ~0 )
809 hb_buffer_close( &es );
812 hb_list_empty( &list );
813 hb_buffer_close(&buf);
817 /***********************************************************************
819 ***********************************************************************
821 * Finding stream duration is difficult. One issue is that the video file
822 * may have chunks from several different program fragments (main feature,
823 * commercials, station id, trailers, etc.) all with their own base pts
824 * value. We can't find the piece boundaries without reading the entire
825 * file but if we compute a rate based on time stamps from two different
826 * pieces the result will be meaningless. The second issue is that the
827 * data rate of compressed video normally varies by 5-10x over the length
828 * of the video. This says that we want to compute the rate over relatively
829 * long segments to get a representative average but long segments increase
830 * the likelihood that we'll cross a piece boundary.
832 * What we do is take time stamp samples at several places in the file
833 * (currently 16) then compute the average rate (i.e., ticks of video per
834 * byte of the file) for all pairs of samples (N^2 rates computed for N
835 * samples). Some of those rates will be absurd because the samples came
836 * from different segments. Some will be way low or high because the
837 * samples came from a low or high motion part of the segment. But given
838 * that we're comparing *all* pairs the majority of the computed rates
839 * should be near the overall average. So we median filter the computed
840 * rates to pick the most representative value.
842 **********************************************************************/
844 uint64_t pos; /* file position of this PTS sample */
845 uint64_t pts; /* PTS from video stream */
848 #define NDURSAMPLES 16
850 // get one (position, timestamp) sampple from a transport or program
852 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
854 struct pts_pos pp = { 0, 0 };
856 if ( stream->hb_stream_type == transport )
859 fseeko( stream->file_handle, fpos, SEEK_SET );
860 align_to_next_packet( stream );
861 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
864 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
867 if ( ( buf[7] >> 7 ) != 1 )
869 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
872 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
873 ( (uint64_t)buf[10] << 22 ) |
874 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
875 ( (uint64_t)buf[12] << 7 ) |
876 ( (uint64_t)buf[13] >> 1 );
880 // round address down to nearest dvd sector start
881 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
882 fseeko( stream->file_handle, fpos, SEEK_SET );
883 if ( stream->hb_stream_type == program )
885 skip_to_next_pack( stream );
887 pp.pts = hb_ps_stream_getVideoPTS( stream );
889 pp.pos = ftello(stream->file_handle);
893 static int dur_compare( const void *a, const void *b )
895 const double *aval = a, *bval = b;
896 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
899 // given an array of (position, time) samples, compute a max-likelihood
900 // estimate of the average rate by computing the rate between all pairs
901 // of samples then taking the median of those rates.
902 static double compute_stream_rate( struct pts_pos *pp, int n )
905 double rates[NDURSAMPLES * NDURSAMPLES / 2];
908 // the following nested loops compute the rates between all pairs.
910 for ( i = 0; i < n-1; ++i )
912 // Bias the median filter by not including pairs that are "far"
913 // from one another. This is to handle cases where the file is
914 // made of roughly equal size pieces where a symmetric choice of
915 // pairs results in having the same number of intra-piece &
916 // inter-piece rate estimates. This would mean that the median
917 // could easily fall in the inter-piece part of the data which
918 // would give a bogus estimate. The 'ns' index creates an
919 // asymmetry that favors locality.
920 int ns = i + ( n >> 1 );
923 for ( j = i+1; j < ns; ++j )
925 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
927 *rp = ((double)( pp[j].pts - pp[i].pts )) /
928 ((double)( pp[j].pos - pp[i].pos ));
933 // now compute and return the median of all the (n*n/2) rates we computed
935 int nrates = rp - rates;
936 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
937 return rates[nrates >> 1];
940 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
942 struct pts_pos ptspos[NDURSAMPLES];
943 struct pts_pos *pp = ptspos;
946 fseeko(stream->file_handle, 0, SEEK_END);
947 uint64_t fsize = ftello(stream->file_handle);
948 uint64_t fincr = fsize / NDURSAMPLES;
949 uint64_t fpos = fincr / 2;
950 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
952 *pp++ = hb_sample_pts(stream, fpos);
954 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
955 inTitle->duration = dur;
957 inTitle->hours = dur / 3600;
958 inTitle->minutes = ( dur % 3600 ) / 60;
959 inTitle->seconds = dur % 60;
961 rewind(stream->file_handle);
964 /***********************************************************************
966 ***********************************************************************
968 **********************************************************************/
969 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
971 if ( src_stream->hb_stream_type == ffmpeg )
973 return ffmpeg_read( src_stream, b );
975 if ( src_stream->hb_stream_type == dvd_program )
977 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
978 src_stream->file_handle);
979 return (amt_read > 0);
981 if ( src_stream->hb_stream_type == program )
983 // a general program stream has arbitrary sized pack's. we're
984 // currently positioned at the start of a pack so read up to but
985 // not including the start of the next, expanding the buffer
987 uint8_t *cp = b->data;
988 uint8_t *ep = cp + b->alloc;
989 uint32_t strt_code = -1;
992 // consume the first byte of the initial pack so we don't match on
993 // it in the loop below.
994 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
999 flockfile( src_stream->file_handle );
1000 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1002 strt_code = ( strt_code << 8 ) | c;
1003 if ( strt_code == 0x000001ba )
1004 // we found the start of the next pack
1008 // need to expand the buffer
1009 int curSize = cp - b->data;
1010 hb_buffer_realloc( b, curSize * 2 );
1011 cp = b->data + curSize;
1012 ep = b->data + b->alloc;
1016 funlockfile( src_stream->file_handle );
1018 // if we didn't terminate on an eof back up so the next read
1019 // starts on the pack boundary.
1020 b->size = cp - b->data;
1023 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1028 return hb_ts_stream_decode( src_stream, b->data );
1031 /***********************************************************************
1033 ***********************************************************************
1035 **********************************************************************/
1036 int hb_stream_seek( hb_stream_t * src_stream, float f )
1038 if ( src_stream->hb_stream_type == ffmpeg )
1040 return ffmpeg_seek( src_stream, f );
1042 off_t stream_size, cur_pos, new_pos;
1043 double pos_ratio = f;
1044 cur_pos = ftello( src_stream->file_handle );
1045 fseeko( src_stream->file_handle, 0, SEEK_END );
1046 stream_size = ftello( src_stream->file_handle );
1047 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1048 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1050 int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1053 fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1057 if ( src_stream->hb_stream_type == transport )
1059 // We need to drop the current decoder output and move
1060 // forwards to the next transport stream packet.
1061 hb_ts_stream_reset(src_stream);
1063 else if ( src_stream->hb_stream_type == program )
1065 skip_to_next_pack( src_stream );
1071 static const char* make_upper( const char* s )
1073 static char name[8];
1075 char *ep = cp + sizeof(name)-1;
1077 while ( *s && cp < ep )
1079 *cp++ = islower(*s)? toupper(*s) : *s;
1086 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1089 * This is a duplicate of code in dvd.c - it should get factored out
1090 * into a common routine. We probably should only be putting the lang
1091 * code or a lang pointer into the audio config & let the common description
1092 * formatting routine in scan.c do all the stuff below.
1094 const char *codec_name;
1097 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1098 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1099 avcodec_find_decoder( cc->codec_id ) )
1101 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1102 if ( !strcmp( codec_name, "LIBFAAD" ) )
1107 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1108 avcodec_find_decoder( audio->config.in.codec_param ) )
1110 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1114 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1115 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1116 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1117 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1118 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1121 snprintf( audio->config.lang.description,
1122 sizeof( audio->config.lang.description ), "%s (%s)",
1123 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1125 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1126 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1127 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1128 "%s", lang->iso639_2);
1131 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1134 off_t cur_pos = ftello(stream->file_handle);
1135 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1138 fseeko(stream->file_handle, 0, SEEK_SET);
1139 align_to_next_packet(stream);
1140 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1142 /* check that we found a PES header */
1144 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1146 // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1147 // extended stream id (ISO 13818-1(2007)). If we cared about the
1148 // real id we'd have to look inside the PES extension to find it.
1149 // But since we remap stream id's when we generate PS packets from
1150 // the TS packets we can just ignore the actual id.
1151 if ( buf[3] == 0xbd || buf[3] == 0xfd )
1153 audio->id = 0x80bd | (aud_pid_index << 8);
1154 stype = stream->ts_stream_type[1 + aud_pid_index];
1155 if ( st2codec[stype].kind == U )
1157 // XXX assume unknown stream types are AC-3 (if they're not
1158 // audio we'll find that out during the scan but if they're
1159 // some other type of audio we'll end up ignoring them).
1161 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1163 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1165 else if ((buf[3] & 0xe0) == 0xc0)
1167 audio->id = 0xc0 | aud_pid_index;
1168 stype = stream->ts_stream_type[1 + aud_pid_index];
1169 if ( st2codec[stype].kind == U )
1171 // XXX assume unknown stream types are MPEG audio
1173 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1177 // if we found an audio stream type & HB has a codec that can decode it
1178 // finish configuring the audio so we'll add it to the title's list.
1179 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1181 stream->ts_streamid[1 + aud_pid_index] = audio->id;
1182 audio->config.in.codec = st2codec[stype].codec;
1183 audio->config.in.codec_param = st2codec[stype].codec_param;
1184 set_audio_description( audio,
1185 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1186 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1187 stream->ts_audio_pids[aud_pid_index],
1188 stype, st2codec[stype].name, audio->id);
1194 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1195 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1196 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1200 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1201 stream->ts_audio_pids[aud_pid_index],
1202 stream->ts_stream_type[1 + aud_pid_index]);
1205 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1209 static void add_audio_to_title(hb_title_t *title, int id)
1211 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1217 audio->config.in.codec = HB_ACODEC_MPGA;
1218 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1221 // type 2 is a DVD subtitle stream - just ignore it */
1225 audio->config.in.codec = HB_ACODEC_AC3;
1226 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1229 audio->config.in.codec = HB_ACODEC_LPCM;
1230 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1233 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1238 set_audio_description( audio, lang_for_code( 0 ) );
1239 hb_list_add( title->list_audio, audio );
1242 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1244 off_t cur_pos = ftello(stream->file_handle);
1245 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1246 hb_list_t *list = hb_list_init();
1247 // how many blocks we read while searching for audio streams
1248 int blksleft = 4096;
1249 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1250 // so we use a bitmap to keep track of the ones we've already seen.
1251 // Bit 'i' of smap is set if we've already added the audio for
1252 // audio substream id 'i' to the title's audio list.
1255 // start looking 20% into the file since there's occasionally no
1256 // audio at the beginning (particularly for vobs).
1257 hb_stream_seek(stream, 0.2f);
1259 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1263 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1264 hb_demux_ps( buf, list, 0 );
1266 while ( ( es = hb_list_item( list, 0 ) ) )
1268 hb_list_rem( list, es );
1269 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1271 // this PES contains some kind of audio - get the substream id
1272 // and check if we've seen it already.
1273 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1274 if ( (smap & (1 << ssid)) == 0 )
1276 // we haven't seen this stream before - add it to the
1277 // title's list of audio streams.
1278 smap |= (1 << ssid);
1279 add_audio_to_title(title, es->id);
1282 hb_buffer_close( &es );
1285 hb_list_empty( &list );
1286 hb_buffer_close(&buf);
1287 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1290 /***********************************************************************
1292 ***********************************************************************
1294 **********************************************************************/
1296 static void hb_ts_stream_init(hb_stream_t *stream)
1300 for (i=0; i < kMaxNumberDecodeStreams; i++)
1302 stream->ts_streamcont[i] = -1;
1304 stream->ts_video_pids[0] = -1;
1305 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1307 stream-> ts_audio_pids[i] = -1;
1310 stream->ts_packet = malloc( stream->packetsize );
1312 // Find the audio and video pids in the stream
1313 hb_ts_stream_find_pids(stream);
1315 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1317 // demuxing buffer for TS to PS conversion
1318 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1321 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
1324 #define MAX_HOLE 208*80
1326 static off_t align_to_next_packet(hb_stream_t *stream)
1328 uint8_t buf[MAX_HOLE];
1330 off_t start = ftello(stream->file_handle);
1332 if ( start >= stream->packetsize ) {
1333 start -= stream->packetsize;
1334 fseeko(stream->file_handle, start, SEEK_SET);
1337 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1339 const uint8_t *bp = buf;
1342 for ( i = sizeof(buf); --i >= 0; ++bp )
1344 if ( have_ts_sync( bp, stream->packetsize ) )
1351 pos = ( bp - buf ) - stream->packetsize + 188;
1356 fseeko(stream->file_handle, start+pos, SEEK_SET);
1367 static const unsigned int bitmask[] = {
1368 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1369 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1370 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1371 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1373 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1377 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1378 (bb->buf[2] << 8) | bb->buf[3];
1380 memset(bb->buf, 0, bufsize);
1383 static inline int buf_size(bitbuf_t *bb)
1385 return bb->pos >> 3;
1388 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1391 int left = 32 - (bb->pos & 31);
1395 val = (bb->val >> (left - bits)) & bitmask[bits];
1400 val = (bb->val & bitmask[left]) << (bits - left);
1404 int pos = bb->pos >> 3;
1405 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1409 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1417 // extract what useful information we can from the elementary stream
1418 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1419 // Descriptors with info we don't currently use are ignored.
1420 // The descriptor list & descriptor item formats are defined in
1421 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1422 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1423 const uint8_t *dp, uint8_t dlen)
1425 const uint8_t *ep = dp + dlen;
1431 case 10: // ISO_639_language descriptor
1432 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1442 static const char *stream_type_name (uint8_t stream_type)
1444 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1447 int decode_program_map(hb_stream_t* stream)
1450 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1452 get_bits(&bb, 8); // table_id
1454 unsigned int section_length = get_bits(&bb, 12);
1455 stream->pmt_info.section_length = section_length;
1457 unsigned int program_number = get_bits(&bb, 16);
1458 stream->pmt_info.program_number = program_number;
1460 get_bits(&bb, 5); // version_number
1462 get_bits(&bb, 8); // section_number
1463 get_bits(&bb, 8); // last_section_number
1465 unsigned int PCR_PID = get_bits(&bb, 13);
1466 stream->pmt_info.PCR_PID = PCR_PID;
1468 unsigned int program_info_length = get_bits(&bb, 12);
1469 stream->pmt_info.program_info_length = program_info_length;
1472 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1473 for (i = 0; i < program_info_length; i++)
1475 descriptor_buf[i] = get_bits(&bb, 8);
1478 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1479 int done_reading_stream_types = 0;
1480 while (!done_reading_stream_types)
1482 unsigned char stream_type = get_bits(&bb, 8);
1484 unsigned int elementary_PID = get_bits(&bb, 13);
1486 unsigned int ES_info_length = get_bits(&bb, 12);
1489 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1490 for (i=0; i < ES_info_length; i++)
1492 ES_info_buf[i] = get_bits(&bb, 8);
1496 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1498 stream->ts_video_pids[0] = elementary_PID;
1499 stream->ts_stream_type[0] = stream_type;
1500 stream->ts_number_video_pids = 1;
1504 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1505 // for mpeg audio. But content producers seem to use other
1506 // values (0x04 and 0x06 have both been observed) so at this point
1507 // we say everything that isn't a video pid is audio then at the end
1508 // of hb_stream_title_scan we'll figure out which are really audio
1509 // by looking at the PES headers.
1510 i = stream->ts_number_audio_pids;
1511 if (i < kMaxNumberAudioPIDS)
1513 stream->ts_audio_pids[i] = elementary_PID;
1514 stream->ts_stream_type[1 + i] = stream_type;
1515 if (ES_info_length > 0)
1517 decode_element_descriptors(stream, i, ES_info_buf,
1520 ++stream->ts_number_audio_pids;
1524 cur_pos += 5 /* stream header */ + ES_info_length;
1528 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1529 done_reading_stream_types = 1;
1532 free(descriptor_buf);
1536 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1538 // Get adaption header info
1540 int adaption = (buf[3] & 0x30) >> 4;
1543 else if (adaption == 0x2)
1545 else if (adaption == 0x3)
1546 adapt_len = buf[4] + 1;
1547 if (adapt_len > 184)
1550 // Get payload start indicator
1552 start = (buf[1] & 0x40) != 0;
1554 // Get pointer length - only valid in packets with a start flag
1555 int pointer_len = 0;
1556 if (start && stream->pmt_info.reading)
1558 // We just finished a bunch of packets - parse the program map details
1560 if (stream->pmt_info.tablebuf[0] == 0x02)
1561 decode_ok = decode_program_map(stream);
1562 free(stream->pmt_info.tablebuf);
1563 stream->pmt_info.tablebuf = NULL;
1564 stream->pmt_info.tablepos = 0;
1565 stream->pmt_info.reading = 0;
1572 pointer_len = buf[4 + adapt_len] + 1;
1573 stream->pmt_info.tablepos = 0;
1575 // Get Continuity Counter
1576 int continuity_counter = buf[3] & 0x0f;
1577 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1579 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1582 stream->pmt_info.current_continuity_counter = continuity_counter;
1583 stream->pmt_info.reading |= start;
1585 // Add the payload for this packet to the current buffer
1586 int amount_to_copy = 184 - adapt_len - pointer_len;
1587 if (stream->pmt_info.reading && (amount_to_copy > 0))
1589 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1591 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1592 stream->pmt_info.tablepos += amount_to_copy;
1598 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1600 unsigned char tablebuf[1024];
1601 unsigned int tablepos = 0;
1606 // Get adaption header info
1608 int adaption = (buf[3] & 0x30) >> 4;
1611 else if (adaption == 0x2)
1613 else if (adaption == 0x3)
1614 adapt_len = buf[4] + 1;
1615 if (adapt_len > 184)
1618 // Get pointer length
1619 int pointer_len = buf[4 + adapt_len] + 1;
1621 // Get payload start indicator
1623 start = (buf[1] & 0x40) != 0;
1628 // Add the payload for this packet to the current buffer
1629 if (reading && (184 - adapt_len) > 0)
1631 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1633 hb_log("decode_PAT - Bad program section length (> 1024)");
1636 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1637 tablepos += 184 - adapt_len - pointer_len;
1640 if (start && reading)
1642 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1645 unsigned int pos = 0;
1646 //while (pos < tablepos)
1649 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1651 unsigned char section_id = get_bits(&bb, 8);
1653 unsigned int section_len = get_bits(&bb, 12);
1654 get_bits(&bb, 16); // transport_id
1656 get_bits(&bb, 5); // version_num
1657 get_bits(&bb, 1); // current_next
1658 get_bits(&bb, 8); // section_num
1659 get_bits(&bb, 8); // last_section
1665 // Program Association Section
1666 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1667 section_len -= 4; // Ignore the CRC
1669 stream->ts_number_pat_entries = 0;
1670 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1672 unsigned int pkt_program_num = get_bits(&bb, 16);
1673 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1675 get_bits(&bb, 3); // Reserved
1676 if (pkt_program_num == 0)
1678 get_bits(&bb, 13); // pkt_network_id
1682 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1683 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1686 stream->ts_number_pat_entries++;
1700 pos += 3 + section_len;
1708 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1710 // align to first packet
1711 align_to_next_packet(stream);
1713 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1714 // to find the program map PID and then decode that to get the list of audio and video PIDs
1718 const uint8_t *buf = next_packet( stream );
1721 hb_log("hb_ts_stream_find_pids - end of file");
1726 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1728 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1730 decode_PAT(buf, stream);
1735 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1737 // There are some streams where the PAT table has multiple entries as if their are
1738 // multiple programs in the same transport stream, and yet there's actually only one
1739 // program really in the stream. This seems to be true for transport streams that
1740 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1741 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1742 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1743 // PAT info on export to match what's actually on the stream.
1744 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1745 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1746 // be to build a title choice popup from the PAT program number details and then select from
1747 // their - but right now the API's not capable of that.
1748 if (pid == stream->pat_info[pat_index].program_map_PID)
1750 if (build_program_map(buf, stream) > 0)
1754 // Keep going until we have a complete set of PIDs
1755 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1759 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1760 hb_log(" Video PIDS : ");
1762 for (i=0; i < stream->ts_number_video_pids; i++)
1764 hb_log( " 0x%x type %s (0x%x)",
1765 stream->ts_video_pids[i],
1766 stream_type_name(stream->ts_stream_type[i]),
1767 stream->ts_stream_type[i]);
1769 hb_log(" Audio PIDS : ");
1770 for (i = 0; i < stream->ts_number_audio_pids; i++)
1772 hb_log( " 0x%x type %s (0x%x)",
1773 stream->ts_audio_pids[i],
1774 stream_type_name(stream->ts_stream_type[i+1]),
1775 stream->ts_stream_type[i+1] );
1780 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1782 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1784 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1785 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1788 memcpy( stream->fwrite_buf, buf, size );
1789 stream->fwrite_buf += size;
1792 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1796 buf[0] = 0x00; // pack id
1801 buf[4] = 0x44 | // SCR
1802 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1803 ( ( time >> 28 ) & 3 );
1804 buf[5] = time >> 20;
1806 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1807 ( ( time >> 13 ) & 3 );
1809 buf[8] = 0x04 | ( time << 3 );
1811 buf[9] = 0x01; // SCR extension
1813 buf[10] = 384000 >> (22 - 8); // program mux rate
1814 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1815 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1817 buf[13] = 0xf8 | stuffing;
1820 for (i = 0; i < stuffing; ++i )
1823 fwrite64(stream, buf, 14 + stuffing );
1826 static void pad_buffer(hb_stream_t* stream, int pad)
1838 fwrite64(stream, buf, 6);
1841 while ( --pad >= 0 )
1843 fwrite64(stream, buf, 1);
1847 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1851 memset(buf, 0, sizeof(buf) );
1854 buf[4] = ( len + 3 ) >> 8;
1858 fwrite64(stream, buf, 9);
1861 static void generate_output_data(hb_stream_t *stream, int curstream)
1863 uint8_t *tdat = stream->ts_buf[curstream];
1866 // we always ship a PACK header plus all the data in our demux buf.
1867 // AC3 audio also always needs its substream header.
1868 len = 14 + stream->ts_pos[curstream];
1869 if ( stream->ts_stream_type[curstream] == 0x81)
1874 if ( ! stream->ts_start[curstream] )
1876 // we're in the middle of a chunk of PES data - we need to add
1877 // a 'continuation' PES header after the PACK header.
1881 // Write out pack header
1882 // If we don't have 2048 bytes we need to pad to 2048. We can
1883 // add a padding frame after our data but we need at least 7
1884 // bytes of space to do it (6 bytes of header & 1 of pad). If
1885 // we have fewer than 7 bytes left we need to fill the excess
1886 // space with stuffing bytes added to the pack header.
1888 if ( len > HB_DVD_READ_BUFFER_SIZE )
1890 hb_log( "stream ts length botch %d", len );
1892 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1894 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1896 write_pack(stream, stream->ts_nextpcr, stuffing );
1897 stream->ts_nextpcr += 10;
1899 if ( stream->ts_start[curstream] )
1901 // Start frames already have a PES header but we have modify it
1902 // to map from TS PID to PS stream id. Also, if the stream is AC3
1903 // audio we have to insert an AC3 stream header between the end of
1904 // the PES header and the start of the stream data.
1906 stream->ts_start[curstream] = 0;
1907 tdat[3] = stream->ts_streamid[curstream];
1909 uint16_t plen = stream->ts_pos[curstream] - 6;
1910 if ( stream->ts_stream_type[curstream] == 0x81)
1912 // We have to add an AC3 header in front of the data. Add its
1913 // size to the PES packet length.
1915 tdat[4] = plen >> 8;
1918 // Write out the PES header
1919 int hdrsize = 9 + tdat[8];
1920 fwrite64(stream, tdat, hdrsize);
1922 // add a four byte DVD ac3 stream header
1923 uint8_t ac3_substream_id[4];
1924 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1925 ac3_substream_id[0] = 0x80 | ssid; // substream id
1926 ac3_substream_id[1] = 0x01; // number of sync words
1927 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1928 ac3_substream_id[3] = 0x02;
1929 fwrite64(stream, ac3_substream_id, 4);
1931 // add the rest of the data
1932 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1936 // not audio - don't need to modify the stream so write what we've got
1937 tdat[4] = plen >> 8;
1939 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1944 // data without a PES start header needs a simple 'continuation'
1945 // PES header. AC3 audio also needs its substream header.
1946 if ( stream->ts_stream_type[curstream] != 0x81)
1948 make_pes_header(stream, stream->ts_pos[curstream],
1949 stream->ts_streamid[curstream]);
1953 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1954 stream->ts_streamid[curstream]);
1956 // add a four byte DVD ac3 stream header
1957 uint8_t ac3_substream_id[4];
1958 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1959 ac3_substream_id[0] = 0x80 | ssid; // substream id
1960 ac3_substream_id[1] = 0x01; // number of sync words
1961 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1962 ac3_substream_id[3] = 0x02;
1963 fwrite64(stream, ac3_substream_id, 4);
1965 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1969 int left = HB_DVD_READ_BUFFER_SIZE - len;
1972 pad_buffer(stream, left);
1975 stream->ts_pos[curstream] = 0;
1978 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1980 // For mpeg2: look for a gop start or i-frame picture start
1981 // for h.264: look for idr nal type or a slice header for an i-frame
1987 if ( stream->ts_stream_type[0] <= 2 )
1989 // This section of the code handles MPEG-1 and MPEG-2 video streams
1990 for (i = 13 + adapt_len; i < 188; i++)
1992 strid = (strid << 8) | buf[i];
1993 if ( ( strid >> 8 ) == 1 )
1995 // we found a start code
1999 case 0xB8: // group_start_code (GOP header)
2000 case 0xB3: // sequence_header code
2003 case 0x00: // picture_start_code
2004 // picture_header, let's see if it's an I-frame
2007 // check if picture_coding_type == 1
2008 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2010 // found an I-frame picture
2018 // didn't find an I-frame
2021 if ( stream->ts_stream_type[0] == 0x1b )
2023 // we have an h.264 stream
2024 for (i = 13 + adapt_len; i < 188; i++)
2026 strid = (strid << 8) | buf[i];
2027 if ( ( strid >> 8 ) == 1 )
2029 // we found a start code - remove the ref_idc from the nal type
2030 uint8_t nal_type = strid & 0x1f;
2031 if ( nal_type == 0x05 )
2032 // h.264 IDR picture start
2035 if ( nal_type == 0x01 )
2037 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2038 uint8_t id = buf[i+1];
2039 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2040 id == 0x88 || id == 0x8a )
2047 // didn't find an I-frame
2051 // we don't understand the stream type so just say "yes" otherwise
2052 // we'll discard all the video.
2056 /***********************************************************************
2057 * hb_ts_stream_decode
2058 ***********************************************************************
2060 **********************************************************************/
2061 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2064 * stash the output buffer pointer in our stream so we don't have to
2065 * pass it & its original value to everything we call.
2067 stream->fwrite_buf = obuf;
2068 stream->fwrite_buf_orig = obuf;
2070 // spin until we get a packet of data from some stream or hit eof
2073 int64_t pcr = stream->ts_lastpcr;
2076 const uint8_t *buf = next_packet(stream);
2079 // end of file - we didn't finish filling our ps write buffer
2080 // so just discard the remainder (the partial buffer is useless)
2081 hb_log("hb_ts_stream_decode - eof");
2085 /* This next section validates the packet */
2087 // Get pid and use it to find stream state.
2088 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2089 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2093 int errorbit = (buf[1] & 0x80) != 0;
2096 ts_err( stream, curstream, "packet error bit set");
2100 // Get adaption header info
2101 int adaption = (buf[3] & 0x30) >> 4;
2105 ts_err( stream, curstream, "adaptation code 0");
2108 else if (adaption == 0x2)
2110 else if (adaption == 0x3)
2112 adapt_len = buf[4] + 1;
2113 if (adapt_len > 184)
2115 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2120 // if there's an adaptation header & PCR_flag is set
2121 // get the PCR (Program Clock Reference)
2122 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2124 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2125 ( (uint64_t)buf[7] << (33 - 16) ) |
2126 ( (uint64_t)buf[8] << (33 - 24) ) |
2127 ( (uint64_t)buf[9] << (33 - 32) ) |
2129 stream->ts_nextpcr = pcr;
2131 // remember the pcr across calls to this routine
2132 stream->ts_lastpcr = pcr;
2137 // don't accumulate data until we get a pcr
2142 // Continuity only increments for adaption values of 0x3 or 0x01
2143 // and is not checked for start packets.
2145 int start = (buf[1] & 0x40) != 0;
2147 if ( (adaption & 0x01) != 0 )
2149 int continuity = (buf[3] & 0xF);
2150 if ( continuity == stream->ts_streamcont[curstream] )
2152 // we got a duplicate packet (usually used to introduce
2153 // a PCR when one is needed). The only thing that can
2154 // change in the dup is the PCR which we grabbed above
2155 // so ignore the rest.
2158 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2159 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2161 ts_err( stream, curstream, "continuity error: got %d expected %d",
2163 (stream->ts_streamcont[curstream] + 1) & 0xf );
2164 stream->ts_streamcont[curstream] = continuity;
2167 stream->ts_streamcont[curstream] = continuity;
2170 /* If we get here the packet is valid - process its data */
2174 // Found a random access point (now we can start a frame/audio packet..)
2176 // If we were skipping a bad packet, start fresh on this new PES packet..
2177 if (stream->ts_skipbad[curstream] == 1)
2179 // video skips to an iframe after a bad packet to minimize
2180 // screen corruption
2181 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2185 stream->ts_skipbad[curstream] = 0;
2188 // If we don't have video yet, check to see if this is an
2189 // i_frame (group of picture start)
2190 if ( curstream == 0 )
2192 if ( !stream->ts_foundfirst[0] )
2194 if ( !isIframe( stream, buf, adapt_len ) )
2196 // didn't find an I frame
2199 stream->ts_foundfirst[0] = 1;
2203 else if ( ! stream->ts_foundfirst[curstream] )
2205 // start other streams only after first video frame found.
2206 if ( ! stream->ts_foundfirst[0] )
2210 stream->ts_foundfirst[curstream] = 1;
2213 // If we have some data already on this stream, turn it into
2214 // a program stream packet. Then add the payload for this
2215 // packet to the current pid's buffer.
2216 if ( stream->ts_pos[curstream] )
2218 generate_output_data(stream, curstream);
2219 stream->ts_start[curstream] = 1;
2220 memcpy(stream->ts_buf[curstream],
2221 buf + 4 + adapt_len, 184 - adapt_len);
2222 stream->ts_pos[curstream] = 184 - adapt_len;
2225 stream->ts_start[curstream] = 1;
2228 // Add the payload for this packet to the current buffer
2229 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2230 (184 - adapt_len) > 0)
2232 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2233 buf + 4 + adapt_len, 184 - adapt_len);
2234 stream->ts_pos[curstream] += 184 - adapt_len;
2236 // if the next TS packet could possibly overflow our 2K output buffer
2237 // we need to generate a packet now. Overflow would be 184 bytes of
2238 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2239 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2241 // we have enough data to make a PS packet
2242 generate_output_data(stream, curstream);
2249 static void hb_ts_stream_reset(hb_stream_t *stream)
2253 for (i=0; i < kMaxNumberDecodeStreams; i++)
2255 stream->ts_pos[i] = 0;
2256 stream->ts_foundfirst[i] = 0;
2257 stream->ts_skipbad[i] = 0;
2258 stream->ts_streamcont[i] = -1;
2259 stream->ts_start[i] = 0;
2262 stream->ts_lastpcr = -1;
2263 stream->ts_nextpcr = -1;
2267 stream->last_error_frame = -10000;
2268 stream->last_error_count = 0;
2270 align_to_next_packet(stream);
2273 // ------------------------------------------------------------------
2274 // Support for reading media files via the ffmpeg libraries.
2276 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2278 // add a codec to the context here so it will be there when we
2279 // read the first packet.
2280 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2281 context->workaround_bugs = FF_BUG_AUTODETECT;
2282 context->error_resilience = 1;
2283 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2284 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2285 avcodec_open( context, codec );
2288 // The ffmpeg stream reader / parser shares a lot of state with the
2289 // decoder via a codec context kept in the AVStream of the reader's
2290 // AVFormatContext. Since decoding is done in a different thread we
2291 // have to somehow pass this codec context to the decoder and we have
2292 // to do it before the first packet is read (so we can't put the info
2293 // in the buf we'll send downstream). Decoders don't have any way to
2294 // get to the stream directly (they're not passed the title or job
2295 // pointers during a scan) so this is a back door for the decoder to
2296 // get the codec context. We just stick the stream pointer in the next
2297 // slot an array of pointers maintained as a circular list then return
2298 // the index into the list combined with the ffmpeg stream index as the
2299 // codec_param that will be passed to the decoder init routine. We make
2300 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2301 // so that we don't have to do a complicated allocator or worry about
2302 // deleting entries on close.
2304 // Entries can only be added to this list during a scan and are never
2305 // deleted so the list access doesn't require locking.
2306 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2307 static int ffmpeg_stream_cur; // where we put the last stream pointer
2308 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2309 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2311 // add a stream to the list & return the appropriate codec_param to access it
2312 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2314 if ( !ffmpeg_streams )
2316 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2319 // the title scan adds all the ffmpeg media streams at once so we
2320 // only add a new entry to our stream list if the stream is different
2322 int slot = ffmpeg_stream_cur;
2323 if ( ffmpeg_streams[slot] != stream )
2325 // new stream - put it in the next slot of the stream list
2326 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2327 ffmpeg_streams[slot] = stream;
2330 ffmpeg_add_codec( stream, stream_index );
2332 return ( stream_index << ffmpeg_sl_bits ) | slot;
2335 // we're about to open 'title' to convert it - remap the stream associated
2336 // with the video & audio codec params of the title to refer to 'stream'
2337 // (the original scan stream was closed and no longer exists).
2338 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2340 // all the video & audio came from the same stream so remapping
2341 // the video's stream slot takes care of everything.
2342 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2343 ffmpeg_streams[slot] = stream;
2345 // add codecs for all the streams used by the title
2346 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2350 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2352 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2354 ffmpeg_add_codec( stream,
2355 audio->config.in.codec_param >> ffmpeg_sl_bits );
2360 void *hb_ffmpeg_context( int codec_param )
2362 int slot = codec_param & (ffmpeg_sl_size - 1);
2363 int stream_index = codec_param >> ffmpeg_sl_bits;
2364 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2367 void *hb_ffmpeg_avstream( int codec_param )
2369 int slot = codec_param & (ffmpeg_sl_size - 1);
2370 int stream_index = codec_param >> ffmpeg_sl_bits;
2371 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2374 static AVFormatContext *ffmpeg_deferred_close;
2376 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2378 if ( ffmpeg_deferred_close )
2380 av_close_input_file( ffmpeg_deferred_close );
2381 ffmpeg_deferred_close = NULL;
2383 AVFormatContext *ic;
2385 av_log_set_level( AV_LOG_ERROR );
2386 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2390 if ( av_find_stream_info( ic ) < 0 )
2393 stream->ffmpeg_ic = ic;
2394 stream->hb_stream_type = ffmpeg;
2398 // we're opening for read. scan passed out codec params that
2399 // indexed its stream so we need to remap them so they point
2401 ffmpeg_remap_stream( stream, title );
2402 ffmpeg_seek( stream, 0. );
2403 av_log_set_level( AV_LOG_ERROR );
2407 // we're opening for scan. let ffmpeg put some info into the
2408 // log about what we've got.
2409 av_log_set_level( AV_LOG_INFO );
2410 dump_format( ic, 0, stream->path, 0 );
2411 av_log_set_level( AV_LOG_ERROR );
2413 // accept this file if it has at least one video stream we can decode
2415 for (i = 0; i < ic->nb_streams; ++i )
2417 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2422 if ( i >= ic->nb_streams )
2428 av_close_input_file( ic );
2432 static void ffmpeg_close( hb_stream_t *d )
2434 // XXX since we're sharing the CodecContext with the downstream
2435 // decoder proc we can't close the stream. We need to reference count
2436 // this so we can close it when both are done with their instance but
2437 // for now just defer the close until the next stream open or close.
2438 if ( ffmpeg_deferred_close )
2440 av_close_input_file( ffmpeg_deferred_close );
2442 ffmpeg_deferred_close = d->ffmpeg_ic;
2445 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2447 AVStream *st = stream->ffmpeg_ic->streams[id];
2448 AVCodecContext *codec = st->codec;
2450 // scan will ignore any audio without a bitrate. Since we've already
2451 // typed the audio in order to determine its codec we set up the audio
2453 if ( codec->bit_rate || codec->sample_rate )
2455 static const int chan2layout[] = {
2456 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2457 HB_INPUT_CH_LAYOUT_MONO,
2458 HB_INPUT_CH_LAYOUT_STEREO,
2459 HB_INPUT_CH_LAYOUT_2F1R,
2460 HB_INPUT_CH_LAYOUT_2F2R,
2461 HB_INPUT_CH_LAYOUT_3F2R,
2462 HB_INPUT_CH_LAYOUT_4F2R,
2463 HB_INPUT_CH_LAYOUT_STEREO,
2464 HB_INPUT_CH_LAYOUT_STEREO,
2467 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2470 if ( codec->codec_id == CODEC_ID_AC3 )
2472 audio->config.in.codec = HB_ACODEC_AC3;
2476 audio->config.in.codec = HB_ACODEC_FFMPEG;
2477 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2479 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2480 audio->config.in.samplerate = codec->sample_rate;
2481 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2484 set_audio_description( audio, lang_for_code2( st->language ) );
2486 hb_list_add( title->list_audio, audio );
2490 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2492 AVFormatContext *ic = stream->ffmpeg_ic;
2494 // 'Barebones Title'
2495 hb_title_t *title = hb_title_init( stream->path, 0 );
2498 // Copy part of the stream path to the title name
2499 char *sep = strrchr(stream->path, '/');
2501 strcpy(title->name, sep+1);
2502 char *dot_term = strrchr(title->name, '.');
2506 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2507 title->duration = dur;
2509 title->hours = dur / 3600;
2510 title->minutes = ( dur % 3600 ) / 60;
2511 title->seconds = dur % 60;
2514 hb_chapter_t * chapter;
2515 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2517 chapter->duration = title->duration;
2518 chapter->hours = title->hours;
2519 chapter->minutes = title->minutes;
2520 chapter->seconds = title->seconds;
2521 hb_list_add( title->list_chapter, chapter );
2523 // set the title to decode the first video stream in the file
2524 title->demuxer = HB_NULL_DEMUXER;
2525 title->video_codec = 0;
2527 for (i = 0; i < ic->nb_streams; ++i )
2529 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2530 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2531 title->video_codec == 0 )
2533 title->video_id = i;
2535 // We have to use the 'internal' avcodec decoder because
2536 // it needs to share the codec context from this video
2537 // stream. The parser internal to av_read_frame
2538 // passes a bunch of state info to the decoder via the context.
2539 title->video_codec = WORK_DECAVCODECVI;
2540 title->video_codec_param = ffmpeg_codec_param( stream, i );
2542 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2543 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2545 add_ffmpeg_audio( title, stream, i );
2549 title->container_name = strdup( ic->iformat->name );
2550 title->data_rate = ic->bit_rate;
2555 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2557 if ( pts == AV_NOPTS_VALUE )
2559 return (int64_t)( (double)pts * conv_factor );
2562 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2566 if ( av_read_frame( stream->ffmpeg_ic, &pkt ) < 0 )
2570 if ( pkt.size > buf->alloc )
2572 // need to expand buffer
2573 hb_buffer_realloc( buf, pkt.size );
2575 memcpy( buf->data, pkt.data, pkt.size );
2576 buf->id = pkt.stream_index;
2577 buf->size = pkt.size;
2578 int64_t pts = pkt.pts != AV_NOPTS_VALUE? pkt.pts :
2579 pkt.dts != AV_NOPTS_VALUE? pkt.dts : -1;
2580 buf->start = av_to_hb_pts( pts,
2581 av_q2d(stream->ffmpeg_ic->streams[pkt.stream_index]->time_base)*90000. );
2582 buf->renderOffset = av_to_hb_pts( pkt.pts,
2583 av_q2d(stream->ffmpeg_ic->streams[pkt.stream_index]->time_base)*90000. );
2584 av_free_packet( &pkt );
2588 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2590 AVFormatContext *ic = stream->ffmpeg_ic;
2591 int64_t pos = (double)ic->duration * (double)frac;
2592 av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );