3 This file is part of the HandBrake source code.
4 Homepage: <http://handbrake.fr/>.
5 It may be used under the terms of the GNU General Public License. */
13 #include "a52dec/a52.h"
14 #include "libavcodec/avcodec.h"
15 #include "libavformat/avformat.h"
17 #define min(a, b) a < b ? a : b
20 * This table defines how ISO MPEG stream type codes map to HandBrake
21 * codecs. It is indexed by the 8 bit stream type and contains the codec
22 * worker object id and a parameter for that worker proc (ignored except
23 * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
25 * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
26 * doesn't handle the stream type.
29 enum { U, A, V } kind; /* unknown / audio / video */
30 int codec; /* HB worker object id of codec */
31 int codec_param; /* param for codec (usually ffmpeg codec id) */
32 const char* name; /* description of type */
33 int extra_hdr; /* needs a substream header added to PS pack */
36 #define st(id, kind, codec, codec_param, name) \
37 [id] = { kind, codec, codec_param, name, 0 }
38 #define se(id, kind, codec, codec_param, name) \
39 [id] = { kind, codec, codec_param, name, 1 }
41 static const stream2codec_t st2codec[256] = {
42 st(0x01, V, WORK_DECMPEG2, 0, "MPEG1"),
43 st(0x02, V, WORK_DECMPEG2, 0, "MPEG2"),
44 st(0x03, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG1"),
45 st(0x04, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG2"),
46 st(0x05, U, 0, 0, "ISO 13818-1 private section"),
47 st(0x06, U, 0, 0, "ISO 13818-1 PES private data"),
48 st(0x07, U, 0, 0, "ISO 13522 MHEG"),
49 st(0x08, U, 0, 0, "ISO 13818-1 DSM-CC"),
50 st(0x09, U, 0, 0, "ISO 13818-1 auxiliary"),
51 st(0x0a, U, 0, 0, "ISO 13818-6 encap"),
52 st(0x0b, U, 0, 0, "ISO 13818-6 DSM-CC U-N msgs"),
53 st(0x0c, U, 0, 0, "ISO 13818-6 Stream descriptors"),
54 st(0x0d, U, 0, 0, "ISO 13818-6 Sections"),
55 st(0x0e, U, 0, 0, "ISO 13818-1 auxiliary"),
56 st(0x0f, A, HB_ACODEC_MPGA, CODEC_ID_AAC, "ISO 13818-7 AAC Audio"),
57 st(0x10, V, WORK_DECAVCODECV, CODEC_ID_MPEG4, "MPEG4"),
58 st(0x11, A, HB_ACODEC_MPGA, CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
59 st(0x12, U, 0, 0, "MPEG4 generic"),
61 st(0x14, U, 0, 0, "ISO 13818-6 DSM-CC download"),
63 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
65 st(0x80, U, 0, 0, "DigiCipher II Video"),
66 se(0x81, A, HB_ACODEC_AC3, 0, "AC-3"),
67 se(0x82, A, HB_ACODEC_DCA, 0, "HDMV DTS"),
68 st(0x83, A, HB_ACODEC_LPCM, 0, "LPCM"),
69 st(0x84, A, 0, 0, "SDDS"),
70 st(0x85, U, 0, 0, "ATSC Program ID"),
71 st(0x86, U, 0, 0, "SCTE 35 splice info"),
72 st(0x87, A, 0, 0, "E-AC-3"),
74 se(0x8a, A, HB_ACODEC_DCA, 0, "DTS"),
76 se(0x91, A, HB_ACODEC_AC3, 0, "AC-3"),
77 st(0x92, U, 0, 0, "Subtitle"),
79 st(0x94, A, 0, 0, "SDDS"),
80 st(0xa0, V, 0, 0, "MSCODEC"),
82 st(0xea, V, WORK_DECAVCODECV, CODEC_ID_VC1, "VC1"),
87 hb_stream_type_unknown = 0,
94 #define kMaxNumberVideoPIDS 1
95 #define kMaxNumberAudioPIDS 15
96 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
97 #define kMaxNumberPMTStreams 32
102 int frames; /* video frames so far */
103 int errors; /* total errors so far */
104 int last_error_frame; /* frame # at last error message */
105 int last_error_count; /* # errors at last error message */
106 int packetsize; /* Transport Stream packet size */
108 int64_t ts_lastpcr; /* the last pcr we found in the TS stream */
109 int64_t ts_nextpcr; /* the next pcr to put in a PS packet */
111 uint8_t *ts_packet; /* buffer for one TS packet */
112 uint8_t *ts_buf[kMaxNumberDecodeStreams];
113 int ts_pos[kMaxNumberDecodeStreams];
114 int8_t ts_foundfirst[kMaxNumberDecodeStreams];
115 int8_t ts_skipbad[kMaxNumberDecodeStreams];
116 int8_t ts_streamcont[kMaxNumberDecodeStreams];
117 int8_t ts_start[kMaxNumberDecodeStreams];
119 uint8_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
120 uint8_t *fwrite_buf_orig; /* PS buffer start (set by hb_ts_stream_decode) */
123 * Stuff before this point is dynamic state updated as we read the
124 * stream. Stuff after this point is stream description state that
125 * we learn during the initial scan but cache so it can be
126 * reused during the conversion read.
128 uint8_t ts_number_video_pids;
129 uint8_t ts_number_audio_pids;
131 int16_t ts_video_pids[kMaxNumberVideoPIDS];
132 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
134 uint8_t ts_streamid[kMaxNumberDecodeStreams];
135 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
136 uint8_t ts_extra_hdr[kMaxNumberDecodeStreams];
140 hb_stream_type_t hb_stream_type;
143 AVFormatContext *ffmpeg_ic;
144 AVPacket *ffmpeg_pkt;
145 double ffmpeg_tsconv[MAX_STREAMS];
152 } a52_info[kMaxNumberAudioPIDS];
156 unsigned short program_number;
157 unsigned short program_map_PID;
158 } pat_info[kMaxNumberPMTStreams];
159 int ts_number_pat_entries;
164 unsigned char *tablebuf;
165 unsigned int tablepos;
166 unsigned char current_continuity_counter;
170 unsigned int PCR_PID;
171 int program_info_length;
172 unsigned char *progam_info_descriptor_data;
175 unsigned char stream_type;
176 unsigned short elementary_PID;
177 unsigned short ES_info_length;
178 unsigned char *es_info_descriptor_data;
179 } pmt_stream_info[kMaxNumberPMTStreams];
183 /***********************************************************************
185 **********************************************************************/
186 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
187 static void hb_ts_stream_init(hb_stream_t *stream);
188 static void hb_ts_stream_find_pids(hb_stream_t *stream);
189 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
190 static void hb_ts_stream_reset(hb_stream_t *stream);
191 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
193 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
194 static off_t align_to_next_packet(hb_stream_t *stream);
196 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
197 static void ffmpeg_close( hb_stream_t *d );
198 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
199 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
200 static int ffmpeg_seek( hb_stream_t *stream, float frac );
203 * streams have a bunch of state that's learned during the scan. We don't
204 * want to throw away the state when scan does a close then relearn
205 * everything when reader does an open. So we save the stream state on
206 * the close following a scan and reuse it when 'reader' does an open.
208 static hb_list_t *stream_state_list;
210 static hb_stream_t *hb_stream_lookup( const char *path )
212 if ( stream_state_list == NULL )
218 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
220 if ( strcmp( path, ss->path ) == 0 )
228 static void hb_stream_state_delete( hb_stream_t *ss )
230 hb_list_rem( stream_state_list, ss );
237 * these frontend hb_log because transport streams can have a lot of errors
238 * so we want to rate limit messages. this routine limits the number of
239 * messages to at most one per minute of video. other errors that occur
240 * during the minute are counted & the count is output with the next
241 * error msg we print.
243 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
245 // limit error printing to at most one per minute of video (at 30fps)
247 if ( stream->frames - stream->last_error_frame >= 30*60 )
251 vsnprintf( msg, sizeof(msg), log, args );
253 if ( stream->errors - stream->last_error_count < 10 )
255 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
259 int Edelta = stream->errors - stream->last_error_count;
260 double Epcnt = (double)Edelta * 100. /
261 (stream->frames - stream->last_error_frame);
262 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
263 Edelta, Epcnt, stream->frames, msg );
265 stream->last_error_frame = stream->frames;
266 stream->last_error_count = stream->errors;
270 static void ts_warn( hb_stream_t *stream, char *log, ... )
273 va_start( args, log );
274 ts_warn_helper( stream, log, args );
278 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
281 va_start( args, log );
282 ts_warn_helper( stream, log, args );
285 stream->ts_skipbad[curstream] = 1;
286 stream->ts_pos[curstream] = 0;
287 stream->ts_streamcont[curstream] = -1;
290 static int check_ps_sync(const uint8_t *buf)
292 // a legal MPEG program stream must start with a Pack header in the
294 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
295 (buf[2] == 0x01) && (buf[3] == 0xba);
298 static int check_ps_sys(const uint8_t *buf)
300 // a legal MPEG program stream must start with a Pack followed by a
301 // SYS. If we've already verified the pack, this skips over it and checks
302 // for the sys header.
303 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
304 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
305 (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
308 static int check_ts_sync(const uint8_t *buf)
310 // must have initial sync byte, no scrambling & a legal adaptation ctrl
311 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
314 static int have_ts_sync(const uint8_t *buf, int psize)
316 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
317 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
318 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
319 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
322 static int hb_stream_check_for_ts(const uint8_t *buf)
324 // transport streams should have a sync byte every 188 bytes.
325 // search the first 8KB of buf looking for at least 8 consecutive
326 // correctly located sync patterns.
329 for ( offset = 0; offset < 8*1024-8*188; ++offset )
331 if ( have_ts_sync( &buf[offset], 188) )
332 return 188 | (offset << 8);
333 if ( have_ts_sync( &buf[offset], 192) )
334 return 192 | (offset << 8);
335 if ( have_ts_sync( &buf[offset], 204) )
336 return 204 | (offset << 8);
337 if ( have_ts_sync( &buf[offset], 208) )
338 return 208 | (offset << 8);
343 static int hb_stream_check_for_ps(const uint8_t *buf)
345 // program streams should start with a PACK then a SYS header.
346 return check_ps_sync(buf) && check_ps_sys(buf);
349 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
351 // DVD program streams should have a Pack header every 2048 bytes.
352 // check that we have 4 of these in a row.
353 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
354 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
357 static int hb_stream_get_type(hb_stream_t *stream)
361 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
364 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
366 int offset = psize >> 8;
368 hb_log("file is MPEG Transport Stream with %d byte packets"
369 " offset %d bytes", psize, offset);
370 stream->packetsize = psize;
371 stream->hb_stream_type = transport;
372 hb_ts_stream_init(stream);
375 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
377 hb_log("file is MPEG DVD Program Stream");
378 stream->hb_stream_type = dvd_program;
381 if ( hb_stream_check_for_ps(buf) != 0 )
383 hb_log("file is MPEG Program Stream");
384 stream->hb_stream_type = program;
391 static void hb_stream_delete_dynamic( hb_stream_t *d )
395 fclose( d->file_handle );
396 d->file_handle = NULL;
403 free( d->ts_packet );
406 for (i = 0; i < kMaxNumberDecodeStreams; i++)
416 static void hb_stream_delete( hb_stream_t *d )
418 hb_stream_delete_dynamic( d );
423 /***********************************************************************
425 ***********************************************************************
427 **********************************************************************/
428 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
430 FILE *f = fopen( path, "r" );
433 hb_log( "hb_stream_open: open %s failed", path );
437 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
441 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
446 * if we're opening the stream to read & convert, we need
447 * the state we saved when we scanned the stream. if we're
448 * opening the stream to scan it we want to rebuild the state
449 * (even if we have saved state, the stream may have changed).
451 hb_stream_t *ss = hb_stream_lookup( path );
452 if ( title && ss && ss->hb_stream_type != ffmpeg )
455 * copy the saved state since we might be encoding the same stream
458 memcpy( d, ss, sizeof(*d) );
461 d->path = strdup( path );
463 if ( d->hb_stream_type == transport )
465 d->ts_packet = malloc( d->packetsize );
468 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
470 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
472 hb_stream_seek( d, 0. );
474 if ( d->packetsize == 188 )
476 // Assume that an over-the-air transport stream can lose PCR
477 // packets and try to filter out the timing inconsistencies.
478 title->flaky_clock = 1;
485 * opening for scan - delete any saved state then (re)scan the stream.
486 * If it's something we can deal with (MPEG2 PS or TS) return a stream
487 * reference structure & null otherwise.
491 hb_stream_state_delete( ss );
495 d->path = strdup( path );
496 if (d->path != NULL )
498 if ( hb_stream_get_type( d ) != 0 )
502 fclose( d->file_handle );
503 d->file_handle = NULL;
504 if ( ffmpeg_open( d, title ) )
509 if ( d->file_handle )
511 fclose( d->file_handle );
517 hb_log( "hb_stream_open: open %s failed", path );
522 /***********************************************************************
524 ***********************************************************************
525 * Closes and frees everything
526 **********************************************************************/
527 void hb_stream_close( hb_stream_t ** _d )
529 hb_stream_t *stream = * _d;
531 if ( stream->hb_stream_type == ffmpeg )
533 ffmpeg_close( stream );
534 hb_stream_delete( stream );
539 if ( stream->frames )
541 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
542 stream->errors, (double)stream->errors * 100. /
543 (double)stream->frames );
547 * if the stream was opened for a scan, cache the result, otherwise delete
550 if ( stream->title == NULL )
552 hb_stream_delete_dynamic( stream );
553 if ( stream_state_list == NULL )
555 stream_state_list = hb_list_init();
557 hb_list_add( stream_state_list, stream );
561 hb_stream_delete( stream );
566 /* when the file was first opened we made entries for all the audio elementary
567 * streams we found in it. Streams that were later found during the preview scan
568 * now have an audio codec, type, rate, etc., associated with them. At the end
569 * of the scan we delete all the audio entries that weren't found by the scan
570 * or don't have a format we support. This routine deletes audio entry 'indx'
571 * by copying all later entries down one slot. */
572 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
576 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
578 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
579 stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
580 stream->ts_extra_hdr[1 + indx] = stream->ts_extra_hdr[1+i];
581 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
584 --stream->ts_number_audio_pids;
587 static int index_of_pid(int pid, hb_stream_t *stream)
591 if ( pid == stream->ts_video_pids[0] )
594 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
595 if ( pid == stream->ts_audio_pids[i] )
601 /***********************************************************************
602 * hb_ps_stream_title_scan
603 ***********************************************************************
605 **********************************************************************/
606 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
608 if ( stream->hb_stream_type == ffmpeg )
609 return ffmpeg_title_scan( stream );
612 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
615 // Copy part of the stream path to the title name
616 char *sep = strrchr(stream->path, '/');
618 strcpy(aTitle->name, sep+1);
619 char *dot_term = strrchr(aTitle->name, '.');
623 // Height, width, rate and aspect ratio information is filled in when the previews are built
625 hb_stream_duration(stream, aTitle);
628 hb_chapter_t * chapter;
629 chapter = calloc( sizeof( hb_chapter_t ), 1 );
631 chapter->duration = aTitle->duration;
632 chapter->hours = aTitle->hours;
633 chapter->minutes = aTitle->minutes;
634 chapter->seconds = aTitle->seconds;
635 hb_list_add( aTitle->list_chapter, chapter );
637 // Figure out how many audio streams we really have:
638 // - For transport streams, for each PID listed in the PMT (whether
639 // or not it was an audio stream type) read the bitstream until we
640 // find an packet from that PID containing a PES header and see if
641 // the elementary stream is an audio type.
642 // - For program streams read the first 4MB and take every unique
643 // audio stream we find.
644 if (stream->hb_stream_type == transport)
648 for (i=0; i < stream->ts_number_audio_pids; i++)
650 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
651 if (audio->config.in.codec)
652 hb_list_add( aTitle->list_audio, audio );
656 hb_stream_delete_audio_entry(stream, i);
661 // add the PCR PID if we don't already have it
662 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
664 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
665 stream->pmt_info.PCR_PID;
668 // set up the video codec to use for this title
669 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
670 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
674 hb_ps_stream_find_audio_ids(stream, aTitle);
681 * read the next transport stream packet from 'stream'. Return NULL if
682 * we hit eof & a pointer to the sync byte otherwise.
684 static const uint8_t *next_packet( hb_stream_t *stream )
686 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
690 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
699 // lost sync - back up to where we started then try to re-establish.
700 off_t pos = ftello(stream->file_handle) - stream->packetsize;
701 off_t pos2 = align_to_next_packet(stream);
704 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
707 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
713 * skip to the start of the next PACK header in program stream src_stream.
715 static void skip_to_next_pack( hb_stream_t *src_stream )
717 // scan forward until we find the start of the next pack
718 uint32_t strt_code = -1;
721 flockfile( src_stream->file_handle );
722 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
724 strt_code = ( strt_code << 8 ) | c;
725 if ( strt_code == 0x000001ba )
726 // we found the start of the next pack
729 funlockfile( src_stream->file_handle );
731 // if we didn't terminate on an eof back up so the next read
732 // starts on the pack boundary.
735 fseeko( src_stream->file_handle, -4, SEEK_CUR );
740 * scan the next MB of 'stream' to find the next start packet for
741 * the Packetized Elementary Stream associated with TS PID 'pid'.
743 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
745 int npack = 300000; // max packets to read
749 const uint8_t *buf = next_packet( stream );
752 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
757 * The PES header is only in TS packets with 'start' set so we check
758 * that first then check for the right PID.
760 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
761 buf[2] != (pid & 0xff))
763 // not a start packet or not the pid we want
767 /* skip over the TS hdr to return a pointer to the PES hdr */
769 switch (buf[3] & 0x30)
771 case 0x00: // illegal
772 case 0x20: // fill packet
775 case 0x30: // adaptation
778 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
784 /* PES hdr has to begin with an mpeg start code */
785 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
795 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
797 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
798 hb_list_t *list = hb_list_init();
799 // how many blocks we read while searching for a video PES header
803 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
807 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
808 hb_demux_ps( buf, list, 0 );
810 while ( ( es = hb_list_item( list, 0 ) ) )
812 hb_list_rem( list, es );
813 if ( es->id == 0xe0 )
815 // this PES contains video - if there's a PTS we're done
816 // hb_demux_ps left the PTS in buf_es->start.
817 if ( es->start != ~0 )
824 hb_buffer_close( &es );
827 hb_list_empty( &list );
828 hb_buffer_close(&buf);
832 /***********************************************************************
834 ***********************************************************************
836 * Finding stream duration is difficult. One issue is that the video file
837 * may have chunks from several different program fragments (main feature,
838 * commercials, station id, trailers, etc.) all with their own base pts
839 * value. We can't find the piece boundaries without reading the entire
840 * file but if we compute a rate based on time stamps from two different
841 * pieces the result will be meaningless. The second issue is that the
842 * data rate of compressed video normally varies by 5-10x over the length
843 * of the video. This says that we want to compute the rate over relatively
844 * long segments to get a representative average but long segments increase
845 * the likelihood that we'll cross a piece boundary.
847 * What we do is take time stamp samples at several places in the file
848 * (currently 16) then compute the average rate (i.e., ticks of video per
849 * byte of the file) for all pairs of samples (N^2 rates computed for N
850 * samples). Some of those rates will be absurd because the samples came
851 * from different segments. Some will be way low or high because the
852 * samples came from a low or high motion part of the segment. But given
853 * that we're comparing *all* pairs the majority of the computed rates
854 * should be near the overall average. So we median filter the computed
855 * rates to pick the most representative value.
857 **********************************************************************/
859 uint64_t pos; /* file position of this PTS sample */
860 uint64_t pts; /* PTS from video stream */
863 #define NDURSAMPLES 16
865 // get one (position, timestamp) sampple from a transport or program
867 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
869 struct pts_pos pp = { 0, 0 };
871 if ( stream->hb_stream_type == transport )
874 fseeko( stream->file_handle, fpos, SEEK_SET );
875 align_to_next_packet( stream );
876 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
879 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
882 if ( ( buf[7] >> 7 ) != 1 )
884 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
887 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
888 ( (uint64_t)buf[10] << 22 ) |
889 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
890 ( (uint64_t)buf[12] << 7 ) |
891 ( (uint64_t)buf[13] >> 1 );
895 // round address down to nearest dvd sector start
896 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
897 fseeko( stream->file_handle, fpos, SEEK_SET );
898 if ( stream->hb_stream_type == program )
900 skip_to_next_pack( stream );
902 pp.pts = hb_ps_stream_getVideoPTS( stream );
904 pp.pos = ftello(stream->file_handle);
908 static int dur_compare( const void *a, const void *b )
910 const double *aval = a, *bval = b;
911 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
914 // given an array of (position, time) samples, compute a max-likelihood
915 // estimate of the average rate by computing the rate between all pairs
916 // of samples then taking the median of those rates.
917 static double compute_stream_rate( struct pts_pos *pp, int n )
920 double rates[NDURSAMPLES * NDURSAMPLES / 2];
923 // the following nested loops compute the rates between all pairs.
925 for ( i = 0; i < n-1; ++i )
927 // Bias the median filter by not including pairs that are "far"
928 // from one another. This is to handle cases where the file is
929 // made of roughly equal size pieces where a symmetric choice of
930 // pairs results in having the same number of intra-piece &
931 // inter-piece rate estimates. This would mean that the median
932 // could easily fall in the inter-piece part of the data which
933 // would give a bogus estimate. The 'ns' index creates an
934 // asymmetry that favors locality.
935 int ns = i + ( n >> 1 );
938 for ( j = i+1; j < ns; ++j )
940 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
942 *rp = ((double)( pp[j].pts - pp[i].pts )) /
943 ((double)( pp[j].pos - pp[i].pos ));
948 // now compute and return the median of all the (n*n/2) rates we computed
950 int nrates = rp - rates;
951 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
952 return rates[nrates >> 1];
955 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
957 struct pts_pos ptspos[NDURSAMPLES];
958 struct pts_pos *pp = ptspos;
961 fseeko(stream->file_handle, 0, SEEK_END);
962 uint64_t fsize = ftello(stream->file_handle);
963 uint64_t fincr = fsize / NDURSAMPLES;
964 uint64_t fpos = fincr / 2;
965 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
967 *pp++ = hb_sample_pts(stream, fpos);
969 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
970 inTitle->duration = dur;
972 inTitle->hours = dur / 3600;
973 inTitle->minutes = ( dur % 3600 ) / 60;
974 inTitle->seconds = dur % 60;
976 rewind(stream->file_handle);
979 /***********************************************************************
981 ***********************************************************************
983 **********************************************************************/
984 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
986 if ( src_stream->hb_stream_type == ffmpeg )
988 return ffmpeg_read( src_stream, b );
990 if ( src_stream->hb_stream_type == dvd_program )
992 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
993 src_stream->file_handle);
994 return (amt_read > 0);
996 if ( src_stream->hb_stream_type == program )
998 // a general program stream has arbitrary sized pack's. we're
999 // currently positioned at the start of a pack so read up to but
1000 // not including the start of the next, expanding the buffer
1002 uint8_t *cp = b->data;
1003 uint8_t *ep = cp + b->alloc;
1004 uint32_t strt_code = -1;
1007 // consume the first byte of the initial pack so we don't match on
1008 // it in the loop below.
1009 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1014 flockfile( src_stream->file_handle );
1015 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1017 strt_code = ( strt_code << 8 ) | c;
1018 if ( strt_code == 0x000001ba )
1019 // we found the start of the next pack
1023 // need to expand the buffer
1024 int curSize = cp - b->data;
1025 hb_buffer_realloc( b, curSize * 2 );
1026 cp = b->data + curSize;
1027 ep = b->data + b->alloc;
1031 funlockfile( src_stream->file_handle );
1033 // if we didn't terminate on an eof back up so the next read
1034 // starts on the pack boundary.
1035 b->size = cp - b->data;
1038 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1043 return hb_ts_stream_decode( src_stream, b->data );
1046 /***********************************************************************
1048 ***********************************************************************
1050 **********************************************************************/
1051 int hb_stream_seek( hb_stream_t * src_stream, float f )
1053 if ( src_stream->hb_stream_type == ffmpeg )
1055 return ffmpeg_seek( src_stream, f );
1057 off_t stream_size, cur_pos, new_pos;
1058 double pos_ratio = f;
1059 cur_pos = ftello( src_stream->file_handle );
1060 fseeko( src_stream->file_handle, 0, SEEK_END );
1061 stream_size = ftello( src_stream->file_handle );
1062 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1063 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1065 int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1068 fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1072 if ( src_stream->hb_stream_type == transport )
1074 // We need to drop the current decoder output and move
1075 // forwards to the next transport stream packet.
1076 hb_ts_stream_reset(src_stream);
1078 else if ( src_stream->hb_stream_type == program )
1080 skip_to_next_pack( src_stream );
1086 static const char* make_upper( const char* s )
1088 static char name[8];
1090 char *ep = cp + sizeof(name)-1;
1092 while ( *s && cp < ep )
1094 *cp++ = islower(*s)? toupper(*s) : *s;
1101 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1104 * This is a duplicate of code in dvd.c - it should get factored out
1105 * into a common routine. We probably should only be putting the lang
1106 * code or a lang pointer into the audio config & let the common description
1107 * formatting routine in scan.c do all the stuff below.
1109 const char *codec_name;
1112 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1113 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1114 avcodec_find_decoder( cc->codec_id ) )
1116 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1117 if ( !strcmp( codec_name, "LIBFAAD" ) )
1122 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1123 avcodec_find_decoder( audio->config.in.codec_param ) )
1125 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1129 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1130 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1131 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1132 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1133 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1136 snprintf( audio->config.lang.description,
1137 sizeof( audio->config.lang.description ), "%s (%s)",
1138 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1140 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1141 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1142 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1143 "%s", lang->iso639_2);
1146 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1149 off_t cur_pos = ftello(stream->file_handle);
1150 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1153 fseeko(stream->file_handle, 0, SEEK_SET);
1154 align_to_next_packet(stream);
1155 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1157 /* check that we found a PES header */
1159 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1161 // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1162 // extended stream id (ISO 13818-1(2007)). If we cared about the
1163 // real id we'd have to look inside the PES extension to find it.
1164 // But since we remap stream id's when we generate PS packets from
1165 // the TS packets we can just ignore the actual id.
1166 if ( buf[3] == 0xbd || buf[3] == 0xfd )
1168 audio->id = 0x80bd | (aud_pid_index << 8);
1169 stype = stream->ts_stream_type[1 + aud_pid_index];
1170 if ( st2codec[stype].kind == U )
1172 // XXX assume unknown stream types are AC-3 (if they're not
1173 // audio we'll find that out during the scan but if they're
1174 // some other type of audio we'll end up ignoring them).
1176 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1178 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1180 else if ((buf[3] & 0xe0) == 0xc0)
1182 audio->id = 0xc0 | aud_pid_index;
1183 stype = stream->ts_stream_type[1 + aud_pid_index];
1184 if ( st2codec[stype].kind == U )
1186 // XXX assume unknown stream types are MPEG audio
1188 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1192 // if we found an audio stream type & HB has a codec that can decode it
1193 // finish configuring the audio so we'll add it to the title's list.
1194 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1196 stream->ts_streamid[1 + aud_pid_index] = audio->id;
1197 stream->ts_extra_hdr[1 + aud_pid_index] = st2codec[stype].extra_hdr;
1198 audio->config.in.codec = st2codec[stype].codec;
1199 audio->config.in.codec_param = st2codec[stype].codec_param;
1200 set_audio_description( audio,
1201 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1202 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1203 stream->ts_audio_pids[aud_pid_index],
1204 stype, st2codec[stype].name, audio->id);
1210 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1211 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1212 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1216 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1217 stream->ts_audio_pids[aud_pid_index],
1218 stream->ts_stream_type[1 + aud_pid_index]);
1221 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1225 static void add_audio_to_title(hb_title_t *title, int id)
1227 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1233 audio->config.in.codec = HB_ACODEC_MPGA;
1234 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1237 // type 2 is a DVD subtitle stream - just ignore it */
1241 audio->config.in.codec = HB_ACODEC_AC3;
1242 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1245 audio->config.in.codec = HB_ACODEC_LPCM;
1246 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1249 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1254 set_audio_description( audio, lang_for_code( 0 ) );
1255 hb_list_add( title->list_audio, audio );
1258 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1260 off_t cur_pos = ftello(stream->file_handle);
1261 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1262 hb_list_t *list = hb_list_init();
1263 // how many blocks we read while searching for audio streams
1264 int blksleft = 4096;
1265 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1266 // so we use a bitmap to keep track of the ones we've already seen.
1267 // Bit 'i' of smap is set if we've already added the audio for
1268 // audio substream id 'i' to the title's audio list.
1271 // start looking 20% into the file since there's occasionally no
1272 // audio at the beginning (particularly for vobs).
1273 hb_stream_seek(stream, 0.2f);
1275 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1279 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1280 hb_demux_ps( buf, list, 0 );
1282 while ( ( es = hb_list_item( list, 0 ) ) )
1284 hb_list_rem( list, es );
1285 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1287 // this PES contains some kind of audio - get the substream id
1288 // and check if we've seen it already.
1289 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1290 if ( (smap & (1 << ssid)) == 0 )
1292 // we haven't seen this stream before - add it to the
1293 // title's list of audio streams.
1294 smap |= (1 << ssid);
1295 add_audio_to_title(title, es->id);
1298 hb_buffer_close( &es );
1301 hb_list_empty( &list );
1302 hb_buffer_close(&buf);
1303 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1306 /***********************************************************************
1308 ***********************************************************************
1310 **********************************************************************/
1312 static void hb_ts_stream_init(hb_stream_t *stream)
1316 for (i=0; i < kMaxNumberDecodeStreams; i++)
1318 stream->ts_streamcont[i] = -1;
1320 stream->ts_video_pids[0] = -1;
1321 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1323 stream-> ts_audio_pids[i] = -1;
1326 stream->ts_packet = malloc( stream->packetsize );
1328 // Find the audio and video pids in the stream
1329 hb_ts_stream_find_pids(stream);
1331 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1333 // demuxing buffer for TS to PS conversion
1334 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1337 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
1340 #define MAX_HOLE 208*80
1342 static off_t align_to_next_packet(hb_stream_t *stream)
1344 uint8_t buf[MAX_HOLE];
1346 off_t start = ftello(stream->file_handle);
1348 if ( start >= stream->packetsize ) {
1349 start -= stream->packetsize;
1350 fseeko(stream->file_handle, start, SEEK_SET);
1353 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1355 const uint8_t *bp = buf;
1358 for ( i = sizeof(buf); --i >= 0; ++bp )
1360 if ( have_ts_sync( bp, stream->packetsize ) )
1367 pos = ( bp - buf ) - stream->packetsize + 188;
1372 fseeko(stream->file_handle, start+pos, SEEK_SET);
1383 static const unsigned int bitmask[] = {
1384 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1385 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1386 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1387 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1389 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1393 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1394 (bb->buf[2] << 8) | bb->buf[3];
1396 memset(bb->buf, 0, bufsize);
1399 static inline int buf_size(bitbuf_t *bb)
1401 return bb->pos >> 3;
1404 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1407 int left = 32 - (bb->pos & 31);
1411 val = (bb->val >> (left - bits)) & bitmask[bits];
1416 val = (bb->val & bitmask[left]) << (bits - left);
1420 int pos = bb->pos >> 3;
1421 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1425 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1433 // extract what useful information we can from the elementary stream
1434 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1435 // Descriptors with info we don't currently use are ignored.
1436 // The descriptor list & descriptor item formats are defined in
1437 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1438 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1439 const uint8_t *dp, uint8_t dlen)
1441 const uint8_t *ep = dp + dlen;
1447 case 10: // ISO_639_language descriptor
1448 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1458 static const char *stream_type_name (uint8_t stream_type)
1460 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1463 int decode_program_map(hb_stream_t* stream)
1466 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1468 get_bits(&bb, 8); // table_id
1470 unsigned int section_length = get_bits(&bb, 12);
1471 stream->pmt_info.section_length = section_length;
1473 unsigned int program_number = get_bits(&bb, 16);
1474 stream->pmt_info.program_number = program_number;
1476 get_bits(&bb, 5); // version_number
1478 get_bits(&bb, 8); // section_number
1479 get_bits(&bb, 8); // last_section_number
1481 unsigned int PCR_PID = get_bits(&bb, 13);
1482 stream->pmt_info.PCR_PID = PCR_PID;
1484 unsigned int program_info_length = get_bits(&bb, 12);
1485 stream->pmt_info.program_info_length = program_info_length;
1488 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1489 for (i = 0; i < program_info_length; i++)
1491 descriptor_buf[i] = get_bits(&bb, 8);
1494 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1495 int done_reading_stream_types = 0;
1496 while (!done_reading_stream_types)
1498 unsigned char stream_type = get_bits(&bb, 8);
1500 unsigned int elementary_PID = get_bits(&bb, 13);
1502 unsigned int ES_info_length = get_bits(&bb, 12);
1505 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1506 for (i=0; i < ES_info_length; i++)
1508 ES_info_buf[i] = get_bits(&bb, 8);
1512 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1514 stream->ts_video_pids[0] = elementary_PID;
1515 stream->ts_stream_type[0] = stream_type;
1516 stream->ts_number_video_pids = 1;
1520 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1521 // for mpeg audio. But content producers seem to use other
1522 // values (0x04 and 0x06 have both been observed) so at this point
1523 // we say everything that isn't a video pid is audio then at the end
1524 // of hb_stream_title_scan we'll figure out which are really audio
1525 // by looking at the PES headers.
1526 i = stream->ts_number_audio_pids;
1527 if (i < kMaxNumberAudioPIDS)
1529 stream->ts_audio_pids[i] = elementary_PID;
1530 stream->ts_stream_type[1 + i] = stream_type;
1531 if (ES_info_length > 0)
1533 decode_element_descriptors(stream, i, ES_info_buf,
1536 ++stream->ts_number_audio_pids;
1540 cur_pos += 5 /* stream header */ + ES_info_length;
1544 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1545 done_reading_stream_types = 1;
1548 free(descriptor_buf);
1552 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1554 // Get adaption header info
1556 int adaption = (buf[3] & 0x30) >> 4;
1559 else if (adaption == 0x2)
1561 else if (adaption == 0x3)
1562 adapt_len = buf[4] + 1;
1563 if (adapt_len > 184)
1566 // Get payload start indicator
1568 start = (buf[1] & 0x40) != 0;
1570 // Get pointer length - only valid in packets with a start flag
1571 int pointer_len = 0;
1572 if (start && stream->pmt_info.reading)
1574 // We just finished a bunch of packets - parse the program map details
1576 if (stream->pmt_info.tablebuf[0] == 0x02)
1577 decode_ok = decode_program_map(stream);
1578 free(stream->pmt_info.tablebuf);
1579 stream->pmt_info.tablebuf = NULL;
1580 stream->pmt_info.tablepos = 0;
1581 stream->pmt_info.reading = 0;
1588 pointer_len = buf[4 + adapt_len] + 1;
1589 stream->pmt_info.tablepos = 0;
1591 // Get Continuity Counter
1592 int continuity_counter = buf[3] & 0x0f;
1593 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1595 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1598 stream->pmt_info.current_continuity_counter = continuity_counter;
1599 stream->pmt_info.reading |= start;
1601 // Add the payload for this packet to the current buffer
1602 int amount_to_copy = 184 - adapt_len - pointer_len;
1603 if (stream->pmt_info.reading && (amount_to_copy > 0))
1605 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1607 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1608 stream->pmt_info.tablepos += amount_to_copy;
1614 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1616 unsigned char tablebuf[1024];
1617 unsigned int tablepos = 0;
1622 // Get adaption header info
1624 int adaption = (buf[3] & 0x30) >> 4;
1627 else if (adaption == 0x2)
1629 else if (adaption == 0x3)
1630 adapt_len = buf[4] + 1;
1631 if (adapt_len > 184)
1634 // Get pointer length
1635 int pointer_len = buf[4 + adapt_len] + 1;
1637 // Get payload start indicator
1639 start = (buf[1] & 0x40) != 0;
1644 // Add the payload for this packet to the current buffer
1645 if (reading && (184 - adapt_len) > 0)
1647 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1649 hb_log("decode_PAT - Bad program section length (> 1024)");
1652 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1653 tablepos += 184 - adapt_len - pointer_len;
1656 if (start && reading)
1658 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1661 unsigned int pos = 0;
1662 //while (pos < tablepos)
1665 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1667 unsigned char section_id = get_bits(&bb, 8);
1669 unsigned int section_len = get_bits(&bb, 12);
1670 get_bits(&bb, 16); // transport_id
1672 get_bits(&bb, 5); // version_num
1673 get_bits(&bb, 1); // current_next
1674 get_bits(&bb, 8); // section_num
1675 get_bits(&bb, 8); // last_section
1681 // Program Association Section
1682 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1683 section_len -= 4; // Ignore the CRC
1685 stream->ts_number_pat_entries = 0;
1686 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1688 unsigned int pkt_program_num = get_bits(&bb, 16);
1689 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1691 get_bits(&bb, 3); // Reserved
1692 if (pkt_program_num == 0)
1694 get_bits(&bb, 13); // pkt_network_id
1698 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1699 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1702 stream->ts_number_pat_entries++;
1716 pos += 3 + section_len;
1724 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1726 // align to first packet
1727 align_to_next_packet(stream);
1729 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1730 // to find the program map PID and then decode that to get the list of audio and video PIDs
1734 const uint8_t *buf = next_packet( stream );
1737 hb_log("hb_ts_stream_find_pids - end of file");
1742 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1744 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1746 decode_PAT(buf, stream);
1751 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1753 // There are some streams where the PAT table has multiple entries as if their are
1754 // multiple programs in the same transport stream, and yet there's actually only one
1755 // program really in the stream. This seems to be true for transport streams that
1756 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1757 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1758 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1759 // PAT info on export to match what's actually on the stream.
1760 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1761 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1762 // be to build a title choice popup from the PAT program number details and then select from
1763 // their - but right now the API's not capable of that.
1764 if (pid == stream->pat_info[pat_index].program_map_PID)
1766 if (build_program_map(buf, stream) > 0)
1770 // Keep going until we have a complete set of PIDs
1771 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1775 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1776 hb_log(" Video PIDS : ");
1778 for (i=0; i < stream->ts_number_video_pids; i++)
1780 hb_log( " 0x%x type %s (0x%x)",
1781 stream->ts_video_pids[i],
1782 stream_type_name(stream->ts_stream_type[i]),
1783 stream->ts_stream_type[i]);
1785 hb_log(" Audio PIDS : ");
1786 for (i = 0; i < stream->ts_number_audio_pids; i++)
1788 hb_log( " 0x%x type %s (0x%x)",
1789 stream->ts_audio_pids[i],
1790 stream_type_name(stream->ts_stream_type[i+1]),
1791 stream->ts_stream_type[i+1] );
1796 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1798 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1800 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1801 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1804 memcpy( stream->fwrite_buf, buf, size );
1805 stream->fwrite_buf += size;
1808 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1812 buf[0] = 0x00; // pack id
1817 buf[4] = 0x44 | // SCR
1818 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1819 ( ( time >> 28 ) & 3 );
1820 buf[5] = time >> 20;
1822 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1823 ( ( time >> 13 ) & 3 );
1825 buf[8] = 0x04 | ( time << 3 );
1827 buf[9] = 0x01; // SCR extension
1829 buf[10] = 384000 >> (22 - 8); // program mux rate
1830 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1831 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1833 buf[13] = 0xf8 | stuffing;
1836 for (i = 0; i < stuffing; ++i )
1839 fwrite64(stream, buf, 14 + stuffing );
1842 static void pad_buffer(hb_stream_t* stream, int pad)
1854 fwrite64(stream, buf, 6);
1857 while ( --pad >= 0 )
1859 fwrite64(stream, buf, 1);
1863 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1867 memset(buf, 0, sizeof(buf) );
1870 buf[4] = ( len + 3 ) >> 8;
1874 fwrite64(stream, buf, 9);
1877 static void generate_output_data(hb_stream_t *stream, int curstream)
1879 uint8_t *tdat = stream->ts_buf[curstream];
1882 // we always ship a PACK header plus all the data in our demux buf.
1883 // AC3 audio also always needs its substream header.
1884 len = 14 + stream->ts_pos[curstream];
1885 if ( stream->ts_extra_hdr[curstream] )
1890 if ( ! stream->ts_start[curstream] )
1892 // we're in the middle of a chunk of PES data - we need to add
1893 // a 'continuation' PES header after the PACK header.
1897 // Write out pack header
1898 // If we don't have 2048 bytes we need to pad to 2048. We can
1899 // add a padding frame after our data but we need at least 7
1900 // bytes of space to do it (6 bytes of header & 1 of pad). If
1901 // we have fewer than 7 bytes left we need to fill the excess
1902 // space with stuffing bytes added to the pack header.
1904 if ( len > HB_DVD_READ_BUFFER_SIZE )
1906 hb_log( "stream ts length botch %d", len );
1908 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1910 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1912 write_pack(stream, stream->ts_nextpcr, stuffing );
1913 stream->ts_nextpcr += 10;
1915 if ( stream->ts_start[curstream] )
1917 // Start frames already have a PES header but we have modify it
1918 // to map from TS PID to PS stream id. Also, if the stream is AC3
1919 // audio we have to insert an AC3 stream header between the end of
1920 // the PES header and the start of the stream data.
1922 stream->ts_start[curstream] = 0;
1923 tdat[3] = stream->ts_streamid[curstream];
1925 uint16_t plen = stream->ts_pos[curstream] - 6;
1926 if ( stream->ts_extra_hdr[curstream] )
1928 // We have to add an AC3 header in front of the data. Add its
1929 // size to the PES packet length.
1931 tdat[4] = plen >> 8;
1934 // Write out the PES header
1935 int hdrsize = 9 + tdat[8];
1936 fwrite64(stream, tdat, hdrsize);
1938 // add a four byte DVD ac3 stream header
1939 uint8_t ac3_substream_id[4];
1940 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1941 ac3_substream_id[0] = 0x80 | ssid; // substream id
1942 ac3_substream_id[1] = 0x01; // number of sync words
1943 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1944 ac3_substream_id[3] = 0x02;
1945 fwrite64(stream, ac3_substream_id, 4);
1947 // add the rest of the data
1948 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1952 // not audio - don't need to modify the stream so write what we've got
1953 tdat[4] = plen >> 8;
1955 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1960 // data without a PES start header needs a simple 'continuation'
1961 // PES header. AC3 audio also needs its substream header.
1962 if ( stream->ts_extra_hdr[curstream] == 0 )
1964 make_pes_header(stream, stream->ts_pos[curstream],
1965 stream->ts_streamid[curstream]);
1969 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1970 stream->ts_streamid[curstream]);
1972 // add a four byte DVD ac3 stream header
1973 uint8_t ac3_substream_id[4];
1974 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1975 ac3_substream_id[0] = 0x80 | ssid; // substream id
1976 ac3_substream_id[1] = 0x01; // number of sync words
1977 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1978 ac3_substream_id[3] = 0x02;
1979 fwrite64(stream, ac3_substream_id, 4);
1981 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1985 int left = HB_DVD_READ_BUFFER_SIZE - len;
1988 pad_buffer(stream, left);
1991 stream->ts_pos[curstream] = 0;
1994 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1996 // For mpeg2: look for a gop start or i-frame picture start
1997 // for h.264: look for idr nal type or a slice header for an i-frame
2003 if ( stream->ts_stream_type[0] <= 2 )
2005 // This section of the code handles MPEG-1 and MPEG-2 video streams
2006 for (i = 13 + adapt_len; i < 188; i++)
2008 strid = (strid << 8) | buf[i];
2009 if ( ( strid >> 8 ) == 1 )
2011 // we found a start code
2015 case 0xB8: // group_start_code (GOP header)
2016 case 0xB3: // sequence_header code
2019 case 0x00: // picture_start_code
2020 // picture_header, let's see if it's an I-frame
2023 // check if picture_coding_type == 1
2024 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2026 // found an I-frame picture
2034 // didn't find an I-frame
2037 if ( stream->ts_stream_type[0] == 0x1b )
2039 // we have an h.264 stream
2040 for (i = 13 + adapt_len; i < 188; i++)
2042 strid = (strid << 8) | buf[i];
2043 if ( ( strid >> 8 ) == 1 )
2045 // we found a start code - remove the ref_idc from the nal type
2046 uint8_t nal_type = strid & 0x1f;
2047 if ( nal_type == 0x05 )
2048 // h.264 IDR picture start
2051 if ( nal_type == 0x01 )
2053 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2054 uint8_t id = buf[i+1];
2055 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2056 id == 0x88 || id == 0x8a )
2063 // didn't find an I-frame
2067 // we don't understand the stream type so just say "yes" otherwise
2068 // we'll discard all the video.
2072 /***********************************************************************
2073 * hb_ts_stream_decode
2074 ***********************************************************************
2076 **********************************************************************/
2077 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2080 * stash the output buffer pointer in our stream so we don't have to
2081 * pass it & its original value to everything we call.
2083 stream->fwrite_buf = obuf;
2084 stream->fwrite_buf_orig = obuf;
2086 // spin until we get a packet of data from some stream or hit eof
2089 int64_t pcr = stream->ts_lastpcr;
2092 const uint8_t *buf = next_packet(stream);
2095 // end of file - we didn't finish filling our ps write buffer
2096 // so just discard the remainder (the partial buffer is useless)
2097 hb_log("hb_ts_stream_decode - eof");
2101 /* This next section validates the packet */
2103 // Get pid and use it to find stream state.
2104 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2105 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2109 int errorbit = (buf[1] & 0x80) != 0;
2112 ts_err( stream, curstream, "packet error bit set");
2116 // Get adaption header info
2117 int adaption = (buf[3] & 0x30) >> 4;
2121 ts_err( stream, curstream, "adaptation code 0");
2124 else if (adaption == 0x2)
2126 else if (adaption == 0x3)
2128 adapt_len = buf[4] + 1;
2129 if (adapt_len > 184)
2131 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2136 // if there's an adaptation header & PCR_flag is set
2137 // get the PCR (Program Clock Reference)
2138 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2140 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2141 ( (uint64_t)buf[7] << (33 - 16) ) |
2142 ( (uint64_t)buf[8] << (33 - 24) ) |
2143 ( (uint64_t)buf[9] << (33 - 32) ) |
2145 stream->ts_nextpcr = pcr;
2147 // remember the pcr across calls to this routine
2148 stream->ts_lastpcr = pcr;
2151 // If we don't have a pcr yet, the right thing to do here would
2152 // be a 'continue' so we don't process anything until we have a
2153 // clock reference. Unfortunately the HD Home Run appears to null
2154 // out the pcr field of some streams so we keep going & substitute
2155 // the video stream dts for the pcr when there's no pcr.
2158 // Continuity only increments for adaption values of 0x3 or 0x01
2159 // and is not checked for start packets.
2161 int start = (buf[1] & 0x40) != 0;
2163 if ( (adaption & 0x01) != 0 )
2165 int continuity = (buf[3] & 0xF);
2166 if ( continuity == stream->ts_streamcont[curstream] )
2168 // we got a duplicate packet (usually used to introduce
2169 // a PCR when one is needed). The only thing that can
2170 // change in the dup is the PCR which we grabbed above
2171 // so ignore the rest.
2174 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2175 stream->ts_foundfirst[curstream] &&
2176 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2178 ts_err( stream, curstream, "continuity error: got %d expected %d",
2180 (stream->ts_streamcont[curstream] + 1) & 0xf );
2181 stream->ts_streamcont[curstream] = continuity;
2184 stream->ts_streamcont[curstream] = continuity;
2187 /* If we get here the packet is valid - process its data */
2191 // Found a random access point (now we can start a frame/audio packet..)
2193 // If we were skipping a bad packet, start fresh on this new PES packet..
2194 if (stream->ts_skipbad[curstream] == 1)
2196 // video skips to an iframe after a bad packet to minimize
2197 // screen corruption
2198 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2202 stream->ts_skipbad[curstream] = 0;
2205 // If we don't have video yet, check to see if this is an
2206 // i_frame (group of picture start)
2207 if ( curstream == 0 )
2209 if ( !stream->ts_foundfirst[0] )
2211 if ( !isIframe( stream, buf, adapt_len ) )
2213 // didn't find an I frame
2216 stream->ts_foundfirst[0] = 1;
2220 // if we don't have a pcr yet use the dts from this frame
2223 // PES must begin with an mpeg start code & contain
2225 const uint8_t *pes = buf + adapt_len + 4;
2226 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2227 ( pes[7] >> 6 ) == 0 )
2231 // if we have a dts use it otherwise use the pts
2232 pes += (pes[7] & 0x40)? 14 : 9;
2234 pcr = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2235 pcr |= ( pes[1] << 22 ) |
2236 ( ( pes[2] >> 1 ) << 15 ) |
2239 stream->ts_nextpcr = pcr;
2242 else if ( ! stream->ts_foundfirst[curstream] )
2244 // start other streams only after first video frame found.
2245 if ( ! stream->ts_foundfirst[0] )
2249 stream->ts_foundfirst[curstream] = 1;
2252 // If we have some data already on this stream, turn it into
2253 // a program stream packet. Then add the payload for this
2254 // packet to the current pid's buffer.
2255 if ( stream->ts_pos[curstream] )
2257 generate_output_data(stream, curstream);
2258 stream->ts_start[curstream] = 1;
2259 memcpy(stream->ts_buf[curstream],
2260 buf + 4 + adapt_len, 184 - adapt_len);
2261 stream->ts_pos[curstream] = 184 - adapt_len;
2264 stream->ts_start[curstream] = 1;
2267 // Add the payload for this packet to the current buffer
2268 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2269 (184 - adapt_len) > 0)
2271 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2272 buf + 4 + adapt_len, 184 - adapt_len);
2273 stream->ts_pos[curstream] += 184 - adapt_len;
2275 // if the next TS packet could possibly overflow our 2K output buffer
2276 // we need to generate a packet now. Overflow would be 184 bytes of
2277 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2278 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2280 // we have enough data to make a PS packet
2281 generate_output_data(stream, curstream);
2288 static void hb_ts_stream_reset(hb_stream_t *stream)
2292 for (i=0; i < kMaxNumberDecodeStreams; i++)
2294 stream->ts_pos[i] = 0;
2295 stream->ts_foundfirst[i] = 0;
2296 stream->ts_skipbad[i] = 0;
2297 stream->ts_streamcont[i] = -1;
2298 stream->ts_start[i] = 0;
2301 stream->ts_lastpcr = -1;
2302 stream->ts_nextpcr = -1;
2306 stream->last_error_frame = -10000;
2307 stream->last_error_count = 0;
2309 align_to_next_packet(stream);
2312 // ------------------------------------------------------------------
2313 // Support for reading media files via the ffmpeg libraries.
2315 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2317 // add a codec to the context here so it will be there when we
2318 // read the first packet.
2319 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2320 context->workaround_bugs = FF_BUG_AUTODETECT;
2321 context->error_recognition = 1;
2322 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2323 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2324 avcodec_open( context, codec );
2327 // The ffmpeg stream reader / parser shares a lot of state with the
2328 // decoder via a codec context kept in the AVStream of the reader's
2329 // AVFormatContext. Since decoding is done in a different thread we
2330 // have to somehow pass this codec context to the decoder and we have
2331 // to do it before the first packet is read (so we can't put the info
2332 // in the buf we'll send downstream). Decoders don't have any way to
2333 // get to the stream directly (they're not passed the title or job
2334 // pointers during a scan) so this is a back door for the decoder to
2335 // get the codec context. We just stick the stream pointer in the next
2336 // slot an array of pointers maintained as a circular list then return
2337 // the index into the list combined with the ffmpeg stream index as the
2338 // codec_param that will be passed to the decoder init routine. We make
2339 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2340 // so that we don't have to do a complicated allocator or worry about
2341 // deleting entries on close.
2343 // Entries can only be added to this list during a scan and are never
2344 // deleted so the list access doesn't require locking.
2345 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2346 static int ffmpeg_stream_cur; // where we put the last stream pointer
2347 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2348 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2350 // add a stream to the list & return the appropriate codec_param to access it
2351 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2353 if ( !ffmpeg_streams )
2355 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2358 // the title scan adds all the ffmpeg media streams at once so we
2359 // only add a new entry to our stream list if the stream is different
2361 int slot = ffmpeg_stream_cur;
2362 if ( ffmpeg_streams[slot] != stream )
2364 // new stream - put it in the next slot of the stream list
2365 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2366 ffmpeg_streams[slot] = stream;
2369 ffmpeg_add_codec( stream, stream_index );
2371 return ( stream_index << ffmpeg_sl_bits ) | slot;
2374 // we're about to open 'title' to convert it - remap the stream associated
2375 // with the video & audio codec params of the title to refer to 'stream'
2376 // (the original scan stream was closed and no longer exists).
2377 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2379 // tell ffmpeg we want a pts on every frame it returns
2380 stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2382 // all the video & audio came from the same stream so remapping
2383 // the video's stream slot takes care of everything.
2384 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2385 ffmpeg_streams[slot] = stream;
2387 // add codecs for all the streams used by the title
2388 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2392 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2394 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2396 ffmpeg_add_codec( stream,
2397 audio->config.in.codec_param >> ffmpeg_sl_bits );
2402 void *hb_ffmpeg_context( int codec_param )
2404 int slot = codec_param & (ffmpeg_sl_size - 1);
2405 int stream_index = codec_param >> ffmpeg_sl_bits;
2406 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2409 void *hb_ffmpeg_avstream( int codec_param )
2411 int slot = codec_param & (ffmpeg_sl_size - 1);
2412 int stream_index = codec_param >> ffmpeg_sl_bits;
2413 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2416 static AVFormatContext *ffmpeg_deferred_close;
2418 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2420 if ( ffmpeg_deferred_close )
2422 av_close_input_file( ffmpeg_deferred_close );
2423 ffmpeg_deferred_close = NULL;
2425 AVFormatContext *ic;
2427 av_log_set_level( AV_LOG_ERROR );
2428 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2432 if ( av_find_stream_info( ic ) < 0 )
2435 stream->ffmpeg_ic = ic;
2436 stream->hb_stream_type = ffmpeg;
2437 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2438 av_init_packet( stream->ffmpeg_pkt );
2442 // we're opening for read. scan passed out codec params that
2443 // indexed its stream so we need to remap them so they point
2445 ffmpeg_remap_stream( stream, title );
2446 ffmpeg_seek( stream, 0. );
2447 av_log_set_level( AV_LOG_ERROR );
2451 // we're opening for scan. let ffmpeg put some info into the
2452 // log about what we've got.
2453 av_log_set_level( AV_LOG_INFO );
2454 dump_format( ic, 0, stream->path, 0 );
2455 av_log_set_level( AV_LOG_ERROR );
2457 // accept this file if it has at least one video stream we can decode
2459 for (i = 0; i < ic->nb_streams; ++i )
2461 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2466 if ( i >= ic->nb_streams )
2472 av_close_input_file( ic );
2476 static void ffmpeg_close( hb_stream_t *d )
2478 // XXX since we're sharing the CodecContext with the downstream
2479 // decoder proc we can't close the stream. We need to reference count
2480 // this so we can close it when both are done with their instance but
2481 // for now just defer the close until the next stream open or close.
2482 if ( ffmpeg_deferred_close )
2484 av_close_input_file( ffmpeg_deferred_close );
2486 ffmpeg_deferred_close = d->ffmpeg_ic;
2487 if ( d->ffmpeg_pkt != NULL )
2489 free( d->ffmpeg_pkt );
2490 d->ffmpeg_pkt = NULL;
2494 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2496 AVStream *st = stream->ffmpeg_ic->streams[id];
2497 AVCodecContext *codec = st->codec;
2499 // scan will ignore any audio without a bitrate. Since we've already
2500 // typed the audio in order to determine its codec we set up the audio
2502 if ( codec->bit_rate || codec->sample_rate )
2504 static const int chan2layout[] = {
2505 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2506 HB_INPUT_CH_LAYOUT_MONO,
2507 HB_INPUT_CH_LAYOUT_STEREO,
2508 HB_INPUT_CH_LAYOUT_2F1R,
2509 HB_INPUT_CH_LAYOUT_2F2R,
2510 HB_INPUT_CH_LAYOUT_3F2R,
2511 HB_INPUT_CH_LAYOUT_4F2R,
2512 HB_INPUT_CH_LAYOUT_STEREO,
2513 HB_INPUT_CH_LAYOUT_STEREO,
2516 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2519 if ( codec->codec_id == CODEC_ID_AC3 )
2521 audio->config.in.codec = HB_ACODEC_AC3;
2523 else if ( codec->codec_id == CODEC_ID_DTS )
2525 audio->config.in.codec = HB_ACODEC_DCA;
2529 audio->config.in.codec = HB_ACODEC_FFMPEG;
2530 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2532 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2533 audio->config.in.samplerate = codec->sample_rate;
2534 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2537 set_audio_description( audio, lang_for_code2( st->language ) );
2539 hb_list_add( title->list_audio, audio );
2543 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2545 AVFormatContext *ic = stream->ffmpeg_ic;
2547 // 'Barebones Title'
2548 hb_title_t *title = hb_title_init( stream->path, 0 );
2551 // Copy part of the stream path to the title name
2552 char *sep = strrchr(stream->path, '/');
2554 strcpy(title->name, sep+1);
2555 char *dot_term = strrchr(title->name, '.');
2559 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2560 title->duration = dur;
2562 title->hours = dur / 3600;
2563 title->minutes = ( dur % 3600 ) / 60;
2564 title->seconds = dur % 60;
2567 hb_chapter_t * chapter;
2568 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2570 chapter->duration = title->duration;
2571 chapter->hours = title->hours;
2572 chapter->minutes = title->minutes;
2573 chapter->seconds = title->seconds;
2574 hb_list_add( title->list_chapter, chapter );
2576 // set the title to decode the first video stream in the file
2577 title->demuxer = HB_NULL_DEMUXER;
2578 title->video_codec = 0;
2580 for (i = 0; i < ic->nb_streams; ++i )
2582 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2583 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2584 title->video_codec == 0 )
2586 title->video_id = i;
2588 // We have to use the 'internal' avcodec decoder because
2589 // it needs to share the codec context from this video
2590 // stream. The parser internal to av_read_frame
2591 // passes a bunch of state info to the decoder via the context.
2592 title->video_codec = WORK_DECAVCODECVI;
2593 title->video_codec_param = ffmpeg_codec_param( stream, i );
2595 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2596 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2598 add_ffmpeg_audio( title, stream, i );
2602 title->container_name = strdup( ic->iformat->name );
2603 title->data_rate = ic->bit_rate;
2608 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2610 if ( pts == AV_NOPTS_VALUE )
2612 return (int64_t)( (double)pts * conv_factor );
2615 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2618 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2620 // XXX the following conditional is to handle avi files that
2621 // use M$ 'packed b-frames' and occasionally have negative
2622 // sizes for the null frames these require.
2623 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2627 if ( stream->ffmpeg_pkt->size <= 0 )
2629 // M$ "invalid and inefficient" packed b-frames require 'null frames'
2630 // following them to preserve the timing (since the packing puts two
2631 // or more frames in what looks like one avi frame). The contents and
2632 // size of these null frames are ignored by the ff_h263_decode_frame
2633 // as long as they're < 20 bytes. We need a positive size so we use
2634 // one byte if we're given a zero or negative size. We don't know
2635 // if the pkt data points anywhere reasonable so we just stick a
2636 // byte of zero in our outbound buf.
2642 if ( stream->ffmpeg_pkt->size > buf->alloc )
2644 // need to expand buffer
2645 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2647 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2648 buf->size = stream->ffmpeg_pkt->size;
2650 buf->id = stream->ffmpeg_pkt->stream_index;
2652 // if we haven't done it already, compute a conversion factor to go
2653 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2654 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2657 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2658 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2659 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2662 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2663 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2664 if ( buf->renderOffset >= 0 && buf->start == -1 )
2666 buf->start = buf->renderOffset;
2668 av_free_packet( stream->ffmpeg_pkt );
2672 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2674 AVFormatContext *ic = stream->ffmpeg_ic;
2675 int64_t pos = (double)ic->duration * (double)frac;
2676 av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );