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
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.
28 * U - Unknown (to be determined by further processing)
33 typedef enum { N, U, A, V, P } 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 #if defined(OLD_LATM_PATCH)
62 st(0x11, A, HB_ACODEC_MPGA, CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
64 st(0x11, N, 0, 0, "MPEG4 LATM AAC"),
66 st(0x12, U, 0, 0, "MPEG4 generic"),
68 st(0x14, N, 0, 0, "ISO 13818-6 DSM-CC download"),
70 st(0x1b, V, WORK_DECAVCODECV, CODEC_ID_H264, "H.264"),
72 st(0x80, N, HB_ACODEC_MPGA, CODEC_ID_PCM_BLURAY, "DigiCipher II Video"),
73 st(0x81, A, HB_ACODEC_AC3, 0, "AC-3"),
74 st(0x82, A, HB_ACODEC_DCA, 0, "HDMV DTS"),
75 st(0x83, A, HB_ACODEC_LPCM, 0, "LPCM"),
76 st(0x84, A, 0, 0, "SDDS"),
77 st(0x85, U, 0, 0, "ATSC Program ID"),
78 st(0x86, A, HB_ACODEC_DCA, 0, "DTS-HD"),
79 st(0x87, A, 0, 0, "E-AC-3"),
81 st(0x8a, A, HB_ACODEC_DCA, 0, "DTS"),
83 st(0x91, A, HB_ACODEC_AC3, 0, "AC-3"),
84 st(0x92, N, 0, 0, "Subtitle"),
86 st(0x94, A, 0, 0, "SDDS"),
87 st(0xa0, V, 0, 0, "MSCODEC"),
89 st(0xea, V, WORK_DECAVCODECV, CODEC_ID_VC1, "VC1"),
94 hb_stream_type_unknown = 0,
101 #define kMaxNumberDecodeStreams 32
102 #define kMaxNumberPMTStreams 32
107 int frames; /* video frames so far */
108 int errors; /* total errors so far */
109 int last_error_frame; /* frame # at last error message */
110 int last_error_count; /* # errors at last error message */
111 int packetsize; /* Transport Stream packet size */
113 uint8_t need_keyframe; // non-zero if want to start at a keyframe
114 uint8_t ts_found_pcr; // non-zero if we've found at least one input pcr
115 int ts_pcr_out; // sequence number of most recent output pcr
116 int ts_pcr_in; // sequence number of most recent input pcr
117 int64_t ts_pcr; // most recent input pcr
118 int64_t ts_pcrhist[4]; // circular buffer of output pcrs
120 uint8_t *ts_packet; /* buffer for one TS packet */
121 hb_buffer_t *ts_buf[kMaxNumberDecodeStreams];
122 int ts_pos[kMaxNumberDecodeStreams];
123 int8_t ts_skipbad[kMaxNumberDecodeStreams];
124 int8_t ts_streamcont[kMaxNumberDecodeStreams];
125 uint8_t ts_pkt_summary[kMaxNumberDecodeStreams][8];
127 hb_buffer_t *fwrite_buf; /* PS buffer (set by hb_ts_stream_decode) */
129 int chapter; /* Chapter that we are currently in */
130 int64_t chapter_end; /* HB time that the current chapter ends */
133 * Stuff before this point is dynamic state updated as we read the
134 * stream. Stuff after this point is stream description state that
135 * we learn during the initial scan but cache so it can be
136 * reused during the conversion read.
138 uint8_t ts_number_pids;
139 uint8_t ts_flags; // stream characteristics:
140 #define TS_HAS_PCR (1 << 0) // at least one PCR seen
141 #define TS_HAS_RAP (1 << 1) // Random Access Point bit seen
142 #define TS_HAS_RSEI (1 << 2) // "Restart point" SEI seen
143 uint8_t ts_IDRs; // # IDRs found during duration scan
145 int16_t ts_pids[kMaxNumberDecodeStreams];
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 kind_t ts_stream_kind[kMaxNumberDecodeStreams];
151 uint8_t ts_multiplexed[kMaxNumberDecodeStreams];
155 hb_stream_type_t hb_stream_type;
158 AVFormatContext *ffmpeg_ic;
159 AVPacket *ffmpeg_pkt;
160 double ffmpeg_tsconv[MAX_STREAMS];
161 uint8_t ffmpeg_video_id;
168 } a52_info[kMaxNumberDecodeStreams];
172 unsigned short program_number;
173 unsigned short program_map_PID;
174 } pat_info[kMaxNumberPMTStreams];
175 int ts_number_pat_entries;
180 unsigned char *tablebuf;
181 unsigned int tablepos;
182 unsigned char current_continuity_counter;
186 unsigned int PCR_PID;
188 int program_info_length;
191 unsigned char stream_type;
192 unsigned short elementary_PID;
193 unsigned short ES_info_length;
194 unsigned char *es_info_descriptor_data;
195 } pmt_stream_info[kMaxNumberPMTStreams];
199 /***********************************************************************
201 **********************************************************************/
202 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
203 static void hb_ts_stream_init(hb_stream_t *stream);
204 static void hb_ts_stream_find_pids(hb_stream_t *stream);
205 static int hb_ts_stream_decode(hb_stream_t *stream, hb_buffer_t *obuf);
206 static void hb_ts_stream_reset(hb_stream_t *stream);
207 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
209 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
210 static off_t align_to_next_packet(hb_stream_t *stream);
212 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
213 static void ffmpeg_close( hb_stream_t *d );
214 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
215 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
216 static int ffmpeg_seek( hb_stream_t *stream, float frac );
217 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts );
220 * streams have a bunch of state that's learned during the scan. We don't
221 * want to throw away the state when scan does a close then relearn
222 * everything when reader does an open. So we save the stream state on
223 * the close following a scan and reuse it when 'reader' does an open.
225 static hb_list_t *stream_state_list;
227 static hb_stream_t *hb_stream_lookup( const char *path )
229 if ( stream_state_list == NULL )
235 while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
237 if ( strcmp( path, ss->path ) == 0 )
245 static void hb_stream_state_delete( hb_stream_t *ss )
247 hb_list_rem( stream_state_list, ss );
254 * these frontend hb_log because transport streams can have a lot of errors
255 * so we want to rate limit messages. this routine limits the number of
256 * messages to at most one per minute of video. other errors that occur
257 * during the minute are counted & the count is output with the next
258 * error msg we print.
260 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
262 // limit error printing to at most one per minute of video (at 30fps)
264 if ( stream->frames - stream->last_error_frame >= 30*60 )
268 vsnprintf( msg, sizeof(msg), log, args );
270 if ( stream->errors - stream->last_error_count < 10 )
272 hb_log( "stream: error near frame %d: %s", stream->frames, msg );
276 int Edelta = stream->errors - stream->last_error_count;
277 double Epcnt = (double)Edelta * 100. /
278 (stream->frames - stream->last_error_frame);
279 hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
280 Edelta, Epcnt, stream->frames, msg );
282 stream->last_error_frame = stream->frames;
283 stream->last_error_count = stream->errors;
287 static void ts_warn( hb_stream_t*, char*, ... ) HB_WPRINTF(2,3);
288 static void ts_err( hb_stream_t*, int, char*, ... ) HB_WPRINTF(3,4);
290 static void ts_warn( hb_stream_t *stream, char *log, ... )
293 va_start( args, log );
294 ts_warn_helper( stream, log, args );
298 static kind_t ts_stream_kind( hb_stream_t *stream, int curstream )
300 return st2codec[stream->ts_stream_type[curstream]].kind;
303 static int index_of_pid(hb_stream_t *stream, int pid)
307 for ( i = 0; i < stream->ts_number_pids; ++i )
308 if ( pid == stream->ts_pids[i] )
314 static int index_of_video(hb_stream_t *stream)
318 for ( i = 0; i < stream->ts_number_pids; ++i )
319 if ( V == stream->ts_stream_kind[i] )
325 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
328 va_start( args, log );
329 ts_warn_helper( stream, log, args );
332 stream->ts_skipbad[curstream] = 1;
333 stream->ts_pos[curstream] = 0;
334 stream->ts_streamcont[curstream] = -1;
337 static int check_ps_sync(const uint8_t *buf)
339 // a legal MPEG program stream must start with a Pack header in the
341 return (buf[0] == 0x00) && (buf[1] == 0x00) &&
342 (buf[2] == 0x01) && (buf[3] == 0xba);
345 static int check_ps_sc(const uint8_t *buf)
347 // a legal MPEG program stream must start with a Pack followed by a
348 // some other start code. If we've already verified the pack, this skip
349 // it and checks for a start code prefix.
350 int pos = 14 + ( buf[13] & 0x7 ); // skip over the PACK
351 return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) && (buf[pos+2] == 0x01);
354 static int check_ts_sync(const uint8_t *buf)
356 // must have initial sync byte, no scrambling & a legal adaptation ctrl
357 return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
360 static int have_ts_sync(const uint8_t *buf, int psize)
362 return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
363 check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
364 check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
365 check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
368 static int hb_stream_check_for_ts(const uint8_t *buf)
370 // transport streams should have a sync byte every 188 bytes.
371 // search the first 8KB of buf looking for at least 8 consecutive
372 // correctly located sync patterns.
375 for ( offset = 0; offset < 8*1024-8*188; ++offset )
377 if ( have_ts_sync( &buf[offset], 188) )
378 return 188 | (offset << 8);
379 if ( have_ts_sync( &buf[offset], 192) )
380 return 192 | (offset << 8);
381 if ( have_ts_sync( &buf[offset], 204) )
382 return 204 | (offset << 8);
383 if ( have_ts_sync( &buf[offset], 208) )
384 return 208 | (offset << 8);
389 static int hb_stream_check_for_ps(hb_stream_t *stream)
396 fseek(stream->file_handle, 0, SEEK_SET);
398 // program streams should start with a PACK then some other mpeg start
399 // code (usually a SYS but that might be missing if we only have a clip).
400 while (pos < 512 * 1024)
404 if ( fread(buf, 1, sizeof(buf), stream->file_handle) != sizeof(buf) )
407 for ( offset = 0; offset < 8*1024-27; ++offset )
409 if ( check_ps_sync( &buf[offset] ) && check_ps_sc( &buf[offset] ) )
411 int pes_offset, prev, data_len;
416 pes_offset = 14 + (buf[13] & 0x7);
417 sid = buf[pes_offset+3];
418 data_len = (buf[pes_offset+4] << 8) + buf[pes_offset+5];
419 if ( data_len && sid > 0xba && sid < 0xf9 )
421 prev = ftell( stream->file_handle );
422 pos = pes_offset + 6 + data_len + prev;
423 fseek( stream->file_handle, pos, SEEK_SET );
424 if ( fread(sc_buf, 1, 4, stream->file_handle) != 4 )
426 if (sc_buf[0] == 0x00 && sc_buf[1] == 0x00 &&
431 fseek( stream->file_handle, prev, SEEK_SET );
435 fseek( stream->file_handle, -27, SEEK_CUR );
436 pos = ftell( stream->file_handle );
441 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
443 // DVD program streams should have a Pack header every 2048 bytes.
444 // check that we have 4 of these in a row.
445 return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
446 check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
449 static int hb_stream_get_type(hb_stream_t *stream)
453 if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
456 if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
458 int offset = psize >> 8;
460 hb_log("file is MPEG Transport Stream with %d byte packets"
461 " offset %d bytes", psize, offset);
462 stream->packetsize = psize;
463 stream->hb_stream_type = transport;
464 hb_ts_stream_init(stream);
465 if ( index_of_video( stream ) < 0 )
471 if ( hb_stream_check_for_dvd_ps(buf) != 0 )
473 hb_log("file is MPEG DVD Program Stream");
474 stream->hb_stream_type = dvd_program;
477 if ( hb_stream_check_for_ps(stream) != 0 )
479 hb_log("file is MPEG Program Stream");
480 stream->hb_stream_type = program;
487 static void hb_stream_delete_dynamic( hb_stream_t *d )
491 fclose( d->file_handle );
492 d->file_handle = NULL;
499 free( d->ts_packet );
502 for (i = 0; i < kMaxNumberDecodeStreams; i++)
506 hb_buffer_close(&(d->ts_buf[i]));
512 static void hb_stream_delete( hb_stream_t *d )
514 hb_stream_delete_dynamic( d );
519 static int audio_inactive( hb_stream_t *stream, int idx )
521 int pid = stream->ts_pids[idx];
525 // PID declared inactive by hb_stream_title_scan
528 if ( pid == stream->pmt_info.PCR_PID )
530 // PCR PID is always active
534 // see if we should make the stream inactive because scan.c didn't
535 // find a valid audio bitstream.
537 for ( i = 0; i < hb_list_count( stream->title->list_audio ); ++i )
539 hb_audio_t *audio = hb_list_item( stream->title->list_audio, i );
540 if ( audio->id == pid )
546 // not in the title's audio list - declare the PID inactive
547 stream->ts_pids[idx] = -stream->ts_pids[idx];
551 /***********************************************************************
553 ***********************************************************************
555 **********************************************************************/
556 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
558 FILE *f = fopen( path, "rb" );
561 hb_log( "hb_stream_open: open %s failed", path );
565 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
569 hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
574 * if we're opening the stream to read & convert, we need
575 * the state we saved when we scanned the stream. if we're
576 * opening the stream to scan it we want to rebuild the state
577 * (even if we have saved state, the stream may have changed).
579 hb_stream_t *ss = hb_stream_lookup( path );
580 if ( title && ss && ss->hb_stream_type != ffmpeg )
583 * copy the saved state since we might be encoding the same stream
586 memcpy( d, ss, sizeof(*d) );
589 d->path = strdup( path );
591 if ( d->hb_stream_type == transport )
593 d->ts_packet = malloc( d->packetsize );
596 for ( i = 0; i < d->ts_number_pids; i++)
598 if ( d->ts_stream_kind[i] == A &&
599 audio_inactive( d, i ) )
601 // this PID isn't wanted (we don't have a codec for it
602 // or scan didn't find audio parameters)
605 d->ts_buf[i] = hb_buffer_init(d->packetsize);
606 d->ts_buf[i]->size = 0;
608 hb_stream_seek( d, 0. );
614 * opening for scan - delete any saved state then (re)scan the stream.
615 * If it's something we can deal with (MPEG2 PS or TS) return a stream
616 * reference structure & null otherwise.
620 hb_stream_state_delete( ss );
624 d->path = strdup( path );
625 if (d->path != NULL )
627 if ( hb_stream_get_type( d ) != 0 )
631 fclose( d->file_handle );
632 d->file_handle = NULL;
633 if ( ffmpeg_open( d, title ) )
638 if ( d->file_handle )
640 fclose( d->file_handle );
646 hb_log( "hb_stream_open: open %s failed", path );
651 hb_stream_t * hb_bd_stream_open( hb_title_t *title )
655 hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
658 hb_log( "hb_bd_stream_open: can't allocate space for stream state" );
662 for (ii = 0; ii < kMaxNumberDecodeStreams; ii++)
664 d->ts_streamcont[ii] = -1;
668 d->file_handle = NULL;
673 d->ts_number_pids = 0;
674 d->ts_pids[0] = title->video_id;
675 d->ts_stream_type[0] = title->video_stream_type;
676 d->ts_stream_kind[0] = V;
680 for ( ii = 0; ( audio = hb_list_item( title->list_audio, ii ) ); ++ii )
682 d->ts_pids[d->ts_number_pids] = audio->id;
683 d->ts_stream_type[d->ts_number_pids] = audio->config.in.stream_type;
684 d->ts_stream_kind[d->ts_number_pids] = A;
686 if ( d->ts_stream_type[d->ts_number_pids] == 0x83 &&
687 title->reg_desc == STR4_TO_UINT32("HDMV") )
689 // This is an interleaved TrueHD/AC-3 stream and the esid of
691 d->ts_multiplexed[d->ts_number_pids] = 0x76;
692 d->ts_stream_type[d->ts_number_pids] = 0x81;
694 if ( d->ts_stream_type[d->ts_number_pids] == 0x86 &&
695 title->reg_desc == STR4_TO_UINT32("HDMV") )
697 // This is an interleaved DTS-HD/DTS stream and the esid of
699 d->ts_multiplexed[d->ts_number_pids] = 0x71;
700 d->ts_stream_type[d->ts_number_pids] = 0x82;
706 d->ts_flags = TS_HAS_RAP;
707 // When scanning, title->job == NULL. We don't need to wait for
708 // a PCR when scanning. In fact, it trips us up on the first
709 // preview of every title since we would have to read quite a
710 // lot of data before finding the PCR.
711 if (title->pcr_pid != 0xFFFF && title->job)
713 if ( index_of_pid( d, title->pcr_pid ) < 0 )
715 // BD PCR PID is specified to always be 0x1001
716 d->ts_pids[d->ts_number_pids] = 0x1001;
717 d->ts_stream_kind[d->ts_number_pids] = P;
723 d->hb_stream_type = transport;
725 for ( ii = 0; ii < d->ts_number_pids; ii++ )
727 d->ts_buf[ii] = hb_buffer_init(d->packetsize);
728 d->ts_buf[ii]->size = 0;
734 /***********************************************************************
736 ***********************************************************************
737 * Closes and frees everything
738 **********************************************************************/
739 void hb_stream_close( hb_stream_t ** _d )
741 hb_stream_t *stream = * _d;
743 if ( stream->hb_stream_type == ffmpeg )
745 ffmpeg_close( stream );
746 hb_stream_delete( stream );
751 if ( stream->frames )
753 hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
754 stream->errors, (double)stream->errors * 100. /
755 (double)stream->frames );
759 * if the stream was opened for a scan, cache the result, otherwise delete
762 if ( stream->title == NULL )
764 hb_stream_delete_dynamic( stream );
765 if ( stream_state_list == NULL )
767 stream_state_list = hb_list_init();
769 hb_list_add( stream_state_list, stream );
773 hb_stream_delete( stream );
778 /* when the file was first opened we made entries for all the audio elementary
779 * streams we found in it. Streams that were later found during the preview scan
780 * now have an audio codec, type, rate, etc., associated with them. At the end
781 * of the scan we delete all the audio entries that weren't found by the scan
782 * or don't have a format we support. This routine deletes audio entry 'indx'
783 * by setting its PID to an invalid value so no packet will match it. (We can't
784 * move any of the entries since the index of the entry is used as the id
785 * of the media stream for HB. */
786 static void hb_stream_delete_entry(hb_stream_t *stream, int indx)
788 if ( stream->ts_pids[indx] > 0 )
790 stream->ts_pids[indx] = -stream->ts_pids[indx];
794 /***********************************************************************
795 * hb_ps_stream_title_scan
796 ***********************************************************************
798 **********************************************************************/
799 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
801 if ( stream->hb_stream_type == ffmpeg )
802 return ffmpeg_title_scan( stream );
805 hb_title_t *aTitle = hb_title_init( stream->path, 0 );
806 aTitle->type = HB_STREAM_TYPE;
809 // Copy part of the stream path to the title name
810 char *sep = strrchr(stream->path, '/');
812 strcpy(aTitle->name, sep+1);
813 char *dot_term = strrchr(aTitle->name, '.');
817 // Height, width, rate and aspect ratio information is filled in when the previews are built
819 hb_stream_duration(stream, aTitle);
822 hb_chapter_t * chapter;
823 chapter = calloc( sizeof( hb_chapter_t ), 1 );
825 chapter->duration = aTitle->duration;
826 chapter->hours = aTitle->hours;
827 chapter->minutes = aTitle->minutes;
828 chapter->seconds = aTitle->seconds;
829 hb_list_add( aTitle->list_chapter, chapter );
831 // Figure out how many audio streams we really have:
832 // - For transport streams, for each PID listed in the PMT (whether
833 // or not it was an audio stream type) read the bitstream until we
834 // find an packet from that PID containing a PES header and see if
835 // the elementary stream is an audio type.
836 // - For program streams read the first 4MB and take every unique
837 // audio stream we find.
838 if (stream->hb_stream_type == transport)
842 for (i=0; i < stream->ts_number_pids; i++)
844 hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
847 hb_list_add( aTitle->list_audio, audio );
851 // make sure we're grabbing the PCR PID
852 if ( index_of_pid( stream, stream->pmt_info.PCR_PID ) < 0 )
854 stream->ts_pids[stream->ts_number_pids] = stream->pmt_info.PCR_PID;
855 stream->ts_stream_kind[stream->ts_number_pids] = P;
856 stream->ts_number_pids++;
859 for (i = 0; i < stream->ts_number_pids; i++)
861 kind_t kind = stream->ts_stream_kind[i];
863 if ( kind == N || kind == U )
865 hb_stream_delete_entry(stream, i);
869 // set the video id, codec & muxer
870 int idx = index_of_video( stream );
873 hb_title_close( &aTitle );
877 aTitle->video_id = stream->ts_pids[idx];
878 aTitle->video_codec = st2codec[stream->ts_stream_type[idx]].codec;
879 aTitle->video_codec_param = st2codec[stream->ts_stream_type[idx]].codec_param;
880 aTitle->demuxer = HB_MPEG2_TS_DEMUXER;
882 if ( ( stream->ts_flags & TS_HAS_PCR ) == 0 )
884 hb_log( "transport stream missing PCRs - using video DTS instead" );
887 if ( stream->ts_IDRs < 1 )
889 hb_log( "transport stream doesn't seem to have video IDR frames" );
890 aTitle->flags |= HBTF_NO_IDR;
895 hb_ps_stream_find_audio_ids(stream, aTitle);
902 * read the next transport stream packet from 'stream'. Return NULL if
903 * we hit eof & a pointer to the sync byte otherwise.
905 static const uint8_t *next_packet( hb_stream_t *stream )
907 uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
911 if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
920 // lost sync - back up to where we started then try to re-establish.
921 off_t pos = ftello(stream->file_handle) - stream->packetsize;
922 off_t pos2 = align_to_next_packet(stream);
925 hb_log( "next_packet: eof while re-establishing sync @ %"PRId64, pos );
928 ts_warn( stream, "next_packet: sync lost @ %"PRId64", regained after %"PRId64" bytes",
934 * skip to the start of the next PACK header in program stream src_stream.
936 static void skip_to_next_pack( hb_stream_t *src_stream )
938 // scan forward until we find the start of the next pack
939 uint32_t strt_code = -1;
942 flockfile( src_stream->file_handle );
943 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
945 strt_code = ( strt_code << 8 ) | c;
946 if ( strt_code == 0x000001ba )
947 // we found the start of the next pack
950 funlockfile( src_stream->file_handle );
952 // if we didn't terminate on an eof back up so the next read
953 // starts on the pack boundary.
956 fseeko( src_stream->file_handle, -4, SEEK_CUR );
960 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
962 // For mpeg2: look for a gop start or i-frame picture start
963 // for h.264: look for idr nal type or a slice header for an i-frame
964 // for vc1: look for a Sequence header
969 if ( stream->ts_stream_type[0] <= 2 )
971 // This section of the code handles MPEG-1 and MPEG-2 video streams
972 for (i = 13 + adapt_len; i < 188; i++)
974 strid = (strid << 8) | buf[i];
975 if ( ( strid >> 8 ) == 1 )
977 // we found a start code
981 case 0xB8: // group_start_code (GOP header)
982 case 0xB3: // sequence_header code
985 case 0x00: // picture_start_code
986 // picture_header, let's see if it's an I-frame
989 // check if picture_coding_type == 1
990 if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
992 // found an I-frame picture
1000 // didn't find an I-frame
1003 if ( stream->ts_stream_type[0] == 0x1b )
1005 // we have an h.264 stream
1006 for (i = 13 + adapt_len; i < 188; i++)
1008 strid = (strid << 8) | buf[i];
1009 if ( ( strid >> 8 ) == 1 )
1011 // we found a start code - remove the ref_idc from the nal type
1012 uint8_t nal_type = strid & 0x1f;
1013 if ( nal_type == 0x05 )
1014 // h.264 IDR picture start
1018 // didn't find an I-frame
1021 if ( stream->ts_stream_type[0] == 0xea )
1023 // we have an vc1 stream
1024 for (i = 13 + adapt_len; i < 188; i++)
1026 strid = (strid << 8) | buf[i];
1027 if ( strid == 0x10f )
1029 // the ffmpeg vc1 decoder requires a seq hdr code in the first
1034 // didn't find an I-frame
1038 // we don't understand the stream type so just say "yes" otherwise
1039 // we'll discard all the video.
1044 * scan the next MB of 'stream' to find the next start packet for
1045 * the Packetized Elementary Stream associated with TS PID 'pid'.
1047 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
1049 int npack = 300000; // max packets to read
1051 while (--npack >= 0)
1053 const uint8_t *buf = next_packet( stream );
1056 hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
1060 // while we're reading the stream, check if it has valid PCRs
1061 // and/or random access points.
1062 uint32_t pack_pid = ( (buf[1] & 0x1f) << 8 ) | buf[2];
1063 if ( pack_pid == stream->pmt_info.PCR_PID )
1065 if ( ( buf[5] & 0x10 ) &&
1066 ( ( ( buf[3] & 0x30 ) == 0x20 ) ||
1067 ( ( buf[3] & 0x30 ) == 0x30 && buf[4] > 6 ) ) )
1069 stream->ts_flags |= TS_HAS_PCR;
1072 if ( buf[5] & 0x40 )
1074 stream->ts_flags |= TS_HAS_RAP;
1078 * The PES header is only in TS packets with 'start' set so we check
1079 * that first then check for the right PID.
1081 if ((buf[1] & 0x40) == 0 || pack_pid != pid )
1083 // not a start packet or not the pid we want
1087 /* skip over the TS hdr to return a pointer to the PES hdr */
1089 switch (buf[3] & 0x30)
1091 case 0x00: // illegal
1092 case 0x20: // fill packet
1095 case 0x30: // adaptation
1098 hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
1101 udata += buf[4] + 1;
1104 /* PES hdr has to begin with an mpeg start code */
1105 if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
1111 /* didn't find it */
1115 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
1117 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1118 hb_list_t *list = hb_list_init();
1119 // how many blocks we read while searching for a video PES header
1120 int blksleft = 1024;
1123 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1127 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1128 hb_demux_ps( buf, list, 0 );
1130 while ( ( es = hb_list_item( list, 0 ) ) )
1132 hb_list_rem( list, es );
1133 if ( es->id == 0xe0 )
1135 // this PES contains video - if there's a PTS we're done
1136 // hb_demux_ps left the PTS in buf_es->start.
1137 if ( es->start != ~0 )
1144 hb_buffer_close( &es );
1147 hb_list_empty( &list );
1148 hb_buffer_close(&buf);
1152 /***********************************************************************
1153 * hb_stream_duration
1154 ***********************************************************************
1156 * Finding stream duration is difficult. One issue is that the video file
1157 * may have chunks from several different program fragments (main feature,
1158 * commercials, station id, trailers, etc.) all with their own base pts
1159 * value. We can't find the piece boundaries without reading the entire
1160 * file but if we compute a rate based on time stamps from two different
1161 * pieces the result will be meaningless. The second issue is that the
1162 * data rate of compressed video normally varies by 5-10x over the length
1163 * of the video. This says that we want to compute the rate over relatively
1164 * long segments to get a representative average but long segments increase
1165 * the likelihood that we'll cross a piece boundary.
1167 * What we do is take time stamp samples at several places in the file
1168 * (currently 16) then compute the average rate (i.e., ticks of video per
1169 * byte of the file) for all pairs of samples (N^2 rates computed for N
1170 * samples). Some of those rates will be absurd because the samples came
1171 * from different segments. Some will be way low or high because the
1172 * samples came from a low or high motion part of the segment. But given
1173 * that we're comparing *all* pairs the majority of the computed rates
1174 * should be near the overall average. So we median filter the computed
1175 * rates to pick the most representative value.
1177 **********************************************************************/
1179 uint64_t pos; /* file position of this PTS sample */
1180 uint64_t pts; /* PTS from video stream */
1183 #define NDURSAMPLES 128
1185 // get one (position, timestamp) sampple from a transport or program
1187 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
1189 struct pts_pos pp = { 0, 0 };
1191 if ( stream->hb_stream_type == transport )
1194 fseeko( stream->file_handle, fpos, SEEK_SET );
1195 align_to_next_packet( stream );
1196 int pid = stream->ts_pids[index_of_video(stream)];
1197 buf = hb_ts_stream_getPEStype( stream, pid );
1200 hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
1203 if ( ( buf[7] >> 7 ) != 1 )
1205 hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
1208 pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
1209 ( (uint64_t)buf[10] << 22 ) |
1210 ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
1211 ( (uint64_t)buf[12] << 7 ) |
1212 ( (uint64_t)buf[13] >> 1 );
1214 if ( isIframe( stream, buf, -4 ) )
1216 if ( stream->ts_IDRs < 255 )
1224 // round address down to nearest dvd sector start
1225 fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
1226 fseeko( stream->file_handle, fpos, SEEK_SET );
1227 if ( stream->hb_stream_type == program )
1229 skip_to_next_pack( stream );
1231 pp.pts = hb_ps_stream_getVideoPTS( stream );
1233 pp.pos = ftello(stream->file_handle);
1237 static int dur_compare( const void *a, const void *b )
1239 const double *aval = a, *bval = b;
1240 return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
1243 // given an array of (position, time) samples, compute a max-likelihood
1244 // estimate of the average rate by computing the rate between all pairs
1245 // of samples then taking the median of those rates.
1246 static double compute_stream_rate( struct pts_pos *pp, int n )
1249 double rates[NDURSAMPLES * NDURSAMPLES / 8];
1252 // the following nested loops compute the rates between all pairs.
1254 for ( i = 0; i < n-1; ++i )
1256 // Bias the median filter by not including pairs that are "far"
1257 // from one another. This is to handle cases where the file is
1258 // made of roughly equal size pieces where a symmetric choice of
1259 // pairs results in having the same number of intra-piece &
1260 // inter-piece rate estimates. This would mean that the median
1261 // could easily fall in the inter-piece part of the data which
1262 // would give a bogus estimate. The 'ns' index creates an
1263 // asymmetry that favors locality.
1264 int ns = i + ( n >> 3 );
1267 for ( j = i+1; j < ns; ++j )
1269 if ( (uint64_t)(pp[j].pts - pp[i].pts) > 90000LL*3600*6 )
1271 if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
1273 *rp = ((double)( pp[j].pts - pp[i].pts )) /
1274 ((double)( pp[j].pos - pp[i].pos ));
1279 // now compute and return the median of all the (n*n/2) rates we computed
1281 int nrates = rp - rates;
1282 qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
1283 return rates[nrates >> 1];
1286 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
1288 struct pts_pos ptspos[NDURSAMPLES];
1289 struct pts_pos *pp = ptspos;
1292 fseeko(stream->file_handle, 0, SEEK_END);
1293 uint64_t fsize = ftello(stream->file_handle);
1294 uint64_t fincr = fsize / NDURSAMPLES;
1295 uint64_t fpos = fincr / 2;
1296 for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
1298 *pp++ = hb_sample_pts(stream, fpos);
1300 uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
1301 inTitle->duration = dur;
1303 inTitle->hours = dur / 3600;
1304 inTitle->minutes = ( dur % 3600 ) / 60;
1305 inTitle->seconds = dur % 60;
1307 rewind(stream->file_handle);
1310 /***********************************************************************
1312 ***********************************************************************
1314 **********************************************************************/
1315 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
1317 if ( src_stream->hb_stream_type == ffmpeg )
1319 return ffmpeg_read( src_stream, b );
1321 if ( src_stream->hb_stream_type == dvd_program )
1323 size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
1324 src_stream->file_handle);
1325 return (amt_read > 0);
1327 if ( src_stream->hb_stream_type == program )
1329 // a general program stream has arbitrary sized pack's. we're
1330 // currently positioned at the start of a pack so read up to but
1331 // not including the start of the next, expanding the buffer
1333 uint8_t *cp = b->data;
1334 uint8_t *ep = cp + b->alloc;
1335 uint32_t strt_code = -1;
1338 // consume the first byte of the initial pack so we don't match on
1339 // it in the loop below.
1340 if ( ( c = getc( src_stream->file_handle ) ) == EOF )
1345 flockfile( src_stream->file_handle );
1346 while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1348 strt_code = ( strt_code << 8 ) | c;
1349 if ( strt_code == 0x000001ba )
1350 // we found the start of the next pack
1354 // need to expand the buffer
1355 int curSize = cp - b->data;
1356 hb_buffer_realloc( b, curSize * 2 );
1357 cp = b->data + curSize;
1358 ep = b->data + b->alloc;
1361 // Non-video streams can emulate start codes, so we need
1362 // to inspect PES packets and skip over their data
1363 // sections to avoid mis-detection of the next pack header.
1364 if ( ( strt_code >> 8 ) == 0x000001 &&
1365 ( strt_code & 0xff ) >= 0xbb )
1368 c = getc_unlocked( src_stream->file_handle );
1372 c = getc_unlocked( src_stream->file_handle );
1376 if ( cp+len+2 > ep )
1378 // need to expand the buffer
1379 int curSize = cp - b->data;
1380 if ( curSize * 2 > curSize+len+2 )
1381 hb_buffer_realloc( b, curSize * 2 );
1383 hb_buffer_realloc( b, curSize + len + 2 );
1384 cp = b->data + curSize;
1385 ep = b->data + b->alloc;
1389 fread( cp, 1, len, src_stream->file_handle );
1393 funlockfile( src_stream->file_handle );
1395 // if we didn't terminate on an eof back up so the next read
1396 // starts on the pack boundary.
1397 b->size = cp - b->data;
1400 fseeko( src_stream->file_handle, -4, SEEK_CUR );
1401 // Only 3 of the 4 bytes read were added to the buffer.
1406 return hb_ts_stream_decode( src_stream, b );
1409 int64_t ffmpeg_initial_timestamp( hb_stream_t * stream )
1411 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id];
1412 if ( s->nb_index_entries < 1 )
1415 return s->index_entries[0].timestamp;
1417 int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
1420 if ( stream->hb_stream_type != ffmpeg )
1422 // currently meaningliess for transport and program streams
1425 if ( !stream || !stream->title ||
1426 chapter_num > hb_list_count( stream->title->list_chapter ) )
1431 int64_t sum_dur = 0;
1432 hb_chapter_t *chapter = NULL;
1434 for ( i = 0; i < chapter_num; ++i)
1436 chapter = hb_list_item( stream->title->list_chapter, i );
1437 sum_dur += chapter->duration;
1439 stream->chapter = chapter_num - 1;
1440 stream->chapter_end = sum_dur;
1442 int64_t pos = ( ( ( sum_dur - chapter->duration ) * AV_TIME_BASE ) / 90000 ) + ffmpeg_initial_timestamp( stream );
1444 hb_deep_log( 2, "Seeking to chapter %d: starts %"PRId64", ends %"PRId64", AV pos %"PRId64,
1445 chapter_num, sum_dur - chapter->duration, sum_dur, pos);
1447 if ( chapter_num > 1 && pos > 0 )
1449 av_seek_frame( stream->ffmpeg_ic, -1, pos, 0);
1453 // ffmpeg has a bug that causes the first PTS after
1454 // av_find_stream_info() is called to be incorrect.
1455 // av_find_stream_info is called whenever opening a file
1456 // with ffmpeg. av_seek_frame clears the condition
1457 // that causes the problem. since hb_stream_seek_chapter
1458 // is called before we start reading, make sure
1459 // we do a seek here.
1460 av_seek_frame( stream->ffmpeg_ic, -1, ffmpeg_initial_timestamp( stream ), AVSEEK_FLAG_BACKWARD );
1465 /***********************************************************************
1467 ***********************************************************************
1468 * Return the number of the chapter that we are currently in. We store
1469 * the chapter number starting from 0, so + 1 for the real chpater num.
1470 **********************************************************************/
1471 int hb_stream_chapter( hb_stream_t * src_stream )
1473 return( src_stream->chapter + 1 );
1476 /***********************************************************************
1478 ***********************************************************************
1480 **********************************************************************/
1481 int hb_stream_seek( hb_stream_t * stream, float f )
1483 if ( stream->hb_stream_type == ffmpeg )
1485 return ffmpeg_seek( stream, f );
1487 off_t stream_size, cur_pos, new_pos;
1488 double pos_ratio = f;
1489 cur_pos = ftello( stream->file_handle );
1490 fseeko( stream->file_handle, 0, SEEK_END );
1491 stream_size = ftello( stream->file_handle );
1492 new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1493 new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1495 int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
1498 fseeko( stream->file_handle, cur_pos, SEEK_SET );
1502 if ( stream->hb_stream_type == transport )
1504 // We need to drop the current decoder output and move
1505 // forwards to the next transport stream packet.
1506 hb_ts_stream_reset(stream);
1509 if ( stream->ts_IDRs )
1511 // the stream has IDRs so look for one.
1512 stream->need_keyframe = 1;
1517 // we're at the beginning - say we have video sync so that we
1518 // won't drop initial SPS & PPS data on an AVC stream.
1519 stream->need_keyframe = 0;
1522 else if ( stream->hb_stream_type == program )
1524 skip_to_next_pack( stream );
1530 int hb_stream_seek_ts( hb_stream_t * stream, int64_t ts )
1532 if ( stream->hb_stream_type == ffmpeg )
1534 return ffmpeg_seek_ts( stream, ts );
1539 static const char* make_upper( const char* s )
1541 static char name[8];
1543 char *ep = cp + sizeof(name)-1;
1545 while ( *s && cp < ep )
1547 *cp++ = islower(*s)? toupper(*s) : *s;
1554 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1557 * This is a duplicate of code in dvd.c - it should get factored out
1558 * into a common routine. We probably should only be putting the lang
1559 * code or a lang pointer into the audio config & let the common description
1560 * formatting routine in scan.c do all the stuff below.
1562 const char *codec_name;
1565 if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1566 ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1567 avcodec_find_decoder( cc->codec_id ) )
1569 codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1570 if ( !strcmp( codec_name, "LIBFAAD" ) )
1575 else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1576 avcodec_find_decoder( audio->config.in.codec_param ) )
1578 codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1582 codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1583 audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1584 audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" :
1585 audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" :
1586 audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1589 snprintf( audio->config.lang.description,
1590 sizeof( audio->config.lang.description ), "%s (%s)",
1591 strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1594 if (audio->config.in.codec == HB_ACODEC_FFMPEG)
1596 int layout = audio->config.in.channel_layout;
1597 char *desc = audio->config.lang.description +
1598 strlen( audio->config.lang.description );
1599 sprintf( desc, " (%d.%d ch)",
1600 HB_INPUT_CH_LAYOUT_GET_DISCRETE_FRONT_COUNT(layout) +
1601 HB_INPUT_CH_LAYOUT_GET_DISCRETE_REAR_COUNT(layout),
1602 HB_INPUT_CH_LAYOUT_GET_DISCRETE_LFE_COUNT(layout) );
1605 snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1606 strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1607 snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1608 "%s", lang->iso639_2);
1611 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1614 off_t cur_pos = ftello(stream->file_handle);
1615 hb_audio_t *audio = NULL;
1620 kind = stream->ts_stream_kind[idx];
1622 if ( kind != A && kind != U && kind != N )
1627 stype = stream->ts_stream_type[idx];
1629 fseeko(stream->file_handle, 0, SEEK_SET);
1630 align_to_next_packet(stream);
1632 buf = hb_ts_stream_getPEStype(stream, stream->ts_pids[idx]);
1634 /* check that we found a PES header */
1635 if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1637 // 0xbd ("private stream 1") is the normal container for non-ISO
1638 // media - AC3/DCA/PCM/etc.
1639 if ( buf[3] == 0xbd )
1643 // XXX assume unknown stream types are AC-3 (if they're not
1644 // audio we'll find that out during the scan but if they're
1645 // some other type of audio we'll end up ignoring them).
1647 stream->ts_stream_type[idx] = 0x81;
1650 if ( stype == 0x80 &&
1651 stream->pmt_info.reg_desc == STR4_TO_UINT32("HDMV") )
1653 // LPCM audio in bluray have an stype of 0x80
1654 // 0x80 is used for other DigiCipher normally
1655 // To distinguish, Bluray streams have a reg_desc of HDMV
1659 else if ( buf[3] == 0xfd )
1661 // 0xfd indicates an extended stream id (ISO 13818-1(2007)).
1662 // the blu ray consortium apparently forgot to read the portion
1663 // of the MPEG spec that says one PID should map to one media
1664 // stream and multiplexed multiple types of audio into one PID
1665 // using the extended stream identifier of the PES header to
1666 // distinguish them. So we have to check if that's happening and
1667 // if so tell the runtime what esid we want.
1668 if ( st2codec[stype].kind == A && stype == 0x83 &&
1669 stream->ts_format_id[idx] == TS_FORMAT_ID_AC3 )
1671 // This is an interleaved TrueHD/AC-3 stream and the esid of
1673 stream->ts_multiplexed[idx] = 0x76;
1675 stream->ts_stream_type[idx] = 0x81;
1678 if ( st2codec[stype].kind == A && stype == 0x86 )
1680 // This is an interleaved DTS-HD/DTS stream and the esid of
1682 stream->ts_multiplexed[idx] = 0x71;
1684 stream->ts_stream_type[idx] = 0x82;
1688 else if ((buf[3] & 0xe0) == 0xc0)
1690 // 0xC0 - 0xCF are the normal containers for ISO-standard
1691 // media (mpeg2 audio and mpeg4 AAC).
1692 if ( st2codec[stype].kind == U )
1694 // XXX assume unknown stream types are MPEG audio
1696 stream->ts_stream_type[idx] = 0x03;
1707 // if we found an audio stream type & HB has a codec that can decode it
1708 // finish configuring the audio so we'll add it to the title's list.
1709 if ( kind == A && st2codec[stype].codec )
1711 audio = calloc( sizeof( hb_audio_t ), 1 );
1713 stream->ts_stream_kind[idx] = A;
1714 audio->id = stream->ts_pids[idx];
1715 audio->config.in.codec = st2codec[stype].codec;
1716 audio->config.in.codec_param = st2codec[stype].codec_param;
1717 set_audio_description( audio,
1718 lang_for_code( stream->a52_info[idx].lang_code ) );
1719 hb_log("transport stream pid 0x%x (type 0x%x) may be %s audio (id 0x%x)",
1720 stream->ts_pids[idx],
1721 stype, st2codec[stype].name, audio->id);
1728 hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1729 "isn't audio", stream->ts_pids[idx],
1730 stream->ts_stream_type[idx], buf[3]);
1734 hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1735 stream->ts_pids[idx],
1736 stream->ts_stream_type[idx]);
1739 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1744 static void add_audio_to_title(hb_title_t *title, int id)
1746 hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1752 audio->config.in.codec = HB_ACODEC_MPGA;
1753 hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1756 // type 2 is a DVD subtitle stream - just ignore it */
1760 audio->config.in.codec = HB_ACODEC_AC3;
1761 hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1764 audio->config.in.codec = HB_ACODEC_LPCM;
1765 hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1768 hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1773 set_audio_description( audio, lang_for_code( 0 ) );
1774 hb_list_add( title->list_audio, audio );
1777 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1779 off_t cur_pos = ftello(stream->file_handle);
1780 hb_buffer_t *buf = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1781 hb_list_t *list = hb_list_init();
1782 // how many blocks we read while searching for audio streams
1783 int blksleft = 4096;
1784 // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1785 // so we use a bitmap to keep track of the ones we've already seen.
1786 // Bit 'i' of smap is set if we've already added the audio for
1787 // audio substream id 'i' to the title's audio list.
1790 // start looking 20% into the file since there's occasionally no
1791 // audio at the beginning (particularly for vobs).
1792 hb_stream_seek(stream, 0.2f);
1794 while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1798 // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1799 hb_demux_ps( buf, list, 0 );
1801 while ( ( es = hb_list_item( list, 0 ) ) )
1803 hb_list_rem( list, es );
1804 if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1806 // this PES contains some kind of audio - get the substream id
1807 // and check if we've seen it already.
1808 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1809 if ( (smap & (1 << ssid)) == 0 )
1811 // we haven't seen this stream before - add it to the
1812 // title's list of audio streams.
1813 smap |= (1 << ssid);
1814 add_audio_to_title(title, es->id);
1817 hb_buffer_close( &es );
1820 hb_list_empty( &list );
1821 hb_buffer_close(&buf);
1822 fseeko(stream->file_handle, cur_pos, SEEK_SET);
1825 /***********************************************************************
1827 ***********************************************************************
1829 **********************************************************************/
1831 static void hb_ts_stream_init(hb_stream_t *stream)
1835 for (i=0; i < kMaxNumberDecodeStreams; i++)
1837 stream->ts_streamcont[i] = -1;
1838 stream-> ts_pids[i] = -1;
1840 stream->ts_packet = malloc( stream->packetsize );
1842 // Find the audio and video pids in the stream
1843 hb_ts_stream_find_pids(stream);
1845 for (i = 0; i < stream->ts_number_pids; i++)
1847 // demuxing buffer for TS to PS conversion
1848 stream->ts_buf[i] = hb_buffer_init(stream->packetsize);
1849 stream->ts_buf[i]->size = 0;
1853 #define MAX_HOLE 208*80
1855 static off_t align_to_next_packet(hb_stream_t *stream)
1857 uint8_t buf[MAX_HOLE];
1859 off_t start = ftello(stream->file_handle);
1862 if ( start >= stream->packetsize ) {
1863 start -= stream->packetsize;
1864 fseeko(stream->file_handle, start, SEEK_SET);
1870 if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1872 const uint8_t *bp = buf;
1875 for ( i = sizeof(buf) - 8 * stream->packetsize; --i >= 0; ++bp )
1877 if ( have_ts_sync( bp, stream->packetsize ) )
1884 pos = ( bp - buf ) - stream->packetsize + 188;
1887 fseeko(stream->file_handle, -8 * stream->packetsize, SEEK_CUR);
1888 start = ftello(stream->file_handle);
1895 fseeko(stream->file_handle, start+pos, SEEK_SET);
1896 return start - orig + pos;
1906 static const unsigned int bitmask[] = {
1907 0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1908 0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1909 0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1910 0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1912 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1916 bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1917 (bb->buf[2] << 8) | bb->buf[3];
1919 memset(bb->buf, 0, bufsize);
1922 static inline int buf_size(bitbuf_t *bb)
1924 return bb->pos >> 3;
1927 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1930 int left = 32 - (bb->pos & 31);
1934 val = (bb->val >> (left - bits)) & bitmask[bits];
1939 val = (bb->val & bitmask[left]) << (bits - left);
1943 int pos = bb->pos >> 3;
1944 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1948 val |= (bb->val >> (32 - bits)) & bitmask[bits];
1956 // extract what useful information we can from the elementary stream
1957 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1958 // Descriptors with info we don't currently use are ignored.
1959 // The descriptor list & descriptor item formats are defined in
1960 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1961 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1962 const uint8_t *dp, uint8_t dlen)
1964 const uint8_t *ep = dp + dlen;
1970 case 5: // Registration descriptor
1971 stream->ts_format_id[esindx] = (dp[2] << 24) | (dp[3] << 16) |
1972 (dp[4] << 8) | dp[5];
1975 case 10: // ISO_639_language descriptor
1976 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1979 case 0x6a: // DVB AC-3 descriptor
1980 stream->ts_stream_type[esindx] = 0x81;
1990 static const char *stream_type_name (uint8_t stream_type)
1992 return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1995 int decode_program_map(hb_stream_t* stream)
1998 set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
2000 get_bits(&bb, 8); // table_id
2002 unsigned int section_length = get_bits(&bb, 12);
2003 stream->pmt_info.section_length = section_length;
2005 unsigned int program_number = get_bits(&bb, 16);
2006 stream->pmt_info.program_number = program_number;
2008 get_bits(&bb, 5); // version_number
2010 get_bits(&bb, 8); // section_number
2011 get_bits(&bb, 8); // last_section_number
2013 stream->pmt_info.PCR_PID = get_bits(&bb, 13);
2015 int program_info_length = get_bits(&bb, 12);
2016 stream->pmt_info.program_info_length = program_info_length;
2019 for (i = 0; i < program_info_length - 2; )
2022 tag = get_bits(&bb, 8);
2023 len = get_bits(&bb, 8);
2025 if ( i + len > program_info_length )
2029 if (tag == 0x05 && len >= 4)
2031 // registration descriptor
2032 stream->pmt_info.reg_desc = get_bits(&bb, 32);
2037 for ( j = 0; j < len; j++ )
2043 for ( ; i < program_info_length; i++ )
2048 int cur_pos = 9 /* data after the section length field*/ + program_info_length;
2049 int done_reading_stream_types = 0;
2050 while (!done_reading_stream_types)
2052 unsigned char stream_type = get_bits(&bb, 8);
2054 unsigned int elementary_PID = get_bits(&bb, 13);
2056 unsigned int ES_info_length = get_bits(&bb, 12);
2059 unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
2060 for (i=0; i < ES_info_length; i++)
2062 ES_info_buf[i] = get_bits(&bb, 8);
2065 if ( index_of_pid( stream, elementary_PID ) < 0 )
2067 // Defined audio stream types are 0x81 for AC-3/A52 audio
2068 // and 0x03 for mpeg audio. But content producers seem to
2069 // use other values (0x04 and 0x06 have both been observed)
2070 // so at this point we say everything that isn't a video
2071 // pid is audio then at the end of hb_stream_title_scan
2072 // we'll figure out which are really audio by looking at
2074 i = stream->ts_number_pids;
2075 if (i < kMaxNumberDecodeStreams)
2077 stream->ts_pids[i] = elementary_PID;
2078 stream->ts_stream_type[i] = stream_type;
2079 if (ES_info_length > 0)
2081 decode_element_descriptors(stream, i, ES_info_buf,
2084 stream->ts_stream_kind[i] = ts_stream_kind(stream, i);
2085 ++stream->ts_number_pids;
2089 cur_pos += 5 /* stream header */ + ES_info_length;
2093 if (cur_pos >= section_length - 4 /* stop before the CRC */)
2094 done_reading_stream_types = 1;
2100 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
2102 // Get adaption header info
2104 int adaption = (buf[3] & 0x30) >> 4;
2107 else if (adaption == 0x2)
2109 else if (adaption == 0x3)
2110 adapt_len = buf[4] + 1;
2111 if (adapt_len > 184)
2114 // Get payload start indicator
2116 start = (buf[1] & 0x40) != 0;
2118 // Get pointer length - only valid in packets with a start flag
2119 int pointer_len = 0;
2123 pointer_len = buf[4 + adapt_len] + 1;
2124 stream->pmt_info.tablepos = 0;
2126 // Get Continuity Counter
2127 int continuity_counter = buf[3] & 0x0f;
2128 if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
2130 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
2133 stream->pmt_info.current_continuity_counter = continuity_counter;
2134 stream->pmt_info.reading |= start;
2136 // Add the payload for this packet to the current buffer
2137 int amount_to_copy = 184 - adapt_len - pointer_len;
2138 if (stream->pmt_info.reading && (amount_to_copy > 0))
2140 stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
2142 memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
2143 stream->pmt_info.tablepos += amount_to_copy;
2145 if (stream->pmt_info.tablepos > 3)
2147 // We have enough to check the section length
2149 length = ((stream->pmt_info.tablebuf[1] << 8) +
2150 stream->pmt_info.tablebuf[2]) & 0xFFF;
2151 if (stream->pmt_info.tablepos > length + 1)
2153 // We just finished a bunch of packets - parse the program map details
2155 if (stream->pmt_info.tablebuf[0] == 0x02)
2156 decode_ok = decode_program_map(stream);
2157 free(stream->pmt_info.tablebuf);
2158 stream->pmt_info.tablebuf = NULL;
2159 stream->pmt_info.tablepos = 0;
2160 stream->pmt_info.reading = 0;
2170 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
2172 unsigned char tablebuf[1024];
2173 unsigned int tablepos = 0;
2178 // Get adaption header info
2180 int adaption = (buf[3] & 0x30) >> 4;
2183 else if (adaption == 0x2)
2185 else if (adaption == 0x3)
2186 adapt_len = buf[4] + 1;
2187 if (adapt_len > 184)
2190 // Get pointer length
2191 int pointer_len = buf[4 + adapt_len] + 1;
2193 // Get payload start indicator
2195 start = (buf[1] & 0x40) != 0;
2200 // Add the payload for this packet to the current buffer
2201 if (reading && (184 - adapt_len) > 0)
2203 if (tablepos + 184 - adapt_len - pointer_len > 1024)
2205 hb_log("decode_PAT - Bad program section length (> 1024)");
2208 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
2209 tablepos += 184 - adapt_len - pointer_len;
2212 if (start && reading)
2214 memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
2217 unsigned int pos = 0;
2218 //while (pos < tablepos)
2221 set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
2223 unsigned char section_id = get_bits(&bb, 8);
2225 unsigned int section_len = get_bits(&bb, 12);
2226 get_bits(&bb, 16); // transport_id
2228 get_bits(&bb, 5); // version_num
2229 get_bits(&bb, 1); // current_next
2230 get_bits(&bb, 8); // section_num
2231 get_bits(&bb, 8); // last_section
2237 // Program Association Section
2238 section_len -= 5; // Already read transport stream ID, version num, section num, and last section num
2239 section_len -= 4; // Ignore the CRC
2241 stream->ts_number_pat_entries = 0;
2242 while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
2244 unsigned int pkt_program_num = get_bits(&bb, 16);
2245 stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
2247 get_bits(&bb, 3); // Reserved
2248 if (pkt_program_num == 0)
2250 get_bits(&bb, 13); // pkt_network_id
2254 unsigned int pkt_program_map_PID = get_bits(&bb, 13);
2255 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
2258 stream->ts_number_pat_entries++;
2272 pos += 3 + section_len;
2280 static void hb_ts_stream_find_pids(hb_stream_t *stream)
2282 // To be different from every other broadcaster in the world, New Zealand TV
2283 // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
2284 // we may have the tail of the previous program at the beginning of this
2285 // file, take our PMT from the middle of the file.
2286 fseeko(stream->file_handle, 0, SEEK_END);
2287 uint64_t fsize = ftello(stream->file_handle);
2288 fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
2289 align_to_next_packet(stream);
2291 // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
2292 // to find the program map PID and then decode that to get the list of audio and video PIDs
2296 const uint8_t *buf = next_packet( stream );
2300 hb_log("hb_ts_stream_find_pids - end of file");
2305 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
2307 if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
2309 decode_PAT(buf, stream);
2314 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
2316 // There are some streams where the PAT table has multiple entries as if their are
2317 // multiple programs in the same transport stream, and yet there's actually only one
2318 // program really in the stream. This seems to be true for transport streams that
2319 // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
2320 // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
2321 // but the EyeTV is only recording a single (selected) program number and not rewriting the
2322 // PAT info on export to match what's actually on the stream.
2323 // Until we have a way of handling multiple programs per transport stream elegantly we'll match
2324 // on the first pat entry for which we find a matching program map PID. The ideal solution would
2325 // be to build a title choice popup from the PAT program number details and then select from
2326 // their - but right now the API's not capable of that.
2327 if (stream->pat_info[pat_index].program_number != 0 &&
2328 pid == stream->pat_info[pat_index].program_map_PID)
2330 if (build_program_map(buf, stream) > 0)
2334 // Keep going until we have a complete set of PIDs
2335 if ( index_of_video( stream ) >= 0 )
2339 hb_log("hb_ts_stream_find_pids - found the following PIDS");
2340 hb_log(" Video PIDS : ");
2342 for (i=0; i < stream->ts_number_pids; i++)
2344 if ( stream->ts_stream_kind[i] == V )
2346 hb_log( " 0x%x type %s (0x%x)",
2348 stream_type_name(stream->ts_stream_type[i]),
2349 stream->ts_stream_type[i]);
2352 hb_log(" Audio PIDS : ");
2353 for (i = 0; i < stream->ts_number_pids; i++)
2355 if ( stream->ts_stream_kind[i] != V )
2357 hb_log( " 0x%x type %s (0x%x)",
2359 stream_type_name(stream->ts_stream_type[i]),
2360 stream->ts_stream_type[i] );
2366 static void fwrite64( hb_stream_t *stream, void *buf, int len )
2370 int pos = stream->fwrite_buf->size;
2371 if ( pos + len > stream->fwrite_buf->alloc )
2373 int size = MAX(stream->fwrite_buf->alloc * 2, pos + len);
2374 hb_buffer_realloc(stream->fwrite_buf, size);
2376 memcpy( &(stream->fwrite_buf->data[pos]), buf, len );
2377 stream->fwrite_buf->size += len;
2381 // convert a PES PTS or DTS to an int64
2382 static int64_t pes_timestamp( const uint8_t *pes )
2384 int64_t ts = ( (uint64_t)(pes[0] & 0xe ) << 29 );
2385 ts |= ( pes[1] << 22 ) | ( ( pes[2] >> 1 ) << 15 ) |
2386 ( pes[3] << 7 ) | ( pes[4] >> 1 );
2390 static void generate_output_data(hb_stream_t *stream, int curstream)
2392 hb_buffer_t *buf = stream->fwrite_buf;
2393 uint8_t *tdat = stream->ts_buf[curstream]->data;
2395 buf->id = stream->ts_pids[curstream];
2396 switch (stream->ts_stream_kind[curstream])
2399 buf->type = AUDIO_BUF;
2403 buf->type = VIDEO_BUF;
2407 buf->type = OTHER_BUF;
2411 // check if this packet was referenced to an older pcr and if that
2412 // pcr was significantly different than the one we're using now.
2413 // (the reason for the uint cast on the pcr difference is that the
2414 // difference is significant if it advanced by more than 200ms or if
2415 // it went backwards by any amount. The negative numbers look like huge
2416 // unsigned ints so the cast allows both conditions to be checked at once.
2417 int bufpcr = stream->ts_buf[curstream]->cur;
2418 int curpcr = stream->ts_pcr_out;
2419 if ( bufpcr && bufpcr < curpcr &&
2420 (uint64_t)(stream->ts_pcrhist[curpcr & 3] - stream->ts_pcrhist[bufpcr & 3]) > 200*90LL )
2422 // we've sent up a new pcr but have a packet referenced to an
2423 // old pcr and the difference was enough to trigger a discontinuity
2424 // correction. smash the timestamps or we'll mess up the correction.
2426 buf->renderOffset = -1;
2430 if ( stream->ts_pcr_out != stream->ts_pcr_in )
2432 // we have a new pcr
2433 stream->ts_pcr_out = stream->ts_pcr_in;
2434 buf->stop = stream->ts_pcr;
2435 stream->ts_pcrhist[stream->ts_pcr_out & 3] = stream->ts_pcr;
2442 // put the PTS & possible DTS into 'start' & 'renderOffset' then strip
2443 // off the PES header.
2444 if ( tdat[7] & 0xc0 )
2446 buf->start = pes_timestamp( tdat + 9 );
2447 buf->renderOffset = ( tdat[7] & 0x40 )? pes_timestamp( tdat + 14 ) :
2453 buf->renderOffset = -1;
2456 int hlen = tdat[8] + 9;
2458 fwrite64( stream, tdat + hlen, stream->ts_pos[curstream] - hlen );
2460 stream->ts_pos[curstream] = 0;
2461 stream->ts_buf[curstream]->size = 0;
2464 static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
2466 if (stream->ts_pos[idx] + len > stream->ts_buf[idx]->alloc)
2470 size = MAX(stream->ts_buf[idx]->alloc * 2, stream->ts_pos[idx] + len);
2471 hb_buffer_realloc(stream->ts_buf[idx], size);
2473 memcpy(stream->ts_buf[idx]->data + stream->ts_pos[idx], buf, len);
2474 stream->ts_pos[idx] += len;
2475 stream->ts_buf[idx]->size += len;
2478 /***********************************************************************
2479 * hb_ts_stream_decode
2480 ***********************************************************************
2482 **********************************************************************/
2483 int hb_ts_decode_pkt( hb_stream_t *stream, const uint8_t * pkt, hb_buffer_t *obuf )
2486 * stash the output buffer pointer in our stream so we don't have to
2487 * pass it & its original value to everything we call.
2490 stream->fwrite_buf = obuf;
2492 int video_index = index_of_video(stream);
2496 /* This next section validates the packet */
2498 // Get pid and use it to find stream state.
2499 int pid = ((pkt[1] & 0x1F) << 8) | pkt[2];
2500 if ( ( curstream = index_of_pid( stream, pid ) ) < 0 )
2506 int errorbit = (pkt[1] & 0x80) != 0;
2509 ts_err( stream, curstream, "packet error bit set");
2513 // Get adaption header info
2514 int adaption = (pkt[3] & 0x30) >> 4;
2518 ts_err( stream, curstream, "adaptation code 0");
2521 else if (adaption == 0x2)
2523 else if (adaption == 0x3)
2525 adapt_len = pkt[4] + 1;
2526 if (adapt_len > 184)
2528 ts_err( stream, curstream, "invalid adapt len %d", adapt_len);
2533 if ( adapt_len > 0 )
2535 if ( pkt[5] & 0x40 )
2537 // found a random access point
2539 // if there's an adaptation header & PCR_flag is set
2540 // get the PCR (Program Clock Reference)
2541 if ( adapt_len > 7 && ( pkt[5] & 0x10 ) != 0 )
2543 stream->ts_pcr = ( (uint64_t)pkt[6] << (33 - 8) ) |
2544 ( (uint64_t)pkt[7] << (33 - 16) ) |
2545 ( (uint64_t)pkt[8] << (33 - 24) ) |
2546 ( (uint64_t)pkt[9] << (33 - 32) ) |
2548 ++stream->ts_pcr_in;
2549 stream->ts_found_pcr = 1;
2550 stream->ts_flags |= TS_HAS_PCR;
2554 // If we don't have a PCR yet but the stream has PCRs just loop
2555 // so we don't process anything until we have a clock reference.
2556 // Unfortunately the HD Home Run appears to null out the PCR so if
2557 // we didn't detect a PCR during scan keep going and we'll use
2558 // the video stream DTS for the PCR.
2560 if ( !stream->ts_found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
2566 // Continuity only increments for adaption values of 0x3 or 0x01
2567 // and is not checked for start packets.
2569 int start = (pkt[1] & 0x40) != 0;
2571 if ( (adaption & 0x01) != 0 )
2573 int continuity = (pkt[3] & 0xF);
2574 if ( continuity == stream->ts_streamcont[curstream] )
2576 // Spliced transport streams can have duplicate
2577 // continuity counts at the splice boundary.
2578 // Test to see if the packet is really a duplicate
2579 // by comparing packet summaries to see if they
2583 summary[0] = adaption;
2584 summary[1] = adapt_len;
2585 if (adapt_len + 4 + 6 + 9 <= 188)
2587 memcpy(&summary[2], pkt+4+adapt_len+9, 6);
2591 memset(&summary[2], 0, 6);
2593 if ( memcmp( summary, stream->ts_pkt_summary[curstream], 8 ) == 0 )
2595 // we got a duplicate packet (usually used to introduce
2596 // a PCR when one is needed). The only thing that can
2597 // change in the dup is the PCR which we grabbed above
2598 // so ignore the rest.
2602 if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2603 !stream->ts_skipbad[curstream] &&
2604 (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2606 ts_err( stream, curstream, "continuity error: got %d expected %d",
2608 (stream->ts_streamcont[curstream] + 1) & 0xf );
2609 stream->ts_streamcont[curstream] = continuity;
2612 stream->ts_streamcont[curstream] = continuity;
2614 // Save a summary of this packet for later duplicate
2615 // testing. The summary includes some header information
2616 // and payload bytes. Should be enough to detect
2618 stream->ts_pkt_summary[curstream][0] = adaption;
2619 stream->ts_pkt_summary[curstream][1] = adapt_len;
2620 if (adapt_len + 4 + 6 + 9 <= 188)
2622 memcpy(&stream->ts_pkt_summary[curstream][2],
2623 pkt+4+adapt_len+9, 6);
2627 memset(&stream->ts_pkt_summary[curstream][2], 0, 6);
2631 /* If we get here the packet is valid - process its data */
2635 // Found a random access point (now we can start a frame/audio packet..)
2637 if ( stream->need_keyframe )
2639 // we're looking for the first video frame because we're
2640 // doing random access during 'scan'
2641 if ( curstream != video_index || !isIframe( stream, pkt, adapt_len ) )
2643 // not the video stream or didn't find an I frame
2644 // but we'll only wait 255 video frames for an I frame.
2645 if ( curstream != video_index || ++stream->need_keyframe )
2650 stream->need_keyframe = 0;
2653 // If we were skipping a bad packet, start fresh on this new PES packet..
2654 if (stream->ts_skipbad[curstream] == 1)
2656 stream->ts_skipbad[curstream] = 0;
2659 if ( curstream == video_index )
2663 // if we don't have a pcr yet use the dts from this frame
2664 if ( !stream->ts_found_pcr )
2666 // PES must begin with an mpeg start code & contain
2668 const uint8_t *pes = pkt + adapt_len + 4;
2669 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2670 ( pes[7] >> 6 ) == 0 )
2674 // if we have a dts use it otherwise use the pts
2675 stream->ts_pcr = pes_timestamp( pes + ( pes[7] & 0x40?14:9 ) );
2676 ++stream->ts_pcr_in;
2680 // if this is a multiplexed stream make sure this is the
2681 // substream we want.
2682 if ( stream->ts_multiplexed[curstream] )
2684 // PES must begin with an mpeg start code & contain
2686 const uint8_t *pes = pkt + adapt_len + 4;
2687 if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2690 stream->ts_skipbad[curstream] = 1;
2693 // the last byte of the header is the extension id. see if
2694 // it's the one we want.
2695 if ( pes[pes[8]+8] != stream->ts_multiplexed[curstream] )
2697 stream->ts_skipbad[curstream] = 1;
2702 // If we have some data already on this stream, turn it into
2703 // a program stream packet. Then add the payload for this
2704 // packet to the current pid's buffer.
2705 if ( stream->ts_pos[curstream] )
2707 // we have to ship the old packet before updating the pcr
2708 // since the packet we've been accumulating is referenced
2710 generate_output_data(stream, curstream);
2712 // remember the pcr that was in effect when we started
2714 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2715 hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2719 // remember the pcr that was in effect when we started this packet.
2720 stream->ts_buf[curstream]->cur = stream->ts_pcr_in;
2723 // Add the payload for this packet to the current buffer
2724 if (!stream->ts_skipbad[curstream] && (184 - adapt_len) > 0)
2726 hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
2728 // see if we've hit the end of this PES packet
2729 const uint8_t *pes = stream->ts_buf[curstream]->data;
2730 int len = ( pes[4] << 8 ) + pes[5] + 6;
2731 if ( len > 6 && stream->ts_pos[curstream] == len &&
2732 pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
2734 generate_output_data(stream, curstream);
2741 static int hb_ts_stream_decode( hb_stream_t *stream, hb_buffer_t *obuf )
2743 // spin until we get a packet of data from some stream or hit eof
2746 const uint8_t *buf = next_packet(stream);
2749 // end of file - we didn't finish filling our ps write buffer
2750 // so just discard the remainder (the partial buffer is useless)
2751 hb_log("hb_ts_stream_decode - eof");
2755 if (hb_ts_decode_pkt( stream, buf, obuf ))
2763 static void hb_ts_stream_reset(hb_stream_t *stream)
2767 for (i=0; i < kMaxNumberDecodeStreams; i++)
2769 stream->ts_pos[i] = 0;
2770 stream->ts_skipbad[i] = 1;
2771 stream->ts_streamcont[i] = -1;
2774 stream->need_keyframe = 0;
2776 stream->ts_found_pcr = 0;
2777 stream->ts_pcr_out = 0;
2778 stream->ts_pcr_in = 0;
2783 stream->last_error_frame = -10000;
2784 stream->last_error_count = 0;
2786 align_to_next_packet(stream);
2789 // ------------------------------------------------------------------
2790 // Support for reading media files via the ffmpeg libraries.
2792 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2794 // add a codec to the context here so it will be there when we
2795 // read the first packet.
2796 AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2797 context->workaround_bugs = FF_BUG_AUTODETECT;
2798 context->error_recognition = 1;
2799 context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2800 AVCodec *codec = avcodec_find_decoder( context->codec_id );
2801 hb_avcodec_open( context, codec );
2804 // The ffmpeg stream reader / parser shares a lot of state with the
2805 // decoder via a codec context kept in the AVStream of the reader's
2806 // AVFormatContext. Since decoding is done in a different thread we
2807 // have to somehow pass this codec context to the decoder and we have
2808 // to do it before the first packet is read (so we can't put the info
2809 // in the buf we'll send downstream). Decoders don't have any way to
2810 // get to the stream directly (they're not passed the title or job
2811 // pointers during a scan) so this is a back door for the decoder to
2812 // get the codec context. We just stick the stream pointer in the next
2813 // slot an array of pointers maintained as a circular list then return
2814 // the index into the list combined with the ffmpeg stream index as the
2815 // codec_param that will be passed to the decoder init routine. We make
2816 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2817 // so that we don't have to do a complicated allocator or worry about
2818 // deleting entries on close.
2820 // Entries can only be added to this list during a scan and are never
2821 // deleted so the list access doesn't require locking.
2822 static hb_stream_t **ffmpeg_streams; // circular list of stream pointers
2823 static int ffmpeg_stream_cur; // where we put the last stream pointer
2824 #define ffmpeg_sl_bits (10) // log2 stream list size (in entries)
2825 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2827 // add a stream to the list & return the appropriate codec_param to access it
2828 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2830 if ( !ffmpeg_streams )
2832 ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2835 // the title scan adds all the ffmpeg media streams at once so we
2836 // only add a new entry to our stream list if the stream is different
2838 int slot = ffmpeg_stream_cur;
2839 if ( ffmpeg_streams[slot] != stream )
2841 // new stream - put it in the next slot of the stream list
2842 slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2843 ffmpeg_streams[slot] = stream;
2846 ffmpeg_add_codec( stream, stream_index );
2848 return ( stream_index << ffmpeg_sl_bits ) | slot;
2851 // we're about to open 'title' to convert it - remap the stream associated
2852 // with the video & audio codec params of the title to refer to 'stream'
2853 // (the original scan stream was closed and no longer exists).
2854 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2856 // all the video & audio came from the same stream so remapping
2857 // the video's stream slot takes care of everything.
2858 int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2859 ffmpeg_streams[slot] = stream;
2861 // add codecs for all the streams used by the title
2862 ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2866 for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2868 if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2870 ffmpeg_add_codec( stream,
2871 audio->config.in.codec_param >> ffmpeg_sl_bits );
2876 void *hb_ffmpeg_context( int codec_param )
2878 if ( ffmpeg_streams == NULL )
2881 int slot = codec_param & (ffmpeg_sl_size - 1);
2882 int stream_index = codec_param >> ffmpeg_sl_bits;
2883 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2886 void *hb_ffmpeg_avstream( int codec_param )
2888 if ( ffmpeg_streams == NULL )
2891 int slot = codec_param & (ffmpeg_sl_size - 1);
2892 int stream_index = codec_param >> ffmpeg_sl_bits;
2893 return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2896 static AVFormatContext *ffmpeg_deferred_close;
2898 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2900 if ( ffmpeg_deferred_close )
2902 av_close_input_file( ffmpeg_deferred_close );
2903 ffmpeg_deferred_close = NULL;
2905 AVFormatContext *ic;
2907 av_log_set_level( AV_LOG_ERROR );
2908 if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2912 if ( av_find_stream_info( ic ) < 0 )
2915 stream->ffmpeg_ic = ic;
2916 stream->hb_stream_type = ffmpeg;
2917 stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2918 av_init_packet( stream->ffmpeg_pkt );
2919 stream->chapter_end = INT64_MAX;
2923 // we're opening for read. scan passed out codec params that
2924 // indexed its stream so we need to remap them so they point
2926 ffmpeg_remap_stream( stream, title );
2927 av_log_set_level( AV_LOG_ERROR );
2931 // we're opening for scan. let ffmpeg put some info into the
2932 // log about what we've got.
2933 av_log_set_level( AV_LOG_INFO );
2934 dump_format( ic, 0, stream->path, 0 );
2935 av_log_set_level( AV_LOG_ERROR );
2937 // accept this file if it has at least one video stream we can decode
2939 for (i = 0; i < ic->nb_streams; ++i )
2941 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2946 if ( i >= ic->nb_streams )
2952 av_close_input_file( ic );
2956 static void ffmpeg_close( hb_stream_t *d )
2958 // XXX since we're sharing the CodecContext with the downstream
2959 // decoder proc we can't close the stream. We need to reference count
2960 // this so we can close it when both are done with their instance but
2961 // for now just defer the close until the next stream open or close.
2962 if ( ffmpeg_deferred_close )
2964 av_close_input_file( ffmpeg_deferred_close );
2966 ffmpeg_deferred_close = d->ffmpeg_ic;
2967 if ( d->ffmpeg_pkt != NULL )
2969 free( d->ffmpeg_pkt );
2970 d->ffmpeg_pkt = NULL;
2974 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2976 AVStream *st = stream->ffmpeg_ic->streams[id];
2977 AVCodecContext *codec = st->codec;
2980 // scan will ignore any audio without a bitrate. Since we've already
2981 // typed the audio in order to determine its codec we set up the audio
2983 layout = hb_ff_layout_xlat( codec->channel_layout, codec->channels );
2986 // Unsupported layout
2989 if ( codec->bit_rate || codec->sample_rate )
2991 hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2994 if ( codec->codec_id == CODEC_ID_AC3 )
2996 audio->config.in.codec = HB_ACODEC_AC3;
2998 else if ( codec->codec_id == CODEC_ID_DTS )
3000 audio->config.in.codec = HB_ACODEC_DCA;
3004 audio->config.in.codec = HB_ACODEC_FFMPEG;
3005 audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
3007 audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
3008 audio->config.in.samplerate = codec->sample_rate;
3009 audio->config.in.channel_layout = layout;
3012 set_audio_description( audio, lang_for_code2( st->language ) );
3014 hb_list_add( title->list_audio, audio );
3020 * MkvVobSubtitlePrivateData = ( Line )*
3021 * Line = FieldName ':' ' ' FieldValue '\n'
3023 * FieldValue = [^\n]+
3025 * The line of interest is:
3026 * PaletteLine = "palette" ':' ' ' RRGGBB ( ',' ' ' RRGGBB )*
3028 * More information on the format at:
3029 * http://www.matroska.org/technical/specs/subtitles/images.html
3031 static int ffmpeg_parse_vobsub_extradata_mkv( AVCodecContext *codec, hb_subtitle_t *subtitle )
3033 // lines = (string) codec->extradata;
3034 char *lines = malloc( codec->extradata_size + 1 );
3035 if ( lines == NULL )
3037 memcpy( lines, codec->extradata, codec->extradata_size );
3038 lines[codec->extradata_size] = '\0';
3042 int gotDimensions = 0;
3044 char *curLine, *curLine_parserData;
3045 for ( curLine = strtok_r( lines, "\n", &curLine_parserData );
3047 curLine = strtok_r( NULL, "\n", &curLine_parserData ) )
3051 int numElementsRead = sscanf(curLine, "palette: "
3052 "%06x, %06x, %06x, %06x, "
3053 "%06x, %06x, %06x, %06x, "
3054 "%06x, %06x, %06x, %06x, "
3055 "%06x, %06x, %06x, %06x",
3056 &rgb[0], &rgb[1], &rgb[2], &rgb[3],
3057 &rgb[4], &rgb[5], &rgb[6], &rgb[7],
3058 &rgb[8], &rgb[9], &rgb[10], &rgb[11],
3059 &rgb[12], &rgb[13], &rgb[14], &rgb[15]);
3061 if (numElementsRead == 16) {
3067 int numElementsRead = sscanf(curLine, "size: %dx%d",
3068 &subtitle->width, &subtitle->height);
3070 if (numElementsRead == 2) {
3074 if (gotPalette && gotDimensions)
3078 if (subtitle->width == 0 || subtitle->height == 0)
3080 subtitle->width = 720;
3081 subtitle->height = 480;
3089 for (i=0; i<16; i++)
3090 subtitle->palette[i] = hb_rgb2yuv(rgb[i]);
3100 * Format: 8-bit {0,Y,Cb,Cr} x 16
3102 static int ffmpeg_parse_vobsub_extradata_mp4( AVCodecContext *codec, hb_subtitle_t *subtitle )
3104 if ( codec->extradata_size != 4*16 )
3108 for ( i=0, j=0; i<16; i++, j+=4 )
3110 subtitle->palette[i] =
3111 codec->extradata[j+1] << 16 | // Y
3112 codec->extradata[j+2] << 8 | // Cb
3113 codec->extradata[j+3] << 0; // Cr
3115 if (codec->width <= 0 || codec->height <= 0)
3117 subtitle->width = 720;
3118 subtitle->height = 480;
3122 subtitle->width = codec->width;
3123 subtitle->height = codec->height;
3129 * Parses the 'subtitle->palette' information from the specific VOB subtitle track's private data.
3130 * Returns 0 if successful or 1 if parsing failed or was incomplete.
3132 static int ffmpeg_parse_vobsub_extradata( AVCodecContext *codec, hb_subtitle_t *subtitle )
3134 // XXX: Better if we actually chose the correct parser based on the input container
3136 ffmpeg_parse_vobsub_extradata_mkv( codec, subtitle ) &&
3137 ffmpeg_parse_vobsub_extradata_mp4( codec, subtitle );
3140 static void add_ffmpeg_subtitle( hb_title_t *title, hb_stream_t *stream, int id )
3142 AVStream *st = stream->ffmpeg_ic->streams[id];
3143 AVCodecContext *codec = st->codec;
3145 hb_subtitle_t *subtitle = calloc( 1, sizeof(*subtitle) );
3149 switch ( codec->codec_id )
3151 case CODEC_ID_DVD_SUBTITLE:
3152 subtitle->format = PICTURESUB;
3153 subtitle->source = VOBSUB;
3154 subtitle->config.dest = RENDERSUB; // By default render (burn-in) the VOBSUB.
3155 if ( ffmpeg_parse_vobsub_extradata( codec, subtitle ) )
3156 hb_log( "add_ffmpeg_subtitle: malformed extradata for VOB subtitle track; "
3157 "subtitle colors likely to be wrong" );
3160 subtitle->format = TEXTSUB;
3161 subtitle->source = UTF8SUB;
3162 subtitle->config.dest = PASSTHRUSUB;
3164 case CODEC_ID_MOV_TEXT: // TX3G
3165 subtitle->format = TEXTSUB;
3166 subtitle->source = TX3GSUB;
3167 subtitle->config.dest = PASSTHRUSUB;
3170 subtitle->format = TEXTSUB;
3171 subtitle->source = SSASUB;
3172 subtitle->config.dest = PASSTHRUSUB;
3175 hb_log( "add_ffmpeg_subtitle: unknown subtitle stream type: 0x%x", (int) codec->codec_id );
3180 iso639_lang_t *language = lang_for_code2( st->language );
3181 strcpy( subtitle->lang, language->eng_name );
3182 strncpy( subtitle->iso639_2, language->iso639_2, 4 );
3184 hb_list_add(title->list_subtitle, subtitle);
3187 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
3189 AVFormatContext *ic = stream->ffmpeg_ic;
3191 // 'Barebones Title'
3192 hb_title_t *title = hb_title_init( stream->path, 0 );
3193 title->type = HB_STREAM_TYPE;
3196 // Copy part of the stream path to the title name
3197 char *sep = strrchr(stream->path, '/');
3199 strcpy(title->name, sep+1);
3200 char *dot_term = strrchr(title->name, '.');
3204 uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
3205 title->duration = dur;
3207 title->hours = dur / 3600;
3208 title->minutes = ( dur % 3600 ) / 60;
3209 title->seconds = dur % 60;
3211 // set the title to decode the first video stream in the file
3212 title->demuxer = HB_NULL_DEMUXER;
3213 title->video_codec = 0;
3215 for (i = 0; i < ic->nb_streams; ++i )
3217 if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
3218 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
3219 title->video_codec == 0 )
3221 AVCodecContext *context = ic->streams[i]->codec;
3222 if ( context->pix_fmt != PIX_FMT_YUV420P &&
3223 !sws_isSupportedInput( context->pix_fmt ) )
3225 hb_log( "ffmpeg_title_scan: Unsupported color space" );
3228 title->video_id = i;
3229 stream->ffmpeg_video_id = i;
3231 // We have to use the 'internal' avcodec decoder because
3232 // it needs to share the codec context from this video
3233 // stream. The parser internal to av_read_frame
3234 // passes a bunch of state info to the decoder via the context.
3235 title->video_codec = WORK_DECAVCODECVI;
3236 title->video_codec_param = ffmpeg_codec_param( stream, i );
3238 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
3239 avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
3241 add_ffmpeg_audio( title, stream, i );
3243 else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_SUBTITLE )
3245 add_ffmpeg_subtitle( title, stream, i );
3249 title->container_name = strdup( ic->iformat->name );
3250 title->data_rate = ic->bit_rate;
3252 hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );
3254 if( ic->nb_chapters != 0 )
3257 uint64_t duration_sum = 0;
3258 for( i = 0; i < ic->nb_chapters; i++ )
3259 if( ( m = ic->chapters[i] ) != NULL )
3261 hb_chapter_t * chapter;
3262 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3263 chapter->index = i+1;
3264 chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000 - duration_sum;
3265 duration_sum += chapter->duration;
3266 chapter->hours = chapter->duration / 90000 / 3600;
3267 chapter->minutes = ( ( chapter->duration / 90000 ) % 3600 ) / 60;
3268 chapter->seconds = ( chapter->duration / 90000 ) % 60;
3269 strcpy( chapter->title, m->title );
3270 hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
3271 chapter->index, chapter->title,
3272 chapter->duration, chapter->hours,
3273 chapter->minutes, chapter->seconds );
3274 hb_list_add( title->list_chapter, chapter );
3279 * Fill the metadata.
3281 decmetadata( title );
3283 if( hb_list_count( title->list_chapter ) == 0 )
3285 // Need at least one chapter
3286 hb_chapter_t * chapter;
3287 chapter = calloc( sizeof( hb_chapter_t ), 1 );
3289 chapter->duration = title->duration;
3290 chapter->hours = title->hours;
3291 chapter->minutes = title->minutes;
3292 chapter->seconds = title->seconds;
3293 hb_list_add( title->list_chapter, chapter );
3299 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
3301 if ( pts == AV_NOPTS_VALUE )
3303 return (int64_t)( (double)pts * conv_factor );
3306 static int ffmpeg_is_keyframe( hb_stream_t *stream )
3310 switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
3313 // XXX the VC1 codec doesn't mark key frames so to get previews
3314 // we do it ourselves here. The decoder gets messed up if it
3315 // doesn't get a SEQ header first so we consider that to be a key frame.
3316 pkt = stream->ffmpeg_pkt->data;
3317 if ( !pkt[0] && !pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
3323 // XXX the ffmpeg WMV3 codec doesn't mark key frames.
3324 // Only M$ could make I-frame detection this complicated: there
3325 // are two to four bits of unused junk ahead of the frame type
3326 // so we have to look at the sequence header to find out how much
3327 // to skip. Then there are three different ways of coding the type
3328 // depending on whether it's main or advanced profile then whether
3329 // there are bframes or not so we have to look at the sequence
3330 // header to get that.
3331 pkt = stream->ffmpeg_pkt->data;
3332 uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
3334 if ( ( seqhdr[3] & 0x02 ) == 0 )
3337 if ( ( seqhdr[3] & 0x80 ) == 0 )
3338 // no RANGEREDUCTION
3340 if ( seqhdr[3] & 0x70 )
3341 // stream has b-frames
3342 return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;
3344 return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;
3349 return ( stream->ffmpeg_pkt->flags & PKT_FLAG_KEY );
3352 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
3356 if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
3358 // XXX the following conditional is to handle avi files that
3359 // use M$ 'packed b-frames' and occasionally have negative
3360 // sizes for the null frames these require.
3361 if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
3365 if ( stream->ffmpeg_pkt->size <= 0 )
3367 // M$ "invalid and inefficient" packed b-frames require 'null frames'
3368 // following them to preserve the timing (since the packing puts two
3369 // or more frames in what looks like one avi frame). The contents and
3370 // size of these null frames are ignored by the ff_h263_decode_frame
3371 // as long as they're < 20 bytes. We need a positive size so we use
3372 // one byte if we're given a zero or negative size. We don't know
3373 // if the pkt data points anywhere reasonable so we just stick a
3374 // byte of zero in our outbound buf.
3380 if ( stream->ffmpeg_pkt->size > buf->alloc )
3382 // sometimes we get absurd sizes from ffmpeg
3383 if ( stream->ffmpeg_pkt->size >= (1 << 25) )
3385 hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
3386 av_free_packet( stream->ffmpeg_pkt );
3387 return ffmpeg_read( stream, buf );
3389 // need to expand buffer
3390 hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
3392 memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
3393 buf->size = stream->ffmpeg_pkt->size;
3395 buf->id = stream->ffmpeg_pkt->stream_index;
3396 if ( buf->id == stream->ffmpeg_video_id )
3398 if ( stream->need_keyframe )
3400 // we've just done a seek (generally for scan or live preview) and
3401 // want to start at a keyframe. Some ffmpeg codecs seek to a key
3402 // frame but most don't. So we spin until we either get a keyframe
3403 // or we've looked through 50 video frames without finding one.
3404 if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
3406 av_free_packet( stream->ffmpeg_pkt );
3409 stream->need_keyframe = 0;
3414 // if we haven't done it already, compute a conversion factor to go
3415 // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
3416 double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
3419 AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
3420 tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
3421 stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
3424 buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
3425 buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
3426 if ( buf->renderOffset >= 0 && buf->start == -1 )
3428 buf->start = buf->renderOffset;
3430 else if ( buf->renderOffset == -1 && buf->start >= 0 )
3432 buf->renderOffset = buf->start;
3436 * Fill out buf->stop for subtitle packets
3438 * libavcodec's MKV demuxer stores the duration of UTF-8 subtitles (CODEC_ID_TEXT)
3439 * in the 'convergence_duration' field for some reason.
3441 * Other subtitles' durations are stored in the 'duration' field.
3443 * VOB subtitles (CODEC_ID_DVD_SUBTITLE) do not have their duration stored in
3444 * either field. This is not a problem because the VOB decoder can extract this
3445 * information from the packet payload itself.
3447 * SSA subtitles (CODEC_ID_SSA) do not have their duration stored in
3448 * either field. This is not a problem because the SSA decoder can extract this
3449 * information from the packet payload itself.
3451 enum CodecID ffmpeg_pkt_codec = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_id;
3452 if ( ffmpeg_pkt_codec == CODEC_ID_TEXT ) {
3453 int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->convergence_duration;
3454 int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3455 buf->stop = buf->start + buf_duration;
3457 if ( ffmpeg_pkt_codec == CODEC_ID_MOV_TEXT ) {
3458 int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->duration;
3459 int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
3460 buf->stop = buf->start + buf_duration;
3464 * Check to see whether this video buffer is on a chapter
3465 * boundary, if so mark it as such in the buffer then advance
3466 * chapter_end to the end of the next chapter.
3467 * If there are no chapters, chapter_end is always initialized to INT64_MAX
3468 * (roughly 3 million years at our 90KHz clock rate) so the test
3469 * below handles both the chapters & no chapters case.
3471 if ( buf->id == stream->ffmpeg_video_id && buf->start >= stream->chapter_end )
3473 hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
3474 stream->chapter+1 );
3478 stream->chapter_end += chapter->duration;
3479 buf->new_chap = stream->chapter + 1;
3480 hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
3481 buf->new_chap, buf->start);
3483 // Must have run out of chapters, stop looking.
3484 stream->chapter_end = INT64_MAX;
3489 av_free_packet( stream->ffmpeg_pkt );
3493 static int ffmpeg_seek( hb_stream_t *stream, float frac )
3495 AVFormatContext *ic = stream->ffmpeg_ic;
3498 int64_t pos = (double)ic->duration * (double)frac;
3499 if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
3501 pos += ic->start_time;
3503 av_seek_frame( ic, -1, pos, 0 );
3504 stream->need_keyframe = 1;
3508 av_seek_frame( ic, -1, 0LL, AVSEEK_FLAG_BACKWARD );
3513 // Assumes that we are always seeking forward
3514 static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
3516 AVFormatContext *ic = stream->ffmpeg_ic;
3519 pos = ts * AV_TIME_BASE / 90000 + ffmpeg_initial_timestamp( stream );
3520 stream->need_keyframe = 1;
3521 // Seek to the nearest timestamp before that requested where
3522 // there is an I-frame
3523 return av_seek_frame( ic, -1, pos, AVSEEK_FLAG_BACKWARD );