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 = 100000; // 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);
776 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
778 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
779 hb_list_t *list = hb_list_init();
780 // how many blocks we read while searching for a video PES header
784 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
788 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
789 hb_demux_ps( buf, list, 0 );
791 while ( ( es = hb_list_item( list, 0 ) ) )
793 hb_list_rem( list, es );
794 if ( es->id == 0xe0 )
796 // this PES contains video - if there's a PTS we're done
797 // hb_demux_ps left the PTS in buf_es->start.
798 if ( es->start != ~0 )
805 hb_buffer_close( &es );
808 hb_list_empty( &list );
809 hb_buffer_close(&buf);
813 /***********************************************************************
815 ***********************************************************************
817 * Finding stream duration is difficult. One issue is that the video file
818 * may have chunks from several different program fragments (main feature,
819 * commercials, station id, trailers, etc.) all with their own base pts
820 * value. We can't find the piece boundaries without reading the entire
821 * file but if we compute a rate based on time stamps from two different
822 * pieces the result will be meaningless. The second issue is that the
823 * data rate of compressed video normally varies by 5-10x over the length
824 * of the video. This says that we want to compute the rate over relatively
825 * long segments to get a representative average but long segments increase
826 * the likelihood that we'll cross a piece boundary.
828 * What we do is take time stamp samples at several places in the file
829 * (currently 16) then compute the average rate (i.e., ticks of video per
830 * byte of the file) for all pairs of samples (N^2 rates computed for N
831 * samples). Some of those rates will be absurd because the samples came
832 * from different segments. Some will be way low or high because the
833 * samples came from a low or high motion part of the segment. But given
834 * that we're comparing *all* pairs the majority of the computed rates
835 * should be near the overall average. So we median filter the computed
836 * rates to pick the most representative value.
838 **********************************************************************/
840 uint64_t pos; /* file position of this PTS sample */
841 uint64_t pts; /* PTS from video stream */
844 #define NDURSAMPLES 16
846 // get one (position, timestamp) sampple from a transport or program
848 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
850 struct pts_pos pp = { 0, 0 };
852 if ( stream->hb_stream_type == transport )
855 fseeko( stream->file_handle, fpos, SEEK_SET );
856 align_to_next_packet( stream );
857 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
860 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
863 if ( ( buf[7] >> 7 ) != 1 )
865 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
868 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
869 ( (uint64_t)buf[10] << 22 ) |
870 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
871 ( (uint64_t)buf[12] << 7 ) |
872 ( (uint64_t)buf[13] >> 1 );
876 // round address down to nearest dvd sector start
877 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
878 fseeko( stream->file_handle, fpos, SEEK_SET );
879 if ( stream->hb_stream_type == program )
881 skip_to_next_pack( stream );
883 pp.pts = hb_ps_stream_getVideoPTS( stream );
885 pp.pos = ftello(stream->file_handle);
889 static int dur_compare( const void *a, const void *b )
891 const double *aval = a, *bval = b;
892 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
895 // given an array of (position, time) samples, compute a max-likelihood
896 // estimate of the average rate by computing the rate between all pairs
897 // of samples then taking the median of those rates.
898 static double compute_stream_rate( struct pts_pos *pp, int n )
901 double rates[NDURSAMPLES * NDURSAMPLES / 2];
904 // the following nested loops compute the rates between all pairs.
906 for ( i = 0; i < n-1; ++i )
908 // Bias the median filter by not including pairs that are "far"
909 // from one another. This is to handle cases where the file is
910 // made of roughly equal size pieces where a symmetric choice of
911 // pairs results in having the same number of intra-piece &
912 // inter-piece rate estimates. This would mean that the median
913 // could easily fall in the inter-piece part of the data which
914 // would give a bogus estimate. The 'ns' index creates an
915 // asymmetry that favors locality.
916 int ns = i + ( n >> 1 );
919 for ( j = i+1; j < ns; ++j )
921 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
923 *rp = ((double)( pp[j].pts - pp[i].pts )) /
924 ((double)( pp[j].pos - pp[i].pos ));
929 // now compute and return the median of all the (n*n/2) rates we computed
931 int nrates = rp - rates;
932 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
933 return rates[nrates >> 1];
936 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
938 struct pts_pos ptspos[NDURSAMPLES];
939 struct pts_pos *pp = ptspos;
942 fseeko(stream->file_handle, 0, SEEK_END);
943 uint64_t fsize = ftello(stream->file_handle);
944 uint64_t fincr = fsize / NDURSAMPLES;
945 uint64_t fpos = fincr / 2;
946 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
948 *pp++ = hb_sample_pts(stream, fpos);
950 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
951 inTitle->duration = dur;
953 inTitle->hours = dur / 3600;
954 inTitle->minutes = ( dur % 3600 ) / 60;
955 inTitle->seconds = dur % 60;
957 rewind(stream->file_handle);
960 /***********************************************************************
962 ***********************************************************************
964 **********************************************************************/
965 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
967 if ( src_stream->hb_stream_type == ffmpeg )
969 return ffmpeg_read( src_stream, b );
971 if ( src_stream->hb_stream_type == dvd_program )
973 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
974 src_stream->file_handle);
975 return (amt_read > 0);
977 if ( src_stream->hb_stream_type == program )
979 // a general program stream has arbitrary sized pack's. we're
980 // currently positioned at the start of a pack so read up to but
981 // not including the start of the next, expanding the buffer
983 uint8_t *cp = b->data;
984 uint8_t *ep = cp + b->alloc;
985 uint32_t strt_code = -1;
988 // consume the first byte of the initial pack so we don't match on
989 // it in the loop below.
990 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
995 flockfile( src_stream->file_handle );
996 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
998 strt_code = ( strt_code << 8 ) | c;
999 if ( strt_code == 0x000001ba )
1000 // we found the start of the next pack
1004 // need to expand the buffer
1005 int curSize = cp - b->data;
1006 hb_buffer_realloc( b, curSize * 2 );
1007 cp = b->data + curSize;
1008 ep = b->data + b->alloc;
1012 funlockfile( src_stream->file_handle );
1014 // if we didn't terminate on an eof back up so the next read
1015 // starts on the pack boundary.
1016 b->size = cp - b->data;
1019 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1024 return hb_ts_stream_decode( src_stream, b->data );
1027 /***********************************************************************
1029 ***********************************************************************
1031 **********************************************************************/
1032 int hb_stream_seek( hb_stream_t * src_stream, float f )
1034 if ( src_stream->hb_stream_type == ffmpeg )
1036 return ffmpeg_seek( src_stream, f );
1038 off_t stream_size, cur_pos, new_pos;
1039 double pos_ratio = f;
1040 cur_pos = ftello( src_stream->file_handle );
1041 fseeko( src_stream->file_handle, 0, SEEK_END );
1042 stream_size = ftello( src_stream->file_handle );
1043 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1044 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1046 int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1049 fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1053 if ( src_stream->hb_stream_type == transport )
1055 // We need to drop the current decoder output and move
1056 // forwards to the next transport stream packet.
1057 hb_ts_stream_reset(src_stream);
1059 else if ( src_stream->hb_stream_type == program )
1061 skip_to_next_pack( src_stream );
1067 static const char* make_upper( const char* s )
1069 static char name[8];
1071 char *ep = cp + sizeof(name)-1;
1073 while ( *s && cp < ep )
1075 *cp++ = islower(*s)? toupper(*s) : *s;
1082 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1085 * This is a duplicate of code in dvd.c - it should get factored out
1086 * into a common routine. We probably should only be putting the lang
1087 * code or a lang pointer into the audio config & let the common description
1088 * formatting routine in scan.c do all the stuff below.
1090 const char *codec_name;
1093 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1094 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1095 avcodec_find_decoder( cc->codec_id ) )
1097 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1098 if ( !strcmp( codec_name, "LIBFAAD" ) )
1103 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1104 avcodec_find_decoder( audio->config.in.codec_param ) )
1106 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1110 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1111 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1112 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1113 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1114 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1117 snprintf( audio->config.lang.description,
1118 sizeof( audio->config.lang.description ), "%s (%s)",
1119 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1121 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1122 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1123 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1124 "%s", lang->iso639_2);
1127 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1130 off_t cur_pos = ftello(stream->file_handle);
1131 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1134 fseeko(stream->file_handle, 0, SEEK_SET);
1135 align_to_next_packet(stream);
1136 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1138 /* check that we found a PES header */
1140 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1142 // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1143 // extended stream id (ISO 13818-1(2007)). If we cared about the
1144 // real id we'd have to look inside the PES extension to find it.
1145 // But since we remap stream id's when we generate PS packets from
1146 // the TS packets we can just ignore the actual id.
1147 if ( buf[3] == 0xbd || buf[3] == 0xfd )
1149 audio->id = 0x80bd | (aud_pid_index << 8);
1150 stype = stream->ts_stream_type[1 + aud_pid_index];
1151 if ( st2codec[stype].kind == U )
1153 // XXX assume unknown stream types are AC-3 (if they're not
1154 // audio we'll find that out during the scan but if they're
1155 // some other type of audio we'll end up ignoring them).
1157 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1159 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1161 else if ((buf[3] & 0xe0) == 0xc0)
1163 audio->id = 0xc0 | aud_pid_index;
1164 stype = stream->ts_stream_type[1 + aud_pid_index];
1165 if ( st2codec[stype].kind == U )
1167 // XXX assume unknown stream types are MPEG audio
1169 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1173 // if we found an audio stream type & HB has a codec that can decode it
1174 // finish configuring the audio so we'll add it to the title's list.
1175 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1177 stream->ts_streamid[1 + aud_pid_index] = audio->id;
1178 audio->config.in.codec = st2codec[stype].codec;
1179 audio->config.in.codec_param = st2codec[stype].codec_param;
1180 set_audio_description( audio,
1181 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1182 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1183 stream->ts_audio_pids[aud_pid_index],
1184 stype, st2codec[stype].name, audio->id);
1188 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1189 stream->ts_audio_pids[aud_pid_index],
1190 stream->ts_stream_type[1 + aud_pid_index]);
1192 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1196 static void add_audio_to_title(hb_title_t *title, int id)
1198 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1204 audio->config.in.codec = HB_ACODEC_MPGA;
1205 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1208 // type 2 is a DVD subtitle stream - just ignore it */
1212 audio->config.in.codec = HB_ACODEC_AC3;
1213 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1216 audio->config.in.codec = HB_ACODEC_LPCM;
1217 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1220 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1225 set_audio_description( audio, lang_for_code( 0 ) );
1226 hb_list_add( title->list_audio, audio );
1229 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1231 off_t cur_pos = ftello(stream->file_handle);
1232 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1233 hb_list_t *list = hb_list_init();
1234 // how many blocks we read while searching for audio streams
1235 int blksleft = 4096;
1236 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1237 // so we use a bitmap to keep track of the ones we've already seen.
1238 // Bit 'i' of smap is set if we've already added the audio for
1239 // audio substream id 'i' to the title's audio list.
1242 // start looking 20% into the file since there's occasionally no
1243 // audio at the beginning (particularly for vobs).
1244 hb_stream_seek(stream, 0.2f);
1246 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1250 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1251 hb_demux_ps( buf, list, 0 );
1253 while ( ( es = hb_list_item( list, 0 ) ) )
1255 hb_list_rem( list, es );
1256 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1258 // this PES contains some kind of audio - get the substream id
1259 // and check if we've seen it already.
1260 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1261 if ( (smap & (1 << ssid)) == 0 )
1263 // we haven't seen this stream before - add it to the
1264 // title's list of audio streams.
1265 smap |= (1 << ssid);
1266 add_audio_to_title(title, es->id);
1269 hb_buffer_close( &es );
1272 hb_list_empty( &list );
1273 hb_buffer_close(&buf);
1274 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1277 /***********************************************************************
1279 ***********************************************************************
1281 **********************************************************************/
1283 static void hb_ts_stream_init(hb_stream_t *stream)
1287 for (i=0; i < kMaxNumberDecodeStreams; i++)
1289 stream->ts_streamcont[i] = -1;
1291 stream->ts_video_pids[0] = -1;
1292 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1294 stream-> ts_audio_pids[i] = -1;
1297 stream->ts_packet = malloc( stream->packetsize );
1299 // Find the audio and video pids in the stream
1300 hb_ts_stream_find_pids(stream);
1302 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1304 // demuxing buffer for TS to PS conversion
1305 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1308 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
1311 #define MAX_HOLE 208*80
1313 static off_t align_to_next_packet(hb_stream_t *stream)
1315 uint8_t buf[MAX_HOLE];
1317 off_t start = ftello(stream->file_handle);
1319 if ( start >= stream->packetsize ) {
1320 start -= stream->packetsize;
1321 fseeko(stream->file_handle, start, SEEK_SET);
1324 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1326 const uint8_t *bp = buf;
1329 for ( i = sizeof(buf); --i >= 0; ++bp )
1331 if ( have_ts_sync( bp, stream->packetsize ) )
1338 pos = ( bp - buf ) - stream->packetsize + 188;
1343 fseeko(stream->file_handle, start+pos, SEEK_SET);
1354 static const unsigned int bitmask[] = {
1355 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1356 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1357 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1358 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1360 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1364 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1365 (bb->buf[2] << 8) | bb->buf[3];
1367 memset(bb->buf, 0, bufsize);
1370 static inline int buf_size(bitbuf_t *bb)
1372 return bb->pos >> 3;
1375 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1378 int left = 32 - (bb->pos & 31);
1382 val = (bb->val >> (left - bits)) & bitmask[bits];
1387 val = (bb->val & bitmask[left]) << (bits - left);
1391 int pos = bb->pos >> 3;
1392 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1396 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1404 // extract what useful information we can from the elementary stream
1405 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1406 // Descriptors with info we don't currently use are ignored.
1407 // The descriptor list & descriptor item formats are defined in
1408 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1409 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1410 const uint8_t *dp, uint8_t dlen)
1412 const uint8_t *ep = dp + dlen;
1418 case 10: // ISO_639_language descriptor
1419 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1429 static const char *stream_type_name (uint8_t stream_type)
1431 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1434 int decode_program_map(hb_stream_t* stream)
1437 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1439 get_bits(&bb, 8); // table_id
1441 unsigned int section_length = get_bits(&bb, 12);
1442 stream->pmt_info.section_length = section_length;
1444 unsigned int program_number = get_bits(&bb, 16);
1445 stream->pmt_info.program_number = program_number;
1447 get_bits(&bb, 5); // version_number
1449 get_bits(&bb, 8); // section_number
1450 get_bits(&bb, 8); // last_section_number
1452 unsigned int PCR_PID = get_bits(&bb, 13);
1453 stream->pmt_info.PCR_PID = PCR_PID;
1455 unsigned int program_info_length = get_bits(&bb, 12);
1456 stream->pmt_info.program_info_length = program_info_length;
1459 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1460 for (i = 0; i < program_info_length; i++)
1462 descriptor_buf[i] = get_bits(&bb, 8);
1465 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1466 int done_reading_stream_types = 0;
1467 while (!done_reading_stream_types)
1469 unsigned char stream_type = get_bits(&bb, 8);
1471 unsigned int elementary_PID = get_bits(&bb, 13);
1473 unsigned int ES_info_length = get_bits(&bb, 12);
1476 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1477 for (i=0; i < ES_info_length; i++)
1479 ES_info_buf[i] = get_bits(&bb, 8);
1483 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1485 stream->ts_video_pids[0] = elementary_PID;
1486 stream->ts_stream_type[0] = stream_type;
1487 stream->ts_number_video_pids = 1;
1491 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1492 // for mpeg audio. But content producers seem to use other
1493 // values (0x04 and 0x06 have both been observed) so at this point
1494 // we say everything that isn't a video pid is audio then at the end
1495 // of hb_stream_title_scan we'll figure out which are really audio
1496 // by looking at the PES headers.
1497 i = stream->ts_number_audio_pids;
1498 if (i < kMaxNumberAudioPIDS)
1500 stream->ts_audio_pids[i] = elementary_PID;
1501 stream->ts_stream_type[1 + i] = stream_type;
1502 if (ES_info_length > 0)
1504 decode_element_descriptors(stream, i, ES_info_buf,
1507 ++stream->ts_number_audio_pids;
1511 cur_pos += 5 /* stream header */ + ES_info_length;
1515 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1516 done_reading_stream_types = 1;
1519 free(descriptor_buf);
1523 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1525 // Get adaption header info
1527 int adaption = (buf[3] & 0x30) >> 4;
1530 else if (adaption == 0x2)
1532 else if (adaption == 0x3)
1533 adapt_len = buf[4] + 1;
1534 if (adapt_len > 184)
1537 // Get payload start indicator
1539 start = (buf[1] & 0x40) != 0;
1541 // Get pointer length - only valid in packets with a start flag
1542 int pointer_len = 0;
1543 if (start && stream->pmt_info.reading)
1545 // We just finished a bunch of packets - parse the program map details
1547 if (stream->pmt_info.tablebuf[0] == 0x02)
1548 decode_ok = decode_program_map(stream);
1549 free(stream->pmt_info.tablebuf);
1550 stream->pmt_info.tablebuf = NULL;
1551 stream->pmt_info.tablepos = 0;
1552 stream->pmt_info.reading = 0;
1559 pointer_len = buf[4 + adapt_len] + 1;
1560 stream->pmt_info.tablepos = 0;
1562 // Get Continuity Counter
1563 int continuity_counter = buf[3] & 0x0f;
1564 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1566 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1569 stream->pmt_info.current_continuity_counter = continuity_counter;
1570 stream->pmt_info.reading |= start;
1572 // Add the payload for this packet to the current buffer
1573 int amount_to_copy = 184 - adapt_len - pointer_len;
1574 if (stream->pmt_info.reading && (amount_to_copy > 0))
1576 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1578 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1579 stream->pmt_info.tablepos += amount_to_copy;
1585 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1587 unsigned char tablebuf[1024];
1588 unsigned int tablepos = 0;
1593 // Get adaption header info
1595 int adaption = (buf[3] & 0x30) >> 4;
1598 else if (adaption == 0x2)
1600 else if (adaption == 0x3)
1601 adapt_len = buf[4] + 1;
1602 if (adapt_len > 184)
1605 // Get pointer length
1606 int pointer_len = buf[4 + adapt_len] + 1;
1608 // Get payload start indicator
1610 start = (buf[1] & 0x40) != 0;
1615 // Add the payload for this packet to the current buffer
1616 if (reading && (184 - adapt_len) > 0)
1618 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1620 hb_log("decode_PAT - Bad program section length (> 1024)");
1623 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1624 tablepos += 184 - adapt_len - pointer_len;
1627 if (start && reading)
1629 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1632 unsigned int pos = 0;
1633 //while (pos < tablepos)
1636 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1638 unsigned char section_id = get_bits(&bb, 8);
1640 unsigned int section_len = get_bits(&bb, 12);
1641 get_bits(&bb, 16); // transport_id
1643 get_bits(&bb, 5); // version_num
1644 get_bits(&bb, 1); // current_next
1645 get_bits(&bb, 8); // section_num
1646 get_bits(&bb, 8); // last_section
1652 // Program Association Section
1653 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1654 section_len -= 4; // Ignore the CRC
1656 stream->ts_number_pat_entries = 0;
1657 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1659 unsigned int pkt_program_num = get_bits(&bb, 16);
1660 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1662 get_bits(&bb, 3); // Reserved
1663 if (pkt_program_num == 0)
1665 get_bits(&bb, 13); // pkt_network_id
1669 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1670 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1673 stream->ts_number_pat_entries++;
1687 pos += 3 + section_len;
1695 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1697 // align to first packet
1698 align_to_next_packet(stream);
1700 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1701 // to find the program map PID and then decode that to get the list of audio and video PIDs
1705 const uint8_t *buf = next_packet( stream );
1708 hb_log("hb_ts_stream_find_pids - end of file");
1713 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1715 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1717 decode_PAT(buf, stream);
1722 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1724 // There are some streams where the PAT table has multiple entries as if their are
1725 // multiple programs in the same transport stream, and yet there's actually only one
1726 // program really in the stream. This seems to be true for transport streams that
1727 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1728 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1729 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1730 // PAT info on export to match what's actually on the stream.
1731 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1732 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1733 // be to build a title choice popup from the PAT program number details and then select from
1734 // their - but right now the API's not capable of that.
1735 if (pid == stream->pat_info[pat_index].program_map_PID)
1737 if (build_program_map(buf, stream) > 0)
1741 // Keep going until we have a complete set of PIDs
1742 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1746 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1747 hb_log(" Video PIDS : ");
1749 for (i=0; i < stream->ts_number_video_pids; i++)
1751 hb_log( " 0x%x type %s (0x%x)",
1752 stream->ts_video_pids[i],
1753 stream_type_name(stream->ts_stream_type[i]),
1754 stream->ts_stream_type[i]);
1756 hb_log(" Audio PIDS : ");
1757 for (i = 0; i < stream->ts_number_audio_pids; i++)
1759 hb_log( " 0x%x type %s (0x%x)",
1760 stream->ts_audio_pids[i],
1761 stream_type_name(stream->ts_stream_type[i+1]),
1762 stream->ts_stream_type[i+1] );
1767 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1769 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1771 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1772 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1775 memcpy( stream->fwrite_buf, buf, size );
1776 stream->fwrite_buf += size;
1779 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1783 buf[0] = 0x00; // pack id
1788 buf[4] = 0x44 | // SCR
1789 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1790 ( ( time >> 28 ) & 3 );
1791 buf[5] = time >> 20;
1793 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1794 ( ( time >> 13 ) & 3 );
1796 buf[8] = 0x04 | ( time << 3 );
1798 buf[9] = 0x01; // SCR extension
1800 buf[10] = 384000 >> (22 - 8); // program mux rate
1801 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1802 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1804 buf[13] = 0xf8 | stuffing;
1807 for (i = 0; i < stuffing; ++i )
1810 fwrite64(stream, buf, 14 + stuffing );
1813 static void pad_buffer(hb_stream_t* stream, int pad)
1825 fwrite64(stream, buf, 6);
1828 while ( --pad >= 0 )
1830 fwrite64(stream, buf, 1);
1834 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1838 memset(buf, 0, sizeof(buf) );
1841 buf[4] = ( len + 3 ) >> 8;
1845 fwrite64(stream, buf, 9);
1848 static void generate_output_data(hb_stream_t *stream, int curstream)
1850 uint8_t *tdat = stream->ts_buf[curstream];
1853 // we always ship a PACK header plus all the data in our demux buf.
1854 // AC3 audio also always needs its substream header.
1855 len = 14 + stream->ts_pos[curstream];
1856 if ( stream->ts_stream_type[curstream] == 0x81)
1861 if ( ! stream->ts_start[curstream] )
1863 // we're in the middle of a chunk of PES data - we need to add
1864 // a 'continuation' PES header after the PACK header.
1868 // Write out pack header
1869 // If we don't have 2048 bytes we need to pad to 2048. We can
1870 // add a padding frame after our data but we need at least 7
1871 // bytes of space to do it (6 bytes of header & 1 of pad). If
1872 // we have fewer than 7 bytes left we need to fill the excess
1873 // space with stuffing bytes added to the pack header.
1875 if ( len > HB_DVD_READ_BUFFER_SIZE )
1877 hb_log( "stream ts length botch %d", len );
1879 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1881 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1883 write_pack(stream, stream->ts_nextpcr, stuffing );
1884 stream->ts_nextpcr += 10;
1886 if ( stream->ts_start[curstream] )
1888 // Start frames already have a PES header but we have modify it
1889 // to map from TS PID to PS stream id. Also, if the stream is AC3
1890 // audio we have to insert an AC3 stream header between the end of
1891 // the PES header and the start of the stream data.
1893 stream->ts_start[curstream] = 0;
1894 tdat[3] = stream->ts_streamid[curstream];
1896 uint16_t plen = stream->ts_pos[curstream] - 6;
1897 if ( stream->ts_stream_type[curstream] == 0x81)
1899 // We have to add an AC3 header in front of the data. Add its
1900 // size to the PES packet length.
1902 tdat[4] = plen >> 8;
1905 // Write out the PES header
1906 int hdrsize = 9 + tdat[8];
1907 fwrite64(stream, tdat, hdrsize);
1909 // add a four byte DVD ac3 stream header
1910 uint8_t ac3_substream_id[4];
1911 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1912 ac3_substream_id[0] = 0x80 | ssid; // substream id
1913 ac3_substream_id[1] = 0x01; // number of sync words
1914 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1915 ac3_substream_id[3] = 0x02;
1916 fwrite64(stream, ac3_substream_id, 4);
1918 // add the rest of the data
1919 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1923 // not audio - don't need to modify the stream so write what we've got
1924 tdat[4] = plen >> 8;
1926 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1931 // data without a PES start header needs a simple 'continuation'
1932 // PES header. AC3 audio also needs its substream header.
1933 if ( stream->ts_stream_type[curstream] != 0x81)
1935 make_pes_header(stream, stream->ts_pos[curstream],
1936 stream->ts_streamid[curstream]);
1940 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1941 stream->ts_streamid[curstream]);
1943 // add a four byte DVD ac3 stream header
1944 uint8_t ac3_substream_id[4];
1945 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1946 ac3_substream_id[0] = 0x80 | ssid; // substream id
1947 ac3_substream_id[1] = 0x01; // number of sync words
1948 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1949 ac3_substream_id[3] = 0x02;
1950 fwrite64(stream, ac3_substream_id, 4);
1952 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1956 int left = HB_DVD_READ_BUFFER_SIZE - len;
1959 pad_buffer(stream, left);
1962 stream->ts_pos[curstream] = 0;
1965 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1967 // For mpeg2: look for a gop start or i-frame picture start
1968 // for h.264: look for idr nal type or a slice header for an i-frame
1974 if ( stream->ts_stream_type[0] <= 2 )
1976 // This section of the code handles MPEG-1 and MPEG-2 video streams
1977 for (i = 13 + adapt_len; i < 188; i++)
1979 strid = (strid << 8) | buf[i];
1980 if ( ( strid >> 8 ) == 1 )
1982 // we found a start code
1986 case 0xB8: // group_start_code (GOP header)
1987 case 0xB3: // sequence_header code
1990 case 0x00: // picture_start_code
1991 // picture_header, let's see if it's an I-frame
1994 // check if picture_coding_type == 1
1995 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
1997 // found an I-frame picture
2005 // didn't find an I-frame
2008 if ( stream->ts_stream_type[0] == 0x1b )
2010 // we have an h.264 stream
2011 for (i = 13 + adapt_len; i < 188; i++)
2013 strid = (strid << 8) | buf[i];
2014 if ( ( strid >> 8 ) == 1 )
2016 // we found a start code - remove the ref_idc from the nal type
2017 uint8_t nal_type = strid & 0x1f;
2018 if ( nal_type == 0x05 )
2019 // h.264 IDR picture start
2022 if ( nal_type == 0x01 )
2024 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2025 uint8_t id = buf[i+1];
2026 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2027 id == 0x88 || id == 0x8a )
2034 // didn't find an I-frame
2038 // we don't understand the stream type so just say "yes" otherwise
2039 // we'll discard all the video.
2043 /***********************************************************************
2044 * hb_ts_stream_decode
2045 ***********************************************************************
2047 **********************************************************************/
2048 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2051 * stash the output buffer pointer in our stream so we don't have to
2052 * pass it & its original value to everything we call.
2054 stream->fwrite_buf = obuf;
2055 stream->fwrite_buf_orig = obuf;
2057 // spin until we get a packet of data from some stream or hit eof
2060 int64_t pcr = stream->ts_lastpcr;
2063 const uint8_t *buf = next_packet(stream);
2066 // end of file - we didn't finish filling our ps write buffer
2067 // so just discard the remainder (the partial buffer is useless)
2068 hb_log("hb_ts_stream_decode - eof");
2072 /* This next section validates the packet */
2074 // Get pid and use it to find stream state.
2075 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2076 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2080 int errorbit = (buf[1] & 0x80) != 0;
2083 ts_err( stream, curstream, "packet error bit set");
2087 // Get adaption header info
2088 int adaption = (buf[3] & 0x30) >> 4;
2092 ts_err( stream, curstream, "adaptation code 0");
2095 else if (adaption == 0x2)
2097 else if (adaption == 0x3)
2099 adapt_len = buf[4] + 1;
2100 if (adapt_len > 184)
2102 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2107 // if there's an adaptation header & PCR_flag is set
2108 // get the PCR (Program Clock Reference)
2109 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2111 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2112 ( (uint64_t)buf[7] << (33 - 16) ) |
2113 ( (uint64_t)buf[8] << (33 - 24) ) |
2114 ( (uint64_t)buf[9] << (33 - 32) ) |
2116 stream->ts_nextpcr = pcr;
2118 // remember the pcr across calls to this routine
2119 stream->ts_lastpcr = pcr;
2124 // don't accumulate data until we get a pcr
2129 // Continuity only increments for adaption values of 0x3 or 0x01
2130 // and is not checked for start packets.
2132 int start = (buf[1] & 0x40) != 0;
2134 if ( (adaption & 0x01) != 0 )
2136 int continuity = (buf[3] & 0xF);
2137 if ( continuity == stream->ts_streamcont[curstream] )
2139 // we got a duplicate packet (usually used to introduce
2140 // a PCR when one is needed). The only thing that can
2141 // change in the dup is the PCR which we grabbed above
2142 // so ignore the rest.
2145 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2146 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2148 ts_err( stream, curstream, "continuity error: got %d expected %d",
2150 (stream->ts_streamcont[curstream] + 1) & 0xf );
2151 stream->ts_streamcont[curstream] = continuity;
2154 stream->ts_streamcont[curstream] = continuity;
2157 /* If we get here the packet is valid - process its data */
2161 // Found a random access point (now we can start a frame/audio packet..)
2163 // If we were skipping a bad packet, start fresh on this new PES packet..
2164 if (stream->ts_skipbad[curstream] == 1)
2166 // video skips to an iframe after a bad packet to minimize
2167 // screen corruption
2168 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2172 stream->ts_skipbad[curstream] = 0;
2175 // If we don't have video yet, check to see if this is an
2176 // i_frame (group of picture start)
2177 if ( curstream == 0 )
2179 if ( !stream->ts_foundfirst[0] )
2181 if ( !isIframe( stream, buf, adapt_len ) )
2183 // didn't find an I frame
2186 stream->ts_foundfirst[0] = 1;
2190 else if ( ! stream->ts_foundfirst[curstream] )
2192 // start other streams only after first video frame found.
2193 if ( ! stream->ts_foundfirst[0] )
2197 stream->ts_foundfirst[curstream] = 1;
2200 // If we have some data already on this stream, turn it into
2201 // a program stream packet. Then add the payload for this
2202 // packet to the current pid's buffer.
2203 if ( stream->ts_pos[curstream] )
2205 generate_output_data(stream, curstream);
2206 stream->ts_start[curstream] = 1;
2207 memcpy(stream->ts_buf[curstream],
2208 buf + 4 + adapt_len, 184 - adapt_len);
2209 stream->ts_pos[curstream] = 184 - adapt_len;
2212 stream->ts_start[curstream] = 1;
2215 // Add the payload for this packet to the current buffer
2216 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2217 (184 - adapt_len) > 0)
2219 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2220 buf + 4 + adapt_len, 184 - adapt_len);
2221 stream->ts_pos[curstream] += 184 - adapt_len;
2223 // if the next TS packet could possibly overflow our 2K output buffer
2224 // we need to generate a packet now. Overflow would be 184 bytes of
2225 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2226 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2228 // we have enough data to make a PS packet
2229 generate_output_data(stream, curstream);
2236 static void hb_ts_stream_reset(hb_stream_t *stream)
2240 for (i=0; i < kMaxNumberDecodeStreams; i++)
2242 stream->ts_pos[i] = 0;
2243 stream->ts_foundfirst[i] = 0;
2244 stream->ts_skipbad[i] = 0;
2245 stream->ts_streamcont[i] = -1;
2246 stream->ts_start[i] = 0;
2249 stream->ts_lastpcr = -1;
2250 stream->ts_nextpcr = -1;
2254 stream->last_error_frame = -10000;
2255 stream->last_error_count = 0;
2257 align_to_next_packet(stream);
2260 // ------------------------------------------------------------------
2261 // Support for reading media files via the ffmpeg libraries.
2263 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2265 // add a codec to the context here so it will be there when we
2266 // read the first packet.
2267 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2268 context->workaround_bugs = FF_BUG_AUTODETECT;
2269 context->error_resilience = 1;
2270 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2271 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2272 avcodec_open( context, codec );
2275 // The ffmpeg stream reader / parser shares a lot of state with the
2276 // decoder via a codec context kept in the AVStream of the reader's
2277 // AVFormatContext. Since decoding is done in a different thread we
2278 // have to somehow pass this codec context to the decoder and we have
2279 // to do it before the first packet is read (so we can't put the info
2280 // in the buf we'll send downstream). Decoders don't have any way to
2281 // get to the stream directly (they're not passed the title or job
2282 // pointers during a scan) so this is a back door for the decoder to
2283 // get the codec context. We just stick the stream pointer in the next
2284 // slot an array of pointers maintained as a circular list then return
2285 // the index into the list combined with the ffmpeg stream index as the
2286 // codec_param that will be passed to the decoder init routine. We make
2287 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2288 // so that we don't have to do a complicated allocator or worry about
2289 // deleting entries on close.
2291 // Entries can only be added to this list during a scan and are never
2292 // deleted so the list access doesn't require locking.
2293 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2294 static int ffmpeg_stream_cur; // where we put the last stream pointer
2295 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2296 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2298 // add a stream to the list & return the appropriate codec_param to access it
2299 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2301 if ( !ffmpeg_streams )
2303 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2306 // the title scan adds all the ffmpeg media streams at once so we
2307 // only add a new entry to our stream list if the stream is different
2309 int slot = ffmpeg_stream_cur;
2310 if ( ffmpeg_streams[slot] != stream )
2312 // new stream - put it in the next slot of the stream list
2313 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2314 ffmpeg_streams[slot] = stream;
2317 ffmpeg_add_codec( stream, stream_index );
2319 return ( stream_index << ffmpeg_sl_bits ) | slot;
2322 // we're about to open 'title' to convert it - remap the stream associated
2323 // with the video & audio codec params of the title to refer to 'stream'
2324 // (the original scan stream was closed and no longer exists).
2325 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2327 // all the video & audio came from the same stream so remapping
2328 // the video's stream slot takes care of everything.
2329 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2330 ffmpeg_streams[slot] = stream;
2332 // add codecs for all the streams used by the title
2333 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2337 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2339 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2341 ffmpeg_add_codec( stream,
2342 audio->config.in.codec_param >> ffmpeg_sl_bits );
2347 void *hb_ffmpeg_context( int codec_param )
2349 int slot = codec_param & (ffmpeg_sl_size - 1);
2350 int stream_index = codec_param >> ffmpeg_sl_bits;
2351 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2354 void *hb_ffmpeg_avstream( int codec_param )
2356 int slot = codec_param & (ffmpeg_sl_size - 1);
2357 int stream_index = codec_param >> ffmpeg_sl_bits;
2358 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2361 static AVFormatContext *ffmpeg_deferred_close;
2363 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2365 if ( ffmpeg_deferred_close )
2367 av_close_input_file( ffmpeg_deferred_close );
2368 ffmpeg_deferred_close = NULL;
2370 AVFormatContext *ic;
2372 av_log_set_level( AV_LOG_ERROR );
2373 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2377 if ( av_find_stream_info( ic ) < 0 )
2380 stream->ffmpeg_ic = ic;
2381 stream->hb_stream_type = ffmpeg;
2385 // we're opening for read. scan passed out codec params that
2386 // indexed its stream so we need to remap them so they point
2388 ffmpeg_remap_stream( stream, title );
2389 ffmpeg_seek( stream, 0. );
2390 av_log_set_level( AV_LOG_ERROR );
2394 // we're opening for scan. let ffmpeg put some info into the
2395 // log about what we've got.
2396 av_log_set_level( AV_LOG_INFO );
2397 dump_format( ic, 0, stream->path, 0 );
2398 av_log_set_level( AV_LOG_ERROR );
2400 // accept this file if it has at least one video stream we can decode
2402 for (i = 0; i < ic->nb_streams; ++i )
2404 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2409 if ( i >= ic->nb_streams )
2415 av_close_input_file( ic );
2419 static void ffmpeg_close( hb_stream_t *d )
2421 // XXX since we're sharing the CodecContext with the downstream
2422 // decoder proc we can't close the stream. We need to reference count
2423 // this so we can close it when both are done with their instance but
2424 // for now just defer the close until the next stream open or close.
2425 if ( ffmpeg_deferred_close )
2427 av_close_input_file( ffmpeg_deferred_close );
2429 ffmpeg_deferred_close = d->ffmpeg_ic;
2432 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2434 AVStream *st = stream->ffmpeg_ic->streams[id];
2435 AVCodecContext *codec = st->codec;
2437 // scan will ignore any audio without a bitrate. Since we've already
2438 // typed the audio in order to determine its codec we set up the audio
2440 if ( codec->bit_rate || codec->sample_rate )
2442 static const int chan2layout[] = {
2443 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2444 HB_INPUT_CH_LAYOUT_MONO,
2445 HB_INPUT_CH_LAYOUT_STEREO,
2446 HB_INPUT_CH_LAYOUT_2F1R,
2447 HB_INPUT_CH_LAYOUT_2F2R,
2448 HB_INPUT_CH_LAYOUT_3F2R,
2449 HB_INPUT_CH_LAYOUT_4F2R,
2450 HB_INPUT_CH_LAYOUT_STEREO,
2451 HB_INPUT_CH_LAYOUT_STEREO,
2454 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2457 if ( codec->codec_id == CODEC_ID_AC3 )
2459 audio->config.in.codec = HB_ACODEC_AC3;
2463 audio->config.in.codec = HB_ACODEC_FFMPEG;
2464 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2466 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2467 audio->config.in.samplerate = codec->sample_rate;
2468 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2471 set_audio_description( audio, lang_for_code2( st->language ) );
2473 hb_list_add( title->list_audio, audio );
2477 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2479 AVFormatContext *ic = stream->ffmpeg_ic;
2481 // 'Barebones Title'
2482 hb_title_t *title = hb_title_init( stream->path, 0 );
2485 // Copy part of the stream path to the title name
2486 char *sep = strrchr(stream->path, '/');
2488 strcpy(title->name, sep+1);
2489 char *dot_term = strrchr(title->name, '.');
2493 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2494 title->duration = dur;
2496 title->hours = dur / 3600;
2497 title->minutes = ( dur % 3600 ) / 60;
2498 title->seconds = dur % 60;
2501 hb_chapter_t * chapter;
2502 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2504 chapter->duration = title->duration;
2505 chapter->hours = title->hours;
2506 chapter->minutes = title->minutes;
2507 chapter->seconds = title->seconds;
2508 hb_list_add( title->list_chapter, chapter );
2510 // set the title to decode the first video stream in the file
2511 title->demuxer = HB_NULL_DEMUXER;
2512 title->video_codec = 0;
2514 for (i = 0; i < ic->nb_streams; ++i )
2516 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2517 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2518 title->video_codec == 0 )
2520 title->video_id = i;
2522 // We have to use the 'internal' avcodec decoder because
2523 // it needs to share the codec context from this video
2524 // stream. The parser internal to av_read_frame
2525 // passes a bunch of state info to the decoder via the context.
2526 title->video_codec = WORK_DECAVCODECVI;
2527 title->video_codec_param = ffmpeg_codec_param( stream, i );
2529 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2530 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2532 add_ffmpeg_audio( title, stream, i );
2536 title->container_name = strdup( ic->iformat->name );
2537 title->data_rate = ic->bit_rate;
2542 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2544 if ( pts == AV_NOPTS_VALUE )
2546 return (int64_t)( (double)pts * conv_factor );
2549 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2553 if ( av_read_frame( stream->ffmpeg_ic, &pkt ) < 0 )
2557 if ( pkt.size > buf->alloc )
2559 // need to expand buffer
2560 hb_buffer_realloc( buf, pkt.size );
2562 memcpy( buf->data, pkt.data, pkt.size );
2563 buf->id = pkt.stream_index;
2564 buf->size = pkt.size;
2565 int64_t pts = pkt.pts != AV_NOPTS_VALUE? pkt.pts :
2566 pkt.dts != AV_NOPTS_VALUE? pkt.dts : -1;
2567 buf->start = av_to_hb_pts( pts,
2568 av_q2d(stream->ffmpeg_ic->streams[pkt.stream_index]->time_base)*90000. );
2569 buf->renderOffset = av_to_hb_pts( pkt.pts,
2570 av_q2d(stream->ffmpeg_ic->streams[pkt.stream_index]->time_base)*90000. );
2571 av_free_packet( &pkt );
2575 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2577 AVFormatContext *ic = stream->ffmpeg_ic;
2578 int64_t pos = (double)ic->duration * (double)frac;
2579 av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );