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. */
14 #include "a52dec/a52.h"
15 #include "mp4v2/mp4v2.h"
17 #define min(a, b) a < b ? a : b
18 #define STR4_TO_UINT32(p) \
19 ((((const uint8_t*)(p))[0] << 24) | \
20 (((const uint8_t*)(p))[1] << 16) | \
21 (((const uint8_t*)(p))[2] << 8) | \
22 ((const uint8_t*)(p))[3])
25 * This table defines how ISO MPEG stream type codes map to HandBrake
26 * codecs. It is indexed by the 8 bit stream type and contains the codec
27 * worker object id and a parameter for that worker proc (ignored except
28 * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
30 * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
31 * doesn't handle the stream type.
33 typedef enum { N, U, A, V } kind_t;
35 kind_t kind; /* not handled / unknown / audio / video */
36 int codec; /* HB worker object id of codec */
37 int codec_param; /* param for codec (usually ffmpeg codec id) */
38 const char* name; /* description of type */
41 #define st(id, kind, codec, codec_param, name) \
42 [id] = { kind, codec, codec_param, name }
44 static const stream2codec_t st2codec[256] = {
45 st(0x01, V, WORK_DECMPEG2, 0, "MPEG1"),
46 st(0x02, V, WORK_DECMPEG2, 0, "MPEG2"),
47 st(0x03, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG1"),
48 st(0x04, A, HB_ACODEC_MPGA, CODEC_ID_MP2, "MPEG2"),
49 st(0x05, N, 0, 0, "ISO 13818-1 private section"),
50 st(0x06, U, 0, 0, "ISO 13818-1 PES private data"),
51 st(0x07, N, 0, 0, "ISO 13522 MHEG"),
52 st(0x08, N, 0, 0, "ISO 13818-1 DSM-CC"),
53 st(0x09, N, 0, 0, "ISO 13818-1 auxiliary"),
54 st(0x0a, N, 0, 0, "ISO 13818-6 encap"),
55 st(0x0b, N, 0, 0, "ISO 13818-6 DSM-CC U-N msgs"),
56 st(0x0c, N, 0, 0, "ISO 13818-6 Stream descriptors"),
57 st(0x0d, N, 0, 0, "ISO 13818-6 Sections"),
58 st(0x0e, N, 0, 0, "ISO 13818-1 auxiliary"),
59 st(0x0f, A, HB_ACODEC_MPGA, CODEC_ID_AAC, "ISO 13818-7 AAC Audio"),
60 st(0x10, V, WORK_DECAVCODECV, CODEC_ID_MPEG4, "MPEG4"),
61 st(0x11, A, HB_ACODEC_MPGA, CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
62 st(0x12, U, 0, 0, "MPEG4 generic"),
64 st(0x14, N, 0, 0, "ISO 13818-6 DSM-CC download"),
66 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
68 st(0x80, N, HB_ACODEC_MPGA, CODEC_ID_PCM_BLURAY, "DigiCipher II Video"),
69 st(0x81, A, HB_ACODEC_AC3, 0, "AC-3"),
70 st(0x82, A, HB_ACODEC_DCA, 0, "HDMV DTS"),
71 st(0x83, A, HB_ACODEC_LPCM, 0, "LPCM"),
72 st(0x84, A, 0, 0, "SDDS"),
73 st(0x85, U, 0, 0, "ATSC Program ID"),
74 st(0x86, A, HB_ACODEC_DCA, 0, "DTS-HD"),
75 st(0x87, A, 0, 0, "E-AC-3"),
77 st(0x8a, A, HB_ACODEC_DCA, 0, "DTS"),
79 st(0x91, A, HB_ACODEC_AC3, 0, "AC-3"),
80 st(0x92, N, 0, 0, "Subtitle"),
82 st(0x94, A, 0, 0, "SDDS"),
83 st(0xa0, V, 0, 0, "MSCODEC"),
85 st(0xea, V, WORK_DECAVCODECV, CODEC_ID_VC1, "VC1"),
90 hb_stream_type_unknown = 0,
97 #define kMaxNumberVideoPIDS 1
98 #define kMaxNumberAudioPIDS 31
99 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
100 #define kMaxNumberPMTStreams 32
105 int frames; /* video frames so far */
106 int errors; /* total errors so far */
107 int last_error_frame; /* frame # at last error message */
108 int last_error_count; /* # errors at last error message */
109 int packetsize; /* Transport Stream packet size */
111 uint8_t need_keyframe; // non-zero if want to start at a keyframe
112 uint8_t ts_found_pcr; // non-zero if we've found at least one input pcr
113 int ts_pcr_out; // sequence number of most recent output pcr
114 int ts_pcr_in; // sequence number of most recent input pcr
115 int64_t ts_pcr; // most recent input pcr
116 int64_t ts_pcrhist[4]; // circular buffer of output pcrs
118 uint8_t *ts_packet; /* buffer for one TS packet */
119 hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
120 int ts_pos[kMaxNumberDecodeStreams];
121 int8_t ts_skipbad[kMaxNumberDecodeStreams];
122 int8_t ts_streamcont[kMaxNumberDecodeStreams];
123 uint8_t ts_pkt_summary[kMaxNumberDecodeStreams][8];
125 hb_buffer_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
127 int chapter; /* Chapter that we are currently in */
128 int64_t chapter_end; /* HB time that the current chapter ends */
131 * Stuff before this point is dynamic state updated as we read the
132 * stream. Stuff after this point is stream description state that
133 * we learn during the initial scan but cache so it can be
134 * reused during the conversion read.
136 uint8_t ts_number_video_pids;
137 uint8_t ts_number_audio_pids;
138 uint8_t ts_flags; // stream characteristics:
139 #define TS_HAS_PCR (1 << 0) // at least one PCR seen
140 #define TS_HAS_RAP (1 << 1) // Random Access Point bit seen
141 #define TS_HAS_RSEI (1 << 2) // "Restart point" SEI seen
142 uint8_t ts_IDRs; // # IDRs found during duration scan
144 int16_t ts_video_pids[kMaxNumberVideoPIDS];
145 int16_t ts_audio_pids[kMaxNumberAudioPIDS];
147 uint32_t ts_format_id[kMaxNumberDecodeStreams];
148 #define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
149 uint8_t ts_stream_type[kMaxNumberDecodeStreams];
150 uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
154 hb_stream_type_t hb_stream_type;
157 AVFormatContext *ffmpeg_ic;
158 AVPacket *ffmpeg_pkt;
159 double ffmpeg_tsconv[MAX_STREAMS];
160 uint8_t ffmpeg_video_id;
167 } a52_info[kMaxNumberAudioPIDS];
171 unsigned short program_number;
172 unsigned short program_map_PID;
173 } pat_info[kMaxNumberPMTStreams];
174 int ts_number_pat_entries;
179 unsigned char *tablebuf;
180 unsigned int tablepos;
181 unsigned char current_continuity_counter;
185 unsigned int PCR_PID;
187 int program_info_length;
190 unsigned char stream_type;
191 unsigned short elementary_PID;
192 unsigned short ES_info_length;
193 unsigned char *es_info_descriptor_data;
194 } pmt_stream_info[kMaxNumberPMTStreams];
198 /***********************************************************************
200 **********************************************************************/
201 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
202 static void hb_ts_stream_init(hb_stream_t *stream);
203 static void hb_ts_stream_find_pids(hb_stream_t *stream);
204 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
205 static void hb_ts_stream_reset(hb_stream_t *stream);
206 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
208 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
209 static off_t align_to_next_packet(hb_stream_t *stream);
211 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
212 static void ffmpeg_close( hb_stream_t *d );
213 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
214 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
215 static int ffmpeg_seek( hb_stream_t *stream, float frac );
216 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts );
219 * streams have a bunch of state that's learned during the scan. We don't
220 * want to throw away the state when scan does a close then relearn
221 * everything when reader does an open. So we save the stream state on
222 * the close following a scan and reuse it when 'reader' does an open.
224 static hb_list_t *stream_state_list;
226 static hb_stream_t *hb_stream_lookup( const char *path )
228 if ( stream_state_list == NULL )
234 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
236 if ( strcmp( path, ss->path ) == 0 )
244 static void hb_stream_state_delete( hb_stream_t *ss )
246 hb_list_rem( stream_state_list, ss );
253 * these frontend hb_log because transport streams can have a lot of errors
254 * so we want to rate limit messages. this routine limits the number of
255 * messages to at most one per minute of video. other errors that occur
256 * during the minute are counted & the count is output with the next
257 * error msg we print.
259 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
261 // limit error printing to at most one per minute of video (at 30fps)
263 if ( stream->frames - stream->last_error_frame >= 30*60 )
267 vsnprintf( msg, sizeof(msg), log, args );
269 if ( stream->errors - stream->last_error_count < 10 )
271 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
275 int Edelta = stream->errors - stream->last_error_count;
276 double Epcnt = (double)Edelta * 100. /
277 (stream->frames - stream->last_error_frame);
278 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
279 Edelta, Epcnt, stream->frames, msg );
281 stream->last_error_frame = stream->frames;
282 stream->last_error_count = stream->errors;
286 static void ts_warn( hb_stream_t*, char*, ... ) HB_WPRINTF(2,3);
287 static void ts_err( hb_stream_t*, int, char*, ... ) HB_WPRINTF(3,4);
289 static void ts_warn( hb_stream_t *stream, char *log, ... )
292 va_start( args, log );
293 ts_warn_helper( stream, log, args );
297 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
300 va_start( args, log );
301 ts_warn_helper( stream, log, args );
304 stream->ts_skipbad[curstream] = 1;
305 stream->ts_pos[curstream] = 0;
306 stream->ts_streamcont[curstream] = -1;
309 static int check_ps_sync(const uint8_t *buf)
311 // a legal MPEG program stream must start with a Pack header in the
313 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
314 (buf[2] == 0x01) && (buf[3] == 0xba);
317 static int check_ps_sc(const uint8_t *buf)
319 // a legal MPEG program stream must start with a Pack followed by a
320 // some other start code. If we've already verified the pack, this skip
321 // it and checks for a start code prefix.
322 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
323 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) && (buf[pos+2] == 0x01);
326 static int check_ts_sync(const uint8_t *buf)
328 // must have initial sync byte, no scrambling & a legal adaptation ctrl
329 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
332 static int have_ts_sync(const uint8_t *buf, int psize)
334 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
335 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
336 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
337 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
340 static int hb_stream_check_for_ts(const uint8_t *buf)
342 // transport streams should have a sync byte every 188 bytes.
343 // search the first 8KB of buf looking for at least 8 consecutive
344 // correctly located sync patterns.
347 for ( offset = 0; offset < 8*1024-8*188; ++offset )
349 if ( have_ts_sync( &buf[offset], 188) )
350 return 188 | (offset << 8);
351 if ( have_ts_sync( &buf[offset], 192) )
352 return 192 | (offset << 8);
353 if ( have_ts_sync( &buf[offset], 204) )
354 return 204 | (offset << 8);
355 if ( have_ts_sync( &buf[offset], 208) )
356 return 208 | (offset << 8);
361 static int hb_stream_check_for_ps(const uint8_t *buf)
363 // program streams should start with a PACK then some other mpeg start
364 // code (usually a SYS but that might be missing if we only have a clip).
367 for ( offset = 0; offset < 8*1024-24; ++offset )
369 if ( check_ps_sync( &buf[offset] ) && check_ps_sc( &buf[offset] ) )
375 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
377 // DVD program streams should have a Pack header every 2048 bytes.
378 // check that we have 4 of these in a row.
379 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
380 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
383 static int hb_stream_get_type(hb_stream_t *stream)
388 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
391 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
393 int offset = psize >> 8;
395 hb_log("file is MPEG Transport Stream with %d byte packets"
396 " offset %d bytes", psize, offset);
397 stream->packetsize = psize;
398 stream->hb_stream_type = transport;
399 hb_ts_stream_init(stream);
400 if ( !stream->ts_number_video_pids || !stream->ts_number_audio_pids )
406 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
408 hb_log("file is MPEG DVD Program Stream");
409 stream->hb_stream_type = dvd_program;
414 if ( hb_stream_check_for_ps(buf) != 0 )
416 hb_log("file is MPEG Program Stream");
417 stream->hb_stream_type = program;
420 // Seek back to handle start codes that run over end of last buffer
421 fseek( stream->file_handle, -28, SEEK_CUR );
422 } while ( --i && fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) );
427 static void hb_stream_delete_dynamic( hb_stream_t *d )
431 fclose( d->file_handle );
432 d->file_handle = NULL;
439 free( d->ts_packet );
442 for (i = 0; i < kMaxNumberDecodeStreams; i++)
446 hb_buffer_close(&(d->ts_buf[i]));
452 static void hb_stream_delete( hb_stream_t *d )
454 hb_stream_delete_dynamic( d );
459 static int audio_inactive( hb_stream_t *stream, int indx )
461 int aud_indx = indx - 1;
463 if ( stream->ts_audio_pids[aud_indx] < 0 )
465 // PID declared inactive by hb_stream_title_scan
468 if ( stream->ts_audio_pids[aud_indx] == stream->pmt_info.PCR_PID )
470 // PCR PID is always active
474 // see if we should make the stream inactive because scan.c didn't
475 // find a valid audio bitstream.
477 for ( i = 0; i < hb_list_count( stream->title->list_audio ); ++i )
479 hb_audio_t *audio = hb_list_item( stream->title->list_audio, i );
480 if ( audio->id == indx )
485 // not in the title's audio list - declare the PID inactive
486 stream->ts_audio_pids[aud_indx] = -stream->ts_audio_pids[aud_indx];
490 /***********************************************************************
492 ***********************************************************************
494 **********************************************************************/
495 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
497 FILE *f = fopen( path, "rb" );
500 hb_log( "hb_stream_open: open %s failed", path );
504 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
508 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
513 * if we're opening the stream to read & convert, we need
514 * the state we saved when we scanned the stream. if we're
515 * opening the stream to scan it we want to rebuild the state
516 * (even if we have saved state, the stream may have changed).
518 hb_stream_t *ss = hb_stream_lookup( path );
519 if ( title && ss && ss->hb_stream_type != ffmpeg )
522 * copy the saved state since we might be encoding the same stream
525 memcpy( d, ss, sizeof(*d) );
528 d->path = strdup( path );
530 if ( d->hb_stream_type == transport )
532 d->ts_packet = malloc( d->packetsize );
535 for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
537 if ( i && audio_inactive( d, i ) )
539 // this PID isn't wanted (we don't have a codec for it
540 // or scan didn't find audio parameters)
543 d->ts_buf[i] = hb_buffer_init(d->packetsize);
544 d->ts_buf[i]->size = 0;
546 hb_stream_seek( d, 0. );
552 * opening for scan - delete any saved state then (re)scan the stream.
553 * If it's something we can deal with (MPEG2 PS or TS) return a stream
554 * reference structure & null otherwise.
558 hb_stream_state_delete( ss );
562 d->path = strdup( path );
563 if (d->path != NULL )
565 if ( hb_stream_get_type( d ) != 0 )
569 fclose( d->file_handle );
570 d->file_handle = NULL;
571 if ( ffmpeg_open( d, title ) )
576 if ( d->file_handle )
578 fclose( d->file_handle );
584 hb_log( "hb_stream_open: open %s failed", path );
589 /***********************************************************************
591 ***********************************************************************
592 * Closes and frees everything
593 **********************************************************************/
594 void hb_stream_close( hb_stream_t ** _d )
596 hb_stream_t *stream = * _d;
598 if ( stream->hb_stream_type == ffmpeg )
600 ffmpeg_close( stream );
601 hb_stream_delete( stream );
606 if ( stream->frames )
608 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
609 stream->errors, (double)stream->errors * 100. /
610 (double)stream->frames );
614 * if the stream was opened for a scan, cache the result, otherwise delete
617 if ( stream->title == NULL )
619 hb_stream_delete_dynamic( stream );
620 if ( stream_state_list == NULL )
622 stream_state_list = hb_list_init();
624 hb_list_add( stream_state_list, stream );
628 hb_stream_delete( stream );
633 /* when the file was first opened we made entries for all the audio elementary
634 * streams we found in it. Streams that were later found during the preview scan
635 * now have an audio codec, type, rate, etc., associated with them. At the end
636 * of the scan we delete all the audio entries that weren't found by the scan
637 * or don't have a format we support. This routine deletes audio entry 'indx'
638 * by setting its PID to an invalid value so no packet will match it. (We can't
639 * move any of the entries since the index of the entry is used as the id
640 * of the media stream for HB. */
641 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
643 if ( stream->ts_audio_pids[indx] > 0 )
645 stream->ts_audio_pids[indx] = -stream->ts_audio_pids[indx];
649 static int index_of_pid(int pid, hb_stream_t *stream)
653 if ( pid == stream->ts_video_pids[0] )
656 for ( i = 0; i < stream->ts_number_audio_pids; ++i )
657 if ( pid == stream->ts_audio_pids[i] )
663 /***********************************************************************
664 * hb_ps_stream_title_scan
665 ***********************************************************************
667 **********************************************************************/
668 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
670 if ( stream->hb_stream_type == ffmpeg )
671 return ffmpeg_title_scan( stream );
674 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
675 aTitle->type = HB_STREAM_TYPE;
678 // Copy part of the stream path to the title name
679 char *sep = strrchr(stream->path, '/');
681 strcpy(aTitle->name, sep+1);
682 char *dot_term = strrchr(aTitle->name, '.');
686 // Height, width, rate and aspect ratio information is filled in when the previews are built
688 hb_stream_duration(stream, aTitle);
691 hb_chapter_t * chapter;
692 chapter = calloc( sizeof( hb_chapter_t ), 1 );
694 chapter->duration = aTitle->duration;
695 chapter->hours = aTitle->hours;
696 chapter->minutes = aTitle->minutes;
697 chapter->seconds = aTitle->seconds;
698 hb_list_add( aTitle->list_chapter, chapter );
700 // Figure out how many audio streams we really have:
701 // - For transport streams, for each PID listed in the PMT (whether
702 // or not it was an audio stream type) read the bitstream until we
703 // find an packet from that PID containing a PES header and see if
704 // the elementary stream is an audio type.
705 // - For program streams read the first 4MB and take every unique
706 // audio stream we find.
707 if (stream->hb_stream_type == transport)
711 for (i=0; i < stream->ts_number_audio_pids; i++)
713 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
714 if (audio->config.in.codec)
715 hb_list_add( aTitle->list_audio, audio );
719 hb_stream_delete_audio_entry(stream, i);
723 // make sure we're grabbing the PCR PID
724 if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
726 stream->ts_audio_pids[stream->ts_number_audio_pids++] =
727 stream->pmt_info.PCR_PID;
730 // set the video id, codec & muxer
731 aTitle->video_id = 0;
732 aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
733 aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
734 aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
736 if ( ( stream->ts_flags & TS_HAS_PCR ) == 0 )
738 hb_log( "transport stream missing PCRs - using video DTS instead" );
741 if ( stream->ts_IDRs < 1 )
743 hb_log( "transport stream doesn't seem to have video IDR frames" );
744 aTitle->flags |= HBTF_NO_IDR;
749 hb_ps_stream_find_audio_ids(stream, aTitle);
756 * read the next transport stream packet from 'stream'. Return NULL if
757 * we hit eof & a pointer to the sync byte otherwise.
759 static const uint8_t *next_packet( hb_stream_t *stream )
761 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
765 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
774 // lost sync - back up to where we started then try to re-establish.
775 off_t pos = ftello(stream->file_handle) - stream->packetsize;
776 off_t pos2 = align_to_next_packet(stream);
779 hb_log( "next_packet: eof while re-establishing sync @ %"PRId64, pos );
782 ts_warn( stream, "next_packet: sync lost @ %"PRId64", regained after %"PRId64" bytes",
788 * skip to the start of the next PACK header in program stream src_stream.
790 static void skip_to_next_pack( hb_stream_t *src_stream )
792 // scan forward until we find the start of the next pack
793 uint32_t strt_code = -1;
796 flockfile( src_stream->file_handle );
797 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
799 strt_code = ( strt_code << 8 ) | c;
800 if ( strt_code == 0x000001ba )
801 // we found the start of the next pack
804 funlockfile( src_stream->file_handle );
806 // if we didn't terminate on an eof back up so the next read
807 // starts on the pack boundary.
810 fseeko( src_stream->file_handle, -4, SEEK_CUR );
814 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
816 // For mpeg2: look for a gop start or i-frame picture start
817 // for h.264: look for idr nal type or a slice header for an i-frame
818 // for vc1: look for a Sequence header
823 if ( stream->ts_stream_type[0] <= 2 )
825 // This section of the code handles MPEG-1 and MPEG-2 video streams
826 for (i = 13 + adapt_len; i < 188; i++)
828 strid = (strid << 8) | buf[i];
829 if ( ( strid >> 8 ) == 1 )
831 // we found a start code
835 case 0xB8: // group_start_code (GOP header)
836 case 0xB3: // sequence_header code
839 case 0x00: // picture_start_code
840 // picture_header, let's see if it's an I-frame
843 // check if picture_coding_type == 1
844 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
846 // found an I-frame picture
854 // didn't find an I-frame
857 if ( stream->ts_stream_type[0] == 0x1b )
859 // we have an h.264 stream
860 for (i = 13 + adapt_len; i < 188; i++)
862 strid = (strid << 8) | buf[i];
863 if ( ( strid >> 8 ) == 1 )
865 // we found a start code - remove the ref_idc from the nal type
866 uint8_t nal_type = strid & 0x1f;
867 if ( nal_type == 0x05 )
868 // h.264 IDR picture start
872 // didn't find an I-frame
875 if ( stream->ts_stream_type[0] == 0xea )
877 // we have an vc1 stream
878 for (i = 13 + adapt_len; i < 188; i++)
880 strid = (strid << 8) | buf[i];
881 if ( strid == 0x10f )
883 // the ffmpeg vc1 decoder requires a seq hdr code in the first
888 // didn't find an I-frame
892 // we don't understand the stream type so just say "yes" otherwise
893 // we'll discard all the video.
898 * scan the next MB of 'stream' to find the next start packet for
899 * the Packetized Elementary Stream associated with TS PID 'pid'.
901 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
903 int npack = 300000; // max packets to read
907 const uint8_t *buf = next_packet( stream );
910 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
914 // while we're reading the stream, check if it has valid PCRs
915 // and/or random access points.
916 uint32_t pack_pid = ( (buf[1] & 0x1f) << 8 ) | buf[2];
917 if ( pack_pid == stream->pmt_info.PCR_PID )
919 if ( ( buf[5] & 0x10 ) &&
920 ( ( ( buf[3] & 0x30 ) == 0x20 ) ||
921 ( ( buf[3] & 0x30 ) == 0x30 && buf[4] > 6 ) ) )
923 stream->ts_flags |= TS_HAS_PCR;
928 stream->ts_flags |= TS_HAS_RAP;
932 * The PES header is only in TS packets with 'start' set so we check
933 * that first then check for the right PID.
935 if ((buf[1] & 0x40) == 0 || pack_pid != pid )
937 // not a start packet or not the pid we want
941 /* skip over the TS hdr to return a pointer to the PES hdr */
943 switch (buf[3] & 0x30)
945 case 0x00: // illegal
946 case 0x20: // fill packet
949 case 0x30: // adaptation
952 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
958 /* PES hdr has to begin with an mpeg start code */
959 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
969 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
971 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
972 hb_list_t *list = hb_list_init();
973 // how many blocks we read while searching for a video PES header
977 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
981 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
982 hb_demux_ps( buf, list, 0 );
984 while ( ( es = hb_list_item( list, 0 ) ) )
986 hb_list_rem( list, es );
987 if ( es->id == 0xe0 )
989 // this PES contains video - if there's a PTS we're done
990 // hb_demux_ps left the PTS in buf_es->start.
991 if ( es->start != ~0 )
998 hb_buffer_close( &es );
1001 hb_list_empty( &list );
1002 hb_buffer_close(&buf);
1006 /***********************************************************************
1007 * hb_stream_duration
1008 ***********************************************************************
1010 * Finding stream duration is difficult. One issue is that the video file
1011 * may have chunks from several different program fragments (main feature,
1012 * commercials, station id, trailers, etc.) all with their own base pts
1013 * value. We can't find the piece boundaries without reading the entire
1014 * file but if we compute a rate based on time stamps from two different
1015 * pieces the result will be meaningless. The second issue is that the
1016 * data rate of compressed video normally varies by 5-10x over the length
1017 * of the video. This says that we want to compute the rate over relatively
1018 * long segments to get a representative average but long segments increase
1019 * the likelihood that we'll cross a piece boundary.
1021 * What we do is take time stamp samples at several places in the file
1022 * (currently 16) then compute the average rate (i.e., ticks of video per
1023 * byte of the file) for all pairs of samples (N^2 rates computed for N
1024 * samples). Some of those rates will be absurd because the samples came
1025 * from different segments. Some will be way low or high because the
1026 * samples came from a low or high motion part of the segment. But given
1027 * that we're comparing *all* pairs the majority of the computed rates
1028 * should be near the overall average. So we median filter the computed
1029 * rates to pick the most representative value.
1031 **********************************************************************/
1033 uint64_t pos; /* file position of this PTS sample */
1034 uint64_t pts; /* PTS from video stream */
1037 #define NDURSAMPLES 128
1039 // get one (position, timestamp) sampple from a transport or program
1041 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
1043 struct pts_pos pp = { 0, 0 };
1045 if ( stream->hb_stream_type == transport )
1048 fseeko( stream->file_handle, fpos, SEEK_SET );
1049 align_to_next_packet( stream );
1050 buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
1053 hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
1056 if ( ( buf[7] >> 7 ) != 1 )
1058 hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
1061 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
1062 ( (uint64_t)buf[10] << 22 ) |
1063 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
1064 ( (uint64_t)buf[12] << 7 ) |
1065 ( (uint64_t)buf[13] >> 1 );
1067 if ( isIframe( stream, buf, -4 ) )
1069 if ( stream->ts_IDRs < 255 )
1077 // round address down to nearest dvd sector start
1078 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
1079 fseeko( stream->file_handle, fpos, SEEK_SET );
1080 if ( stream->hb_stream_type == program )
1082 skip_to_next_pack( stream );
1084 pp.pts = hb_ps_stream_getVideoPTS( stream );
1086 pp.pos = ftello(stream->file_handle);
1090 static int dur_compare( const void *a, const void *b )
1092 const double *aval = a, *bval = b;
1093 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
1096 // given an array of (position, time) samples, compute a max-likelihood
1097 // estimate of the average rate by computing the rate between all pairs
1098 // of samples then taking the median of those rates.
1099 static double compute_stream_rate( struct pts_pos *pp, int n )
1102 double rates[NDURSAMPLES * NDURSAMPLES / 8];
1105 // the following nested loops compute the rates between all pairs.
1107 for ( i = 0; i < n-1; ++i )
1109 // Bias the median filter by not including pairs that are "far"
1110 // from one another. This is to handle cases where the file is
1111 // made of roughly equal size pieces where a symmetric choice of
1112 // pairs results in having the same number of intra-piece &
1113 // inter-piece rate estimates. This would mean that the median
1114 // could easily fall in the inter-piece part of the data which
1115 // would give a bogus estimate. The 'ns' index creates an
1116 // asymmetry that favors locality.
1117 int ns = i + ( n >> 3 );
1120 for ( j = i+1; j < ns; ++j )
1122 if ( (uint64_t)(pp[j].pts - pp[i].pts) > 90000LL*3600*6 )
1124 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
1126 *rp = ((double)( pp[j].pts - pp[i].pts )) /
1127 ((double)( pp[j].pos - pp[i].pos ));
1132 // now compute and return the median of all the (n*n/2) rates we computed
1134 int nrates = rp - rates;
1135 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
1136 return rates[nrates >> 1];
1139 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
1141 struct pts_pos ptspos[NDURSAMPLES];
1142 struct pts_pos *pp = ptspos;
1145 fseeko(stream->file_handle, 0, SEEK_END);
1146 uint64_t fsize = ftello(stream->file_handle);
1147 uint64_t fincr = fsize / NDURSAMPLES;
1148 uint64_t fpos = fincr / 2;
1149 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1151 *pp++ = hb_sample_pts(stream, fpos);
1153 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1154 inTitle->duration = dur;
1156 inTitle->hours = dur / 3600;
1157 inTitle->minutes = ( dur % 3600 ) / 60;
1158 inTitle->seconds = dur % 60;
1160 rewind(stream->file_handle);
1163 /***********************************************************************
1165 ***********************************************************************
1167 **********************************************************************/
1168 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1170 if ( src_stream->hb_stream_type == ffmpeg )
1172 return ffmpeg_read( src_stream, b );
1174 if ( src_stream->hb_stream_type == dvd_program )
1176 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1177 src_stream->file_handle);
1178 return (amt_read > 0);
1180 if ( src_stream->hb_stream_type == program )
1182 // a general program stream has arbitrary sized pack's. we're
1183 // currently positioned at the start of a pack so read up to but
1184 // not including the start of the next, expanding the buffer
1186 uint8_t *cp = b->data;
1187 uint8_t *ep = cp + b->alloc;
1188 uint32_t strt_code = -1;
1191 // consume the first byte of the initial pack so we don't match on
1192 // it in the loop below.
1193 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1198 flockfile( src_stream->file_handle );
1199 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1201 strt_code = ( strt_code << 8 ) | c;
1202 if ( strt_code == 0x000001ba )
1203 // we found the start of the next pack
1207 // need to expand the buffer
1208 int curSize = cp - b->data;
1209 hb_buffer_realloc( b, curSize * 2 );
1210 cp = b->data + curSize;
1211 ep = b->data + b->alloc;
1214 // Non-video streams can emulate start codes, so we need
1215 // to inspect PES packets and skip over their data
1216 // sections to avoid mis-detection of the next pack header.
1217 if ( ( strt_code >> 8 ) == 0x000001 &&
1218 ( strt_code & 0xff ) >= 0xbb )
1221 c = getc_unlocked( src_stream->file_handle );
1225 c = getc_unlocked( src_stream->file_handle );
1229 if ( cp+len+2 > ep )
1231 // need to expand the buffer
1232 int curSize = cp - b->data;
1233 if ( curSize * 2 > curSize+len+2 )
1234 hb_buffer_realloc( b, curSize * 2 );
1236 hb_buffer_realloc( b, curSize + len + 2 );
1237 cp = b->data + curSize;
1238 ep = b->data + b->alloc;
1242 fread( cp, 1, len, src_stream->file_handle );
1246 funlockfile( src_stream->file_handle );
1248 // if we didn't terminate on an eof back up so the next read
1249 // starts on the pack boundary.
1250 b->size = cp - b->data;
1253 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1254 // Only 3 of the 4 bytes read were added to the buffer.
1259 return hb_ts_stream_decode( src_stream, b );
1262 int64_t ffmpeg_initial_timestamp( hb_stream_t * stream )
1264 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id];
1265 if ( s->nb_index_entries < 1 )
1268 return s->index_entries[0].timestamp;
1270 int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
1273 if ( stream->hb_stream_type != ffmpeg )
1275 // currently meaningliess for transport and program streams
1278 if ( !stream || !stream->title ||
1279 chapter_num > hb_list_count( stream->title->list_chapter ) )
1284 int64_t sum_dur = 0;
1285 hb_chapter_t *chapter = NULL;
1287 for ( i = 0; i < chapter_num; ++i)
1289 chapter = hb_list_item( stream->title->list_chapter, i );
1290 sum_dur += chapter->duration;
1292 stream->chapter = chapter_num - 1;
1293 stream->chapter_end = sum_dur;
1295 int64_t pos = ( ( ( sum_dur - chapter->duration ) * AV_TIME_BASE ) / 90000 ) + ffmpeg_initial_timestamp( stream );
1297 hb_deep_log( 2, "Seeking to chapter %d: starts %"PRId64", ends %"PRId64", AV pos %"PRId64,
1298 chapter_num, sum_dur - chapter->duration, sum_dur, pos);
1300 if ( chapter_num > 1 && pos > 0 )
1302 av_seek_frame( stream->ffmpeg_ic, -1, pos, 0);
1306 // ffmpeg has a bug that causes the first PTS after
1307 // av_find_stream_info() is called to be incorrect.
1308 // av_find_stream_info is called whenever opening a file
1309 // with ffmpeg. av_seek_frame clears the condition
1310 // that causes the problem. since hb_stream_seek_chapter
1311 // is called before we start reading, make sure
1312 // we do a seek here.
1313 av_seek_frame( stream->ffmpeg_ic, -1, ffmpeg_initial_timestamp( stream ), AVSEEK_FLAG_BACKWARD );
1318 /***********************************************************************
1320 ***********************************************************************
1321 * Return the number of the chapter that we are currently in. We store
1322 * the chapter number starting from 0, so + 1 for the real chpater num.
1323 **********************************************************************/
1324 int hb_stream_chapter( hb_stream_t * src_stream )
1326 return( src_stream->chapter + 1 );
1329 /***********************************************************************
1331 ***********************************************************************
1333 **********************************************************************/
1334 int hb_stream_seek( hb_stream_t * stream, float f )
1336 if ( stream->hb_stream_type == ffmpeg )
1338 return ffmpeg_seek( stream, f );
1340 off_t stream_size, cur_pos, new_pos;
1341 double pos_ratio = f;
1342 cur_pos = ftello( stream->file_handle );
1343 fseeko( stream->file_handle, 0, SEEK_END );
1344 stream_size = ftello( stream->file_handle );
1345 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1346 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1348 int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1351 fseeko( stream->file_handle, cur_pos, SEEK_SET );
1355 if ( stream->hb_stream_type == transport )
1357 // We need to drop the current decoder output and move
1358 // forwards to the next transport stream packet.
1359 hb_ts_stream_reset(stream);
1362 if ( stream->ts_IDRs )
1364 // the stream has IDRs so look for one.
1365 stream->need_keyframe = 1;
1370 // we're at the beginning - say we have video sync so that we
1371 // won't drop initial SPS & PPS data on an AVC stream.
1372 stream->need_keyframe = 0;
1375 else if ( stream->hb_stream_type == program )
1377 skip_to_next_pack( stream );
1383 int hb_stream_seek_ts( hb_stream_t * stream, int64_t ts )
1385 if ( stream->hb_stream_type == ffmpeg )
1387 return ffmpeg_seek_ts( stream, ts );
1392 static const char* make_upper( const char* s )
1394 static char name[8];
1396 char *ep = cp + sizeof(name)-1;
1398 while ( *s && cp < ep )
1400 *cp++ = islower(*s)? toupper(*s) : *s;
1407 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1410 * This is a duplicate of code in dvd.c - it should get factored out
1411 * into a common routine. We probably should only be putting the lang
1412 * code or a lang pointer into the audio config & let the common description
1413 * formatting routine in scan.c do all the stuff below.
1415 const char *codec_name;
1418 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1419 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1420 avcodec_find_decoder( cc->codec_id ) )
1422 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1423 if ( !strcmp( codec_name, "LIBFAAD" ) )
1428 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1429 avcodec_find_decoder( audio->config.in.codec_param ) )
1431 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1435 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1436 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1437 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1438 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1439 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1442 snprintf( audio->config.lang.description,
1443 sizeof( audio->config.lang.description ), "%s (%s)",
1444 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1447 if (audio->config.in.codec == HB_ACODEC_FFMPEG)
1449 int layout = audio->config.in.channel_layout;
1450 char *desc = audio->config.lang.description +
1451 strlen( audio->config.lang.description );
1452 sprintf( desc, " (%d.%d ch)",
1453 HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(layout) +
1454 HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(layout),
1455 HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(layout) );
1458 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1459 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1460 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1461 "%s", lang->iso639_2);
1464 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1467 off_t cur_pos = ftello(stream->file_handle);
1468 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1471 fseeko(stream->file_handle, 0, SEEK_SET);
1472 align_to_next_packet(stream);
1473 buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1475 /* check that we found a PES header */
1479 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1481 stype = stream->ts_stream_type[1 + aud_pid_index];
1482 kind = st2codec[stype].kind;
1484 // 0xbd ("private stream 1") is the normal container for non-ISO
1485 // media - AC3/DCA/PCM/etc.
1486 if ( buf[3] == 0xbd )
1488 if ( st2codec[stype].kind == U )
1490 // XXX assume unknown stream types are AC-3 (if they're not
1491 // audio we'll find that out during the scan but if they're
1492 // some other type of audio we'll end up ignoring them).
1494 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1495 kind = st2codec[stype].kind;
1497 if ( stype == 0x80 &&
1498 stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1500 // LPCM audio in bluray have an stype of 0x80
1501 // 0x80 is used for other DigiCipher normally
1502 // To distinguish, Bluray streams have a reg_desc of HDMV
1506 else if ( buf[3] == 0xfd )
1508 // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1509 // the blu ray consortium apparently forgot to read the portion
1510 // of the MPEG spec that says one PID should map to one media
1511 // stream and multiplexed multiple types of audio into one PID
1512 // using the extended stream identifier of the PES header to
1513 // distinguish them. So we have to check if that's happening and
1514 // if so tell the runtime what esid we want.
1515 if ( st2codec[stype].kind == A && stype == 0x83 &&
1516 stream->ts_format_id[1 + aud_pid_index] == TS_FORMAT_ID_AC3 )
1518 // This is an interleaved TrueHD/AC-3 stream and the esid of
1520 stream->ts_multiplexed[1 + aud_pid_index] = 0x76;
1522 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1523 kind = st2codec[stype].kind;
1525 if ( st2codec[stype].kind == A && stype == 0x86 )
1527 // This is an interleaved DTS-HD/DTS stream and the esid of
1529 stream->ts_multiplexed[1 + aud_pid_index] = 0x71;
1531 stream->ts_stream_type[1 + aud_pid_index] = 0x82;
1532 kind = st2codec[stype].kind;
1535 else if ((buf[3] & 0xe0) == 0xc0)
1537 // 0xC0 - 0xCF are the normal containers for ISO-standard
1538 // media (mpeg2 audio and mpeg4 AAC).
1539 if ( st2codec[stype].kind == U )
1541 // XXX assume unknown stream types are MPEG audio
1543 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1544 kind = st2codec[stype].kind;
1550 kind = st2codec[stype].kind;
1553 // if we found an audio stream type & HB has a codec that can decode it
1554 // finish configuring the audio so we'll add it to the title's list.
1555 if ( kind == A && st2codec[stype].codec )
1557 audio->id = 1 + aud_pid_index;
1558 audio->config.in.codec = st2codec[stype].codec;
1559 audio->config.in.codec_param = st2codec[stype].codec_param;
1560 set_audio_description( audio,
1561 lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1562 hb_log("transport stream pid 0x%x (type 0x%x) may be %s audio (id 0x%x)",
1563 stream->ts_audio_pids[aud_pid_index],
1564 stype, st2codec[stype].name, audio->id);
1570 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1571 "isn't audio", stream->ts_audio_pids[aud_pid_index],
1572 stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1576 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1577 stream->ts_audio_pids[aud_pid_index],
1578 stream->ts_stream_type[1 + aud_pid_index]);
1581 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1585 static void add_audio_to_title(hb_title_t *title, int id)
1587 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1593 audio->config.in.codec = HB_ACODEC_MPGA;
1594 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1597 // type 2 is a DVD subtitle stream - just ignore it */
1601 audio->config.in.codec = HB_ACODEC_AC3;
1602 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1605 audio->config.in.codec = HB_ACODEC_LPCM;
1606 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1609 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1614 set_audio_description( audio, lang_for_code( 0 ) );
1615 hb_list_add( title->list_audio, audio );
1618 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1620 off_t cur_pos = ftello(stream->file_handle);
1621 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1622 hb_list_t *list = hb_list_init();
1623 // how many blocks we read while searching for audio streams
1624 int blksleft = 4096;
1625 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1626 // so we use a bitmap to keep track of the ones we've already seen.
1627 // Bit 'i' of smap is set if we've already added the audio for
1628 // audio substream id 'i' to the title's audio list.
1631 // start looking 20% into the file since there's occasionally no
1632 // audio at the beginning (particularly for vobs).
1633 hb_stream_seek(stream, 0.2f);
1635 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1639 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1640 hb_demux_ps( buf, list, 0 );
1642 while ( ( es = hb_list_item( list, 0 ) ) )
1644 hb_list_rem( list, es );
1645 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1647 // this PES contains some kind of audio - get the substream id
1648 // and check if we've seen it already.
1649 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1650 if ( (smap & (1 << ssid)) == 0 )
1652 // we haven't seen this stream before - add it to the
1653 // title's list of audio streams.
1654 smap |= (1 << ssid);
1655 add_audio_to_title(title, es->id);
1658 hb_buffer_close( &es );
1661 hb_list_empty( &list );
1662 hb_buffer_close(&buf);
1663 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1666 /***********************************************************************
1668 ***********************************************************************
1670 **********************************************************************/
1672 static void hb_ts_stream_init(hb_stream_t *stream)
1676 for (i=0; i < kMaxNumberDecodeStreams; i++)
1678 stream->ts_streamcont[i] = -1;
1680 stream->ts_video_pids[0] = -1;
1681 for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1683 stream-> ts_audio_pids[i] = -1;
1686 stream->ts_packet = malloc( stream->packetsize );
1688 // Find the audio and video pids in the stream
1689 hb_ts_stream_find_pids(stream);
1691 for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1693 // demuxing buffer for TS to PS conversion
1694 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1695 stream->ts_buf[i]->size = 0;
1699 #define MAX_HOLE 208*80
1701 static off_t align_to_next_packet(hb_stream_t *stream)
1703 uint8_t buf[MAX_HOLE];
1705 off_t start = ftello(stream->file_handle);
1708 if ( start >= stream->packetsize ) {
1709 start -= stream->packetsize;
1710 fseeko(stream->file_handle, start, SEEK_SET);
1716 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1718 const uint8_t *bp = buf;
1721 for ( i = sizeof(buf) - 8 * stream->packetsize; --i >= 0; ++bp )
1723 if ( have_ts_sync( bp, stream->packetsize ) )
1730 pos = ( bp - buf ) - stream->packetsize + 188;
1733 fseeko(stream->file_handle, -8 * stream->packetsize, SEEK_CUR);
1734 start = ftello(stream->file_handle);
1741 fseeko(stream->file_handle, start+pos, SEEK_SET);
1742 return start - orig + pos;
1752 static const unsigned int bitmask[] = {
1753 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1754 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1755 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1756 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1758 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1762 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1763 (bb->buf[2] << 8) | bb->buf[3];
1765 memset(bb->buf, 0, bufsize);
1768 static inline int buf_size(bitbuf_t *bb)
1770 return bb->pos >> 3;
1773 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1776 int left = 32 - (bb->pos & 31);
1780 val = (bb->val >> (left - bits)) & bitmask[bits];
1785 val = (bb->val & bitmask[left]) << (bits - left);
1789 int pos = bb->pos >> 3;
1790 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1794 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1802 // extract what useful information we can from the elementary stream
1803 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1804 // Descriptors with info we don't currently use are ignored.
1805 // The descriptor list & descriptor item formats are defined in
1806 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1807 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1808 const uint8_t *dp, uint8_t dlen)
1810 const uint8_t *ep = dp + dlen;
1816 case 5: // Registration descriptor
1817 stream->ts_format_id[esindx+1] = (dp[2] << 24) | (dp[3] << 16) |
1818 (dp[4] << 8) | dp[5];
1821 case 10: // ISO_639_language descriptor
1822 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1825 case 0x6a: // DVB AC-3 descriptor
1826 stream->ts_stream_type[esindx+1] = 0x81;
1836 static const char *stream_type_name (uint8_t stream_type)
1838 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1841 int decode_program_map(hb_stream_t* stream)
1844 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1846 get_bits(&bb, 8); // table_id
1848 unsigned int section_length = get_bits(&bb, 12);
1849 stream->pmt_info.section_length = section_length;
1851 unsigned int program_number = get_bits(&bb, 16);
1852 stream->pmt_info.program_number = program_number;
1854 get_bits(&bb, 5); // version_number
1856 get_bits(&bb, 8); // section_number
1857 get_bits(&bb, 8); // last_section_number
1859 stream->pmt_info.PCR_PID = get_bits(&bb, 13);
1861 int program_info_length = get_bits(&bb, 12);
1862 stream->pmt_info.program_info_length = program_info_length;
1865 for (i = 0; i < program_info_length - 2; )
1868 tag = get_bits(&bb, 8);
1869 len = get_bits(&bb, 8);
1871 if ( i + len > program_info_length )
1875 if (tag == 0x05 && len >= 4)
1877 // registration descriptor
1878 stream->pmt_info.reg_desc = get_bits(&bb, 32);
1883 for ( j = 0; j < len; j++ )
1889 for ( ; i < program_info_length; i++ )
1894 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
1895 int done_reading_stream_types = 0;
1896 while (!done_reading_stream_types)
1898 unsigned char stream_type = get_bits(&bb, 8);
1900 unsigned int elementary_PID = get_bits(&bb, 13);
1902 unsigned int ES_info_length = get_bits(&bb, 12);
1905 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1906 for (i=0; i < ES_info_length; i++)
1908 ES_info_buf[i] = get_bits(&bb, 8);
1912 if ( index_of_pid( elementary_PID, stream ) < 0 )
1914 // don't have this pid yet
1915 if (stream->ts_number_video_pids == 0 &&
1916 st2codec[stream_type].kind == V )
1918 stream->ts_video_pids[0] = elementary_PID;
1919 stream->ts_stream_type[0] = stream_type;
1920 stream->ts_number_video_pids = 1;
1924 // Defined audio stream types are 0x81 for AC-3/A52 audio
1925 // and 0x03 for mpeg audio. But content producers seem to
1926 // use other values (0x04 and 0x06 have both been observed)
1927 // so at this point we say everything that isn't a video
1928 // pid is audio then at the end of hb_stream_title_scan
1929 // we'll figure out which are really audio by looking at
1931 i = stream->ts_number_audio_pids;
1932 if (i < kMaxNumberAudioPIDS)
1934 stream->ts_audio_pids[i] = elementary_PID;
1935 stream->ts_stream_type[1 + i] = stream_type;
1936 if (ES_info_length > 0)
1938 decode_element_descriptors(stream, i, ES_info_buf,
1941 ++stream->ts_number_audio_pids;
1946 cur_pos += 5 /* stream header */ + ES_info_length;
1950 if (cur_pos >= section_length - 4 /* stop before the CRC */)
1951 done_reading_stream_types = 1;
1957 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1959 // Get adaption header info
1961 int adaption = (buf[3] & 0x30) >> 4;
1964 else if (adaption == 0x2)
1966 else if (adaption == 0x3)
1967 adapt_len = buf[4] + 1;
1968 if (adapt_len > 184)
1971 // Get payload start indicator
1973 start = (buf[1] & 0x40) != 0;
1975 // Get pointer length - only valid in packets with a start flag
1976 int pointer_len = 0;
1980 pointer_len = buf[4 + adapt_len] + 1;
1981 stream->pmt_info.tablepos = 0;
1983 // Get Continuity Counter
1984 int continuity_counter = buf[3] & 0x0f;
1985 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1987 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1990 stream->pmt_info.current_continuity_counter = continuity_counter;
1991 stream->pmt_info.reading |= start;
1993 // Add the payload for this packet to the current buffer
1994 int amount_to_copy = 184 - adapt_len - pointer_len;
1995 if (stream->pmt_info.reading && (amount_to_copy > 0))
1997 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1999 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
2000 stream->pmt_info.tablepos += amount_to_copy;
2002 if (stream->pmt_info.tablepos > 3)
2004 // We have enough to check the section length
2006 length = ((stream->pmt_info.tablebuf[1] << 8) +
2007 stream->pmt_info.tablebuf[2]) & 0xFFF;
2008 if (stream->pmt_info.tablepos > length + 1)
2010 // We just finished a bunch of packets - parse the program map details
2012 if (stream->pmt_info.tablebuf[0] == 0x02)
2013 decode_ok = decode_program_map(stream);
2014 free(stream->pmt_info.tablebuf);
2015 stream->pmt_info.tablebuf = NULL;
2016 stream->pmt_info.tablepos = 0;
2017 stream->pmt_info.reading = 0;
2027 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
2029 unsigned char tablebuf[1024];
2030 unsigned int tablepos = 0;
2035 // Get adaption header info
2037 int adaption = (buf[3] & 0x30) >> 4;
2040 else if (adaption == 0x2)
2042 else if (adaption == 0x3)
2043 adapt_len = buf[4] + 1;
2044 if (adapt_len > 184)
2047 // Get pointer length
2048 int pointer_len = buf[4 + adapt_len] + 1;
2050 // Get payload start indicator
2052 start = (buf[1] & 0x40) != 0;
2057 // Add the payload for this packet to the current buffer
2058 if (reading && (184 - adapt_len) > 0)
2060 if (tablepos + 184 - adapt_len - pointer_len > 1024)
2062 hb_log("decode_PAT - Bad program section length (> 1024)");
2065 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
2066 tablepos += 184 - adapt_len - pointer_len;
2069 if (start && reading)
2071 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
2074 unsigned int pos = 0;
2075 //while (pos < tablepos)
2078 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
2080 unsigned char section_id = get_bits(&bb, 8);
2082 unsigned int section_len = get_bits(&bb, 12);
2083 get_bits(&bb, 16); // transport_id
2085 get_bits(&bb, 5); // version_num
2086 get_bits(&bb, 1); // current_next
2087 get_bits(&bb, 8); // section_num
2088 get_bits(&bb, 8); // last_section
2094 // Program Association Section
2095 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
2096 section_len -= 4; // Ignore the CRC
2098 stream->ts_number_pat_entries = 0;
2099 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
2101 unsigned int pkt_program_num = get_bits(&bb, 16);
2102 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
2104 get_bits(&bb, 3); // Reserved
2105 if (pkt_program_num == 0)
2107 get_bits(&bb, 13); // pkt_network_id
2111 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
2112 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
2115 stream->ts_number_pat_entries++;
2129 pos += 3 + section_len;
2137 static void hb_ts_stream_find_pids(hb_stream_t *stream)
2139 // To be different from every other broadcaster in the world, New Zealand TV
2140 // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
2141 // we may have the tail of the previous program at the beginning of this
2142 // file, take our PMT from the middle of the file.
2143 fseeko(stream->file_handle, 0, SEEK_END);
2144 uint64_t fsize = ftello(stream->file_handle);
2145 fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
2146 align_to_next_packet(stream);
2148 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
2149 // to find the program map PID and then decode that to get the list of audio and video PIDs
2153 const uint8_t *buf = next_packet( stream );
2157 hb_log("hb_ts_stream_find_pids - end of file");
2162 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
2164 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
2166 decode_PAT(buf, stream);
2171 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
2173 // There are some streams where the PAT table has multiple entries as if their are
2174 // multiple programs in the same transport stream, and yet there's actually only one
2175 // program really in the stream. This seems to be true for transport streams that
2176 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
2177 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
2178 // but the EyeTV is only recording a single (selected) program number and not rewriting the
2179 // PAT info on export to match what's actually on the stream.
2180 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
2181 // on the first pat entry for which we find a matching program map PID. The ideal solution would
2182 // be to build a title choice popup from the PAT program number details and then select from
2183 // their - but right now the API's not capable of that.
2184 if (stream->pat_info[pat_index].program_number != 0 &&
2185 pid == stream->pat_info[pat_index].program_map_PID)
2187 if (build_program_map(buf, stream) > 0)
2191 // Keep going until we have a complete set of PIDs
2192 if (stream->ts_number_video_pids > 0)
2196 hb_log("hb_ts_stream_find_pids - found the following PIDS");
2197 hb_log(" Video PIDS : ");
2199 for (i=0; i < stream->ts_number_video_pids; i++)
2201 hb_log( " 0x%x type %s (0x%x)",
2202 stream->ts_video_pids[i],
2203 stream_type_name(stream->ts_stream_type[i]),
2204 stream->ts_stream_type[i]);
2206 hb_log(" Audio PIDS : ");
2207 for (i = 0; i < stream->ts_number_audio_pids; i++)
2209 hb_log( " 0x%x type %s (0x%x)",
2210 stream->ts_audio_pids[i],
2211 stream_type_name(stream->ts_stream_type[i+1]),
2212 stream->ts_stream_type[i+1] );
2217 static void fwrite64( hb_stream_t *stream, void *buf, int len )
2221 int pos = stream->fwrite_buf->size;
2222 if ( pos + len > stream->fwrite_buf->alloc )
2224 int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
2225 hb_buffer_realloc(stream->fwrite_buf, size);
2227 memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
2228 stream->fwrite_buf->size += len;
2232 // convert a PES PTS or DTS to an int64
2233 static int64_t pes_timestamp( const uint8_t *pes )
2235 int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2236 ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
2237 ( pes[3] << 7 ) | ( pes[4] >> 1 );
2241 static void generate_output_data(hb_stream_t *stream, int curstream)
2243 hb_buffer_t *buf = stream->fwrite_buf;
2244 uint8_t *tdat = stream->ts_buf[curstream]->data;
2246 buf->id = curstream;
2248 // check if this packet was referenced to an older pcr and if that
2249 // pcr was significantly different than the one we're using now.
2250 // (the reason for the uint cast on the pcr difference is that the
2251 // difference is significant if it advanced by more than 200ms or if
2252 // it went backwards by any amount. The negative numbers look like huge
2253 // unsigned ints so the cast allows both conditions to be checked at once.
2254 int bufpcr = stream->ts_buf[curstream]->cur;
2255 int curpcr = stream->ts_pcr_out;
2256 if ( bufpcr && bufpcr < curpcr &&
2257 (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2259 // we've sent up a new pcr but have a packet referenced to an
2260 // old pcr and the difference was enough to trigger a discontinuity
2261 // correction. smash the timestamps or we'll mess up the correction.
2263 buf->renderOffset = -1;
2267 if ( stream->ts_pcr_out != stream->ts_pcr_in )
2269 // we have a new pcr
2270 stream->ts_pcr_out = stream->ts_pcr_in;
2271 buf->stop = stream->ts_pcr;
2272 stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2279 // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2280 // off the PES header.
2281 if ( tdat[7] & 0xc0 )
2283 buf->start = pes_timestamp( tdat + 9 );
2284 buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2290 buf->renderOffset = -1;
2293 int hlen = tdat[8] + 9;
2295 fwrite64( stream, tdat + hlen, stream->ts_pos[curstream] - hlen );
2297 stream->ts_pos[curstream] = 0;
2298 stream->ts_buf[curstream]->size = 0;
2301 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2303 if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2307 size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2308 hb_buffer_realloc(stream->ts_buf[idx], size);
2310 memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2311 stream->ts_pos[idx] += len;
2312 stream->ts_buf[idx]->size += len;
2315 /***********************************************************************
2316 * hb_ts_stream_decode
2317 ***********************************************************************
2319 **********************************************************************/
2320 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2323 * stash the output buffer pointer in our stream so we don't have to
2324 * pass it & its original value to everything we call.
2327 stream->fwrite_buf = obuf;
2329 // spin until we get a packet of data from some stream or hit eof
2334 const uint8_t *buf = next_packet(stream);
2337 // end of file - we didn't finish filling our ps write buffer
2338 // so just discard the remainder (the partial buffer is useless)
2339 hb_log("hb_ts_stream_decode - eof");
2343 /* This next section validates the packet */
2345 // Get pid and use it to find stream state.
2346 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2347 if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2351 int errorbit = (buf[1] & 0x80) != 0;
2354 ts_err( stream, curstream, "packet error bit set");
2358 // Get adaption header info
2359 int adaption = (buf[3] & 0x30) >> 4;
2363 ts_err( stream, curstream, "adaptation code 0");
2366 else if (adaption == 0x2)
2368 else if (adaption == 0x3)
2370 adapt_len = buf[4] + 1;
2371 if (adapt_len > 184)
2373 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2378 if ( adapt_len > 0 )
2380 if ( buf[5] & 0x40 )
2382 // found a random access point
2384 // if there's an adaptation header & PCR_flag is set
2385 // get the PCR (Program Clock Reference)
2386 if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2388 stream->ts_pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2389 ( (uint64_t)buf[7] << (33 - 16) ) |
2390 ( (uint64_t)buf[8] << (33 - 24) ) |
2391 ( (uint64_t)buf[9] << (33 - 32) ) |
2393 ++stream->ts_pcr_in;
2394 stream->ts_found_pcr = 1;
2398 // If we don't have a PCR yet but the stream has PCRs just loop
2399 // so we don't process anything until we have a clock reference.
2400 // Unfortunately the HD Home Run appears to null out the PCR so if
2401 // we didn't detect a PCR during scan keep going and we'll use
2402 // the video stream DTS for the PCR.
2404 if ( !stream->ts_found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
2410 // Continuity only increments for adaption values of 0x3 or 0x01
2411 // and is not checked for start packets.
2413 int start = (buf[1] & 0x40) != 0;
2415 if ( (adaption & 0x01) != 0 )
2417 int continuity = (buf[3] & 0xF);
2418 if ( continuity == stream->ts_streamcont[curstream] )
2420 // Spliced transport streams can have duplicate
2421 // continuity counts at the splice boundary.
2422 // Test to see if the packet is really a duplicate
2423 // by comparing packet summaries to see if they
2427 summary[0] = adaption;
2428 summary[1] = adapt_len;
2429 if (adapt_len + 4 + 6 + 9 <= 188)
2431 memcpy(&summary[2], buf+4+adapt_len+9, 6);
2435 memset(&summary[2], 0, 6);
2437 if ( memcmp( summary, stream->ts_pkt_summary[curstream], 8 ) == 0 )
2439 // we got a duplicate packet (usually used to introduce
2440 // a PCR when one is needed). The only thing that can
2441 // change in the dup is the PCR which we grabbed above
2442 // so ignore the rest.
2446 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2447 !stream->ts_skipbad[curstream] &&
2448 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2450 ts_err( stream, curstream, "continuity error: got %d expected %d",
2452 (stream->ts_streamcont[curstream] + 1) & 0xf );
2453 stream->ts_streamcont[curstream] = continuity;
2456 stream->ts_streamcont[curstream] = continuity;
2458 // Save a summary of this packet for later duplicate
2459 // testing. The summary includes some header information
2460 // and payload bytes. Should be enough to detect
2462 stream->ts_pkt_summary[curstream][0] = adaption;
2463 stream->ts_pkt_summary[curstream][1] = adapt_len;
2464 if (adapt_len + 4 + 6 + 9 <= 188)
2466 memcpy(&stream->ts_pkt_summary[curstream][2],
2467 buf+4+adapt_len+9, 6);
2471 memset(&stream->ts_pkt_summary[curstream][2], 0, 6);
2475 /* If we get here the packet is valid - process its data */
2479 // Found a random access point (now we can start a frame/audio packet..)
2481 if ( stream->need_keyframe )
2483 // we're looking for the first video frame because we're
2484 // doing random access during 'scan'
2485 if ( curstream != 0 || !isIframe( stream, buf, adapt_len ) )
2487 // not the video stream or didn't find an I frame
2488 // but we'll only wait 255 video frames for an I frame.
2489 if ( curstream != 0 || ++stream->need_keyframe )
2494 stream->need_keyframe = 0;
2497 // If we were skipping a bad packet, start fresh on this new PES packet..
2498 if (stream->ts_skipbad[curstream] == 1)
2500 stream->ts_skipbad[curstream] = 0;
2503 if ( curstream == 0 )
2507 // if we don't have a pcr yet use the dts from this frame
2508 if ( !stream->ts_found_pcr )
2510 // PES must begin with an mpeg start code & contain
2512 const uint8_t *pes = buf + adapt_len + 4;
2513 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2514 ( pes[7] >> 6 ) == 0 )
2518 // if we have a dts use it otherwise use the pts
2519 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40? 14 : 9 ) );
2520 ++stream->ts_pcr_in;
2524 // if this is a multiplexed stream make sure this is the
2525 // substream we want.
2526 if ( stream->ts_multiplexed[curstream] )
2528 // PES must begin with an mpeg start code & contain
2530 const uint8_t *pes = buf + adapt_len + 4;
2531 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2534 stream->ts_skipbad[curstream] = 1;
2537 // the last byte of the header is the extension id. see if
2538 // it's the one we want.
2539 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2541 stream->ts_skipbad[curstream] = 1;
2546 // If we have some data already on this stream, turn it into
2547 // a program stream packet. Then add the payload for this
2548 // packet to the current pid's buffer.
2549 if ( stream->ts_pos[curstream] )
2551 // we have to ship the old packet before updating the pcr
2552 // since the packet we've been accumulating is referenced
2554 generate_output_data(stream, curstream);
2556 // remember the pcr that was in effect when we started
2558 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2559 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2563 // remember the pcr that was in effect when we started this packet.
2564 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2567 // Add the payload for this packet to the current buffer
2568 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2570 hb_ts_stream_append_pkt(stream, curstream, buf + 4 + adapt_len,
2572 // see if we've hit the end of this PES packet
2573 const uint8_t *pes = stream->ts_buf[curstream]->data;
2574 int len = ( pes[4] << 8 ) + pes[5] + 6;
2575 if ( len > 6 && stream->ts_pos[curstream] == len &&
2576 pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2578 generate_output_data(stream, curstream);
2585 static void hb_ts_stream_reset(hb_stream_t *stream)
2589 for (i=0; i < kMaxNumberDecodeStreams; i++)
2591 stream->ts_pos[i] = 0;
2592 stream->ts_skipbad[i] = 1;
2593 stream->ts_streamcont[i] = -1;
2596 stream->need_keyframe = 0;
2598 stream->ts_found_pcr = 0;
2599 stream->ts_pcr_out = 0;
2600 stream->ts_pcr_in = 0;
2605 stream->last_error_frame = -10000;
2606 stream->last_error_count = 0;
2608 align_to_next_packet(stream);
2611 // ------------------------------------------------------------------
2612 // Support for reading media files via the ffmpeg libraries.
2614 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2616 // add a codec to the context here so it will be there when we
2617 // read the first packet.
2618 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2619 context->workaround_bugs = FF_BUG_AUTODETECT;
2620 context->error_recognition = 1;
2621 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2622 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2623 hb_avcodec_open( context, codec );
2626 // The ffmpeg stream reader / parser shares a lot of state with the
2627 // decoder via a codec context kept in the AVStream of the reader's
2628 // AVFormatContext. Since decoding is done in a different thread we
2629 // have to somehow pass this codec context to the decoder and we have
2630 // to do it before the first packet is read (so we can't put the info
2631 // in the buf we'll send downstream). Decoders don't have any way to
2632 // get to the stream directly (they're not passed the title or job
2633 // pointers during a scan) so this is a back door for the decoder to
2634 // get the codec context. We just stick the stream pointer in the next
2635 // slot an array of pointers maintained as a circular list then return
2636 // the index into the list combined with the ffmpeg stream index as the
2637 // codec_param that will be passed to the decoder init routine. We make
2638 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2639 // so that we don't have to do a complicated allocator or worry about
2640 // deleting entries on close.
2642 // Entries can only be added to this list during a scan and are never
2643 // deleted so the list access doesn't require locking.
2644 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2645 static int ffmpeg_stream_cur; // where we put the last stream pointer
2646 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2647 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2649 // add a stream to the list & return the appropriate codec_param to access it
2650 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2652 if ( !ffmpeg_streams )
2654 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2657 // the title scan adds all the ffmpeg media streams at once so we
2658 // only add a new entry to our stream list if the stream is different
2660 int slot = ffmpeg_stream_cur;
2661 if ( ffmpeg_streams[slot] != stream )
2663 // new stream - put it in the next slot of the stream list
2664 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2665 ffmpeg_streams[slot] = stream;
2668 ffmpeg_add_codec( stream, stream_index );
2670 return ( stream_index << ffmpeg_sl_bits ) | slot;
2673 // we're about to open 'title' to convert it - remap the stream associated
2674 // with the video & audio codec params of the title to refer to 'stream'
2675 // (the original scan stream was closed and no longer exists).
2676 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2678 // all the video & audio came from the same stream so remapping
2679 // the video's stream slot takes care of everything.
2680 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2681 ffmpeg_streams[slot] = stream;
2683 // add codecs for all the streams used by the title
2684 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2688 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2690 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2692 ffmpeg_add_codec( stream,
2693 audio->config.in.codec_param >> ffmpeg_sl_bits );
2698 void *hb_ffmpeg_context( int codec_param )
2700 int slot = codec_param & (ffmpeg_sl_size - 1);
2701 int stream_index = codec_param >> ffmpeg_sl_bits;
2702 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2705 void *hb_ffmpeg_avstream( int codec_param )
2707 int slot = codec_param & (ffmpeg_sl_size - 1);
2708 int stream_index = codec_param >> ffmpeg_sl_bits;
2709 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2712 static AVFormatContext *ffmpeg_deferred_close;
2714 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2716 if ( ffmpeg_deferred_close )
2718 av_close_input_file( ffmpeg_deferred_close );
2719 ffmpeg_deferred_close = NULL;
2721 AVFormatContext *ic;
2723 av_log_set_level( AV_LOG_ERROR );
2724 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2728 if ( av_find_stream_info( ic ) < 0 )
2731 stream->ffmpeg_ic = ic;
2732 stream->hb_stream_type = ffmpeg;
2733 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2734 av_init_packet( stream->ffmpeg_pkt );
2735 stream->chapter_end = INT64_MAX;
2739 // we're opening for read. scan passed out codec params that
2740 // indexed its stream so we need to remap them so they point
2742 ffmpeg_remap_stream( stream, title );
2743 av_log_set_level( AV_LOG_ERROR );
2747 // we're opening for scan. let ffmpeg put some info into the
2748 // log about what we've got.
2749 av_log_set_level( AV_LOG_INFO );
2750 dump_format( ic, 0, stream->path, 0 );
2751 av_log_set_level( AV_LOG_ERROR );
2753 // accept this file if it has at least one video stream we can decode
2755 for (i = 0; i < ic->nb_streams; ++i )
2757 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2762 if ( i >= ic->nb_streams )
2768 av_close_input_file( ic );
2772 static void ffmpeg_close( hb_stream_t *d )
2774 // XXX since we're sharing the CodecContext with the downstream
2775 // decoder proc we can't close the stream. We need to reference count
2776 // this so we can close it when both are done with their instance but
2777 // for now just defer the close until the next stream open or close.
2778 if ( ffmpeg_deferred_close )
2780 av_close_input_file( ffmpeg_deferred_close );
2782 ffmpeg_deferred_close = d->ffmpeg_ic;
2783 if ( d->ffmpeg_pkt != NULL )
2785 free( d->ffmpeg_pkt );
2786 d->ffmpeg_pkt = NULL;
2790 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2792 AVStream *st = stream->ffmpeg_ic->streams[id];
2793 AVCodecContext *codec = st->codec;
2796 // scan will ignore any audio without a bitrate. Since we've already
2797 // typed the audio in order to determine its codec we set up the audio
2799 layout = hb_ff_layout_xlat( codec->channel_layout, codec->channels );
2802 // Unsupported layout
2805 if ( codec->bit_rate || codec->sample_rate )
2807 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2810 if ( codec->codec_id == CODEC_ID_AC3 )
2812 audio->config.in.codec = HB_ACODEC_AC3;
2814 else if ( codec->codec_id == CODEC_ID_DTS )
2816 audio->config.in.codec = HB_ACODEC_DCA;
2820 audio->config.in.codec = HB_ACODEC_FFMPEG;
2821 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2823 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2824 audio->config.in.samplerate = codec->sample_rate;
2825 audio->config.in.channel_layout = layout;
2828 set_audio_description( audio, lang_for_code2( st->language ) );
2830 hb_list_add( title->list_audio, audio );
2835 * Parses the 'subtitle->palette' information from the specific VOB subtitle track's private data.
2836 * Returns 0 if successful or 1 if parsing failed or was incomplete.
2839 * MkvVobSubtitlePrivateData = ( Line )*
2840 * Line = FieldName ':' ' ' FieldValue '\n'
2842 * FieldValue = [^\n]+
2844 * The line of interest is:
2845 * PaletteLine = "palette" ':' ' ' RRGGBB ( ',' ' ' RRGGBB )*
2847 * More information on the format at:
2848 * http://www.matroska.org/technical/specs/subtitles/images.html
2850 static int ffmpeg_parse_vobsub_extradata( AVCodecContext *codec, hb_subtitle_t *subtitle )
2852 if ( codec->extradata_size <= 0 )
2855 // lines = (string) codec->extradata;
2856 char *lines = malloc( codec->extradata_size + 1 );
2857 if ( lines == NULL )
2859 memcpy( lines, codec->extradata, codec->extradata_size );
2860 lines[codec->extradata_size] = '\0';
2865 char *curLine, *curLine_parserData;
2866 for ( curLine = strtok_r( lines, "\n", &curLine_parserData );
2868 curLine = strtok_r( NULL, "\n", &curLine_parserData ) )
2870 int numElementsRead = sscanf(curLine, "palette: "
2871 "%06x, %06x, %06x, %06x, "
2872 "%06x, %06x, %06x, %06x, "
2873 "%06x, %06x, %06x, %06x, "
2874 "%06x, %06x, %06x, %06x",
2875 &rgb[0], &rgb[1], &rgb[2], &rgb[3],
2876 &rgb[4], &rgb[5], &rgb[6], &rgb[7],
2877 &rgb[8], &rgb[9], &rgb[10], &rgb[11],
2878 &rgb[12], &rgb[13], &rgb[14], &rgb[15]);
2880 if (numElementsRead == 16) {
2891 for (i=0; i<16; i++)
2892 subtitle->palette[i] = hb_rgb2yuv(rgb[i]);
2901 static void add_ffmpeg_subtitle( hb_title_t *title, hb_stream_t *stream, int id )
2903 AVStream *st = stream->ffmpeg_ic->streams[id];
2904 AVCodecContext *codec = st->codec;
2906 hb_subtitle_t *subtitle = calloc( 1, sizeof(*subtitle) );
2910 switch ( codec->codec_id )
2912 case CODEC_ID_DVD_SUBTITLE:
2913 subtitle->format = PICTURESUB;
2914 subtitle->source = VOBSUB;
2915 subtitle->config.dest = RENDERSUB; // By default render (burn-in) the VOBSUB.
2916 if ( ffmpeg_parse_vobsub_extradata( codec, subtitle ) )
2917 hb_log( "add_ffmpeg_subtitle: malformed extradata for VOB subtitle track; "
2918 "subtitle colors likely to be wrong" );
2921 subtitle->format = TEXTSUB;
2922 subtitle->source = UTF8SUB;
2923 subtitle->config.dest = PASSTHRUSUB;
2925 case CODEC_ID_MOV_TEXT: // TX3G
2926 subtitle->format = TEXTSUB;
2927 subtitle->source = TX3GSUB;
2928 subtitle->config.dest = PASSTHRUSUB;
2930 // TODO(davidfstr): implement SSA subtitle support
2933 subtitle->format = TEXTSUB;
2934 subtitle->source = SSASUB;
2935 subtitle->config.dest = PASSTHRUSUB;
2939 hb_log( "add_ffmpeg_subtitle: unknown subtitle stream type: 0x%x", (int) codec->codec_id );
2944 iso639_lang_t *language = lang_for_code2( st->language );
2945 strcpy( subtitle->lang, language->eng_name );
2946 strncpy( subtitle->iso639_2, language->iso639_2, 4 );
2948 hb_list_add(title->list_subtitle, subtitle);
2951 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2953 AVFormatContext *ic = stream->ffmpeg_ic;
2955 // 'Barebones Title'
2956 hb_title_t *title = hb_title_init( stream->path, 0 );
2957 title->type = HB_STREAM_TYPE;
2960 // Copy part of the stream path to the title name
2961 char *sep = strrchr(stream->path, '/');
2963 strcpy(title->name, sep+1);
2964 char *dot_term = strrchr(title->name, '.');
2968 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2969 title->duration = dur;
2971 title->hours = dur / 3600;
2972 title->minutes = ( dur % 3600 ) / 60;
2973 title->seconds = dur % 60;
2975 // set the title to decode the first video stream in the file
2976 title->demuxer = HB_NULL_DEMUXER;
2977 title->video_codec = 0;
2979 for (i = 0; i < ic->nb_streams; ++i )
2981 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2982 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2983 title->video_codec == 0 )
2985 AVCodecContext *context = ic->streams[i]->codec;
2986 if ( context->pix_fmt != PIX_FMT_YUV420P &&
2987 !sws_isSupportedInput( context->pix_fmt ) )
2989 hb_log( "ffmpeg_title_scan: Unsupported color space" );
2992 title->video_id = i;
2993 stream->ffmpeg_video_id = i;
2995 // We have to use the 'internal' avcodec decoder because
2996 // it needs to share the codec context from this video
2997 // stream. The parser internal to av_read_frame
2998 // passes a bunch of state info to the decoder via the context.
2999 title->video_codec = WORK_DECAVCODECVI;
3000 title->video_codec_param = ffmpeg_codec_param( stream, i );
3002 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
3003 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
3005 add_ffmpeg_audio( title, stream, i );
3007 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_SUBTITLE )
3009 add_ffmpeg_subtitle( title, stream, i );
3013 title->container_name = strdup( ic->iformat->name );
3014 title->data_rate = ic->bit_rate;
3016 hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );
3018 if( ic->nb_chapters != 0 )
3021 uint64_t duration_sum = 0;
3022 for( i = 0; i < ic->nb_chapters; i++ )
3023 if( ( m = ic->chapters[i] ) != NULL )
3025 hb_chapter_t * chapter;
3026 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3027 chapter->index = i+1;
3028 chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000 - duration_sum;
3029 duration_sum += chapter->duration;
3030 chapter->hours = chapter->duration / 90000 / 3600;
3031 chapter->minutes = ( ( chapter->duration / 90000 ) % 3600 ) / 60;
3032 chapter->seconds = ( chapter->duration / 90000 ) % 60;
3033 strcpy( chapter->title, m->title );
3034 hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
3035 chapter->index, chapter->title,
3036 chapter->duration, chapter->hours,
3037 chapter->minutes, chapter->seconds );
3038 hb_list_add( title->list_chapter, chapter );
3043 * Fill the metadata.
3045 decmetadata( title );
3047 if( hb_list_count( title->list_chapter ) == 0 )
3049 // Need at least one chapter
3050 hb_chapter_t * chapter;
3051 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3053 chapter->duration = title->duration;
3054 chapter->hours = title->hours;
3055 chapter->minutes = title->minutes;
3056 chapter->seconds = title->seconds;
3057 hb_list_add( title->list_chapter, chapter );
3063 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
3065 if ( pts == AV_NOPTS_VALUE )
3067 return (int64_t)( (double)pts * conv_factor );
3070 static int ffmpeg_is_keyframe( hb_stream_t *stream )
3074 switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
3077 // XXX the VC1 codec doesn't mark key frames so to get previews
3078 // we do it ourselves here. The decoder gets messed up if it
3079 // doesn't get a SEQ header first so we consider that to be a key frame.
3080 pkt = stream->ffmpeg_pkt->data;
3081 if ( !pkt[0] && !pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
3087 // XXX the ffmpeg WMV3 codec doesn't mark key frames.
3088 // Only M$ could make I-frame detection this complicated: there
3089 // are two to four bits of unused junk ahead of the frame type
3090 // so we have to look at the sequence header to find out how much
3091 // to skip. Then there are three different ways of coding the type
3092 // depending on whether it's main or advanced profile then whether
3093 // there are bframes or not so we have to look at the sequence
3094 // header to get that.
3095 pkt = stream->ffmpeg_pkt->data;
3096 uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
3098 if ( ( seqhdr[3] & 0x02 ) == 0 )
3101 if ( ( seqhdr[3] & 0x80 ) == 0 )
3102 // no RANGEREDUCTION
3104 if ( seqhdr[3] & 0x70 )
3105 // stream has b-frames
3106 return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;
3108 return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;
3113 return ( stream->ffmpeg_pkt->flags & PKT_FLAG_KEY );
3116 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
3120 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
3122 // XXX the following conditional is to handle avi files that
3123 // use M$ 'packed b-frames' and occasionally have negative
3124 // sizes for the null frames these require.
3125 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
3129 if ( stream->ffmpeg_pkt->size <= 0 )
3131 // M$ "invalid and inefficient" packed b-frames require 'null frames'
3132 // following them to preserve the timing (since the packing puts two
3133 // or more frames in what looks like one avi frame). The contents and
3134 // size of these null frames are ignored by the ff_h263_decode_frame
3135 // as long as they're < 20 bytes. We need a positive size so we use
3136 // one byte if we're given a zero or negative size. We don't know
3137 // if the pkt data points anywhere reasonable so we just stick a
3138 // byte of zero in our outbound buf.
3144 if ( stream->ffmpeg_pkt->size > buf->alloc )
3146 // sometimes we get absurd sizes from ffmpeg
3147 if ( stream->ffmpeg_pkt->size >= (1 << 25) )
3149 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
3150 av_free_packet( stream->ffmpeg_pkt );
3151 return ffmpeg_read( stream, buf );
3153 // need to expand buffer
3154 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
3156 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
3157 buf->size = stream->ffmpeg_pkt->size;
3159 buf->id = stream->ffmpeg_pkt->stream_index;
3160 if ( buf->id == stream->ffmpeg_video_id )
3162 if ( stream->need_keyframe )
3164 // we've just done a seek (generally for scan or live preview) and
3165 // want to start at a keyframe. Some ffmpeg codecs seek to a key
3166 // frame but most don't. So we spin until we either get a keyframe
3167 // or we've looked through 50 video frames without finding one.
3168 if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
3170 av_free_packet( stream->ffmpeg_pkt );
3173 stream->need_keyframe = 0;
3178 // if we haven't done it already, compute a conversion factor to go
3179 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
3180 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
3183 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
3184 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
3185 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
3188 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
3189 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
3190 if ( buf->renderOffset >= 0 && buf->start == -1 )
3192 buf->start = buf->renderOffset;
3194 else if ( buf->renderOffset == -1 && buf->start >= 0 )
3196 buf->renderOffset = buf->start;
3200 * Fill out buf->stop for subtitle packets
3202 * libavcodec's MKV demuxer stores the duration of UTF-8 subtitles (CODEC_ID_TEXT)
3203 * in the 'convergence_duration' field for some reason.
3205 * Other subtitles' durations are stored in the 'duration' field.
3207 * VOB subtitles (CODEC_ID_DVD_SUBTITLE) do not have their duration stored in
3208 * either field. This is not a problem because the VOB decoder can extract this
3209 * information from the packet payload itself.
3211 enum CodecID ffmpeg_pkt_codec = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_id;
3212 if ( ffmpeg_pkt_codec == CODEC_ID_TEXT ) {
3213 int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->convergence_duration;
3214 int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3215 buf->stop = buf->start + buf_duration;
3217 if ( ffmpeg_pkt_codec == CODEC_ID_MOV_TEXT ) {
3218 int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->duration;
3219 int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3220 buf->stop = buf->start + buf_duration;
3224 * Check to see whether this video buffer is on a chapter
3225 * boundary, if so mark it as such in the buffer then advance
3226 * chapter_end to the end of the next chapter.
3227 * If there are no chapters, chapter_end is always initialized to INT64_MAX
3228 * (roughly 3 million years at our 90KHz clock rate) so the test
3229 * below handles both the chapters & no chapters case.
3231 if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
3233 hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
3234 stream->chapter+1 );
3238 stream->chapter_end += chapter->duration;
3239 buf->new_chap = stream->chapter + 1;
3240 hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
3241 buf->new_chap, buf->start);
3243 // Must have run out of chapters, stop looking.
3244 stream->chapter_end = INT64_MAX;
3249 av_free_packet( stream->ffmpeg_pkt );
3253 static int ffmpeg_seek( hb_stream_t *stream, float frac )
3255 AVFormatContext *ic = stream->ffmpeg_ic;
3258 int64_t pos = (double)ic->duration * (double)frac;
3259 if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
3261 pos += ic->start_time;
3263 av_seek_frame( ic, -1, pos, 0 );
3264 stream->need_keyframe = 1;
3268 av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
3273 // Assumes that we are always seeking forward
3274 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
3276 AVFormatContext *ic = stream->ffmpeg_ic;
3279 pos = ts * AV_TIME_BASE / 90000 + ffmpeg_initial_timestamp( stream );
3280 stream->need_keyframe = 1;
3281 // Seek to the nearest timestamp before that requested where
3282 // there is an I-frame
3283 return av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );