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);
373 if ( !stream->ts_number_video_pids || !stream->ts_number_audio_pids )
379 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
381 hb_log("file is MPEG DVD Program Stream");
382 stream->hb_stream_type = dvd_program;
385 if ( hb_stream_check_for_ps(buf) != 0 )
387 hb_log("file is MPEG Program Stream");
388 stream->hb_stream_type = program;
395 static void hb_stream_delete_dynamic( hb_stream_t *d )
399 fclose( d->file_handle );
400 d->file_handle = NULL;
407 free( d->ts_packet );
410 for (i = 0; i < kMaxNumberDecodeStreams; i++)
420 static void hb_stream_delete( hb_stream_t *d )
422 hb_stream_delete_dynamic( d );
427 /***********************************************************************
429 ***********************************************************************
431 **********************************************************************/
432 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
434 FILE *f = fopen( path, "r" );
437 hb_log( "hb_stream_open: open %s failed", path );
441 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
445 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
450 * if we're opening the stream to read & convert, we need
451 * the state we saved when we scanned the stream. if we're
452 * opening the stream to scan it we want to rebuild the state
453 * (even if we have saved state, the stream may have changed).
455 hb_stream_t *ss = hb_stream_lookup( path );
456 if ( title && ss && ss->hb_stream_type != ffmpeg )
459 * copy the saved state since we might be encoding the same stream
462 memcpy( d, ss, sizeof(*d) );
465 d->path = strdup( path );
467 if ( d->hb_stream_type == transport )
469 d->ts_packet = malloc( d->packetsize );
472 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
474 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
476 hb_stream_seek( d, 0. );
478 if ( d->packetsize == 188 )
480 // Assume that an over-the-air transport stream can lose PCR
481 // packets and try to filter out the timing inconsistencies.
482 title->flaky_clock = 1;
489 * opening for scan - delete any saved state then (re)scan the stream.
490 * If it's something we can deal with (MPEG2 PS or TS) return a stream
491 * reference structure & null otherwise.
495 hb_stream_state_delete( ss );
499 d->path = strdup( path );
500 if (d->path != NULL )
502 if ( hb_stream_get_type( d ) != 0 )
506 fclose( d->file_handle );
507 d->file_handle = NULL;
508 if ( ffmpeg_open( d, title ) )
513 if ( d->file_handle )
515 fclose( d->file_handle );
521 hb_log( "hb_stream_open: open %s failed", path );
526 /***********************************************************************
528 ***********************************************************************
529 * Closes and frees everything
530 **********************************************************************/
531 void hb_stream_close( hb_stream_t ** _d )
533 hb_stream_t *stream = * _d;
535 if ( stream->hb_stream_type == ffmpeg )
537 ffmpeg_close( stream );
538 hb_stream_delete( stream );
543 if ( stream->frames )
545 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
546 stream->errors, (double)stream->errors * 100. /
547 (double)stream->frames );
551 * if the stream was opened for a scan, cache the result, otherwise delete
554 if ( stream->title == NULL )
556 hb_stream_delete_dynamic( stream );
557 if ( stream_state_list == NULL )
559 stream_state_list = hb_list_init();
561 hb_list_add( stream_state_list, stream );
565 hb_stream_delete( stream );
570 /* when the file was first opened we made entries for all the audio elementary
571 * streams we found in it. Streams that were later found during the preview scan
572 * now have an audio codec, type, rate, etc., associated with them. At the end
573 * of the scan we delete all the audio entries that weren't found by the scan
574 * or don't have a format we support. This routine deletes audio entry 'indx'
575 * by copying all later entries down one slot. */
576 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
580 for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
582 stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
583 stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
584 stream->ts_extra_hdr[1 + indx] = stream->ts_extra_hdr[1+i];
585 stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
588 --stream->ts_number_audio_pids;
591 static int index_of_pid(int pid, hb_stream_t *stream)
595 if ( pid == stream->ts_video_pids[0] )
598 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
599 if ( pid == stream->ts_audio_pids[i] )
605 /***********************************************************************
606 * hb_ps_stream_title_scan
607 ***********************************************************************
609 **********************************************************************/
610 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
612 if ( stream->hb_stream_type == ffmpeg )
613 return ffmpeg_title_scan( stream );
616 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
619 // Copy part of the stream path to the title name
620 char *sep = strrchr(stream->path, '/');
622 strcpy(aTitle->name, sep+1);
623 char *dot_term = strrchr(aTitle->name, '.');
627 // Height, width, rate and aspect ratio information is filled in when the previews are built
629 hb_stream_duration(stream, aTitle);
632 hb_chapter_t * chapter;
633 chapter = calloc( sizeof( hb_chapter_t ), 1 );
635 chapter->duration = aTitle->duration;
636 chapter->hours = aTitle->hours;
637 chapter->minutes = aTitle->minutes;
638 chapter->seconds = aTitle->seconds;
639 hb_list_add( aTitle->list_chapter, chapter );
641 // Figure out how many audio streams we really have:
642 // - For transport streams, for each PID listed in the PMT (whether
643 // or not it was an audio stream type) read the bitstream until we
644 // find an packet from that PID containing a PES header and see if
645 // the elementary stream is an audio type.
646 // - For program streams read the first 4MB and take every unique
647 // audio stream we find.
648 if (stream->hb_stream_type == transport)
652 for (i=0; i < stream->ts_number_audio_pids; i++)
654 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
655 if (audio->config.in.codec)
656 hb_list_add( aTitle->list_audio, audio );
660 hb_stream_delete_audio_entry(stream, i);
665 // add the PCR PID if we don't already have it
666 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
668 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
669 stream->pmt_info.PCR_PID;
672 // set up the video codec to use for this title
673 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
674 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
678 hb_ps_stream_find_audio_ids(stream, aTitle);
685 * read the next transport stream packet from 'stream'. Return NULL if
686 * we hit eof & a pointer to the sync byte otherwise.
688 static const uint8_t *next_packet( hb_stream_t *stream )
690 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
694 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
703 // lost sync - back up to where we started then try to re-establish.
704 off_t pos = ftello(stream->file_handle) - stream->packetsize;
705 off_t pos2 = align_to_next_packet(stream);
708 hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
711 ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
717 * skip to the start of the next PACK header in program stream src_stream.
719 static void skip_to_next_pack( hb_stream_t *src_stream )
721 // scan forward until we find the start of the next pack
722 uint32_t strt_code = -1;
725 flockfile( src_stream->file_handle );
726 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
728 strt_code = ( strt_code << 8 ) | c;
729 if ( strt_code == 0x000001ba )
730 // we found the start of the next pack
733 funlockfile( src_stream->file_handle );
735 // if we didn't terminate on an eof back up so the next read
736 // starts on the pack boundary.
739 fseeko( src_stream->file_handle, -4, SEEK_CUR );
744 * scan the next MB of 'stream' to find the next start packet for
745 * the Packetized Elementary Stream associated with TS PID 'pid'.
747 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
749 int npack = 300000; // max packets to read
753 const uint8_t *buf = next_packet( stream );
756 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
761 * The PES header is only in TS packets with 'start' set so we check
762 * that first then check for the right PID.
764 if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
765 buf[2] != (pid & 0xff))
767 // not a start packet or not the pid we want
771 /* skip over the TS hdr to return a pointer to the PES hdr */
773 switch (buf[3] & 0x30)
775 case 0x00: // illegal
776 case 0x20: // fill packet
779 case 0x30: // adaptation
782 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
788 /* PES hdr has to begin with an mpeg start code */
789 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
799 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
801 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
802 hb_list_t *list = hb_list_init();
803 // how many blocks we read while searching for a video PES header
807 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
811 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
812 hb_demux_ps( buf, list, 0 );
814 while ( ( es = hb_list_item( list, 0 ) ) )
816 hb_list_rem( list, es );
817 if ( es->id == 0xe0 )
819 // this PES contains video - if there's a PTS we're done
820 // hb_demux_ps left the PTS in buf_es->start.
821 if ( es->start != ~0 )
828 hb_buffer_close( &es );
831 hb_list_empty( &list );
832 hb_buffer_close(&buf);
836 /***********************************************************************
838 ***********************************************************************
840 * Finding stream duration is difficult. One issue is that the video file
841 * may have chunks from several different program fragments (main feature,
842 * commercials, station id, trailers, etc.) all with their own base pts
843 * value. We can't find the piece boundaries without reading the entire
844 * file but if we compute a rate based on time stamps from two different
845 * pieces the result will be meaningless. The second issue is that the
846 * data rate of compressed video normally varies by 5-10x over the length
847 * of the video. This says that we want to compute the rate over relatively
848 * long segments to get a representative average but long segments increase
849 * the likelihood that we'll cross a piece boundary.
851 * What we do is take time stamp samples at several places in the file
852 * (currently 16) then compute the average rate (i.e., ticks of video per
853 * byte of the file) for all pairs of samples (N^2 rates computed for N
854 * samples). Some of those rates will be absurd because the samples came
855 * from different segments. Some will be way low or high because the
856 * samples came from a low or high motion part of the segment. But given
857 * that we're comparing *all* pairs the majority of the computed rates
858 * should be near the overall average. So we median filter the computed
859 * rates to pick the most representative value.
861 **********************************************************************/
863 uint64_t pos; /* file position of this PTS sample */
864 uint64_t pts; /* PTS from video stream */
867 #define NDURSAMPLES 16
869 // get one (position, timestamp) sampple from a transport or program
871 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
873 struct pts_pos pp = { 0, 0 };
875 if ( stream->hb_stream_type == transport )
878 fseeko( stream->file_handle, fpos, SEEK_SET );
879 align_to_next_packet( stream );
880 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
883 hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
886 if ( ( buf[7] >> 7 ) != 1 )
888 hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
891 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
892 ( (uint64_t)buf[10] << 22 ) |
893 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
894 ( (uint64_t)buf[12] << 7 ) |
895 ( (uint64_t)buf[13] >> 1 );
899 // round address down to nearest dvd sector start
900 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
901 fseeko( stream->file_handle, fpos, SEEK_SET );
902 if ( stream->hb_stream_type == program )
904 skip_to_next_pack( stream );
906 pp.pts = hb_ps_stream_getVideoPTS( stream );
908 pp.pos = ftello(stream->file_handle);
912 static int dur_compare( const void *a, const void *b )
914 const double *aval = a, *bval = b;
915 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
918 // given an array of (position, time) samples, compute a max-likelihood
919 // estimate of the average rate by computing the rate between all pairs
920 // of samples then taking the median of those rates.
921 static double compute_stream_rate( struct pts_pos *pp, int n )
924 double rates[NDURSAMPLES * NDURSAMPLES / 2];
927 // the following nested loops compute the rates between all pairs.
929 for ( i = 0; i < n-1; ++i )
931 // Bias the median filter by not including pairs that are "far"
932 // from one another. This is to handle cases where the file is
933 // made of roughly equal size pieces where a symmetric choice of
934 // pairs results in having the same number of intra-piece &
935 // inter-piece rate estimates. This would mean that the median
936 // could easily fall in the inter-piece part of the data which
937 // would give a bogus estimate. The 'ns' index creates an
938 // asymmetry that favors locality.
939 int ns = i + ( n >> 1 );
942 for ( j = i+1; j < ns; ++j )
944 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
946 *rp = ((double)( pp[j].pts - pp[i].pts )) /
947 ((double)( pp[j].pos - pp[i].pos ));
952 // now compute and return the median of all the (n*n/2) rates we computed
954 int nrates = rp - rates;
955 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
956 return rates[nrates >> 1];
959 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
961 struct pts_pos ptspos[NDURSAMPLES];
962 struct pts_pos *pp = ptspos;
965 fseeko(stream->file_handle, 0, SEEK_END);
966 uint64_t fsize = ftello(stream->file_handle);
967 uint64_t fincr = fsize / NDURSAMPLES;
968 uint64_t fpos = fincr / 2;
969 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
971 *pp++ = hb_sample_pts(stream, fpos);
973 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
974 inTitle->duration = dur;
976 inTitle->hours = dur / 3600;
977 inTitle->minutes = ( dur % 3600 ) / 60;
978 inTitle->seconds = dur % 60;
980 rewind(stream->file_handle);
983 /***********************************************************************
985 ***********************************************************************
987 **********************************************************************/
988 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
990 if ( src_stream->hb_stream_type == ffmpeg )
992 return ffmpeg_read( src_stream, b );
994 if ( src_stream->hb_stream_type == dvd_program )
996 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
997 src_stream->file_handle);
998 return (amt_read > 0);
1000 if ( src_stream->hb_stream_type == program )
1002 // a general program stream has arbitrary sized pack's. we're
1003 // currently positioned at the start of a pack so read up to but
1004 // not including the start of the next, expanding the buffer
1006 uint8_t *cp = b->data;
1007 uint8_t *ep = cp + b->alloc;
1008 uint32_t strt_code = -1;
1011 // consume the first byte of the initial pack so we don't match on
1012 // it in the loop below.
1013 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1018 flockfile( src_stream->file_handle );
1019 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1021 strt_code = ( strt_code << 8 ) | c;
1022 if ( strt_code == 0x000001ba )
1023 // we found the start of the next pack
1027 // need to expand the buffer
1028 int curSize = cp - b->data;
1029 hb_buffer_realloc( b, curSize * 2 );
1030 cp = b->data + curSize;
1031 ep = b->data + b->alloc;
1035 funlockfile( src_stream->file_handle );
1037 // if we didn't terminate on an eof back up so the next read
1038 // starts on the pack boundary.
1039 b->size = cp - b->data;
1042 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1047 return hb_ts_stream_decode( src_stream, b->data );
1050 /***********************************************************************
1052 ***********************************************************************
1054 **********************************************************************/
1055 int hb_stream_seek( hb_stream_t * src_stream, float f )
1057 if ( src_stream->hb_stream_type == ffmpeg )
1059 return ffmpeg_seek( src_stream, f );
1061 off_t stream_size, cur_pos, new_pos;
1062 double pos_ratio = f;
1063 cur_pos = ftello( src_stream->file_handle );
1064 fseeko( src_stream->file_handle, 0, SEEK_END );
1065 stream_size = ftello( src_stream->file_handle );
1066 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1067 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1069 int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1072 fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1076 if ( src_stream->hb_stream_type == transport )
1078 // We need to drop the current decoder output and move
1079 // forwards to the next transport stream packet.
1080 hb_ts_stream_reset(src_stream);
1082 else if ( src_stream->hb_stream_type == program )
1084 skip_to_next_pack( src_stream );
1090 static const char* make_upper( const char* s )
1092 static char name[8];
1094 char *ep = cp + sizeof(name)-1;
1096 while ( *s && cp < ep )
1098 *cp++ = islower(*s)? toupper(*s) : *s;
1105 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1108 * This is a duplicate of code in dvd.c - it should get factored out
1109 * into a common routine. We probably should only be putting the lang
1110 * code or a lang pointer into the audio config & let the common description
1111 * formatting routine in scan.c do all the stuff below.
1113 const char *codec_name;
1116 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1117 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1118 avcodec_find_decoder( cc->codec_id ) )
1120 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1121 if ( !strcmp( codec_name, "LIBFAAD" ) )
1126 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1127 avcodec_find_decoder( audio->config.in.codec_param ) )
1129 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1133 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1134 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1135 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1136 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1137 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1140 snprintf( audio->config.lang.description,
1141 sizeof( audio->config.lang.description ), "%s (%s)",
1142 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1144 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1145 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1146 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1147 "%s", lang->iso639_2);
1150 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1153 off_t cur_pos = ftello(stream->file_handle);
1154 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1157 fseeko(stream->file_handle, 0, SEEK_SET);
1158 align_to_next_packet(stream);
1159 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1161 /* check that we found a PES header */
1163 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1165 // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1166 // extended stream id (ISO 13818-1(2007)). If we cared about the
1167 // real id we'd have to look inside the PES extension to find it.
1168 // But since we remap stream id's when we generate PS packets from
1169 // the TS packets we can just ignore the actual id.
1170 if ( buf[3] == 0xbd || buf[3] == 0xfd )
1172 audio->id = 0x80bd | (aud_pid_index << 8);
1173 stype = stream->ts_stream_type[1 + aud_pid_index];
1174 if ( st2codec[stype].kind == U )
1176 // XXX assume unknown stream types are AC-3 (if they're not
1177 // audio we'll find that out during the scan but if they're
1178 // some other type of audio we'll end up ignoring them).
1180 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1182 stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1184 else if ((buf[3] & 0xe0) == 0xc0)
1186 audio->id = 0xc0 | aud_pid_index;
1187 stype = stream->ts_stream_type[1 + aud_pid_index];
1188 if ( st2codec[stype].kind == U )
1190 // XXX assume unknown stream types are MPEG audio
1192 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1196 // if we found an audio stream type & HB has a codec that can decode it
1197 // finish configuring the audio so we'll add it to the title's list.
1198 if ( st2codec[stype].kind == A && st2codec[stype].codec )
1200 stream->ts_streamid[1 + aud_pid_index] = audio->id;
1201 stream->ts_extra_hdr[1 + aud_pid_index] = st2codec[stype].extra_hdr;
1202 audio->config.in.codec = st2codec[stype].codec;
1203 audio->config.in.codec_param = st2codec[stype].codec_param;
1204 set_audio_description( audio,
1205 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1206 hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1207 stream->ts_audio_pids[aud_pid_index],
1208 stype, st2codec[stype].name, audio->id);
1214 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1215 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1216 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1220 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1221 stream->ts_audio_pids[aud_pid_index],
1222 stream->ts_stream_type[1 + aud_pid_index]);
1225 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1229 static void add_audio_to_title(hb_title_t *title, int id)
1231 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1237 audio->config.in.codec = HB_ACODEC_MPGA;
1238 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1241 // type 2 is a DVD subtitle stream - just ignore it */
1245 audio->config.in.codec = HB_ACODEC_AC3;
1246 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1249 audio->config.in.codec = HB_ACODEC_LPCM;
1250 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1253 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1258 set_audio_description( audio, lang_for_code( 0 ) );
1259 hb_list_add( title->list_audio, audio );
1262 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1264 off_t cur_pos = ftello(stream->file_handle);
1265 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1266 hb_list_t *list = hb_list_init();
1267 // how many blocks we read while searching for audio streams
1268 int blksleft = 4096;
1269 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1270 // so we use a bitmap to keep track of the ones we've already seen.
1271 // Bit 'i' of smap is set if we've already added the audio for
1272 // audio substream id 'i' to the title's audio list.
1275 // start looking 20% into the file since there's occasionally no
1276 // audio at the beginning (particularly for vobs).
1277 hb_stream_seek(stream, 0.2f);
1279 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1283 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1284 hb_demux_ps( buf, list, 0 );
1286 while ( ( es = hb_list_item( list, 0 ) ) )
1288 hb_list_rem( list, es );
1289 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1291 // this PES contains some kind of audio - get the substream id
1292 // and check if we've seen it already.
1293 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1294 if ( (smap & (1 << ssid)) == 0 )
1296 // we haven't seen this stream before - add it to the
1297 // title's list of audio streams.
1298 smap |= (1 << ssid);
1299 add_audio_to_title(title, es->id);
1302 hb_buffer_close( &es );
1305 hb_list_empty( &list );
1306 hb_buffer_close(&buf);
1307 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1310 /***********************************************************************
1312 ***********************************************************************
1314 **********************************************************************/
1316 static void hb_ts_stream_init(hb_stream_t *stream)
1320 for (i=0; i < kMaxNumberDecodeStreams; i++)
1322 stream->ts_streamcont[i] = -1;
1324 stream->ts_video_pids[0] = -1;
1325 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1327 stream-> ts_audio_pids[i] = -1;
1330 stream->ts_packet = malloc( stream->packetsize );
1332 // Find the audio and video pids in the stream
1333 hb_ts_stream_find_pids(stream);
1335 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1337 // demuxing buffer for TS to PS conversion
1338 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1341 stream->ts_streamid[0] = 0xE0; // stream 0 must be video
1344 #define MAX_HOLE 208*80
1346 static off_t align_to_next_packet(hb_stream_t *stream)
1348 uint8_t buf[MAX_HOLE];
1350 off_t start = ftello(stream->file_handle);
1352 if ( start >= stream->packetsize ) {
1353 start -= stream->packetsize;
1354 fseeko(stream->file_handle, start, SEEK_SET);
1357 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1359 const uint8_t *bp = buf;
1362 for ( i = sizeof(buf); --i >= 0; ++bp )
1364 if ( have_ts_sync( bp, stream->packetsize ) )
1371 pos = ( bp - buf ) - stream->packetsize + 188;
1376 fseeko(stream->file_handle, start+pos, SEEK_SET);
1387 static const unsigned int bitmask[] = {
1388 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1389 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1390 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1391 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1393 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1397 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1398 (bb->buf[2] << 8) | bb->buf[3];
1400 memset(bb->buf, 0, bufsize);
1403 static inline int buf_size(bitbuf_t *bb)
1405 return bb->pos >> 3;
1408 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1411 int left = 32 - (bb->pos & 31);
1415 val = (bb->val >> (left - bits)) & bitmask[bits];
1420 val = (bb->val & bitmask[left]) << (bits - left);
1424 int pos = bb->pos >> 3;
1425 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1429 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1437 // extract what useful information we can from the elementary stream
1438 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1439 // Descriptors with info we don't currently use are ignored.
1440 // The descriptor list & descriptor item formats are defined in
1441 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1442 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1443 const uint8_t *dp, uint8_t dlen)
1445 const uint8_t *ep = dp + dlen;
1451 case 10: // ISO_639_language descriptor
1452 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1462 static const char *stream_type_name (uint8_t stream_type)
1464 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1467 int decode_program_map(hb_stream_t* stream)
1470 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1472 get_bits(&bb, 8); // table_id
1474 unsigned int section_length = get_bits(&bb, 12);
1475 stream->pmt_info.section_length = section_length;
1477 unsigned int program_number = get_bits(&bb, 16);
1478 stream->pmt_info.program_number = program_number;
1480 get_bits(&bb, 5); // version_number
1482 get_bits(&bb, 8); // section_number
1483 get_bits(&bb, 8); // last_section_number
1485 unsigned int PCR_PID = get_bits(&bb, 13);
1486 stream->pmt_info.PCR_PID = PCR_PID;
1488 unsigned int program_info_length = get_bits(&bb, 12);
1489 stream->pmt_info.program_info_length = program_info_length;
1492 unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1493 for (i = 0; i < program_info_length; i++)
1495 descriptor_buf[i] = get_bits(&bb, 8);
1498 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1499 int done_reading_stream_types = 0;
1500 while (!done_reading_stream_types)
1502 unsigned char stream_type = get_bits(&bb, 8);
1504 unsigned int elementary_PID = get_bits(&bb, 13);
1506 unsigned int ES_info_length = get_bits(&bb, 12);
1509 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1510 for (i=0; i < ES_info_length; i++)
1512 ES_info_buf[i] = get_bits(&bb, 8);
1516 if ( index_of_pid( elementary_PID, stream ) < 0 )
1518 // already have this pid - do nothing
1520 if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1522 stream->ts_video_pids[0] = elementary_PID;
1523 stream->ts_stream_type[0] = stream_type;
1524 stream->ts_number_video_pids = 1;
1528 // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1529 // for mpeg audio. But content producers seem to use other
1530 // values (0x04 and 0x06 have both been observed) so at this point
1531 // we say everything that isn't a video pid is audio then at the end
1532 // of hb_stream_title_scan we'll figure out which are really audio
1533 // by looking at the PES headers.
1534 i = stream->ts_number_audio_pids;
1535 if (i < kMaxNumberAudioPIDS)
1537 stream->ts_audio_pids[i] = elementary_PID;
1538 stream->ts_stream_type[1 + i] = stream_type;
1539 if (ES_info_length > 0)
1541 decode_element_descriptors(stream, i, ES_info_buf,
1544 ++stream->ts_number_audio_pids;
1548 cur_pos += 5 /* stream header */ + ES_info_length;
1552 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1553 done_reading_stream_types = 1;
1556 free(descriptor_buf);
1560 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1562 // Get adaption header info
1564 int adaption = (buf[3] & 0x30) >> 4;
1567 else if (adaption == 0x2)
1569 else if (adaption == 0x3)
1570 adapt_len = buf[4] + 1;
1571 if (adapt_len > 184)
1574 // Get payload start indicator
1576 start = (buf[1] & 0x40) != 0;
1578 // Get pointer length - only valid in packets with a start flag
1579 int pointer_len = 0;
1580 if (start && stream->pmt_info.reading)
1582 // We just finished a bunch of packets - parse the program map details
1584 if (stream->pmt_info.tablebuf[0] == 0x02)
1585 decode_ok = decode_program_map(stream);
1586 free(stream->pmt_info.tablebuf);
1587 stream->pmt_info.tablebuf = NULL;
1588 stream->pmt_info.tablepos = 0;
1589 stream->pmt_info.reading = 0;
1596 pointer_len = buf[4 + adapt_len] + 1;
1597 stream->pmt_info.tablepos = 0;
1599 // Get Continuity Counter
1600 int continuity_counter = buf[3] & 0x0f;
1601 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1603 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1606 stream->pmt_info.current_continuity_counter = continuity_counter;
1607 stream->pmt_info.reading |= start;
1609 // Add the payload for this packet to the current buffer
1610 int amount_to_copy = 184 - adapt_len - pointer_len;
1611 if (stream->pmt_info.reading && (amount_to_copy > 0))
1613 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1615 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1616 stream->pmt_info.tablepos += amount_to_copy;
1622 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1624 unsigned char tablebuf[1024];
1625 unsigned int tablepos = 0;
1630 // Get adaption header info
1632 int adaption = (buf[3] & 0x30) >> 4;
1635 else if (adaption == 0x2)
1637 else if (adaption == 0x3)
1638 adapt_len = buf[4] + 1;
1639 if (adapt_len > 184)
1642 // Get pointer length
1643 int pointer_len = buf[4 + adapt_len] + 1;
1645 // Get payload start indicator
1647 start = (buf[1] & 0x40) != 0;
1652 // Add the payload for this packet to the current buffer
1653 if (reading && (184 - adapt_len) > 0)
1655 if (tablepos + 184 - adapt_len - pointer_len > 1024)
1657 hb_log("decode_PAT - Bad program section length (> 1024)");
1660 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1661 tablepos += 184 - adapt_len - pointer_len;
1664 if (start && reading)
1666 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1669 unsigned int pos = 0;
1670 //while (pos < tablepos)
1673 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1675 unsigned char section_id = get_bits(&bb, 8);
1677 unsigned int section_len = get_bits(&bb, 12);
1678 get_bits(&bb, 16); // transport_id
1680 get_bits(&bb, 5); // version_num
1681 get_bits(&bb, 1); // current_next
1682 get_bits(&bb, 8); // section_num
1683 get_bits(&bb, 8); // last_section
1689 // Program Association Section
1690 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
1691 section_len -= 4; // Ignore the CRC
1693 stream->ts_number_pat_entries = 0;
1694 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1696 unsigned int pkt_program_num = get_bits(&bb, 16);
1697 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1699 get_bits(&bb, 3); // Reserved
1700 if (pkt_program_num == 0)
1702 get_bits(&bb, 13); // pkt_network_id
1706 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1707 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1710 stream->ts_number_pat_entries++;
1724 pos += 3 + section_len;
1732 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1734 // align to first packet
1735 align_to_next_packet(stream);
1737 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1738 // to find the program map PID and then decode that to get the list of audio and video PIDs
1742 const uint8_t *buf = next_packet( stream );
1745 hb_log("hb_ts_stream_find_pids - end of file");
1750 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1752 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1754 decode_PAT(buf, stream);
1759 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1761 // There are some streams where the PAT table has multiple entries as if their are
1762 // multiple programs in the same transport stream, and yet there's actually only one
1763 // program really in the stream. This seems to be true for transport streams that
1764 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1765 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1766 // but the EyeTV is only recording a single (selected) program number and not rewriting the
1767 // PAT info on export to match what's actually on the stream.
1768 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1769 // on the first pat entry for which we find a matching program map PID. The ideal solution would
1770 // be to build a title choice popup from the PAT program number details and then select from
1771 // their - but right now the API's not capable of that.
1772 if (pid == stream->pat_info[pat_index].program_map_PID)
1774 if (build_program_map(buf, stream) > 0)
1778 // Keep going until we have a complete set of PIDs
1779 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1782 // XXX - until we figure out how to handle VC1 just bail when we find it so
1783 // that ffmpeg will claim the input stream.
1784 if ( stream->ts_stream_type[0] == 0xea )
1786 stream->ts_number_video_pids = 0;
1787 stream->ts_number_audio_pids = 0;
1791 hb_log("hb_ts_stream_find_pids - found the following PIDS");
1792 hb_log(" Video PIDS : ");
1794 for (i=0; i < stream->ts_number_video_pids; i++)
1796 hb_log( " 0x%x type %s (0x%x)",
1797 stream->ts_video_pids[i],
1798 stream_type_name(stream->ts_stream_type[i]),
1799 stream->ts_stream_type[i]);
1801 hb_log(" Audio PIDS : ");
1802 for (i = 0; i < stream->ts_number_audio_pids; i++)
1804 hb_log( " 0x%x type %s (0x%x)",
1805 stream->ts_audio_pids[i],
1806 stream_type_name(stream->ts_stream_type[i+1]),
1807 stream->ts_stream_type[i+1] );
1812 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1814 if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1816 hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1817 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1820 memcpy( stream->fwrite_buf, buf, size );
1821 stream->fwrite_buf += size;
1824 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1828 buf[0] = 0x00; // pack id
1833 buf[4] = 0x44 | // SCR
1834 ( ( ( time >> 30 ) & 7 ) << 3 ) |
1835 ( ( time >> 28 ) & 3 );
1836 buf[5] = time >> 20;
1838 ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1839 ( ( time >> 13 ) & 3 );
1841 buf[8] = 0x04 | ( time << 3 );
1843 buf[9] = 0x01; // SCR extension
1845 buf[10] = 384000 >> (22 - 8); // program mux rate
1846 buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1847 buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1849 buf[13] = 0xf8 | stuffing;
1852 for (i = 0; i < stuffing; ++i )
1855 fwrite64(stream, buf, 14 + stuffing );
1858 static void pad_buffer(hb_stream_t* stream, int pad)
1870 fwrite64(stream, buf, 6);
1873 while ( --pad >= 0 )
1875 fwrite64(stream, buf, 1);
1879 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1883 memset(buf, 0, sizeof(buf) );
1886 buf[4] = ( len + 3 ) >> 8;
1890 fwrite64(stream, buf, 9);
1893 static void generate_output_data(hb_stream_t *stream, int curstream)
1895 uint8_t *tdat = stream->ts_buf[curstream];
1898 // we always ship a PACK header plus all the data in our demux buf.
1899 // AC3 audio also always needs its substream header.
1900 len = 14 + stream->ts_pos[curstream];
1901 if ( stream->ts_extra_hdr[curstream] )
1906 if ( ! stream->ts_start[curstream] )
1908 // we're in the middle of a chunk of PES data - we need to add
1909 // a 'continuation' PES header after the PACK header.
1913 // Write out pack header
1914 // If we don't have 2048 bytes we need to pad to 2048. We can
1915 // add a padding frame after our data but we need at least 7
1916 // bytes of space to do it (6 bytes of header & 1 of pad). If
1917 // we have fewer than 7 bytes left we need to fill the excess
1918 // space with stuffing bytes added to the pack header.
1920 if ( len > HB_DVD_READ_BUFFER_SIZE )
1922 hb_log( "stream ts length botch %d", len );
1924 if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1926 stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1928 write_pack(stream, stream->ts_nextpcr, stuffing );
1929 stream->ts_nextpcr += 10;
1931 if ( stream->ts_start[curstream] )
1933 // Start frames already have a PES header but we have modify it
1934 // to map from TS PID to PS stream id. Also, if the stream is AC3
1935 // audio we have to insert an AC3 stream header between the end of
1936 // the PES header and the start of the stream data.
1938 stream->ts_start[curstream] = 0;
1939 tdat[3] = stream->ts_streamid[curstream];
1941 uint16_t plen = stream->ts_pos[curstream] - 6;
1942 if ( stream->ts_extra_hdr[curstream] )
1944 // We have to add an AC3 header in front of the data. Add its
1945 // size to the PES packet length.
1947 tdat[4] = plen >> 8;
1950 // Write out the PES header
1951 int hdrsize = 9 + tdat[8];
1952 fwrite64(stream, tdat, hdrsize);
1954 // add a four byte DVD ac3 stream header
1955 uint8_t ac3_substream_id[4];
1956 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1957 ac3_substream_id[0] = 0x80 | ssid; // substream id
1958 ac3_substream_id[1] = 0x01; // number of sync words
1959 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1960 ac3_substream_id[3] = 0x02;
1961 fwrite64(stream, ac3_substream_id, 4);
1963 // add the rest of the data
1964 fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1968 // not audio - don't need to modify the stream so write what we've got
1969 tdat[4] = plen >> 8;
1971 fwrite64( stream, tdat, stream->ts_pos[curstream] );
1976 // data without a PES start header needs a simple 'continuation'
1977 // PES header. AC3 audio also needs its substream header.
1978 if ( stream->ts_extra_hdr[curstream] == 0 )
1980 make_pes_header(stream, stream->ts_pos[curstream],
1981 stream->ts_streamid[curstream]);
1985 make_pes_header(stream, stream->ts_pos[curstream] + 4,
1986 stream->ts_streamid[curstream]);
1988 // add a four byte DVD ac3 stream header
1989 uint8_t ac3_substream_id[4];
1990 int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1991 ac3_substream_id[0] = 0x80 | ssid; // substream id
1992 ac3_substream_id[1] = 0x01; // number of sync words
1993 ac3_substream_id[2] = 0x00; // first offset (16 bits)
1994 ac3_substream_id[3] = 0x02;
1995 fwrite64(stream, ac3_substream_id, 4);
1997 fwrite64( stream, tdat, stream->ts_pos[curstream] );
2001 int left = HB_DVD_READ_BUFFER_SIZE - len;
2004 pad_buffer(stream, left);
2007 stream->ts_pos[curstream] = 0;
2010 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
2012 // For mpeg2: look for a gop start or i-frame picture start
2013 // for h.264: look for idr nal type or a slice header for an i-frame
2019 if ( stream->ts_stream_type[0] <= 2 )
2021 // This section of the code handles MPEG-1 and MPEG-2 video streams
2022 for (i = 13 + adapt_len; i < 188; i++)
2024 strid = (strid << 8) | buf[i];
2025 if ( ( strid >> 8 ) == 1 )
2027 // we found a start code
2031 case 0xB8: // group_start_code (GOP header)
2032 case 0xB3: // sequence_header code
2035 case 0x00: // picture_start_code
2036 // picture_header, let's see if it's an I-frame
2039 // check if picture_coding_type == 1
2040 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2042 // found an I-frame picture
2050 // didn't find an I-frame
2053 if ( stream->ts_stream_type[0] == 0x1b )
2055 // we have an h.264 stream
2056 for (i = 13 + adapt_len; i < 188; i++)
2058 strid = (strid << 8) | buf[i];
2059 if ( ( strid >> 8 ) == 1 )
2061 // we found a start code - remove the ref_idc from the nal type
2062 uint8_t nal_type = strid & 0x1f;
2063 if ( nal_type == 0x05 )
2064 // h.264 IDR picture start
2067 if ( nal_type == 0x01 )
2069 // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2070 uint8_t id = buf[i+1];
2071 if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2072 id == 0x88 || id == 0x8a )
2079 // didn't find an I-frame
2083 // we don't understand the stream type so just say "yes" otherwise
2084 // we'll discard all the video.
2088 /***********************************************************************
2089 * hb_ts_stream_decode
2090 ***********************************************************************
2092 **********************************************************************/
2093 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2096 * stash the output buffer pointer in our stream so we don't have to
2097 * pass it & its original value to everything we call.
2099 stream->fwrite_buf = obuf;
2100 stream->fwrite_buf_orig = obuf;
2102 // spin until we get a packet of data from some stream or hit eof
2105 int64_t pcr = stream->ts_lastpcr;
2108 const uint8_t *buf = next_packet(stream);
2111 // end of file - we didn't finish filling our ps write buffer
2112 // so just discard the remainder (the partial buffer is useless)
2113 hb_log("hb_ts_stream_decode - eof");
2117 /* This next section validates the packet */
2119 // Get pid and use it to find stream state.
2120 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2121 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2125 int errorbit = (buf[1] & 0x80) != 0;
2128 ts_err( stream, curstream, "packet error bit set");
2132 // Get adaption header info
2133 int adaption = (buf[3] & 0x30) >> 4;
2137 ts_err( stream, curstream, "adaptation code 0");
2140 else if (adaption == 0x2)
2142 else if (adaption == 0x3)
2144 adapt_len = buf[4] + 1;
2145 if (adapt_len > 184)
2147 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2152 // if there's an adaptation header & PCR_flag is set
2153 // get the PCR (Program Clock Reference)
2154 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2156 pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2157 ( (uint64_t)buf[7] << (33 - 16) ) |
2158 ( (uint64_t)buf[8] << (33 - 24) ) |
2159 ( (uint64_t)buf[9] << (33 - 32) ) |
2161 stream->ts_nextpcr = pcr;
2163 // remember the pcr across calls to this routine
2164 stream->ts_lastpcr = pcr;
2167 // If we don't have a pcr yet, the right thing to do here would
2168 // be a 'continue' so we don't process anything until we have a
2169 // clock reference. Unfortunately the HD Home Run appears to null
2170 // out the pcr field of some streams so we keep going & substitute
2171 // the video stream dts for the pcr when there's no pcr.
2174 // Continuity only increments for adaption values of 0x3 or 0x01
2175 // and is not checked for start packets.
2177 int start = (buf[1] & 0x40) != 0;
2179 if ( (adaption & 0x01) != 0 )
2181 int continuity = (buf[3] & 0xF);
2182 if ( continuity == stream->ts_streamcont[curstream] )
2184 // we got a duplicate packet (usually used to introduce
2185 // a PCR when one is needed). The only thing that can
2186 // change in the dup is the PCR which we grabbed above
2187 // so ignore the rest.
2190 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2191 stream->ts_foundfirst[curstream] &&
2192 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2194 ts_err( stream, curstream, "continuity error: got %d expected %d",
2196 (stream->ts_streamcont[curstream] + 1) & 0xf );
2197 stream->ts_streamcont[curstream] = continuity;
2200 stream->ts_streamcont[curstream] = continuity;
2203 /* If we get here the packet is valid - process its data */
2207 // Found a random access point (now we can start a frame/audio packet..)
2209 // If we were skipping a bad packet, start fresh on this new PES packet..
2210 if (stream->ts_skipbad[curstream] == 1)
2212 // video skips to an iframe after a bad packet to minimize
2213 // screen corruption
2214 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2218 stream->ts_skipbad[curstream] = 0;
2221 // If we don't have video yet, check to see if this is an
2222 // i_frame (group of picture start)
2223 if ( curstream == 0 )
2225 if ( !stream->ts_foundfirst[0] )
2227 if ( !isIframe( stream, buf, adapt_len ) )
2229 // didn't find an I frame
2232 stream->ts_foundfirst[0] = 1;
2236 // if we don't have a pcr yet use the dts from this frame
2239 // PES must begin with an mpeg start code & contain
2241 const uint8_t *pes = buf + adapt_len + 4;
2242 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2243 ( pes[7] >> 6 ) == 0 )
2247 // if we have a dts use it otherwise use the pts
2248 pes += (pes[7] & 0x40)? 14 : 9;
2250 pcr = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2251 pcr |= ( pes[1] << 22 ) |
2252 ( ( pes[2] >> 1 ) << 15 ) |
2255 stream->ts_nextpcr = pcr;
2258 else if ( ! stream->ts_foundfirst[curstream] )
2260 // start other streams only after first video frame found.
2261 if ( ! stream->ts_foundfirst[0] )
2265 stream->ts_foundfirst[curstream] = 1;
2268 // If we have some data already on this stream, turn it into
2269 // a program stream packet. Then add the payload for this
2270 // packet to the current pid's buffer.
2271 if ( stream->ts_pos[curstream] )
2273 generate_output_data(stream, curstream);
2274 stream->ts_start[curstream] = 1;
2275 memcpy(stream->ts_buf[curstream],
2276 buf + 4 + adapt_len, 184 - adapt_len);
2277 stream->ts_pos[curstream] = 184 - adapt_len;
2280 stream->ts_start[curstream] = 1;
2283 // Add the payload for this packet to the current buffer
2284 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2285 (184 - adapt_len) > 0)
2287 memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2288 buf + 4 + adapt_len, 184 - adapt_len);
2289 stream->ts_pos[curstream] += 184 - adapt_len;
2291 // if the next TS packet could possibly overflow our 2K output buffer
2292 // we need to generate a packet now. Overflow would be 184 bytes of
2293 // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2294 if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2296 // we have enough data to make a PS packet
2297 generate_output_data(stream, curstream);
2304 static void hb_ts_stream_reset(hb_stream_t *stream)
2308 for (i=0; i < kMaxNumberDecodeStreams; i++)
2310 stream->ts_pos[i] = 0;
2311 stream->ts_foundfirst[i] = 0;
2312 stream->ts_skipbad[i] = 0;
2313 stream->ts_streamcont[i] = -1;
2314 stream->ts_start[i] = 0;
2317 stream->ts_lastpcr = -1;
2318 stream->ts_nextpcr = -1;
2322 stream->last_error_frame = -10000;
2323 stream->last_error_count = 0;
2325 align_to_next_packet(stream);
2328 // ------------------------------------------------------------------
2329 // Support for reading media files via the ffmpeg libraries.
2331 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2333 // add a codec to the context here so it will be there when we
2334 // read the first packet.
2335 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2336 context->workaround_bugs = FF_BUG_AUTODETECT;
2337 context->error_recognition = 1;
2338 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2339 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2340 avcodec_open( context, codec );
2343 // The ffmpeg stream reader / parser shares a lot of state with the
2344 // decoder via a codec context kept in the AVStream of the reader's
2345 // AVFormatContext. Since decoding is done in a different thread we
2346 // have to somehow pass this codec context to the decoder and we have
2347 // to do it before the first packet is read (so we can't put the info
2348 // in the buf we'll send downstream). Decoders don't have any way to
2349 // get to the stream directly (they're not passed the title or job
2350 // pointers during a scan) so this is a back door for the decoder to
2351 // get the codec context. We just stick the stream pointer in the next
2352 // slot an array of pointers maintained as a circular list then return
2353 // the index into the list combined with the ffmpeg stream index as the
2354 // codec_param that will be passed to the decoder init routine. We make
2355 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2356 // so that we don't have to do a complicated allocator or worry about
2357 // deleting entries on close.
2359 // Entries can only be added to this list during a scan and are never
2360 // deleted so the list access doesn't require locking.
2361 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2362 static int ffmpeg_stream_cur; // where we put the last stream pointer
2363 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2364 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2366 // add a stream to the list & return the appropriate codec_param to access it
2367 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2369 if ( !ffmpeg_streams )
2371 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2374 // the title scan adds all the ffmpeg media streams at once so we
2375 // only add a new entry to our stream list if the stream is different
2377 int slot = ffmpeg_stream_cur;
2378 if ( ffmpeg_streams[slot] != stream )
2380 // new stream - put it in the next slot of the stream list
2381 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2382 ffmpeg_streams[slot] = stream;
2385 ffmpeg_add_codec( stream, stream_index );
2387 return ( stream_index << ffmpeg_sl_bits ) | slot;
2390 // we're about to open 'title' to convert it - remap the stream associated
2391 // with the video & audio codec params of the title to refer to 'stream'
2392 // (the original scan stream was closed and no longer exists).
2393 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2395 // tell ffmpeg we want a pts on every frame it returns
2396 stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2398 // all the video & audio came from the same stream so remapping
2399 // the video's stream slot takes care of everything.
2400 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2401 ffmpeg_streams[slot] = stream;
2403 // add codecs for all the streams used by the title
2404 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2408 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2410 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2412 ffmpeg_add_codec( stream,
2413 audio->config.in.codec_param >> ffmpeg_sl_bits );
2418 void *hb_ffmpeg_context( int codec_param )
2420 int slot = codec_param & (ffmpeg_sl_size - 1);
2421 int stream_index = codec_param >> ffmpeg_sl_bits;
2422 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2425 void *hb_ffmpeg_avstream( int codec_param )
2427 int slot = codec_param & (ffmpeg_sl_size - 1);
2428 int stream_index = codec_param >> ffmpeg_sl_bits;
2429 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2432 static AVFormatContext *ffmpeg_deferred_close;
2434 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2436 if ( ffmpeg_deferred_close )
2438 av_close_input_file( ffmpeg_deferred_close );
2439 ffmpeg_deferred_close = NULL;
2441 AVFormatContext *ic;
2443 av_log_set_level( AV_LOG_ERROR );
2444 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2448 if ( av_find_stream_info( ic ) < 0 )
2451 stream->ffmpeg_ic = ic;
2452 stream->hb_stream_type = ffmpeg;
2453 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2454 av_init_packet( stream->ffmpeg_pkt );
2458 // we're opening for read. scan passed out codec params that
2459 // indexed its stream so we need to remap them so they point
2461 ffmpeg_remap_stream( stream, title );
2462 ffmpeg_seek( stream, 0. );
2463 av_log_set_level( AV_LOG_ERROR );
2467 // we're opening for scan. let ffmpeg put some info into the
2468 // log about what we've got.
2469 av_log_set_level( AV_LOG_INFO );
2470 dump_format( ic, 0, stream->path, 0 );
2471 av_log_set_level( AV_LOG_ERROR );
2473 // accept this file if it has at least one video stream we can decode
2475 for (i = 0; i < ic->nb_streams; ++i )
2477 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2482 if ( i >= ic->nb_streams )
2488 av_close_input_file( ic );
2492 static void ffmpeg_close( hb_stream_t *d )
2494 // XXX since we're sharing the CodecContext with the downstream
2495 // decoder proc we can't close the stream. We need to reference count
2496 // this so we can close it when both are done with their instance but
2497 // for now just defer the close until the next stream open or close.
2498 if ( ffmpeg_deferred_close )
2500 av_close_input_file( ffmpeg_deferred_close );
2502 ffmpeg_deferred_close = d->ffmpeg_ic;
2503 if ( d->ffmpeg_pkt != NULL )
2505 free( d->ffmpeg_pkt );
2506 d->ffmpeg_pkt = NULL;
2510 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2512 AVStream *st = stream->ffmpeg_ic->streams[id];
2513 AVCodecContext *codec = st->codec;
2515 // scan will ignore any audio without a bitrate. Since we've already
2516 // typed the audio in order to determine its codec we set up the audio
2518 if ( codec->bit_rate || codec->sample_rate )
2520 static const int chan2layout[] = {
2521 HB_INPUT_CH_LAYOUT_MONO, // We should allow no audio really.
2522 HB_INPUT_CH_LAYOUT_MONO,
2523 HB_INPUT_CH_LAYOUT_STEREO,
2524 HB_INPUT_CH_LAYOUT_2F1R,
2525 HB_INPUT_CH_LAYOUT_2F2R,
2526 HB_INPUT_CH_LAYOUT_3F2R,
2527 HB_INPUT_CH_LAYOUT_4F2R,
2528 HB_INPUT_CH_LAYOUT_STEREO,
2529 HB_INPUT_CH_LAYOUT_STEREO,
2532 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2535 if ( codec->codec_id == CODEC_ID_AC3 )
2537 audio->config.in.codec = HB_ACODEC_AC3;
2539 else if ( codec->codec_id == CODEC_ID_DTS )
2541 audio->config.in.codec = HB_ACODEC_DCA;
2545 audio->config.in.codec = HB_ACODEC_FFMPEG;
2546 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2548 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2549 audio->config.in.samplerate = codec->sample_rate;
2550 audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2553 set_audio_description( audio, lang_for_code2( st->language ) );
2555 hb_list_add( title->list_audio, audio );
2559 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2561 AVFormatContext *ic = stream->ffmpeg_ic;
2563 // 'Barebones Title'
2564 hb_title_t *title = hb_title_init( stream->path, 0 );
2567 // Copy part of the stream path to the title name
2568 char *sep = strrchr(stream->path, '/');
2570 strcpy(title->name, sep+1);
2571 char *dot_term = strrchr(title->name, '.');
2575 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2576 title->duration = dur;
2578 title->hours = dur / 3600;
2579 title->minutes = ( dur % 3600 ) / 60;
2580 title->seconds = dur % 60;
2583 hb_chapter_t * chapter;
2584 chapter = calloc( sizeof( hb_chapter_t ), 1 );
2586 chapter->duration = title->duration;
2587 chapter->hours = title->hours;
2588 chapter->minutes = title->minutes;
2589 chapter->seconds = title->seconds;
2590 hb_list_add( title->list_chapter, chapter );
2592 // set the title to decode the first video stream in the file
2593 title->demuxer = HB_NULL_DEMUXER;
2594 title->video_codec = 0;
2596 for (i = 0; i < ic->nb_streams; ++i )
2598 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2599 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2600 title->video_codec == 0 )
2602 title->video_id = i;
2604 // We have to use the 'internal' avcodec decoder because
2605 // it needs to share the codec context from this video
2606 // stream. The parser internal to av_read_frame
2607 // passes a bunch of state info to the decoder via the context.
2608 title->video_codec = WORK_DECAVCODECVI;
2609 title->video_codec_param = ffmpeg_codec_param( stream, i );
2611 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2612 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2614 add_ffmpeg_audio( title, stream, i );
2618 title->container_name = strdup( ic->iformat->name );
2619 title->data_rate = ic->bit_rate;
2624 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2626 if ( pts == AV_NOPTS_VALUE )
2628 return (int64_t)( (double)pts * conv_factor );
2631 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2634 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2636 // XXX the following conditional is to handle avi files that
2637 // use M$ 'packed b-frames' and occasionally have negative
2638 // sizes for the null frames these require.
2639 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2643 if ( stream->ffmpeg_pkt->size <= 0 )
2645 // M$ "invalid and inefficient" packed b-frames require 'null frames'
2646 // following them to preserve the timing (since the packing puts two
2647 // or more frames in what looks like one avi frame). The contents and
2648 // size of these null frames are ignored by the ff_h263_decode_frame
2649 // as long as they're < 20 bytes. We need a positive size so we use
2650 // one byte if we're given a zero or negative size. We don't know
2651 // if the pkt data points anywhere reasonable so we just stick a
2652 // byte of zero in our outbound buf.
2658 if ( stream->ffmpeg_pkt->size > buf->alloc )
2660 // need to expand buffer
2661 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2663 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2664 buf->size = stream->ffmpeg_pkt->size;
2666 buf->id = stream->ffmpeg_pkt->stream_index;
2668 // if we haven't done it already, compute a conversion factor to go
2669 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2670 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2673 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2674 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2675 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2678 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2679 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2680 if ( buf->renderOffset >= 0 && buf->start == -1 )
2682 buf->start = buf->renderOffset;
2684 av_free_packet( stream->ffmpeg_pkt );
2688 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2690 AVFormatContext *ic = stream->ffmpeg_ic;
2691 int64_t pos = (double)ic->duration * (double)frac;
2692 av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );